Programs & Examples On #Math

Mathematics is the study of quantity, structure, space, and change. Any math questions on this site should be programming related.

Python math module

You can also import as

from math import *

Then you can use any mathematical function without prefixing math. e.g.

sqrt(4)

What is "entropy and information gain"?

I can't give you graphics, but maybe I can give a clear explanation.

Suppose we have an information channel, such as a light that flashes once every day either red or green. How much information does it convey? The first guess might be one bit per day. But what if we add blue, so that the sender has three options? We would like to have a measure of information that can handle things other than powers of two, but still be additive (the way that multiplying the number of possible messages by two adds one bit). We could do this by taking log2(number of possible messages), but it turns out there's a more general way.

Suppose we're back to red/green, but the red bulb has burned out (this is common knowledge) so that the lamp must always flash green. The channel is now useless, we know what the next flash will be so the flashes convey no information, no news. Now we repair the bulb but impose a rule that the red bulb may not flash twice in a row. When the lamp flashes red, we know what the next flash will be. If you try to send a bit stream by this channel, you'll find that you must encode it with more flashes than you have bits (50% more, in fact). And if you want to describe a sequence of flashes, you can do so with fewer bits. The same applies if each flash is independent (context-free), but green flashes are more common than red: the more skewed the probability the fewer bits you need to describe the sequence, and the less information it contains, all the way to the all-green, bulb-burnt-out limit.

It turns out there's a way to measure the amount of information in a signal, based on the the probabilities of the different symbols. If the probability of receiving symbol xi is pi, then consider the quantity

-log pi

The smaller pi, the larger this value. If xi becomes twice as unlikely, this value increases by a fixed amount (log(2)). This should remind you of adding one bit to a message.

If we don't know what the symbol will be (but we know the probabilities) then we can calculate the average of this value, how much we will get, by summing over the different possibilities:

I = -Σ pi log(pi)

This is the information content in one flash.

Red bulb burnt out: pred = 0, pgreen=1, I = -(0 + 0)  = 0
Red and green equiprobable: pred = 1/2, pgreen = 1/2, I = -(2 * 1/2 * log(1/2)) = log(2)
Three colors, equiprobable: pi=1/3, I = -(3 * 1/3 * log(1/3)) = log(3)
Green and red, green twice as likely: pred=1/3, pgreen=2/3, I = -(1/3 log(1/3) + 2/3 log(2/3)) = log(3) - 2/3 log(2)

This is the information content, or entropy, of the message. It is maximal when the different symbols are equiprobable. If you're a physicist you use the natural log, if you're a computer scientist you use log2 and get bits.

What's the difference between “mod” and “remainder”?

sign of remainder will be same as the divisible and the sign of modulus will be same as divisor.

Remainder is simply the remaining part after the arithmetic division between two integer number whereas Modulus is the sum of remainder and divisor when they are oppositely signed and remaining part after the arithmetic division when remainder and divisor both are of same sign.

Example of Remainder:

10 % 3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]

-10 % 3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]

10 % -3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]

-10 % -3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]

Example of Modulus:

5 % 3 = 2 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is also positively signed. As both remainder and divisor are of same sign the result will be same as remainder]

-5 % 3 = 1 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is positively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor -2 + 3 = 1]

5 % -3 = -1 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is negatively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor 2 + -3 = -1]

-5 % -3 = -2 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is also negatively signed. As both remainder and divisor are of same sign the result will be same as remainder]

I hope this will clearly distinguish between remainder and modulus.

How can I check if two segments intersect?

This is my way of checking for line crossing and where the intersection occurs. Lets use x1 through x4 and y1 through y4

Segment1 = {(X1, Y1), (X2, Y2)}
Segment2 = {(X3, Y3), (X4, Y4)}

Then we need some vectors to represent them

dx1 = X2 - X1
dx2 = X4 - X4
dy1 = Y2 - Y1
dy2 = Y4 - Y3

Now we look at the determinant

det = dx1 * dy2 - dx2 * dy1

If the determinant is 0.0, then the line segments are parallel. This could mean they overlap. If they overlap just at endpoints, then there is one intersection solution. Otherwise there will be infinite solutions. With infinitely many solutions, what do say is your point of intersection? So it's an interesting special case. If you know ahead of time that the lines can't overlap then you can just check if det == 0.0 and if so just say they don't intersect and be done. Otherwise, lets continue on

dx3 = X3 - X1
dy3 = Y3 - Y1

det1 = dx1 * dy3 - dx3 * dy1
det2 = dx2 * dy3 - dx3 * dy2

Now, if det, det1 and det2 are all zero, then your lines are co-linear and could overlap. If det is zero but either det1 or det2 are not, then they are not co-linear, but are parallel, so there is no intersection. So what's left now if det is zero is a 1D problem instead of 2D. We will need to check one of two ways, depending if dx1 is zero or not (so we can avoid division by zero). If dx1 is zero then just do the same logic with y values rather than x below.

s = X3 / dx1
t = X4 / dx1

This computes two scalers, such that if we scale the vector (dx1, dy1) by s we get point (x3, y3), and by t we get (x4, y4). So if either s or t is between 0.0 and 1.0, then point 3 or 4 lies on our first line. Negative would mean the point is behind the start of our vector, while > 1.0 means it is further ahead of the end of our vector. 0.0 means it is at (x1, y1) and 1.0 means it is at (x2, y2). If both s and t are < 0.0 or both are > 1.0, then they don't intersect. And that handles the parallel lines special case.

Now, if det != 0.0 then

s = det1 / det
t = det2 / det
if (s < 0.0 || s > 1.0 || t < 0.0 || t > 1.0)
    return false  // no intersect

This is similar to what we were doing above really. Now if we pass the above test, then our line segments intersect, and we can calculate the intersection quite easily like so:

Ix = X1 + t * dx1
Iy = Y1 + t * dy1

If you want to dig deeper into what the math is doing, look into Cramer's Rule.

How to create the most compact mapping n ? isprime(n) up to a limit N?

Here's my take on the answer:

def isprime(num):
    return num <= 3 or (num + 1) % 6 == 0 or (num - 1) % 6 == 0

The function will return True if any of the properties below are True. Those properties mathematically define what a prime is.

  1. The number is less than or equal to 3
  2. The number + 1 is divisible by 6
  3. The number - 1 is divisible by 6

2D Euclidean vector rotations

Rotate by 90 degress around 0,0:

x' = -y
y' = x

Rotate by 90 degress around px,py:

x' = -(y - py) + px
y' = (x - px) + py

pow (x,y) in Java

Additionally for what was said, if you want integer powers of two, then 1 << x (or 1L << x) is a faster way to calculate 2x than Math.pow(2,x) or a multiplication loop, and is guaranteed to give you an int (or long) result.

It only uses the lowest 5 (or 6) bits of x (i.e. x & 31 (or x & 63)), though, shifting between 0 and 31 (or 63) bits.

Check if a number is a perfect square

If you want to loop over a range and do something for every number that is NOT a perfect square, you could do something like this:

def non_squares(upper):
    next_square = 0
    diff = 1
    for i in range(0, upper):
        if i == next_square:
            next_square += diff
            diff += 2
            continue
        yield i

If you want to do something for every number that IS a perfect square, the generator is even easier:

(n * n for n in range(upper))

How to scale down a range of numbers with a known min and max value

For convenience, here is Irritate's algorithm in a Java form. Add error checking, exception handling and tweak as necessary.

public class Algorithms { 
    public static double scale(final double valueIn, final double baseMin, final double baseMax, final double limitMin, final double limitMax) {
        return ((limitMax - limitMin) * (valueIn - baseMin) / (baseMax - baseMin)) + limitMin;
    }
}

Tester:

final double baseMin = 0.0;
final double baseMax = 360.0;
final double limitMin = 90.0;
final double limitMax = 270.0;
double valueIn = 0;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));
valueIn = 360;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));
valueIn = 180;
System.out.println(Algorithms.scale(valueIn, baseMin, baseMax, limitMin, limitMax));

90.0
270.0
180.0

How can I check for NaN values?

for strings in panda take pd.isnull:

if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):

the function as feature extraction for NLTK

def act_features(atext):
features = {}
if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):
    if word not in default_stopwords:
      features['cont({})'.format(word.lower())]=True
return features

Undefined reference to `sin`

You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.

As Paul has already mentioned add "-lm" to link with the math library in the step where you are attempting to generate your executable.

In the comment, linuxD asks:

Why for sin() in <math.h>, do we need -lm option explicitly; but, not for printf() in <stdio.h>?

Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).

This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:

Standard C Library

The Standard C library is automatically searched by cc to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.

Standard C Mathematical Library

This library supports the Base System math routines, as defined in Volume 1. The cc option -lm is used to search this library.

The reasoning behind this separation was influenced by a number of factors:

  1. The UNIX wars led to increasing divergence from the original AT&T UNIX offering.
  2. The number of UNIX platforms added difficulty in developing software for the operating system.
  3. An attempt to define the lowest common denominator for software developers was launched, called 1988 POSIX.
  4. Software developers programmed against the POSIX standard to provide their software on "POSIX compliant systems" in order to reach more platforms.
  5. UNIX customers demanded "POSIX compliant" UNIX systems to run the software.

The pressures that fed into the decision to put -lm in a different library probably included, but are not limited to:

  1. It seems like a good way to keep the size of libc down, as many applications don't use functions embedded in the math library.
  2. It provides flexibility in math library implementation, where some math libraries rely on larger embedded lookup tables while others may rely on smaller lookup tables (computing solutions).
  3. For truly size constrained applications, it permits reimplementations of the math library in a non-standard way (like pulling out just sin() and putting it in a custom built library.

In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm.

To the power of in C?

#include <math.h>


printf ("%d", (int) pow (3, 4));

Performance of Java matrix math libraries?

You should add Apache Mahout to your shopping list.

Calculating the position of points in a circle

Based on the answer above from Daniel, here's my take using Python3.

import numpy


def circlepoints(points,radius,center):
    shape = []
    slice = 2 * 3.14 / points
    for i in range(points):
        angle = slice * i
        new_x = center[0] + radius*numpy.cos(angle)
        new_y = center[1] + radius*numpy.sin(angle)

        p = (new_x,new_y)
        shape.append(p)

    return shape

print(circlepoints(100,20,[0,0]))

How do I find the distance between two points?

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)

How to calculate modulus of large numbers?

This is part of code I made for IBAN validation. Feel free to use.

    static void Main(string[] args)
    {
        int modulo = 97;
        string input = Reverse("100020778788920323232343433");
        int result = 0;
        int lastRowValue = 1;

        for (int i = 0; i < input.Length; i++)
        {
            // Calculating the modulus of a large number Wikipedia http://en.wikipedia.org/wiki/International_Bank_Account_Number                                                                        
            if (i > 0)
            {
                lastRowValue = ModuloByDigits(lastRowValue, modulo);
            }
            result += lastRowValue * int.Parse(input[i].ToString());
        }
        result = result % modulo;
        Console.WriteLine(string.Format("Result: {0}", result));            
    }

    public static int ModuloByDigits(int previousValue, int modulo)
    {
        // Calculating the modulus of a large number Wikipedia http://en.wikipedia.org/wiki/International_Bank_Account_Number                        
        return ((previousValue * 10) % modulo);
    }
    public static string Reverse(string input)
    {
        char[] arr = input.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }

Python division

Make at least one of them float, then it will be float division, not integer:

>>> (20.0-10) / (100-10)
0.1111111111111111

Casting the result to float is too late.

How to calculate percentage when old value is ZERO

When both values are zero, then the change is zero.

If one of the values is zero, it's infinite (ambiguous), but I would set it to 100%.

Here is a C++ code (where v1 is the previous value (old), and v2 is new):

double result = 0;
if (v1 != 0 && v2 != 0) {
  // If values are non-zero, use the standard formula.
  result = (v2 / v1) - 1;
} else if (v1 == 0 || v2 == 0) {
  // Change is zero when both values are zeros, otherwise it's 100%.
  result = v1 == 0 && v2 == 0 ? 0 : 1;
}
result = v2 > v1 ? abs(result) : -abs(result);
// Note: To have format in hundreds, multiply the result by 100.

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

How should I throw a divide by zero exception in Java without actually dividing by zero?

public class ZeroDivisionException extends ArithmeticException {
    // ...
}

if (denominator == 0) {
    throw new ZeroDivisionException();
}

Positive Number to Negative Number in JavaScript?

var x = 100;
var negX = ( -x ); // => -100

How to determine if a point is in a 2D triangle?

This is the simplest concept to determine if a point is inside or outside the triangle or on an arm of a triangle.

Determination of a point is inside a triangle by determinants:

Determination of a point is inside a triangle by determinants

The simplest working code:

#-*- coding: utf-8 -*-

import numpy as np

tri_points = [(1,1),(2,3),(3,1)]

def pisinTri(point,tri_points):
    Dx , Dy = point

    A,B,C = tri_points
    Ax, Ay = A
    Bx, By = B
    Cx, Cy = C

    M1 = np.array([ [Dx - Bx, Dy - By, 0],
                    [Ax - Bx, Ay - By, 0],
                    [1      , 1      , 1]
                  ])

    M2 = np.array([ [Dx - Ax, Dy - Ay, 0],
                    [Cx - Ax, Cy - Ay, 0],
                    [1      , 1      , 1]
                  ])

    M3 = np.array([ [Dx - Cx, Dy - Cy, 0],
                    [Bx - Cx, By - Cy, 0],
                    [1      , 1      , 1]
                  ])

    M1 = np.linalg.det(M1)
    M2 = np.linalg.det(M2)
    M3 = np.linalg.det(M3)
    print(M1,M2,M3)

    if(M1 == 0 or M2 == 0 or M3 ==0):
            print("Point: ",point," lies on the arms of Triangle")
    elif((M1 > 0 and M2 > 0 and M3 > 0)or(M1 < 0 and M2 < 0 and M3 < 0)):
            #if products is non 0 check if all of their sign is same
            print("Point: ",point," lies inside the Triangle")
    else:
            print("Point: ",point," lies outside the Triangle")

print("Vertices of Triangle: ",tri_points)
points = [(0,0),(1,1),(2,3),(3,1),(2,2),(4,4),(1,0),(0,4)]
for c in points:
    pisinTri(c,tri_points)

How do I get the total number of unique pairs of a set in the database?

TLDR; The formula is n(n-1)/2 where n is the number of items in the set.

Explanation:

To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA), you can calculate the summation of 1 + 2 + ... + (n-1) where n is the number of items in the set.

The reasoning is as follows, say you have 4 items:

A
B
C
D

The number of items that can be paired with A is 3, or n-1:

AB
AC
AD

It follows that the number of items that can be paired with B is n-2 (because B has already been paired with A):

BC
BD

and so on...

(n-1) + (n-2) + ... + (n-(n-1))

which is the same as

1 + 2 + ... + (n-1)

or

n(n-1)/2

How to resolve a Java Rounding Double issue

As the previous answers stated, this is a consequence of doing floating point arithmetic.

As a previous poster suggested, When you are doing numeric calculations, use java.math.BigDecimal.

However, there is a gotcha to using BigDecimal. When you are converting from the double value to a BigDecimal, you have a choice of using a new BigDecimal(double) constructor or the BigDecimal.valueOf(double) static factory method. Use the static factory method.

The double constructor converts the entire precision of the double to a BigDecimal while the static factory effectively converts it to a String, then converts that to a BigDecimal.

This becomes relevant when you are running into those subtle rounding errors. A number might display as .585, but internally its value is '0.58499999999999996447286321199499070644378662109375'. If you used the BigDecimal constructor, you would get the number that is NOT equal to 0.585, while the static method would give you a value equal to 0.585.

double value = 0.585;
System.out.println(new BigDecimal(value));
System.out.println(BigDecimal.valueOf(value));

on my system gives

0.58499999999999996447286321199499070644378662109375
0.585

less than 10 add 0 to number

I was bored and playing around JSPerf trying to beat the currently selected answer prepending a zero no matter what and using slice(-2). It's a clever approach but the performance gets a lot worse as the string gets longer.

For numbers zero to ten (one and two character strings) I was able to beat by about ten percent, and the fastest approach was much better when dealing with longer strings by using charAt so it doesn't have to traverse the whole string.

This follow is not quit as simple as slice(-2) but is 86%-89% faster when used across mostly 3 digit numbers (3 character strings).

var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;

How to make scipy.interpolate give an extrapolated result beyond the input range?

I'm afraid that there is no easy to do this in Scipy to my knowledge. You can, as I'm fairly sure that you are aware, turn off the bounds errors and fill all function values beyond the range with a constant, but that doesn't really help. See this question on the mailing list for some more ideas. Maybe you could use some kind of piecewise function, but that seems like a major pain.

Rounding integer division (instead of truncating)

The following correctly rounds the quotient to the nearest integer for both positive and negative operands WITHOUT floating point or conditional branches (see assembly output below). Assumes N-bit 2's complement integers.

#define ASR(x) ((x) < 0 ? -1 : 0)  // Compiles into a (N-1)-bit arithmetic shift right
#define ROUNDING(x,y) ( (y)/2 - (ASR((x)^(y)) & (y)))

int RoundedQuotient(int x, int y)
   {
   return (x + ROUNDING(x,y)) / y ;
   }

The value of ROUNDING will have the same sign as the dividend (x) and half the magnitude of the divisor (y). Adding ROUNDING to the dividend thus increases its magnitude before the integer division truncates the resulting quotient. Here's the output of the gcc compiler with -O3 optimization for a 32-bit ARM Cortex-M4 processor:

RoundedQuotient:                // Input parameters: r0 = x, r1 = y
    eor     r2, r1, r0          // r2 = x^y
    and     r2, r1, r2, asr #31 // r2 = ASR(x^y) & y
    add     r3, r1, r1, lsr #31 // r3 = (y < 0) ? y + 1 : y
    rsb     r3, r2, r3, asr #1  // r3 = y/2 - (ASR(x^y) & y)
    add     r0, r0, r3          // r0 = x + (y/2 - (ASR(x^y) & y)
    sdiv    r0, r0, r1          // r0 = (x + ROUNDING(x,y)) / y
    bx      lr                  // Returns r0 = rounded quotient

How to convert number to words in java

You probably don't need this any more, but I recently wrote a java class to do this. Apparently Yanick Rochon did something similar. It will convert numbers up to 999 Novemdecillion (999*10^60). It could do more if I knew what came after Novemdecillion, but I would be willing to bet it's unnecessary. Just feed the number as a string in cents. The output is also grammatically correct.

Here is a link to the Bitbucket Repo

How do I calculate the normal vector of a line segment?

m1 = (y2 - y1) / (x2 - x1)

if perpendicular two lines:

m1*m2 = -1

then

m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)

y = m2*x + b //b is offset of new perpendicular line.. 

b is something if you want to pass it from a point you defined

What is the behavior of integer division?

I know people have answered your question but in layman terms:

5 / 2 = 2 //since both 5 and 2 are integers and integers division always truncates decimals

5.0 / 2 or 5 / 2.0 or 5.0 /2.0 = 2.5 //here either 5 or 2 or both has decimal hence the quotient you will get will be in decimal.

Mapping two integers to one, in a unique and deterministic way

Although Stephan202's answer is the only truly general one, for integers in a bounded range you can do better. For example, if your range is 0..10,000, then you can do:

#define RANGE_MIN 0
#define RANGE_MAX 10000

unsigned int merge(unsigned int x, unsigned int y)
{
    return (x * (RANGE_MAX - RANGE_MIN + 1)) + y;
}

void split(unsigned int v, unsigned int &x, unsigned int &y)
{
    x = RANGE_MIN + (v / (RANGE_MAX - RANGE_MIN + 1));
    y = RANGE_MIN + (v % (RANGE_MAX - RANGE_MIN + 1));
}

Results can fit in a single integer for a range up to the square root of the integer type's cardinality. This packs slightly more efficiently than Stephan202's more general method. It is also considerably simpler to decode; requiring no square roots, for starters :)

How can I get sin, cos, and tan to use degrees instead of radians?

I created my own little lazy Math-Object for degree (MathD), hope it helps:

//helper
/**
 * converts degree to radians
 * @param degree
 * @returns {number}
 */
var toRadians = function (degree) {
    return degree * (Math.PI / 180);
};

/**
 * Converts radian to degree
 * @param radians
 * @returns {number}
 */
var toDegree = function (radians) {
    return radians * (180 / Math.PI);
}

/**
 * Rounds a number mathematical correct to the number of decimals
 * @param number
 * @param decimals (optional, default: 5)
 * @returns {number}
 */
var roundNumber = function(number, decimals) {
    decimals = decimals || 5;
    return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
}
//the object
var MathD = {
    sin: function(number){
        return roundNumber(Math.sin(toRadians(number)));
    },
    cos: function(number){
        return roundNumber(Math.cos(toRadians(number)));
    },
    tan: function(number){
        return roundNumber(Math.tan(toRadians(number)));
    },
    asin: function(number){
        return roundNumber(toDegree(Math.asin(number)));
    },
    acos: function(number){
       return roundNumber(toDegree(Math.acos(number)));
   },
   atan: function(number){
       return roundNumber(toDegree(Math.atan(number)));
   }
};

How to use nan and inf in C?

<inf.h>

/* IEEE positive infinity.  */

#if __GNUC_PREREQ(3,3)
# define INFINITY   (__builtin_inff())
#else
# define INFINITY   HUGE_VALF
#endif

and

<bits/nan.h>
#ifndef _MATH_H
# error "Never use <bits/nan.h> directly; include <math.h> instead."
#endif


/* IEEE Not A Number.  */

#if __GNUC_PREREQ(3,3)

# define NAN    (__builtin_nanf (""))

#elif defined __GNUC__

# define NAN \
  (__extension__                                  \
   ((union { unsigned __l __attribute__ ((__mode__ (__SI__))); float __d; })  \
    { __l: 0x7fc00000UL }).__d)

#else

# include <endian.h>

# if __BYTE_ORDER == __BIG_ENDIAN
#  define __nan_bytes       { 0x7f, 0xc0, 0, 0 }
# endif
# if __BYTE_ORDER == __LITTLE_ENDIAN
#  define __nan_bytes       { 0, 0, 0xc0, 0x7f }
# endif

static union { unsigned char __c[4]; float __d; } __nan_union
    __attribute_used__ = { __nan_bytes };
# define NAN    (__nan_union.__d)

#endif  /* GCC.  */

Calculate the center point of multiple latitude/longitude coordinate pairs

Out of object in PHP. Given array of coordinate pairs, returns center.

/**
 * Calculate center of given coordinates
 * @param  array    $coordinates    Each array of coordinate pairs
 * @return array                    Center of coordinates
 */
function getCoordsCenter($coordinates) {    
    $lats = $lons = array();
    foreach ($coordinates as $key => $value) {
        array_push($lats, $value[0]);
        array_push($lons, $value[1]);
    }
    $minlat = min($lats);
    $maxlat = max($lats);
    $minlon = min($lons);
    $maxlon = max($lons);
    $lat = $maxlat - (($maxlat - $minlat) / 2);
    $lng = $maxlon - (($maxlon - $minlon) / 2);
    return array("lat" => $lat, "lon" => $lng);
}

Taken idea from #4

How do I calculate a point on a circle’s circumference?

Calculating point around circumference of circle given distance travelled.
For comparison... This may be useful in Game AI when moving around a solid object in a direct path.

enter image description here

public static Point DestinationCoordinatesArc(Int32 startingPointX, Int32 startingPointY,
    Int32 circleOriginX, Int32 circleOriginY, float distanceToMove,
    ClockDirection clockDirection, float radius)
{
    // Note: distanceToMove and radius parameters are float type to avoid integer division
    // which will discard remainder

    var theta = (distanceToMove / radius) * (clockDirection == ClockDirection.Clockwise ? 1 : -1);
    var destinationX = circleOriginX + (startingPointX - circleOriginX) * Math.Cos(theta) - (startingPointY - circleOriginY) * Math.Sin(theta);
    var destinationY = circleOriginY + (startingPointX - circleOriginX) * Math.Sin(theta) + (startingPointY - circleOriginY) * Math.Cos(theta);

    // Round to avoid integer conversion truncation
    return new Point((Int32)Math.Round(destinationX), (Int32)Math.Round(destinationY));
}

/// <summary>
/// Possible clock directions.
/// </summary>
public enum ClockDirection
{
    [Description("Time moving forwards.")]
    Clockwise,
    [Description("Time moving moving backwards.")]
    CounterClockwise
}

private void ButtonArcDemo_Click(object sender, EventArgs e)
{
    Brush aBrush = (Brush)Brushes.Black;
    Graphics g = this.CreateGraphics();

    var startingPointX = 125;
    var startingPointY = 75;
    for (var count = 0; count < 62; count++)
    {
        var point = DestinationCoordinatesArc(
            startingPointX: startingPointX, startingPointY: startingPointY,
            circleOriginX: 75, circleOriginY: 75,
            distanceToMove: 5,
            clockDirection: ClockDirection.Clockwise, radius: 50);
        g.FillRectangle(aBrush, point.X, point.Y, 1, 1);

        startingPointX = point.X;
        startingPointY = point.Y;

        // Pause to visually observe/confirm clock direction
        System.Threading.Thread.Sleep(35);

        Debug.WriteLine($"DestinationCoordinatesArc({point.X}, {point.Y}");
    }
}

Math operations from string

Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.

Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.

And fight the temptation of using eval, that's not safe.

Generate a random point within a circle (uniformly)

Let ? (radius) and f (azimuth) be two random variables corresponding to polar coordinates of an arbitrary point inside the circle. If the points are uniformly distributed then what is the disribution function of ? and f?

For any r: 0 < r < R the probability of radius coordinate ? to be less then r is

P[? < r] = P[point is within a circle of radius r] = S1 / S0 =(r/R)2

Where S1 and S0 are the areas of circle of radius r and R respectively. So the CDF can be given as:

          0          if r<=0
  CDF =   (r/R)**2   if 0 < r <= R
          1          if r > R

And PDF:

PDF = d/dr(CDF) = 2 * (r/R**2) (0 < r <= R).

Note that for R=1 random variable sqrt(X) where X is uniform on [0, 1) has this exact CDF (because P[sqrt(X) < y] = P[x < y**2] = y**2 for 0 < y <= 1).

The distribution of f is obviously uniform from 0 to 2*p. Now you can create random polar coordinates and convert them to Cartesian using trigonometric equations:

x = ? * cos(f)
y = ? * sin(f)

Can't resist to post python code for R=1.

from matplotlib import pyplot as plt
import numpy as np

rho = np.sqrt(np.random.uniform(0, 1, 5000))
phi = np.random.uniform(0, 2*np.pi, 5000)

x = rho * np.cos(phi)
y = rho * np.sin(phi)

plt.scatter(x, y, s = 4)

You will get

enter image description here

What is the maximum number of edges in a directed graph with n nodes?

In an undirected graph (excluding multigraphs), the answer is n*(n-1)/2. In a directed graph an edge may occur in both directions between two nodes, then the answer is n*(n-1).

How can I get a count of the total number of digits in a number?

int i = 855865264;
int NumLen = i.ToString().Length;

Mod in Java produces negative numbers

Since Java 8 you can use the Math.floorMod() method:

Math.floorMod(-1, 2); //== 1

Note: If the modulo-value (here 2) is negative, all output values will be negative too. :)

Source: https://stackoverflow.com/a/25830153/2311557

How to find the Center Coordinate of Rectangle?

The center of rectangle is the midpoint of the diagonal end points of rectangle.

Here the midpoint is ( (x1 + x2) / 2, (y1 + y2) / 2 ).

That means:
xCenter = (x1 + x2) / 2
yCenter = (y1 + y2) / 2

Let me know your code.

How do I round to the nearest 0.5?

Multiply by 2, round, then divide by 2

if you want nearest quarter, multiply by 4, divide by 4, etc

Evaluating string "3*(4+2)" yield int 18

There is not. You will need to use some external library, or write your own parser. If you have the time to do so, I suggest to write your own parser as it is a quite interesting project. Otherwise you will need to use something like bcParser.

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

milliseconds to days

If you don't have another time interval bigger than days:

int days = (int) (milliseconds / (1000*60*60*24));

If you have weeks too:

int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));

It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.

TypeError: 'float' object is not callable

The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].

Is there a standard sign function (signum, sgn) in C/C++?

It seems that most of the answers missed the original question.

Is there a standard sign function (signum, sgn) in C/C++?

Not in the standard library, however there is copysign which can be used almost the same way via copysign(1.0, arg) and there is a true sign function in boost, which might as well be part of the standard.

    #include <boost/math/special_functions/sign.hpp>

    //Returns 1 if x > 0, -1 if x < 0, and 0 if x is zero.
    template <class T>
    inline int sign (const T& z);

http://www.boost.org/doc/libs/1_47_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/sign_functions.html

How to determine if a list of polygon points are in clockwise order?

Here is a simple C# implementation of the algorithm based on this answer.

Let's assume that we have a Vector type having X and Y properties of type double.

public bool IsClockwise(IList<Vector> vertices)
{
    double sum = 0.0;
    for (int i = 0; i < vertices.Count; i++) {
        Vector v1 = vertices[i];
        Vector v2 = vertices[(i + 1) % vertices.Count];
        sum += (v2.X - v1.X) * (v2.Y + v1.Y);
    }
    return sum > 0.0;
}

% is the modulo or remainder operator performing the modulo operation which (according to Wikipedia) finds the remainder after division of one number by another.

How to pad a string with leading zeros in Python 3

Since python 3.6 you can use fstring :

>>> length = 1
>>> print(f'length = {length:03}')
length = 001

How to check if a number is a power of 2

bool isPowerOfTwo(int x_)
{
  register int bitpos, bitpos2;
  asm ("bsrl %1,%0": "+r" (bitpos):"rm" (x_));
  asm ("bsfl %1,%0": "+r" (bitpos2):"rm" (x_));
  return bitpos > 0 && bitpos == bitpos2;
}

What is the fastest factorial function in JavaScript?

This is the simplest way I know of to make a factorial function

function factorial(num) {

    var result = 1;
    for(var i = 2; i<= num; i++) {
        result *= i;
    }
    return result;
}

How Does Modulus Divison Work

The only important thing to understand is that modulus (denoted here by % like in C) is defined through the Euclidean division.

For any two (d, q) integers the following is always true:

d = ( d / q ) * q + ( d % q )

As you can see the value of d%q depends on the value of d/q. Generally for positive integers d/q is truncated toward zero, for instance 5/2 gives 2, hence:

5 = (5/2)*2 + (5%2) => 5 = 2*2 + (5%2) => 5%2 = 1

However for negative integers the situation is less clear and depends on the language and/or the standard. For instance -5/2 can return -2 (truncated toward zero as before) but can also returns -3 (with another language).

In the first case:

-5 = (-5/2)*2 + (-5%2) => -5 = -2*2 + (-5%2) => -5%2 = -1

but in the second one:

-5 = (-5/2)*2 + (-5%2) => -5 = -3*2 + (-5%2) => -5%2 = +1

As said before, just remember the invariant, which is the Euclidean division.

Further details:

How can I use "e" (Euler's number) and power operation in python 2.7

math.e or from math import e (= 2.718281…)

The two expressions math.exp(x) and e**x are equivalent however:
Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x). docs.python

for power use ** (3**2 = 9), not " ^ "
" ^ " is a bitwise XOR operator (& and, | or), it works logicaly with bits. So for example 10^4=14 (maybe unexpectedly) ? consider the bitwise depiction:

(0000 1010 ^ 0000 0100 = 0000 1110) programiz

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

Calculate percentage saved between two numbers?

This is function with inverted option

It will return:

  • 'change' - string that you can use for css class in your template
  • 'result' - plain result
  • 'formatted' - formatted result

function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){

    $value      = $newNumber - $oldNumber;

    $change     = '';
    $sign       = '';

    $result     = 0.00;

    if ( $invert ) {
         if ( $value > 0 ) {
        //  going UP
            $change             = 'up';
            $sign               = '+';
            if ( $oldNumber > 0 ) {
                $result         = ($newNumber / $oldNumber) * 100;
            } else {
                $result     = 100.00;
            }

        }elseif ( $value < 0 ) {        
        //  going DOWN
            $change             = 'down';
            //$value                = abs($value);
            $result             = ($oldNumber / $newNumber) * 100;
            $result             = abs($result);
            $sign               = '-';

        }else {
        //  no changes
        }

    }else{

        if ( $newNumber > $oldNumber ) {

            //  increase
            $change             = 'up';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            }else{
                $result = 100.00;
            }

            $sign               = '+';

        }elseif ( $oldNumber > $newNumber ) {

            //  decrease
            $change             = 'down';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            } else {
                $result = 100.00;
            }

            $sign               = '-';

        }else{

            //  no change

        }

        $result = abs($result);

    }

    $result_formatted       = number_format($result, 2);

    if ( $invert ) {
        if ( $change == 'up' ) {
            $change = 'down';
        }elseif ( $change == 'down' ) {
            $change = 'up';
        }else{
            //
        }

        if ( $sign == '+' ) {
            $sign = '-';
        }elseif ( $sign == '-' ) {
            $sign = '+';
        }else{
            //
        }
    }
    if ( $format ) {
        $formatted          = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
    } else{
        $formatted          = $result_formatted;
    }

    return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}

How to convert latitude or longitude to meters?

There are quite a few ways to calculate this. All of them use aproximations of spherical trigonometry where the radius is the one of the earth.

try http://www.movable-type.co.uk/scripts/latlong.html for a bit of methods and code in different languages.

How do I calculate square root in Python?

Perhaps a simple way to remember: add a dot after the numerator (or denominator)

16 ** (1. / 2)   # 4
289 ** (1. / 2)  # 17
27 ** (1. / 3)   # 3

How can I divide two integers to get a double?

var result = decimal.ToDouble(decimal.Divide(5, 2));

Integer division with remainder in JavaScript?

const idivmod = (a, b) => [a/b |0, a%b];

there is also a proposal working on it Modulus and Additional Integer Math

How can I convert radians to degrees with Python?

I like this method,use sind(x) or cosd(x)

import math

def sind(x):
    return math.sin(math.radians(x))

def cosd(x):
    return math.cos(math.radians(x))

Safest way to convert float to integer in python?

df['Column_Name']=df['Column_Name'].astype(int)

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

What does the ^ (XOR) operator do?

^ is the Python bitwise XOR operator. It is how you spell XOR in python:

>>> 0 ^ 0
0
>>> 0 ^ 1
1
>>> 1 ^ 0
1
>>> 1 ^ 1
0

XOR stands for exclusive OR. It is used in cryptography because it let's you 'flip' the bits using a mask in a reversable operation:

>>> 10 ^ 5
15
>>> 15 ^ 5
10

where 5 is the mask; (input XOR mask) XOR mask gives you the input again.

What is the best way to get all the divisors of a number?

Here is a smart and fast way to do it for numbers up to and around 10**16 in pure Python 3.6,

from itertools import compress

def primes(n):
    """ Returns  a list of primes < n for n > 2 """
    sieve = bytearray([True]) * (n//2)
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1)
    return [2,*compress(range(3,n,2), sieve[1:])]

def factorization(n):
    """ Returns a list of the prime factorization of n """
    pf = []
    for p in primeslist:
      if p*p > n : break
      count = 0
      while not n % p:
        n //= p
        count += 1
      if count > 0: pf.append((p, count))
    if n > 1: pf.append((n, 1))
    return pf

def divisors(n):
    """ Returns an unsorted list of the divisors of n """
    divs = [1]
    for p, e in factorization(n):
        divs += [x*p**k for k in range(1,e+1) for x in divs]
    return divs

n = 600851475143
primeslist = primes(int(n**0.5)+1) 
print(divisors(n))

How do I calculate r-squared using Python and Numpy?

From the numpy.polyfit documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function

E(y|x) = p_d * x**d + p_{d-1} * x **(d-1) + ... + p_1 * x + p_0

So you just need to calculate the R-squared for that fit. The wikipedia page on linear regression gives full details. You are interested in R^2 which you can calculate in a couple of ways, the easisest probably being

SST = Sum(i=1..n) (y_i - y_bar)^2
SSReg = Sum(i=1..n) (y_ihat - y_bar)^2
Rsquared = SSReg/SST

Where I use 'y_bar' for the mean of the y's, and 'y_ihat' to be the fit value for each point.

I'm not terribly familiar with numpy (I usually work in R), so there is probably a tidier way to calculate your R-squared, but the following should be correct

import numpy

# Polynomial Regression
def polyfit(x, y, degree):
    results = {}

    coeffs = numpy.polyfit(x, y, degree)

     # Polynomial Coefficients
    results['polynomial'] = coeffs.tolist()

    # r-squared
    p = numpy.poly1d(coeffs)
    # fit values, and mean
    yhat = p(x)                         # or [p(z) for z in x]
    ybar = numpy.sum(y)/len(y)          # or sum(y)/len(y)
    ssreg = numpy.sum((yhat-ybar)**2)   # or sum([ (yihat - ybar)**2 for yihat in yhat])
    sstot = numpy.sum((y - ybar)**2)    # or sum([ (yi - ybar)**2 for yi in y])
    results['determination'] = ssreg / sstot

    return results

I want to calculate the distance between two points in Java

This may be OLD, but here is the best answer:

    float dist = (float) Math.sqrt(
            Math.pow(x1 - x2, 2) +
            Math.pow(y1 - y2, 2) );

Calculate distance between 2 GPS coordinates

This Lua code is adapted from stuff found on Wikipedia and in Robert Lipe's GPSbabel tool:

local EARTH_RAD = 6378137.0 
  -- earth's radius in meters (official geoid datum, not 20,000km / pi)

local radmiles = EARTH_RAD*100.0/2.54/12.0/5280.0;
  -- earth's radius in miles

local multipliers = {
  radians = 1, miles = radmiles, mi = radmiles, feet = radmiles * 5280,
  meters = EARTH_RAD, m = EARTH_RAD, km = EARTH_RAD / 1000, 
  degrees = 360 / (2 * math.pi), min = 60 * 360 / (2 * math.pi)
}

function gcdist(pt1, pt2, units) -- return distance in radians or given units
  --- this formula works best for points close together or antipodal
  --- rounding error strikes when distance is one-quarter Earth's circumference
  --- (ref: wikipedia Great-circle distance)
  if not pt1.radians then pt1 = rad(pt1) end
  if not pt2.radians then pt2 = rad(pt2) end
  local sdlat = sin((pt1.lat - pt2.lat) / 2.0);
  local sdlon = sin((pt1.lon - pt2.lon) / 2.0);
  local res = sqrt(sdlat * sdlat + cos(pt1.lat) * cos(pt2.lat) * sdlon * sdlon);
  res = res > 1 and 1 or res < -1 and -1 or res
  res = 2 * asin(res);
  if units then return res * assert(multipliers[units])
  else return res
  end
end

How to tell whether a point is to the right or left side of a line

First check if you have a vertical line:

if (x2-x1) == 0
  if x3 < x2
     it's on the left
  if x3 > x2
     it's on the right
  else
     it's on the line

Then, calculate the slope: m = (y2-y1)/(x2-x1)

Then, create an equation of the line using point slope form: y - y1 = m*(x-x1) + y1. For the sake of my explanation, simplify it to slope-intercept form (not necessary in your algorithm): y = mx+b.

Now plug in (x3, y3) for x and y. Here is some pseudocode detailing what should happen:

if m > 0
  if y3 > m*x3 + b
    it's on the left
  else if y3 < m*x3 + b
    it's on the right
  else
    it's on the line
else if m < 0
  if y3 < m*x3 + b
    it's on the left
  if y3 > m*x3+b
    it's on the right
  else
    it's on the line
else
  horizontal line; up to you what you do

What's the simplest way to extend a numpy array in 2 dimensions?

The shortest in terms of lines of code i can think of is for the first question.

>>> import numpy as np
>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7],
   [3, 4, 8],
   [5, 6, 9]])

And the for the second question

    p = np.array(range(20))
>>> p.shape = (4,5)
>>> p
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> n = 2
>>> p = np.append(p[:n],p[n+1:],0)
>>> p = np.append(p[...,:n],p[...,n+1:],1)
>>> p
array([[ 0,  1,  3,  4],
       [ 5,  6,  8,  9],
       [15, 16, 18, 19]])

How to find GCD, LCM on a set of numbers

int lcm = 1;
int y = 0;
boolean flag = false;
for(int i=2;i<=n;i++){
            if(lcm%i!=0){
                for(int j=i-1;j>1;j--){
                    if(i%j==0){
                        flag =true;
                        y = j;
                        break;
                    }
                }
                if(flag){
                    lcm = lcm*i/y;
                }
                else{
                    lcm = lcm*i;
                }
            }
            flag = false;
        }

here, first for loop is for getting every numbers starting from '2'. then if statement check whether the number(i) divides lcm if it does then it skip that no. and if it doesn't then next for loop is for finding a no. which can divides the number(i) if this happens we don't need that no. we only wants its extra factor. so here if the flag is true this means there already had some factors of no. 'i' in lcm. so we divide that factors and multiply the extra factor to lcm. If the number isn't divisible by any of its previous no. then when simply multiply it to the lcm.

Calculating distance between two points (Latitude, Longitude)

As you're using SQL 2008 or later, I'd recommend checking out the GEOGRAPHY data type. SQL has built in support for geospatial queries.

e.g. you'd have a column in your table of type GEOGRAPHY which would be populated with a geospatial representation of the coordinates (check out the MSDN reference linked above for examples). This datatype then exposes methods allowing you to perform a whole host of geospatial queries (e.g. finding the distance between 2 points)

How do you calculate the variance, median, and standard deviation in C++ or Java?

public class Statistics {
    double[] data;
    int size;   

    public Statistics(double[] data) {
        this.data = data;
        size = data.length;
    }   

    double getMean() {
        double sum = 0.0;
        for(double a : data)
            sum += a;
        return sum/size;
    }

    double getVariance() {
        double mean = getMean();
        double temp = 0;
        for(double a :data)
            temp += (a-mean)*(a-mean);
        return temp/(size-1);
    }

    double getStdDev() {
        return Math.sqrt(getVariance());
    }

    public double median() {
       Arrays.sort(data);
       if (data.length % 2 == 0)
          return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
       return data[data.length / 2];
    }
}

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

Do not want scientific notation on plot axis

You can use format or formatC to, ahem, format your axis labels.

For whole numbers, try

x <- 10 ^ (1:10)
format(x, scientific = FALSE)
formatC(x, digits = 0, format = "f")

If the numbers are convertable to actual integers (i.e., not too big), you can also use

formatC(x, format = "d")

How you get the labels onto your axis depends upon the plotting system that you are using.

Evaluating a mathematical expression in a string

I think I would use eval(), but would first check to make sure the string is a valid mathematical expression, as opposed to something malicious. You could use a regex for the validation.

eval() also takes additional arguments which you can use to restrict the namespace it operates in for greater security.

Fastest way to determine if an integer's square root is an integer

It's been pointed out that the last d digits of a perfect square can only take on certain values. The last d digits (in base b) of a number n is the same as the remainder when n is divided by bd, ie. in C notation n % pow(b, d).

This can be generalized to any modulus m, ie. n % m can be used to rule out some percentage of numbers from being perfect squares. The modulus you are currently using is 64, which allows 12, ie. 19% of remainders, as possible squares. With a little coding I found the modulus 110880, which allows only 2016, ie. 1.8% of remainders as possible squares. So depending on the cost of a modulus operation (ie. division) and a table lookup versus a square root on your machine, using this modulus might be faster.

By the way if Java has a way to store a packed array of bits for the lookup table, don't use it. 110880 32-bit words is not much RAM these days and fetching a machine word is going to be faster than fetching a single bit.

Algorithm to find Largest prime factor of a number

Compute a list storing prime numbers first, e.g. 2 3 5 7 11 13 ...

Every time you prime factorize a number, use implementation by Triptych but iterating this list of prime numbers rather than natural integers.

Finding square root without using sqrt function?

Here is a very simple but unsafe approach to find the square-root of a number. Unsafe because it only works by natural numbers, where you know that the base respectively the exponent are natural numbers. I had to use it for a task where i was neither allowed to use the #include<cmath> -library, nor i was allowed to use pointers.

potency = base ^ exponent

// FUNCTION: square-root
int sqrt(int x)
{
    int quotient = 0;
    int i = 0;

    bool resultfound = false;
    while (resultfound == false) {
        if (i*i == x) {
          quotient = i;
          resultfound = true;
        }
        i++;
    }
    return quotient;
}

How to sum array of numbers in Ruby?

array.reduce(0, :+)

While equivalent to array.inject(0, :+), the term reduce is entering a more common vernacular with the rise of MapReduce programming models.

inject, reduce, fold, accumulate, and compress are all synonymous as a class of folding functions. I find consistency across your code base most important, but since various communities tend to prefer one word over another, it’s nonetheless useful to know the alternatives.

To emphasize the map-reduce verbiage, here’s a version that is a little bit more forgiving on what ends up in that array.

array.map(&:to_i).reduce(0, :+)

Some additional relevant reading:

Truncate Two decimal places without rounding

Actually you want 3.46 from 3.4679 . This is only representation of characters.So there is nothing to do with math function.Math function is not intended to do this work. Simply use the following code.

Dim str1 As String
str1=""
str1 ="3.4679" 
  Dim substring As String = str1.Substring(0, 3)

    ' Write the results to the screen.
    Console.WriteLine("Substring: {0}", substring)

Or 
    Please use the following code.
Public function result(ByVal x1 As Double) As String 
  Dim i as  Int32
  i=0
  Dim y as String
  y = ""
  For Each ch as Char In x1.ToString
    If i>3 then
     Exit For
    Else
    y + y +ch
    End if
    i=i+1
  Next
  return y
End Function

The above code can be modified for any numbers Put the following code in a button click event

Dim str As String 
str= result(3.4679)
 MsgBox("The number is " & str)

Circle line-segment collision detection algorithm?

If the line's coordinates are A.x, A.y and B.x, B.y and the circles center is C.x, C.y then the lines formulae are:

x = A.x * t + B.x * (1 - t)

y = A.y * t + B.y * (1 - t)

where 0<=t<=1

and the circle is

(C.x - x)^2 + (C.y - y)^2 = R^2

if you substitute x and y formulae of the line into the circles formula you get a second order equation of t and its solutions are the intersection points (if there are any). If you get a t which is smaller than 0 or greater than 1 then its not a solution but it shows that the line is 'pointing' to the direction of the circle.

Java Round up Any Number

int RoundedUp = (int) Math.ceil(RandomReal);

This seemed to do the perfect job. Worked everytime.

How to test if a double is an integer

Similar to SkonJeet's answer above, but the performance is better (at least in java):

Double zero = 0d;    
zero.longValue() == zero.doubleValue()

Simple 3x3 matrix inverse code (C++)

Why don't you try to code it yourself? Take it as a challenge. :)

For a 3×3 matrix

alt text
(source: wolfram.com)

the matrix inverse is

alt text
(source: wolfram.com)

I'm assuming you know what the determinant of a matrix |A| is.

Images (c) Wolfram|Alpha and mathworld.wolfram (06-11-09, 22.06)

C#: what is the easiest way to subtract time?

This works too:

System.DateTime dTime = DateTime.Now();

// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0); 

System.DateTime result = dTime + tSpan;

To subtract a year:

DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);

How can I use numpy.correlate to do autocorrelation?

I'm a computational biologist, and when I had to compute the auto/cross-correlations between couples of time series of stochastic processes I realized that np.correlate was not doing the job I needed.

Indeed, what seems to be missing from np.correlate is the averaging over all the possible couples of time points at distance .

Here is how I defined a function doing what I needed:

def autocross(x, y):
    c = np.correlate(x, y, "same")
    v = [c[i]/( len(x)-abs( i - (len(x)/2)  ) ) for i in range(len(c))]
    return v

It seems to me none of the previous answers cover this instance of auto/cross-correlation: hope this answer may be useful to somebody working on stochastic processes like me.

What is the standard way to add N seconds to datetime.time in Python?

In a real world environment it's never a good idea to work solely with time, always use datetime, even better utc, to avoid conflicts like overnight, daylight saving, different timezones between user and server etc.

So I'd recommend this approach:

import datetime as dt

_now = dt.datetime.now()  # or dt.datetime.now(dt.timezone.utc)
_in_5_sec = _now + dt.timedelta(seconds=5)

# get '14:39:57':
_in_5_sec.strftime('%H:%M:%S')

Is there a math nCr function in python?

The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

As of Python 3.8, binomial coefficients are available in the standard library as math.comb:

>>> from math import comb
>>> comb(10,3)
120

How do I get whole and fractional parts from double in JSP/Java?

double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;

How do I divide in the Linux console?

Example of integer division using bash to divide $a by $b:

echo $((a/b))

Calculating arithmetic mean (one type of average) in Python

You don't even need numpy or scipy...

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))
3

How can I round down a number in Javascript?

Was fiddling round with someone elses code today and found the following which seems rounds down as well:

var dec = 12.3453465,
int = dec >> 0; // returns 12

For more info on the Sign-propagating right shift(>>) see MDN Bitwise Operators

It took me a while to work out what this was doing :D

But as highlighted above, Math.floor() works and looks more readable in my opinion.

What does a circled plus mean?

That's the XOR operator, not the PLUS operator

XOR works bit by bit, without carrying over like PLUS does

1 XOR 1 = 0
1 XOR 0 = 1
0 XOR 0 = 0
0 XOR 1 = 1

Calculating powers of integers

Unlike Python (where powers can be calculated by a**b) , JAVA has no such shortcut way of accomplishing the result of the power of two numbers. Java has function named pow in the Math class, which returns a Double value

double pow(double base, double exponent)

But you can also calculate powers of integer using the same function. In the following program I did the same and finally I am converting the result into an integer (typecasting). Follow the example:

import java.util.*;
import java.lang.*; // CONTAINS THE Math library
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n= sc.nextInt(); // Accept integer n
        int m = sc.nextInt(); // Accept integer m
        int ans = (int) Math.pow(n,m); // Calculates n ^ m
        System.out.println(ans); // prints answers
    }
}

Alternatively, The java.math.BigInteger.pow(int exponent) returns a BigInteger whose value is (this^exponent). The exponent is an integer rather than a BigInteger. Example:

import java.math.*;
public class BigIntegerDemo {
public static void main(String[] args) {
      BigInteger bi1, bi2; // create 2 BigInteger objects          
      int exponent = 2; // create and assign value to exponent
      // assign value to bi1
      bi1 = new BigInteger("6");
      // perform pow operation on bi1 using exponent
      bi2 = bi1.pow(exponent);
      String str = "Result is " + bi1 + "^" +exponent+ " = " +bi2;
      // print bi2 value
      System.out.println( str );
   }
}

Best way to represent a fraction in Java?

If you're feeling adventurous, take a look at JScience. It has a Rational class that represents fractions.

Why is division in Ruby returning an integer instead of decimal value?

It’s doing integer division. You can make one of the numbers a Float by adding .0:

9.0 / 5  #=> 1.8
9 / 5.0  #=> 1.8

How to get last 7 days data from current datetime to last 7 days in sql server

you can use DATEADD function in your where clause like

select ...... where Createdate >= DATEADD(day,-7,GETDATE())

Define an alias in fish shell

I found the prior answers and comments to be needlessly incomplete and/or confusing. The minimum that I needed to do was:

  1. Create ~/.config/fish/config.fish. This file can optionally be a softlink.
  2. Add to it the line alias myalias echo foo bar.
  3. Restart fish. To confirm the definition, try type myalias. Try the alias.

Android Studio with Google Play Services

Google Play services Integration in Android studio.

Step 1:

SDK manager->Tools Update this

1.Google play services
2.Android Support Repository

Step 2:

chance in build.gradle 
defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services:4.0.+'
}

Step 3:

 android.manifest.xml
<uses-sdk
        android:minSdkVersion="8" />

Step 4:

Sync project file with grandle.
wait for few minute.

Step 5:

File->Project Structure find error with red bulb images,click on go to add dependencies select your app module.
Save

Please put comment if you have require help. Happy coding.

How do I pick randomly from an array?

arr = [1,9,5,2,4,9,5,8,7,9,0,8,2,7,5,8,0,2,9]
arr[rand(arr.count)]

This will return a random element from array.

If You will use the line mentioned below

arr[1+rand(arr.count)]

then in some cases it will return 0 or nil value.

The line mentioned below

rand(number)

always return the value from 0 to number-1.

If we use

1+rand(number)

then it may return number and arr[number] contains no element.

Batch file to delete files older than N days

Have a look at my answer to a similar question:

REM del_old.bat
REM usage: del_old MM-DD-YYY
for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> FILES_TO_KEEP.TXT
for /f "tokens=*" %%a IN ('xcopy *.* /L /I /EXCLUDE:FILES_TO_KEEP.TXT null') do if exist "%%~nxa" del "%%~nxa"

This deletes files older than a given date. I'm sure it can be modified to go back seven days from the current date.

update: I notice that HerbCSO has improved on the above script. I recommend using his version instead.

Git log to get commits only for a specific branch

I needed to export log in one line for a specific branch.

So I probably came out with a simpler solution.
When doing git log --pretty=oneline --graph we can see that all commit not done in the current branch are lines starting with |

So a simple grep -v do the job:
git log --pretty=oneline --graph | grep -v "^|"

Of course you can change the pretty parameter if you need other info, as soon as you keep it in one line.

You probably want to remove merge commit too.
As the message start with "Merge branch", pipe another grep -v and you're done.

In my specific ase, the final command was:
git log --pretty="%ad : %an, %s" --graph | grep -v "^|" | grep -v "Merge branch"

Getting path of captured image in Android using camera intent

Try like this

Pass Camera Intent like below

Intent intent = new Intent(this);
startActivityForResult(intent, REQ_CAMERA_IMAGE);

And after capturing image Write an OnActivityResult as below

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        imageView.setImageBitmap(photo);
        knop.setVisibility(Button.VISIBLE);


        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), photo);

        // CALL THIS METHOD TO GET THE ACTUAL PATH
        File finalFile = new File(getRealPathFromURI(tempUri));

        System.out.println(mImageCaptureUri);
    }  
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    String path = "";
    if (getContentResolver() != null) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            path = cursor.getString(idx);
            cursor.close();
        }
    }
    return path;
}

And check log

Edit:

Lots of people are asking how to not get a thumbnail. You need to add this code instead for the getImageUri method:

public Uri getImageUri(Context inContext, Bitmap inImage) {
    Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
    return Uri.parse(path);
}

The other method Compresses the file. You can adjust the size by changing the number 1000,1000

Watching variables in SSIS during debug

Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?

Typescript sleep

import { timer } from 'rxjs';

await timer(1000).pipe(take(1)).toPromise();

this works better for me

Remove directory from remote repository after adding them to .gitignore

As per my Answer here: How to remove a directory from git repository?

To remove folder/directory only from git repository and not from the local try 3 simple steps.


Steps to remove directory

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root named .gitignore and put that folders name into it. You can put as many as you want

.gitignore file will be look like this

/FolderName

remove directory

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

In PHP 7 you can write it even shorter:

$age = $_GET['age'] ?? 27;

This means that the $age variable will be set to the age parameter if it is provided in the URL, or it will default to 27.

See all new features of PHP 7.

How to Cast Objects in PHP

You can use above function for casting not similar class objects (PHP >= 5.3)

/**
 * Class casting
 *
 * @param string|object $destination
 * @param object $sourceObject
 * @return object
 */
function cast($destination, $sourceObject)
{
    if (is_string($destination)) {
        $destination = new $destination();
    }
    $sourceReflection = new ReflectionObject($sourceObject);
    $destinationReflection = new ReflectionObject($destination);
    $sourceProperties = $sourceReflection->getProperties();
    foreach ($sourceProperties as $sourceProperty) {
        $sourceProperty->setAccessible(true);
        $name = $sourceProperty->getName();
        $value = $sourceProperty->getValue($sourceObject);
        if ($destinationReflection->hasProperty($name)) {
            $propDest = $destinationReflection->getProperty($name);
            $propDest->setAccessible(true);
            $propDest->setValue($destination,$value);
        } else {
            $destination->$name = $value;
        }
    }
    return $destination;
}

EXAMPLE:

class A 
{
  private $_x;   
}

class B 
{
  public $_x;   
}

$a = new A();
$b = new B();

$x = cast('A',$b);
$x = cast('B',$a);

A div with auto resize when changing window width\height

Use vh attributes. It means viewport height and is a percentage. So height: 90vh would mean 90% of the viewport height. This works in most modern browsers.

Eg.

div {
  height: 90vh;
}

You can forego the rest of your silly 100% stuff on the body.

If you have a header you can also do some fun things like take it into account by using the calc function in CSS.

Eg.

div {
  height: calc(100vh - 50px);
}

This will give you 100% of the viewport height, minus 50px for your header.

Python Decimals format

Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

Are there any standard exit status codes in Linux?

Programs return a 16 bit exit code. If the program was killed with a signal then the high order byte contains the signal used, otherwise the low order byte is the exit status returned by the programmer.

How that exit code is assigned to the status variable $? is then up to the shell. Bash keeps the lower 7 bits of the status and then uses 128 + (signal nr) for indicating a signal.

The only "standard" convention for programs is 0 for success, non-zero for error. Another convention used is to return errno on error.

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

Why do I have ORA-00904 even when the column is present?

I use Toad for Oracle and if the table is owned by another username than the one you logged in as and you have access to read the table, you still may need to add the original table owner to the table name.

For example, lets say the table owner's name is 'OWNER1' and you are logged in as 'USER1'. This query may give you a ORA-00904 error:

select * from table_name where x='test';

Prefixing the table_name with the table owner eliminated the error and gives results:

select * from 

Add/remove class with jquery based on vertical scroll?

Here's pure javascript example of handling classes during scrolling.

You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle from lodash lib comes in handy.

And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener once they're not needed (eg during onDestroy lifecycle hook of your component, like destroyed() for Vue, or maybe return function of useEffect hook for React).

_x000D_
_x000D_
const navbar = document.getElementById('navbar')_x000D_
_x000D_
// OnScroll event handler_x000D_
const onScroll = () => {_x000D_
_x000D_
  // Get scroll value_x000D_
  const scroll = document.documentElement.scrollTop_x000D_
_x000D_
  // If scroll value is more than 0 - add class_x000D_
  if (scroll > 0) {_x000D_
    navbar.classList.add("scrolled");_x000D_
  } else {_x000D_
    navbar.classList.remove("scrolled")_x000D_
  }_x000D_
}_x000D_
_x000D_
// Optional - throttling onScroll handler at 100ms with lodash_x000D_
const throttledOnScroll = _.throttle(onScroll, 100, {})_x000D_
_x000D_
// Use either onScroll or throttledOnScroll_x000D_
window.addEventListener('scroll', onScroll)
_x000D_
#navbar {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  width: 100%;_x000D_
  height: 60px;_x000D_
  background-color: #89d0f7;_x000D_
  box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);_x000D_
  transition: box-shadow 500ms;_x000D_
}_x000D_
_x000D_
#navbar.scrolled {_x000D_
  box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
#content {_x000D_
  height: 3000px;_x000D_
  margin-top: 60px;_x000D_
}
_x000D_
<!-- Optional - lodash library, used for throttlin onScroll handler-->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>_x000D_
<header id="navbar"></header>_x000D_
<div id="content"></div>
_x000D_
_x000D_
_x000D_

mysqli_fetch_array while loop columns

Try this...

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

Accessing bash command line args $@ vs $*

This example let may highlight the differ between "at" and "asterix" while we using them. I declared two arrays "fruits" and "vegetables"

fruits=(apple pear plumm peach melon)            
vegetables=(carrot tomato cucumber potatoe onion)

printf "Fruits:\t%s\n" "${fruits[*]}"            
printf "Fruits:\t%s\n" "${fruits[@]}"            
echo + --------------------------------------------- +      
printf "Vegetables:\t%s\n" "${vegetables[*]}"    
printf "Vegetables:\t%s\n" "${vegetables[@]}"    

See the following result the code above:

Fruits: apple pear plumm peach melon
Fruits: apple
Fruits: pear
Fruits: plumm
Fruits: peach
Fruits: melon
+ --------------------------------------------- +
Vegetables: carrot tomato cucumber potatoe onion
Vegetables: carrot
Vegetables: tomato
Vegetables: cucumber
Vegetables: potatoe
Vegetables: onion

How to implement authenticated routes in React Router 4?

Based on the answer of @Tyler McGinnis. I made a different approach using ES6 syntax and nested routes with wrapped components:

import React, { cloneElement, Children } from 'react'
import { Route, Redirect } from 'react-router-dom'

const PrivateRoute = ({ children, authed, ...rest }) =>
  <Route
    {...rest}
    render={(props) => authed ?
      <div>
        {Children.map(children, child => cloneElement(child, { ...child.props }))}
      </div>
      :
      <Redirect to={{ pathname: '/', state: { from: props.location } }} />}
  />

export default PrivateRoute

And using it:

<BrowserRouter>
  <div>
    <PrivateRoute path='/home' authed={auth}>
      <Navigation>
        <Route component={Home} path="/home" />
      </Navigation>
    </PrivateRoute>

    <Route exact path='/' component={PublicHomePage} />
  </div>
</BrowserRouter>

Sending HTTP POST Request In Java

The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the HttpResponse with Java libraries.

Here is the more complete code :

/*
 * Create the POST request
 */
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
/*
 * Execute the HTTP Request
 */
try {
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity respEntity = response.getEntity();

    if (respEntity != null) {
        // EntityUtils to get the response content
        String content =  EntityUtils.toString(respEntity);
    }
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}

error while loading shared libraries: libncurses.so.5:

For Redhat Linux 8 try this:

sudo yum install libncurses*

How to redirect 404 errors to a page in ExpressJS?

While the answers above are correct, for those who want to get this working in IISNODE you also need to specify

<configuration>
    <system.webServer>
        <httpErrors existingResponse="PassThrough"/>
    </system.webServer>
<configuration>

in your web.config (otherwise IIS will eat your output).

How to use componentWillMount() in React Hooks?

Ben Carp's answer seems like only valid one to me.

But since we are using functional ways just another approach can be benefiting from closure and HoC:

const InjectWillmount = function(Node, willMountCallback) {
  let isCalled = true;
  return function() {
    if (isCalled) {
      willMountCallback();
      isCalled = false;
    }
    return Node;
  };
};

Then use it :

const YourNewComponent = InjectWillmount(<YourComponent />, () => {
  console.log("your pre-mount logic here");
});

How do I make a JAR from a .java file?

Here is another fancy way of doing this:

$ ls | grep .java | xargs -I {} javac {} ; jar -cf myJar.jar *.class

Which will grab all the .java files ( ls | grep .java ) from your current directory and compile them into .class (xargs -I {} javac {}) and then create the jar file from the previously compiled classes (jar -cf myJar.jar *.class).

How to hide the soft keyboard from inside a fragment?

Use this static method, from anywhere (Activity / Fragment) you like.

public static void hideKeyboard(Activity activity) {
    try{
        InputMethodManager inputManager = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        View currentFocusedView = activity.getCurrentFocus();
        if (currentFocusedView != null) {
            inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

If you want to use for fragment just call hideKeyboard(((Activity) getActivity())).

SQLite - getting number of rows in a database

If you want to use the MAX(id) instead of the count, after reading the comments from Pax then the following SQL will give you what you want

SELECT COALESCE(MAX(id)+1, 0) FROM words

Open web in new tab Selenium + Python

The other solutions do not work for chrome driver v83.

Instead, it works as follows, suppose there is only 1 opening tab:

driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
driver.get("https://www.example.com")

If there are already more than 1 opening tabs, you should first get the index of the last newly-created tab and switch to the tab before calling the url (Credit to tylerl) :

driver.execute_script("window.open('');")
driver.switch_to.window(len(driver.window_handles)-1)
driver.get("https://www.example.com")

How to print time in format: 2009-08-10 18:17:54.811

trick:

    int time_len = 0, n;
    struct tm *tm_info;
    struct timeval tv;

    gettimeofday(&tv, NULL);
    tm_info = localtime(&tv.tv_sec);
    time_len+=strftime(log_buff, sizeof log_buff, "%y%m%d %H:%M:%S", tm_info);
    time_len+=snprintf(log_buff+time_len,sizeof log_buff-time_len,".%03ld ",tv.tv_usec/1000);

Query Mongodb on month, day, year... of a datetime

You cannot straightly query mongodb collections by date components like day or month. But its possible by using the special $where javascript expression

db.mydatabase.mycollection.find({$where : function() { return this.date.getMonth() == 11} })

or simply

db.mydatabase.mycollection.find({$where : 'return this.date.getMonth() == 11'})

(But i prefer the first one)

Check out the below shell commands to get the parts of date

>date = ISODate("2011-09-25T10:12:34Z")
> date.getYear()
111
> date.getMonth()
8
> date.getdate()
25

EDIT:

Use $where only if you have no other choice. It comes with the performance problems. Please check out the below comments by @kamaradclimber and @dcrosta. I will let this post open so the other folks get the facts about it.

and check out the link $where Clauses and Functions in Queries for more info

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

How do you find the row count for all your tables in Postgres

Simple Two Steps:
(Note : No need to change anything - just copy paste)
1. create function

create function 
cnt_rows(schema text, tablename text) returns integer
as
$body$
declare
  result integer;
  query varchar;
begin
  query := 'SELECT count(1) FROM ' || schema || '.' || tablename;
  execute query into result;
  return result;
end;
$body$
language plpgsql;

2. Run this query to get rows count for all the tables

select sum(cnt_rows) as total_no_of_rows from (select 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE') as subq;

or

To get rows counts tablewise

select
  table_schema,
  table_name, 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE'
order by 3 desc;

How do I temporarily disable triggers in PostgreSQL?

PostgreSQL knows the ALTER TABLE tblname DISABLE TRIGGER USER command, which seems to do what I need. See ALTER TABLE.

How to correctly iterate through getElementsByClassName

 <!--something like this--> 
<html>
<body>



<!-- i've used for loop...this pointer takes current element to apply a 
 particular change on it ...other elements take change by else condition 
-->  


<div class="classname" onclick="myFunction(this);">first</div>  
<div class="classname" onclick="myFunction(this);">second</div>


<script>
function myFunction(p) {
 var x = document.getElementsByClassName("classname");
 var i;
 for (i = 0; i < x.length; i++) {
    if(x[i] == p)
    {
x[i].style.background="blue";
    }
    else{
x[i].style.background="red";
    }
}
}


</script>
<!--this script will only work for a class with onclick event but if u want 
to use all class of same name then u can use querySelectorAll() ...-->




var variable_name=document.querySelectorAll('.classname');
for(var i=0;i<variable_name.length;i++){
variable_name[i].(--your option--);
}



 <!--if u like to divide it on some logic apply it inside this for loop 
 using your nodelist-->

</body>
</html>

Why do I get "warning longer object length is not a multiple of shorter object length"?

You don't give a reproducible example but your warning message tells you exactly what the problem is.

memb only has a length of 10. I'm guessing the length of dih_y2$MemberID isn't a multiple of 10. When using ==, R spits out a warning if it isn't a multiple to let you know that it's probably not doing what you're expecting it to do. == does element-wise checking for equality. I suspect what you want to do is find which of the elements of dih_y2$MemberID are also in the vector memb. To do this you would want to use the %in% operator.

dih_col <- which(dih_y2$MemeberID %in% memb)

How do I convert csv file to rdd

Here is another example using Spark/Scala to convert a CSV to RDD. For a more detailed description see this post.

def main(args: Array[String]): Unit = {
  val csv = sc.textFile("/path/to/your/file.csv")

  // split / clean data
  val headerAndRows = csv.map(line => line.split(",").map(_.trim))
  // get header
  val header = headerAndRows.first
  // filter out header (eh. just check if the first val matches the first header name)
  val data = headerAndRows.filter(_(0) != header(0))
  // splits to map (header/value pairs)
  val maps = data.map(splits => header.zip(splits).toMap)
  // filter out the user "me"
  val result = maps.filter(map => map("user") != "me")
  // print result
  result.foreach(println)
}

Generate random colors (RGB)

Output in the form of (r,b,g) its look like (255,155,100)

from numpy import random
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

sending mail from Batch file

bmail. Just install the EXE and run a line like this:

bmail -s myMailServer -f [email protected] -t [email protected] -a "Production Release Performed"

How do I add a placeholder on a CharField in Django?

Most of the time I just wish to have all placeholders equal to the verbose name of the field defined in my models

I've added a mixin to easily do this to any form that I create,

class ProductForm(PlaceholderMixin, ModelForm):
    class Meta:
        model = Product
        fields = ('name', 'description', 'location', 'store')

And

class PlaceholderMixin:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        field_names = [field_name for field_name, _ in self.fields.items()]
        for field_name in field_names:
            field = self.fields.get(field_name)
            field.widget.attrs.update({'placeholder': field.label})

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

I agree with the previous answer. Your compile SDK version must match the support library. Here is what I did.

  1. You can go to SDK Manager and under SDK Platform, install the Android 5.X with API level 23.
  2. Under Project Structure, change compile SDK Version to API 23, and Build Tools Version to 23.0.0

Then it should build without problem.

OS X Terminal Colors

Here is a solution I've found to enable the global terminal colors.

Edit your .bash_profile (since OS X 10.8) — or (for 10.7 and earlier): .profile or .bashrc or /etc/profile (depending on availability) — in your home directory and add following code:

export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced

CLICOLOR=1 simply enables coloring of your terminal.

LSCOLORS=... specifies how to color specific items.

After editing .bash_profile, start a Terminal and force the changes to take place by executing:

source ~/.bash_profile

Then go to Terminal > Preferences, click on the Profiles tab and then the Text subtab and check Display ANSI Colors.

Verified on Sierra (May 2017).

How can I align YouTube embedded video in the center in bootstrap

<iframe style="display: block; margin: auto;" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen></iframe>

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

DECLARE @day CHAR(2)

SET @day = right('0'+ cast(day(getdate())as nvarchar(2)),2)

print @day

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).

Adding external library into Qt Creator project

LIBS += C:\Program Files\OpenCV\lib

won't work because you're using white-spaces in Program Files. In this case you have to add quotes, so the result will look like this: LIBS += "C:\Program Files\OpenCV\lib". I recommend placing libraries in non white-space locations ;-)

How do you properly determine the current script directory?

Note: this answer is now a package

$ pip install locate

>>> from locate import this_dir
>>> print(this_dir())
C:/Users/simon

For .py scripts as well as interactive usage:

I frequently use the directory of my scripts (for accessing files stored along side them), but I also frequently run these scripts in an interactive shell for debugging purposes. I define __dirpath__ as:

  • When running or importing a .py file, the file's base directory. This is always the correct path.
  • When running an .ipyn notebook, the current working directory. This is always the correct path, since Jupyter sets the working directory as the .ipynb base directory.
  • When running in a REPL, the current working directory. Hmm, what is the actual "correct path" when the code is detached from a file? Rather, make it your responsibility to change into the "correct path" before invoking the REPL.

Python 3.4 (and above):

from pathlib import Path
__dirpath__ = Path(globals().get("__file__", "./_")).absolute().parent

Python 2 (and above):

import os
__dirpath__ = os.path.dirname(os.path.abspath(globals().get("__file__", "./_")))

Explanation:

  • globals() returns all the global variables as a dictionary.
  • .get("__file__", "./_") returns the value from the key "__file__" if it exists in globals(), otherwise it returns the provided default value "./_".
  • The rest of the code just expands __file__ (or "./_") into an absolute filepath, and then returns the filepath's base directory.

'^M' character at end of lines

The easiest way is to use vi. I know that sounds terrible but its simple and already installed on most UNIX environments. The ^M is a new line from Windows/DOS environment.

from the command prompt: $ vi filename

Then press ":" to get to command mode.

Search and Replace all Globally is :%s/^M//g "Press and hold control then press V then M" which will replace ^M with nothing.

Then to write and quit enter ":wq" Done!

How to connect SQLite with Java?

connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");

Instead of this put

connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb");

Minimal web server using netcat

Donno how or why but i manage to find this around and it works for me, i had the problem I wanted to return the result of executing a bash

$ while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; sh test; } | nc -l 8080; done

NOTE: This command was taken from: http://www.razvantudorica.com/08/web-server-in-one-line-of-bash

this executes bash script test and return the result to a browser client connecting to the server running this command on port 8080

My script does this ATM

$ nano test

#!/bin/bash

echo "************PRINT SOME TEXT***************\n"
echo "Hello World!!!"
echo "\n"

echo "Resources:"
vmstat -S M
echo "\n"

echo "Addresses:"
echo "$(ifconfig)"
echo "\n"


echo "$(gpio readall)"

and my web browser is showing

************PRINT SOME TEXT***************

Hello World!!!


Resources:
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 0  0      0    314     18     78    0    0     2     1  306   31  0  0 100  0


Addresses:
eth0      Link encap:Ethernet  HWaddr b8:27:eb:86:e8:c5  
          inet addr:192.168.1.83  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:27734 errors:0 dropped:0 overruns:0 frame:0
          TX packets:26393 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1924720 (1.8 MiB)  TX bytes:3841998 (3.6 MiB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)


GPIOs:
+----------+-Rev2-+------+--------+------+-------+
| wiringPi | GPIO | Phys | Name   | Mode | Value |
+----------+------+------+--------+------+-------+
|      0   |  17  |  11  | GPIO 0 | IN   | Low   |
|      1   |  18  |  12  | GPIO 1 | IN   | Low   |
|      2   |  27  |  13  | GPIO 2 | IN   | Low   |
|      3   |  22  |  15  | GPIO 3 | IN   | Low   |
|      4   |  23  |  16  | GPIO 4 | IN   | Low   |
|      5   |  24  |  18  | GPIO 5 | IN   | Low   |
|      6   |  25  |  22  | GPIO 6 | IN   | Low   |
|      7   |   4  |   7  | GPIO 7 | IN   | Low   |
|      8   |   2  |   3  | SDA    | IN   | High  |
|      9   |   3  |   5  | SCL    | IN   | High  |
|     10   |   8  |  24  | CE0    | IN   | Low   |
|     11   |   7  |  26  | CE1    | IN   | Low   |
|     12   |  10  |  19  | MOSI   | IN   | Low   |
|     13   |   9  |  21  | MISO   | IN   | Low   |
|     14   |  11  |  23  | SCLK   | IN   | Low   |
|     15   |  14  |   8  | TxD    | ALT0 | High  |
|     16   |  15  |  10  | RxD    | ALT0 | High  |
|     17   |  28  |   3  | GPIO 8 | ALT2 | Low   |
|     18   |  29  |   4  | GPIO 9 | ALT2 | Low   |
|     19   |  30  |   5  | GPIO10 | ALT2 | Low   |
|     20   |  31  |   6  | GPIO11 | ALT2 | Low   |
+----------+------+------+--------+------+-------+

simply amazing!

Can a java file have more than one class?

Yes You can have more than one Class in one .Java file . But You have make one of them Public . and save .java file with same name as name of public class. when you will compile that .java file than you will get Separate .class files for each class defined in .java file .

Apart from this there are too many method for defining more than one class in one .java file .

  1. use concept of Inner Classes.
  2. Use Concept of Anonymous Classes .

How to print out all the elements of a List in Java?

public static void main(String[] args) {
        answer(10,60);

    }
    public static void answer(int m,int k){
        AtomicInteger n = new AtomicInteger(m);
        Stream<Integer> stream = Stream.generate(() -> n.incrementAndGet()).limit(k);
        System.out.println(Arrays.toString(stream.toArray()));
    }

Android SharedPreferences in Fragment

This did the trick for me

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs

Convert List<DerivedClass> to List<BaseClass>

This is an extension to BigJim's brilliant answer.

In my case I had a NodeBase class with a Children dictionary, and I needed a way to generically do O(1) lookups from the children. I was attempting to return a private dictionary field in the getter of Children, so obviously I wanted to avoid expensive copying/iterating. Therefore I used Bigjim's code to cast the Dictionary<whatever specific type> to a generic Dictionary<NodeBase>:

// Abstract parent class
public abstract class NodeBase
{
    public abstract IDictionary<string, NodeBase> Children { get; }
    ...
}

// Implementing child class
public class RealNode : NodeBase
{
    private Dictionary<string, RealNode> containedNodes;

    public override IDictionary<string, NodeBase> Children
    {
        // Using a modification of Bigjim's code to cast the Dictionary:
        return new IDictionary<string, NodeBase>().CastDictionary<string, RealNode, NodeBase>();
    }
    ...
}

This worked well. However, I eventually ran into unrelated limitations and ended up creating an abstract FindChild() method in the base class that would do the lookups instead. As it turned out this eliminated the need for the casted dictionary in the first place. (I was able to replace it with a simple IEnumerable for my purposes.)

So the question you might ask (especially if performance is an issue prohibiting you from using .Cast<> or .ConvertAll<>) is:

"Do I really need to cast the entire collection, or can I use an abstract method to hold the special knowledge needed to perform the task and thereby avoid directly accessing the collection?"

Sometimes the simplest solution is the best.

Print a string as hex bytes?

You can use hexdump's

import hexdump
hexdump.dump("Hello World", sep=":")

(append .lower() if you require lower-case). This works for both Python 2 & 3.

How to allow only one radio button to be checked?

Give them the same name, and it will work. By definition Radio buttons will only have one choice, while check boxes can have many.

<input type="radio" name="Radio1" />

MySQL Select Date Equal to Today

This query will use index if you have it for signup_date field

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
    FROM users 
    WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)

How to round the double value to 2 decimal points?

I guess that you need a formatted output.

System.out.printf("%.2f",d);

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

Here's what Oracle's documentation has to say:

By default the heap dump is created in a file called java_pid.hprof in the working directory of the VM, as in the example above. You can specify an alternative file name or directory with the -XX:HeapDumpPath= option. For example -XX:HeapDumpPath=/disk2/dumps will cause the heap dump to be generated in the /disk2/dumps directory.

jquery background-color change on focus and blur

Tested Code:

$("input").css("background","red");

Complete:

$('input:text').focus(function () {
    $(this).css({ 'background': 'Black' });
});

$('input:text').blur(function () {
    $(this).css({ 'background': 'red' });
});

Tested in version:

jquery-1.9.1.js
jquery-ui-1.10.3.js

How to dynamically remove items from ListView on a button click?

As for your last question, here's the problem illustrated with a simple example:

Let's say that your list contains 5 elements: list = [1, 2, 3, 4, 5] and your list of items to remove (i.e. the indices) is indices_to_remove = [0, 2, 4]. In the first iteration of the loop you remove the item at index 0, so your list becomes list = [2, 3, 4, 5]. In the second iteration, you remove the item at index 2, so your list becomes list = [2, 3, 5] (as you can see, this removes the wrong element). Finally, in the third iteration, you try to remove the element at index 4, but the list only contains three elements, so you get an out of bounds exception.

Now that you see what the problem is, hopefully you will be able to come up with a solution. Good luck!

Pass Javascript variable to PHP via ajax

Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset is a function to check if something exists and has a value, not to get access to the value.

Change your PHP to be:

$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;

The above line will check to see if the post variable exists. If it does exist it will set $uid to equal the posted value. If it does not exist then it will set $uid equal to 0.

Later in your code you can check the value of $uid and react accordingly

if($uid==0) {
    echo 'User ID not found';
}

This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.

Why maven? What are the benefits?

I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.

It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.

Creating a JavaScript cookie on a domain and reading it across sub domains

You can also use the Cookies API and do:

browser.cookies.set({
  url: 'example.com',
  name: 'HelloWorld',
  value: 'HelloWorld',
  expirationDate: myDate
}

MDN Set() Method Documentation

jQuery AJAX submit form

Another similar solution using attributes defined on the form element:

<form id="contactForm1" action="/your_url" method="post">
    <!-- Form input fields here (do not forget your name attributes). -->
</form>

<script type="text/javascript">
    var frm = $('#contactForm1');

    frm.submit(function (e) {

        e.preventDefault();

        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                console.log('Submission was successful.');
                console.log(data);
            },
            error: function (data) {
                console.log('An error occurred.');
                console.log(data);
            },
        });
    });
</script>

How do I create batch file to rename large number of files in a folder?

@ECHO off & SETLOCAL EnableDelayedExpansion

SET "_dir=" REM Must finish with '\'
SET "_ext=jpg"
SET "_toEdit=Vacation2010"
SET "_with=December"
FOR %%f IN ("%_dir%*.%_ext%") DO (
    CALL :modifyString "%_toEdit%" "%_with%" "%%~Nf" fileName 
    RENAME "%%f" "!fileName!%%~Xf"
)
GOTO end

:modifyString what with in toReturn
    SET "__in=%~3"
    SET "__in=!__in:%~1=%~2!"
    IF NOT "%~4" == "" (
        SET %~4=%__in%
    ) ELSE (
        ECHO %__in%
    )
    EXIT /B

:end

This script allows you to change the name of all the files that contain Vacation2010 with the same name, but with December instead of Vacation2010.

If you copy and paste the code, you have to save the .bat in the same folder of the photos. If you want to save the script in another directory [E.G. you have a favorite folder for the utilities] you have to change the value of _dir with the path of the photos.

If you have to do the same work for other photos [or others files changig _ext] you have to change the value of _toEdit with the string you want to change [or erase] and the value of _with with the string you want to put instead of _toEdit [SET "_with=" if you simply want to erase the string specified in _toEdit].

Child element click event trigger the parent click event

Without jQuery : DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">
   <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
     AAA
   </div>   
</div>

What is the difference between `new Object()` and object literal notation?

Everyone here is talking about the similarities of the two. I am gonna point out the differences.

  1. Using new Object() allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:

    var obj1 = new Object();
    obj1.a = 1;
    var obj2 = new Object(obj1);
    obj2.a // 1
    
  2. The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.

    var obj = new Object(1);
    typeof obj // "number"
    
  3. The object created using the above method (new Object(1)) would be converted to object type if a property is added to it.

    var obj = new Object(1);
    typeof obj // "number"
    obj.a = 2;
    typeof obj // "object"
    
  4. If the object is a copy of a child class of object, we could add the property without the type conversion.

    var obj = new Object("foo");
    typeof obj // "object"
    obj === "foo" // true
    obj.a = 1;
    obj === "foo" // true
    obj.a // 1
    var str = "foo";
    str.a = 1;
    str.a // undefined
    

Checking if a string array contains a value, and if so, getting its position

You could use the Array.IndexOf method:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
    // the array contains the string and the pos variable
    // will have its position in the array
}

SQL: Combine Select count(*) from multiple tables

Basically you do the counts as sub-queries within a standard select.

An example would be the following, this returns 1 row, two columns

SELECT
 (SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount,
 (SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount,

Typescript empty object for a typed variable

user: USER

this.user = ({} as USER)

How do I install the OpenSSL libraries on Ubuntu?

I found a detailed solution here: Install OpenSSL Manually On Linux

From the blog post...:

Steps to download, compile, and install are as follows (I'm installing version 1.0.1g below; please replace "1.0.1g" with your version number):

Step – 1 : Downloading OpenSSL:

Run the command as below :

$ wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz

Also, download the MD5 hash to verify the integrity of the downloaded file for just varifacation purpose. In the same folder where you have downloaded the OpenSSL file from the website :

$ wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz.md5
$ md5sum openssl-1.0.1g.tar.gz
$ cat openssl-1.0.1g.tar.gz.md5

Step – 2 : Extract files from the downloaded package:

$ tar -xvzf openssl-1.0.1g.tar.gz

Now, enter the directory where the package is extracted like here is openssl-1.0.1g

$ cd openssl-1.0.1g

Step – 3 : Configuration OpenSSL

Run below command with optional condition to set prefix and directory where you want to copy files and folder.

$ ./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl

You can replace “/usr/local/openssl” with the directory path where you want to copy the files and folders. But make sure while doing this steps check for any error message on terminal.

Step – 4 : Compiling OpenSSL

To compile openssl you will need to run 2 command : make, make install as below :

$ make

Note: check for any error message for verification purpose.

Step -5 : Installing OpenSSL:

$ sudo make install

Or without sudo,

$ make install

That’s it. OpenSSL has been successfully installed. You can run the version command to see if it worked or not as below :

$ /usr/local/openssl/bin/openssl version

OpenSSL 1.0.1g 7 Apr 2014

Splitting a string into chunks of a certain size

Changed slightly to return parts whose size not equal to chunkSize

public static IEnumerable<string> Split(this string str, int chunkSize)
    {
        var splits = new List<string>();
        if (str.Length < chunkSize) { chunkSize = str.Length; }
        splits.AddRange(Enumerable.Range(0, str.Length / chunkSize).Select(i => str.Substring(i * chunkSize, chunkSize)));
        splits.Add(str.Length % chunkSize > 0 ? str.Substring((str.Length / chunkSize) * chunkSize, str.Length - ((str.Length / chunkSize) * chunkSize)) : string.Empty);
        return (IEnumerable<string>)splits;
    }

What is the equivalent of Java's final in C#?

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

SFTP in Python? (platform independent)

Twisted can help you with what you are doing, check out their documentation, there are plenty of examples. Also it is a mature product with a big developer/user community behind it.

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

My silly mistake was this: change != to ==

if(convertView != null) { // <---- HERE 
                LayoutInflater layoutInflater = LayoutInflater.from(z_selBoardElectricity.this);
                convertView = layoutInflater.inflate(R.layout.listview_board_alert, null);

                TextView textView = convertView.findViewById(R.id.board_name_tv);
                ImageView imageView = convertView.findViewById(R.id.board_imageview);

                textView.setText(text_list.get(position));
                imageView.setImageDrawable(imageAddressList.get(position));

                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra("MESSAGE", text_list.get(pos));
                        setResult(98, intent);
                        finish();
                    }
                });
            }
return convertView;

How do I set up Android Studio to work completely offline?

Android Studio Version < 3.6:

For Windows:

File -> Settings ->Build, Execution,Deployment -> Build Tools -> Gradle

For Mac OS:

Preferences ->Build, Execution,Deployment -> Build Tools -> Gradle

Check/UnCheck Offline work checkbox as per your need.

Android Studio Version >= 3.6:

follow steps in the image:

enter image description here

Random state (Pseudo-random number) in Scikit learn

train_test_split splits arrays or matrices into random train and test subsets. That means that everytime you run it without specifying random_state, you will get a different result, this is expected behavior. For example:

Run 1:

>>> a, b = np.arange(10).reshape((5, 2)), range(5)
>>> train_test_split(a, b)
[array([[6, 7],
        [8, 9],
        [4, 5]]),
 array([[2, 3],
        [0, 1]]), [3, 4, 2], [1, 0]]

Run 2

>>> train_test_split(a, b)
[array([[8, 9],
        [4, 5],
        [0, 1]]),
 array([[6, 7],
        [2, 3]]), [4, 2, 0], [3, 1]]

It changes. On the other hand if you use random_state=some_number, then you can guarantee that the output of Run 1 will be equal to the output of Run 2, i.e. your split will be always the same. It doesn't matter what the actual random_state number is 42, 0, 21, ... The important thing is that everytime you use 42, you will always get the same output the first time you make the split. This is useful if you want reproducible results, for example in the documentation, so that everybody can consistently see the same numbers when they run the examples. In practice I would say, you should set the random_state to some fixed number while you test stuff, but then remove it in production if you really need a random (and not a fixed) split.

Regarding your second question, a pseudo-random number generator is a number generator that generates almost truly random numbers. Why they are not truly random is out of the scope of this question and probably won't matter in your case, you can take a look here form more details.

How to use jQuery Plugin with Angular 4?

You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?

Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...

  1. Run into synchronization problems and have things wrongly appearing or not disappearing at the right time from your screen
  2. Have performance issues in more complex components, as Angular's internal DOM-representation is bound to zone.js and its change detection-mechanism - so updating the DOM manually will always block the thread your app is running on.
  3. Have other confusing errors you don't know the origin of.
  4. Not being able to test the application correctly (Jasmine requires you to know when elements have been rendered)
  5. Not being able to use Angular Universal or WebWorkers

If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jquery instead of getting it from google's CDN.

TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2 If you need to access elements higher up in the DOM hierarchy (parent or document body) or for some other reason directives like *ngIf, *ngFor, custom directives, pipes and other angular utilities like [style.background], [class.myOwnCustomClass] don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example

How can I match on an attribute that contains a certain string?

To add onto bobince's answer... If whatever tool/library you using uses Xpath 2.0, you can also do this:

//*[count(index-of(tokenize(@class, '\s+' ), $classname)) = 1]

count() is apparently needed because index-of() returns a sequence of each index it has a match at in the string.

How can I compare strings in C using a `switch` statement?

If it is a 2 byte string you can do something like in this concrete example where I switch on ISO639-2 language codes.

    LANIDX_TYPE LanCodeToIdx(const char* Lan)
    {
      if(Lan)
        switch(Lan[0]) {
          case 'A':   switch(Lan[1]) {
                        case 'N': return LANIDX_AN;
                        case 'R': return LANIDX_AR;
                      }
                      break;
          case 'B':   switch(Lan[1]) {
                        case 'E': return LANIDX_BE;
                        case 'G': return LANIDX_BG;
                        case 'N': return LANIDX_BN;
                        case 'R': return LANIDX_BR;
                        case 'S': return LANIDX_BS;
                      }
                      break;
          case 'C':   switch(Lan[1]) {
                        case 'A': return LANIDX_CA;
                        case 'C': return LANIDX_CO;
                        case 'S': return LANIDX_CS;
                        case 'Y': return LANIDX_CY;
                      }
                      break;
          case 'D':   switch(Lan[1]) {
                        case 'A': return LANIDX_DA;
                        case 'E': return LANIDX_DE;
                      }
                      break;
          case 'E':   switch(Lan[1]) {
                        case 'L': return LANIDX_EL;
                        case 'N': return LANIDX_EN;
                        case 'O': return LANIDX_EO;
                        case 'S': return LANIDX_ES;
                        case 'T': return LANIDX_ET;
                        case 'U': return LANIDX_EU;
                      }
                      break;
          case 'F':   switch(Lan[1]) {
                        case 'A': return LANIDX_FA;
                        case 'I': return LANIDX_FI;
                        case 'O': return LANIDX_FO;
                        case 'R': return LANIDX_FR;
                        case 'Y': return LANIDX_FY;
                      }
                      break;
          case 'G':   switch(Lan[1]) {
                        case 'A': return LANIDX_GA;
                        case 'D': return LANIDX_GD;
                        case 'L': return LANIDX_GL;
                        case 'V': return LANIDX_GV;
                      }
                      break;
          case 'H':   switch(Lan[1]) {
                        case 'E': return LANIDX_HE;
                        case 'I': return LANIDX_HI;
                        case 'R': return LANIDX_HR;
                        case 'U': return LANIDX_HU;
                      }
                      break;
          case 'I':   switch(Lan[1]) {
                        case 'S': return LANIDX_IS;
                        case 'T': return LANIDX_IT;
                      }
                      break;
          case 'J':   switch(Lan[1]) {
                        case 'A': return LANIDX_JA;
                      }
                      break;
          case 'K':   switch(Lan[1]) {
                        case 'O': return LANIDX_KO;
                      }
                      break;
          case 'L':   switch(Lan[1]) {
                        case 'A': return LANIDX_LA;
                        case 'B': return LANIDX_LB;
                        case 'I': return LANIDX_LI;
                        case 'T': return LANIDX_LT;
                        case 'V': return LANIDX_LV;
                      }
                      break;
          case 'M':   switch(Lan[1]) {
                        case 'K': return LANIDX_MK;
                        case 'T': return LANIDX_MT;
                      }
                      break;
          case 'N':   switch(Lan[1]) {
                        case 'L': return LANIDX_NL;
                        case 'O': return LANIDX_NO;
                      }
                      break;
          case 'O':   switch(Lan[1]) {
                        case 'C': return LANIDX_OC;
                      }
                      break;
          case 'P':   switch(Lan[1]) {
                        case 'L': return LANIDX_PL;
                        case 'T': return LANIDX_PT;
                      }
                      break;
          case 'R':   switch(Lan[1]) {
                        case 'M': return LANIDX_RM;
                        case 'O': return LANIDX_RO;
                        case 'U': return LANIDX_RU;
                      }
                      break;
          case 'S':   switch(Lan[1]) {
                        case 'C': return LANIDX_SC;
                        case 'K': return LANIDX_SK;
                        case 'L': return LANIDX_SL;
                        case 'Q': return LANIDX_SQ;
                        case 'R': return LANIDX_SR;
                        case 'V': return LANIDX_SV;
                        case 'W': return LANIDX_SW;
                      }
                      break;
          case 'T':   switch(Lan[1]) {
                        case 'R': return LANIDX_TR;
                      }
                      break;
          case 'U':   switch(Lan[1]) {
                        case 'K': return LANIDX_UK;
                        case 'N': return LANIDX_UN;
                      }
                      break;
          case 'W':   switch(Lan[1]) {
                        case 'A': return LANIDX_WA;
                      }
                      break;
          case 'Z':   switch(Lan[1]) {
                        case 'H': return LANIDX_ZH;
                      }
                      break;
        }
      return LANIDX_UNDEFINED;
    }

LANIDX_* being constant integers used to index in arrays.

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

How to make a view with rounded corners?

If you are having problem while adding touch listeners to the layout. Use this layout as parent layout.

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;

public class RoundedCornerLayout extends FrameLayout {
    private final static float CORNER_RADIUS = 6.0f;
    private float cornerRadius;

    public RoundedCornerLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public RoundedCornerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }


    @Override
    protected void dispatchDraw(Canvas canvas) {
        int count = canvas.save();

        final Path path = new Path();
        path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), cornerRadius, cornerRadius, Path.Direction.CW);
        canvas.clipPath(path, Region.Op.REPLACE);

        canvas.clipPath(path);
        super.dispatchDraw(canvas);
        canvas.restoreToCount(count);
    }


}

as

<?xml version="1.0" encoding="utf-8"?>
<com.example.view.RoundedCornerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/patentItem"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingRight="20dp">
        ... your child goes here
    </RelativeLayout>
</com.example.view.RoundedCornerLayout>

Regular expression to detect semi-colon terminated C++ for & while loops

Greg is absolutely correct. This kind of parsing cannot be done with regular expressions. I suppose it is possible to build some horrendous monstrosity that would work for many cases, but then you'll just run across something that does.

You really need to use more traditional parsing techniques. For example, its pretty simple to write a recursive decent parser to do what you need.

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

BLOB to String, SQL Server

It depends on how the data was initially put into the column. Try either of these as one should work:

SELECT CONVERT(NVarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];

Or if it was just varchar...

SELECT CONVERT(VarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];

I used this script to verify and test on SQL Server 2K8 R2:

DECLARE @blob VarBinary(MAX) = CONVERT(VarBinary(MAX), 'test');

-- show the binary representation
SELECT @blob;

-- this doesn't work
SELECT CONVERT(NVarChar(100), @blob);

-- but this does
SELECT CONVERT(VarChar(100), @blob);

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

How to make remote REST call inside Node.js? any CURL?

Look at http.request

var options = {
  host: url,
  port: 80,
  path: '/resource?id=foo&bar=baz',
  method: 'POST'
};

http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
}).end();

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

@echo off

:START
rmdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause

echo.
echo.
echo Note the directory is not found
echo.
echo Press any key to make a temporary directory, cls, and test again
pause

Mkdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause
echo.
echo press any key to goto START and remove temporary directory 
pause 

goto START

HTML/JavaScript: Simple form validation on submit

You need to return the validating function. Something like:

onsubmit="return validateForm();"

Then the validating function should return false on errors. If everything is OK return true. Remember that the server has to validate as well.

What is the best way to modify a list in a 'foreach' loop?

Make a copy of the enumeration, using an IEnumerable extension method in this case, and enumerate over it. This would add a copy of every element in every inner enumerable to that enumeration.

foreach(var item in Enumerable)
{
    foreach(var item2 in item.Enumerable.ToList())
    {
        item.Add(item2)
    }
}

Removing character in list of strings

A faster way is to join the list, replace 8 and split the new string:

mylist = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylist = ' '.join(mylist).replace('8','').split()
print mylist

Get array of object's keys

In case you're here looking for something to list the keys of an n-depth nested object as a flat array:

_x000D_
_x000D_
const getObjectKeys = (obj, prefix = '') => {_x000D_
  return Object.entries(obj).reduce((collector, [key, val]) => {_x000D_
    const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]_x000D_
    if (Object.prototype.toString.call(val) === '[object Object]') {_x000D_
      const newPrefix = prefix ? `${prefix}.${key}` : key_x000D_
      const otherKeys = getObjectKeys(val, newPrefix)_x000D_
      return [ ...newKeys, ...otherKeys ]_x000D_
    }_x000D_
    return newKeys_x000D_
  }, [])_x000D_
}_x000D_
_x000D_
console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))
_x000D_
_x000D_
_x000D_

How do you dynamically allocate a matrix?

or you can just allocate a 1D array but reference elements in a 2D fashion:

to address row 2, column 3 (top left corner is row 0, column 0):

arr[2 * MATRIX_WIDTH + 3]

where MATRIX_WIDTH is the number of elements in a row.

How can I sort a List alphabetically?

Here is what you are looking for

listOfCountryNames.sort(String::compareToIgnoreCase)

How to open a txt file and read numbers in Java

Good news in Java 8 we can do it in one line:

List<Integer> ints = Files.lines(Paths.get(fileName))
                          .map(Integer::parseInt)
                          .collect(Collectors.toList());

Finding the index of elements based on a condition using python list comprehension

Even if it's a late answer: I think this is still a very good question and IMHO Python (without additional libraries or toolkits like numpy) is still lacking a convenient method to access the indices of list elements according to a manually defined filter.

You could manually define a function, which provides that functionality:

def indices(list, filtr=lambda x: bool(x)):
    return [i for i,x in enumerate(list) if filtr(x)]

print(indices([1,0,3,5,1], lambda x: x==1))

Yields: [0, 4]

In my imagination the perfect way would be making a child class of list and adding the indices function as class method. In this way only the filter method would be needed:

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
    def indices(self, filtr=lambda x: bool(x)):
        return [i for i,x in enumerate(self) if filtr(x)]

my_list = MyList([1,0,3,5,1])
my_list.indices(lambda x: x==1)

I elaborated a bit more on that topic here: http://tinyurl.com/jajrr87

How to get selenium to wait for ajax response?

If using python, you may use this function, which clicks the button and waits for the DOM change:

def click_n_wait(driver, button, timeout=5):
    source = driver.page_source
    button.click()
    def compare_source(driver):
        try:
            return source != driver.page_source
        except WebDriverException:
            pass
    WebDriverWait(driver, timeout).until(compare_source)

(CREDIT: based on this stack overflow answer)

IIS7 Settings File Locations

Also check this answer from here: Cannot manually edit applicationhost.config

The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.

So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.

How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.

ImportError: No module named PytQt5

If you are on ubuntu, just install pyqt5 with apt-get command:

    sudo apt-get install python3-pyqt5   # for python3

or

    sudo apt-get install python-pyqt5    # for python2

However, on Ubuntu 14.04 the python-pyqt5 package is left out [source] and need to be installed manually [source]

Call break in nested if statements

Just remove the break. since it is already inside first if it will not execute else. It will exit anyway.

How to strip all non-alphabetic characters from string in SQL Server?

Here's a solution that doesn't require creating a function or listing all instances of characters to replace. It uses a recursive WITH statement in combination with a PATINDEX to find unwanted chars. It will replace all unwanted chars in a column - up to 100 unique bad characters contained in any given string. (E.G. "ABC123DEF234" would contain 4 bad characters 1, 2, 3 and 4) The 100 limit is the maximum number of recursions allowed in a WITH statement, but this doesn't impose a limit on the number of rows to process, which is only limited by the memory available.
If you don't want DISTINCT results, you can remove the two options from the code.

-- Create some test data:
SELECT * INTO #testData 
FROM (VALUES ('ABC DEF,K.l(p)'),('123H,J,234'),('ABCD EFG')) as t(TXT)

-- Actual query:
-- Remove non-alpha chars: '%[^A-Z]%'
-- Remove non-alphanumeric chars: '%[^A-Z0-9]%'
DECLARE @BadCharacterPattern VARCHAR(250) = '%[^A-Z]%';

WITH recurMain as (
    SELECT DISTINCT CAST(TXT AS VARCHAR(250)) AS TXT, PATINDEX(@BadCharacterPattern, TXT) AS BadCharIndex
    FROM #testData
    UNION ALL
    SELECT CAST(TXT AS VARCHAR(250)) AS TXT, PATINDEX(@BadCharacterPattern, TXT) AS BadCharIndex
    FROM (
        SELECT 
            CASE WHEN BadCharIndex > 0 
                THEN REPLACE(TXT, SUBSTRING(TXT, BadCharIndex, 1), '')
                ELSE TXT 
            END AS TXT
        FROM recurMain
        WHERE BadCharIndex > 0
    ) badCharFinder
)
SELECT DISTINCT TXT
FROM recurMain
WHERE BadCharIndex = 0;

Spring RestTemplate timeout

Here is a really simple way to set the timeout:

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    int timeout = 5000;
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
      new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(timeout);
    return clientHttpRequestFactory;
}

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

setAllowUrlEncodedSlash(true) didn't work for me. Still internal method isNormalized return false when having double slash.

I replaced StrictHttpFirewall with DefaultHttpFirewall by having the following code only:

@Bean
public HttpFirewall defaultHttpFirewall() {
    return new DefaultHttpFirewall();
}

Working well for me.
Any risk by using DefaultHttpFirewall?

Job for mysqld.service failed See "systemctl status mysqld.service"

In my particular case, the error was appearing due to missing /var/log/mysql with mysql-server package 5.7.21-1 on Debian-based Linux distro. Having ran strace and sudo /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid ( which is what the systemd service actually runs), it became apparent that the issue was due to this:

2019-01-01T09:09:22.102568Z 0 [ERROR] Could not open file '/var/log/mysql/error.log' for error logging: No such file or directory

I've recently removed contents of several directories in /var/log so it was no surprise. The solution was to create the directory and make it owned by mysql user as in

$ sudo mkdir /var/log/mysql
$ sudo chown -R mysql:mysql /var/log/mysql

Having done that I've happily logged in via sudo mysql -u root and greeted with the old and familiar mysql> prompt

Getting value of selected item in list box as string

The correct solution seems to be:

string text = ((ListBoxItem)ListBox1.SelectedItem).Content.ToString();

Please be sure to use .Content and not .Name.

Why does JPA have a @Transient annotation?

In laymen's terms, if you use the @Transient annotation on an attribute of an entity: this attribute will be singled out and will not be saved to the database. The rest of the attribute of the object within the entity will still be saved.

example:

Im saving the Object to the database using the jpa repository built in save method as so:

userRoleJoinRepository.save(user2);

Can't import javax.servlet.annotation.WebServlet

I had the same issue using Spring, solved by adding Tomcat Server Runtime to build path.

cast a List to a Collection

Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.

First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?

If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).

HTH

'setInterval' vs 'setTimeout'

setInterval repeats the call, setTimeout only runs it once.

How to convert Set<String> to String[]?

Guava style:

Set<String> myset = myMap.keySet();
FluentIterable.from(mySet).toArray(String.class);

more info: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/FluentIterable.html

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

VB.NET VERSION

Okay, so I have just spent several hours looking for a viable method for posting multiple parameters to an MVC 4 WEB API, but most of what I found was either for a 'GET' action or just flat out did not work. However, I finally got this working and I thought I'd share my solution.

  1. Use NuGet packages to download JSON-js json2 and Json.NET. Steps to install NuGet packages:

    (1) In Visual Studio, go to Website > Manage NuGet Packages... enter image description here

    (2) Type json (or something to that effect) into the search bar and find JSON-js json2 and Json.NET. Double-clicking them will install the packages into the current project.enter image description here

    (3) NuGet will automatically place the json file in ~/Scripts/json2.min.js in your project directory. Find the json2.min.js file and drag/drop it into the head of your website. Note: for instructions on installing .js (javascript) files, read this solution.

  2. Create a class object containing the desired parameters. You will use this to access the parameters in the API controller. Example code:

    Public Class PostMessageObj
    
    Private _body As String
    Public Property body As String
        Get
            Return _body
        End Get
        Set(value As String)
            _body = value
        End Set
    End Property
    
    
    Private _id As String
    Public Property id As String
        Get
            Return _id
        End Get
        Set(value As String)
            _id = value
        End Set
    End Property
    End Class
    
  3. Then we setup the actual MVC 4 Web API controller that we will be using for the POST action. In it, we will use Json.NET to deserialize the string object when it is posted. Remember to use the appropriate namespaces. Continuing with the previous example, here is my code:

    Public Sub PostMessage(<FromBody()> ByVal newmessage As String)
    
    Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage)
    
    Dim body As String = t.body
    Dim i As String = t.id
    
    End Sub
    
  4. Now that we have our API controller set up to receive our stringified JSON object, we can call the POST action freely from the client-side using $.ajax; Continuing with the previous example, here is my code (replace localhost+rootpath appropriately):

    var url = 'http://<localhost+rootpath>/api/Offers/PostMessage';
    var dataType = 'json'
    var data = 'nothn'
    var tempdata = { body: 'this is a new message...Ip sum lorem.',
        id: '1234'
    }
    var jsondata = JSON.stringify(tempdata)
    $.ajax({
        type: "POST",
        url: url,
        data: { '': jsondata},
        success: success(data),
        dataType: 'text'
    });
    

As you can see we are basically building the JSON object, converting it into a string, passing it as a single parameter, and then rebuilding it via the JSON.NET framework. I did not include a return value in our API controller so I just placed an arbitrary string value in the success() function.


Author's notes

This was done in Visual Studio 2010 using ASP.NET 4.0, WebForms, VB.NET, and MVC 4 Web API Controller. For anyone having trouble integrating MVC 4 Web API with VS2010, you can download the patch to make it possible. You can download it from Microsoft's Download Center.

Here are some additional references which helped (mostly in C#):

Compare two files report difference in python

You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.

What svn command would list all the files modified on a branch?

You can use the following command:

svn status -q

According to svnbook:

With --quiet (-q), it prints only summary information about locally modified items.

WARNING: The output of this command only shows your modification. So I suggest to do a svn up to get latest version of the file and then use svn status -q to get the files you have modified.

CSS Styling for a Button: Using <input type="button> instead of <button>

The issue isn't with the button, the issue is with the div. As divs are block elements, they default to occupying the full width of their parent element (as a general rule; I'm pretty sure there are some exceptions if you're messing around with different positioning schemes in one document that would cause it to occupy the full width of a higher element in the hierarchy).

Anyway, try adding float: left; to the rules for the .button selector. That will cause the div with class button to fit around the button, and would allow you to have multiple floated divs on the same line if you wanted more div.buttons.

How to make an image center (vertically & horizontally) inside a bigger div

This works correctly:

display: block;
margin-left: auto;
margin-right: auto 

else try this if the above only gives you horizontal centering:

.outerContainer {
   position: relative;
}

.innerContainer {
   width: 50px; //your image/element width here
   height: 50px; //your image/element height here
   overflow: auto;
   margin: auto;
   position: absolute;
   top: 0; left: 0; bottom: 0; right: 0;
}

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

JavaScript: Check if mouse button down?

I think the best approach to this is to keep your own record of the mouse button state, as follows:

var mouseDown = 0;
document.body.onmousedown = function() { 
    mouseDown = 1;
}
document.body.onmouseup = function() {
    mouseDown = 0;
}

and then, later in your code:

if (mouseDown == 1) {
    // the mouse is down, do what you have to do.
}

What is the difference between ng-if and ng-show/ng-hide

Fact, that ng-if directive, unlike ng-show, creates its own scope, leads to interesting practical difference:

_x000D_
_x000D_
angular.module('app', []).controller('ctrl', function($scope){_x000D_
  $scope.delete = function(array, item){_x000D_
    array.splice(array.indexOf(item), 1);_x000D_
  }_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app='app' ng-controller='ctrl'>_x000D_
   <h4>ng-if:</h4>_x000D_
   <ul ng-init='arr1 = [1,2,3]'>_x000D_
      <li ng-repeat='x in arr1'>_x000D_
        {{show}}_x000D_
        <button ng-if='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
        <button ng-if='show' ng-click='delete(arr1, x)'>Yes {{show}}</button>_x000D_
        <button ng-if='show' ng-click='show=!show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
   _x000D_
   <h4>ng-show:</h4>_x000D_
   <ul ng-init='arr2 = [1,2,3]'>_x000D_
      <li ng-repeat='x in arr2'>_x000D_
        {{show}}_x000D_
        <button ng-show='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
        <button ng-show='show' ng-click='delete(arr2, x)'>Yes {{show}}</button>_x000D_
        <button ng-show='show' ng-click='show=!show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
   _x000D_
   <h4>ng-if with $parent:</h4>_x000D_
    <ul ng-init='arr3 = [1,2,3]'>_x000D_
      <li ng-repeat='item in arr3'>_x000D_
        {{show}}_x000D_
        <button ng-if='!show' ng-click='$parent.show=!$parent.show'>Delete {{$parent.show}}</button>_x000D_
        <button ng-if='show' ng-click='delete(arr3, x)'>Yes {{$parent.show}}</button>_x000D_
        <button ng-if='show' ng-click='$parent.show=!$parent.show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

At first list, on-click event, show variable, from innner/own scope, is changed, but ng-if is watching on another variable from outer scope with same name, so solution not works. At case of ng-show we have the only one show variable, that is why it works. To fix first attempt, we should reference to show from parent/outer scope via $parent.show.

How to squash commits in git after they have been pushed?

Squash commits locally with

git rebase -i origin/master~4 master

and then force push with

git push origin +master

Difference between --force and +

From the documentation of git push:

Note that --force applies to all the refs that are pushed, hence using it with push.default set to matching or with multiple push destinations configured with remote.*.push may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a + in front of the refspec to push (e.g git push origin +master to force a push to the master branch).

What's the difference between Perl's backticks, system, and exec?

What's the difference between Perl's backticks (`), system, and exec?

exec -> exec "command"; ,
system -> system("command"); and 
backticks -> print `command`;

exec

exec executes a command and never resumes the Perl script. It's to a script like a return statement is to a function.

If the command is not found, exec returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in perlfunc, because it is a function.

E.g.:

#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";

In above code, there are three print statements, but due to exec leaving the script, only the first print statement is executed. Also, the exec command output is not being assigned to any variable.

Here, only you're only getting the output of the first print statement and of executing the ls command on standard out.

system

system executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.

E.g.:

#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements. As the script is resumed after the system command, all three print statements are executed.

Also, the result of running system is assigned to data2, but the assigned value is 0 (the exit code from ls).

Here, you're getting the output of the first print statement, then that of the ls command, followed by the outputs of the final two print statements on standard out.

backticks (`)

Like system, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system, the return value is STDOUT of the command. qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec, it is an operator.

E.g.:

#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements and all three are being executed. The output of ls is not going to standard out directly, but assigned to the variable data2 and then printed by the final print statement.

Can't specify the 'async' modifier on the 'Main' method of a console app

On MSDN, the documentation for Task.Run Method (Action) provides this example which shows how to run a method asynchronously from main:

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
    public static void Main()
    {
        ShowThreadInfo("Application");

        var t = Task.Run(() => ShowThreadInfo("Task") );
        t.Wait();
    }

    static void ShowThreadInfo(String s)
    {
        Console.WriteLine("{0} Thread ID: {1}",
                          s, Thread.CurrentThread.ManagedThreadId);
    }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3

Note this statement that follows the example:

The examples show that the asynchronous task executes on a different thread than the main application thread.

So, if instead you want the task to run on the main application thread, see the answer by @StephenCleary.

And regarding the thread on which the task runs, also note Stephen's comment on his answer:

You can use a simple Wait or Result, and there's nothing wrong with that. But be aware that there are two important differences: 1) all async continuations run on the thread pool rather than the main thread, and 2) any exceptions are wrapped in an AggregateException.

(See Exception Handling (Task Parallel Library) for how to incorporate exception handling to deal with an AggregateException.)


Finally, on MSDN from the documentation for Task.Delay Method (TimeSpan), this example shows how to run an asynchronous task that returns a value:

using System;
using System.Threading.Tasks;

public class Example
{
    public static void Main()
    {
        var t = Task.Run(async delegate
                {
                    await Task.Delay(TimeSpan.FromSeconds(1.5));
                    return 42;
                });
        t.Wait();
        Console.WriteLine("Task t Status: {0}, Result: {1}",
                          t.Status, t.Result);
    }
}
// The example displays the following output:
//        Task t Status: RanToCompletion, Result: 42

Note that instead of passing a delegate to Task.Run, you can instead pass a lambda function like this:

var t = Task.Run(async () =>
        {
            await Task.Delay(TimeSpan.FromSeconds(1.5));
            return 42;
        });

How do I prevent mails sent through PHP mail() from going to spam?

Try PHP Mailer library.
Or Send mail through SMTP filter it before sending it.
Also Try to give all details like FROM, return-path.

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

 function GetTime(date) {
        var currentTime = (new Date(date))
        var hours = currentTime.getHours()
        //Note: before converting into 12 hour format
        var suffix = '';
        if (hours > 11) {
            suffix += "PM";
        } else {
            suffix += "AM";
        }
        var minutes = currentTime.getMinutes()
        if (minutes < 10) {
            minutes = "0" + minutes
        }
        if (hours > 12) {
            hours -= 12;
        } else if (hours === 0) {
            hours = 12;
        }
        var time = hours + ":" + minutes + " " + suffix;
        return time;
    }

How to read all rows from huge table?

I think your question is similar to this thread: JDBC Pagination which contains solutions for your need.

In particular, for PostgreSQL, you can use the LIMIT and OFFSET keywords in your request: http://www.petefreitag.com/item/451.cfm

PS: In Java code, I suggest you to use PreparedStatement instead of simple Statements: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html

How to show all of columns name on pandas dataframe?

I know it is a repetition but I always end up copy pasting and modifying YOLO's answer:

pd.set_option('display.max_columns', 500)
pd.set_option('display.max_rows', 500)

How to update a single library with Composer?

To install doctrine/doctrine-fixtures-bundle with version 2.1.* and minimum stability @dev use this:

composer require doctrine/doctrine-fixtures-bundle:2.1.*@dev

then to update only this single package:

composer update doctrine/doctrine-fixtures-bundle

Where could I buy a valid SSL certificate?

Let's Encrypt is a free, automated, and open certificate authority made by the Internet Security Research Group (ISRG). It is sponsored by well-known organisations such as Mozilla, Cisco or Google Chrome. All modern browsers are compatible and trust Let's Encrypt.

All certificates are free (even wildcard certificates)! For security reasons, the certificates expire pretty fast (after 90 days). For this reason, it is recommended to install an ACME client, which will handle automatic certificate renewal.

There are many clients you can use to install a Let's Encrypt certificate:

Let’s Encrypt uses the ACME protocol to verify that you control a given domain name and to issue you a certificate. To get a Let’s Encrypt certificate, you’ll need to choose a piece of ACME client software to use. - https://letsencrypt.org/docs/client-options/

String to Binary in C#

Here's an extension function:

        public static string ToBinary(this string data, bool formatBits = false)
        {
            char[] buffer = new char[(((data.Length * 8) + (formatBits ? (data.Length - 1) : 0)))];
            int index = 0;
            for (int i = 0; i < data.Length; i++)
            {
                string binary = Convert.ToString(data[i], 2).PadLeft(8, '0');
                for (int j = 0; j < 8; j++)
                {
                    buffer[index] = binary[j];
                    index++;
                }
                if (formatBits && i < (data.Length - 1))
                {
                    buffer[index] = ' ';
                    index++;
                }
            }
            return new string(buffer);
        }

You can use it like:

Console.WriteLine("Testing".ToBinary());

and if you add 'true' as a parameter, it will automatically separate each binary sequence.

How to select lines between two marker patterns which may occur multiple times with awk/sed

This might work for you (GNU sed):

sed '/^abc$/,/^mno$/{//!b};d' file

Delete all lines except for those between lines starting abc and mno

Two's Complement in Python

you could convert the integer to bytes and then use struct.unpack to convert:

from struct import unpack

x = unpack("b", 0b11111111.to_bytes(length=1, byteorder="little"))
print(x)  # (-1,)

Is there a destructor for Java?

If it's just memory you are worried about, don't. Just trust the GC it does a decent job. I actually saw something about it being so efficient that it could be better for performance to create heaps of tiny objects than to utilize large arrays in some instances.

"Strict Standards: Only variables should be passed by reference" error

Instead of parsing it manually it's better to use pathinfo function:

$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];

How do you use bcrypt for hashing passwords in PHP?

Current thinking: hashes should be the slowest available, not the fastest possible. This suppresses rainbow table attacks.

Also related, but precautionary: An attacker should never have unlimited access to your login screen. To prevent that: Set up an IP address tracking table that records every hit along with the URI. If more than 5 attempts to login come from the same IP address in any five minute period, block with explanation. A secondary approach is to have a two-tiered password scheme, like banks do. Putting a lock-out for failures on the second pass boosts security.

Summary: slow down the attacker by using time-consuming hash functions. Also, block on too many accesses to your login, and add a second password tier.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Default timeout is 15 seconds, to change that, 0 is unlimited, any other number is the number of seconds.

In Code

using (SqlCommand sqlCmd = new SqlCommand(sqlQueryString, sqlConnection))
   {
      sqlCmd.CommandTimeout = 0; // 0 = give it as much time as it needs to complete
      ...
    }

In Your Web.Config, "Command Timeout=0;" do not time out, or as below 1 hour (3600 seconds)

  <add name="ConnectionString" connectionString="Data Source=ServerName;User ID=UserName;Password=Password;Command Timeout=3600;" providerName="System.Data.SqlClient" />

Viewing full version tree in git

if you happen to not have a graphical interface available you can also print out the commit graph on the command line:

git log --oneline --graph --decorate --all

if this command complains with an invalid option --oneline, use:

git log --pretty=oneline --graph --decorate --all

How to create a dotted <hr/> tag?

The <hr> tag is just a short element with a border:

<hr style="border-style: dotted;" />

What does the M stand for in C# Decimal literal notation?

It means it's a decimal literal, as others have said. However, the origins are probably not those suggested elsewhere in this answer. From the C# Annotated Standard (the ECMA version, not the MS version):

The decimal suffix is M/m since D/d was already taken by double. Although it has been suggested that M stands for money, Peter Golde recalls that M was chosen simply as the next best letter in decimal.

A similar annotation mentions that early versions of C# included "Y" and "S" for byte and short literals respectively. They were dropped on the grounds of not being useful very often.

jQuery animate scroll

There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check out AnimatedScroll.js.

Converting between datetime, Timestamp and datetime64

To convert numpy.datetime64 to datetime object that represents time in UTC on numpy-1.8:

>>> from datetime import datetime
>>> import numpy as np
>>> dt = datetime.utcnow()
>>> dt
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> dt64 = np.datetime64(dt)
>>> ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
>>> ts
1354650685.3624549
>>> datetime.utcfromtimestamp(ts)
datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)
>>> np.__version__
'1.8.0.dev-7b75899'

The above example assumes that a naive datetime object is interpreted by np.datetime64 as time in UTC.


To convert datetime to np.datetime64 and back (numpy-1.6):

>>> np.datetime64(datetime.utcnow()).astype(datetime)
datetime.datetime(2012, 12, 4, 13, 34, 52, 827542)

It works both on a single np.datetime64 object and a numpy array of np.datetime64.

Think of np.datetime64 the same way you would about np.int8, np.int16, etc and apply the same methods to convert beetween Python objects such as int, datetime and corresponding numpy objects.

Your "nasty example" works correctly:

>>> from datetime import datetime
>>> import numpy 
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
datetime.datetime(2002, 6, 28, 0, 0)
>>> numpy.__version__
'1.6.2' # current version available via pip install numpy

I can reproduce the long value on numpy-1.8.0 installed as:

pip install git+https://github.com/numpy/numpy.git#egg=numpy-dev

The same example:

>>> from datetime import datetime
>>> import numpy
>>> numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
1025222400000000000L
>>> numpy.__version__
'1.8.0.dev-7b75899'

It returns long because for numpy.datetime64 type .astype(datetime) is equivalent to .astype(object) that returns Python integer (long) on numpy-1.8.

To get datetime object you could:

>>> dt64.dtype
dtype('<M8[ns]')
>>> ns = 1e-9 # number of seconds in a nanosecond
>>> datetime.utcfromtimestamp(dt64.astype(int) * ns)
datetime.datetime(2002, 6, 28, 0, 0)

To get datetime64 that uses seconds directly:

>>> dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100', 's')
>>> dt64.dtype
dtype('<M8[s]')
>>> datetime.utcfromtimestamp(dt64.astype(int))
datetime.datetime(2002, 6, 28, 0, 0)

The numpy docs say that the datetime API is experimental and may change in future numpy versions.

Count how many files in directory PHP

You can simply do the following :

$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));

How to check if element is visible after scrolling?

This should do the trick:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

Simple Utility Function This will allow you to call a utility function that accepts the element you're looking for and if you want the element to be fully in view or partially.

function Utils() {

}

Utils.prototype = {
    constructor: Utils,
    isElementInView: function (element, fullyInView) {
        var pageTop = $(window).scrollTop();
        var pageBottom = pageTop + $(window).height();
        var elementTop = $(element).offset().top;
        var elementBottom = elementTop + $(element).height();

        if (fullyInView === true) {
            return ((pageTop < elementTop) && (pageBottom > elementBottom));
        } else {
            return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
        }
    }
};

var Utils = new Utils();

Usage

var isElementInView = Utils.isElementInView($('#flyout-left-container'), false);

if (isElementInView) {
    console.log('in view');
} else {
    console.log('out of view');
}

Check if a string contains another string

Building on Rene's answer, you could also write a function that returned either TRUE if the substring was present, or FALSE if it wasn't:

Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean
'Purpose: Returns TRUE if one string exists within another
On Error GoTo ErrorMessage
    Contains = InStr(strBaseString, strSearchTerm)
Exit Function
ErrorMessage:
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
End
End Function

How can I handle the warning of file_get_contents() function in PHP?

You could use this script

$url = @file_get_contents("http://www.itreb.info");
if ($url) {
    // if url is true execute this 
    echo $url;
} else {
    // if not exceute this 
    echo "connection error";
}

What is JSON and why would I use it?

We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.

For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON). That is one problem where you could use JSON perhaps.

Here is something practical: Yahoo JSON

Passing an array to a query using a WHERE clause

Assuming you properly sanitize your inputs beforehand...

$matches = implode(',', $galleries);

Then just adjust your query:

SELECT *
FROM galleries
WHERE id IN ( $matches ) 

Quote values appropriately depending on your dataset.

Escaping special characters in Java Regular Expressions

Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?

If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.

So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:

// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";

The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.

matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
... 

In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

See the link below for information about how to use PreparedStatement. I have also quoted from the link.

http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

You must supply values in place of the question mark placeholders (if there are any) before you can execute a PreparedStatement object. Do this by calling one of the setter methods defined in the PreparedStatement class. The following statements supply the two question mark placeholders in the PreparedStatement named updateSales:

updateSales.setInt(1, e.getValue().intValue()); updateSales.setString(2, e.getKey());

jquery - fastest way to remove all rows from a very large table

Using detach is magnitudes faster than any of the other answers here:

$('#mytable').find('tbody').detach();

Don't forget to put the tbody element back into the table since detach removed it:

$('#mytable').append($('<tbody>'));  

Also note that when talking efficiency $(target).find(child) syntax is faster than $(target > child). Why? Sizzle!

Elapsed Time to Empty 3,161 Table Rows

Using the Detach() method (as shown in my example above):

  • Firefox: 0.027s
  • Chrome: 0.027s
  • Edge: 1.73s
  • IE11: 4.02s

Using the empty() method:

  • Firefox: 0.055s
  • Chrome: 0.052s
  • Edge: 137.99s (might as well be frozen)
  • IE11: Freezes and never returns

Why does CSS not support negative padding?

I recently answered a different question where I discussed why the box model is the way it is.

There are specific reasons for each part of the box model. Padding is meant to extend the background beyond its contents. If you need to shrink the background of the container, you should make the parent container the correct size and give the child element some negative margins. In this case the content is not being padded, it's overflowing.

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Until I get a better option, this is the most "bootstrappy" answer I can work out:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/

I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less file:

in _layout.cshtml master page

  • Move footer outside the body-content container
  • Use boostrap's navbar-fixed-bottom on the footer
  • Drop the <hr/> before the footer (as now redundant)

Relevant page HTML:

<div class="container-fluid body-content">
    @RenderBody()
</div>
<footer class="navbar-fixed-bottom">
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>

In Site.less

  • Set HTML and BODY heights to 100%
  • Set BODY overflow to hidden
  • Set body-content div position to absolute
  • Set body-content div top to @navbar-height instead of hard-wiring value
  • Set body-content div bottom to 30px.
  • Set body-content div left and right to 0
  • Set body-content div overflow-y to auto

Site.less

html {
    height: 100%;

    body {
        height: 100%;
        overflow: hidden;

        .container-fluid.body-content {
            position: absolute;
            top: @navbar-height;
            bottom: 30px;
            right: 0;
            left: 0;
            overflow-y: auto;
        }
    }
}

The remaining problem is there seems to be no defining variable for the footer height in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

HTTP GET Request in Node.js Express

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured network. so these two lines would change:

https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......

Slack URL to open a channel from browser

You can use

slack://

in order to open the Slack desktop application. For example, on mac, I've run:

open slack://

from the terminal and it opens the Mac desktop Slack application. Still, I didn't figure out the URL that should be used for opening a certain team, channel or message.

Display Two <div>s Side-by-Side

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

Material Design not styling alert dialogs

Material Design styling alert dialogs: Custom Font, Button, Color & shape,..

 MaterialAlertDialogBuilder(requireContext(),
                R.style.MyAlertDialogTheme
            )
                .setIcon(R.drawable.ic_dialogs_24px)
                .setTitle("Feedback")
                //.setView(R.layout.edit_text)
                .setMessage("Do you have any additional comments?")
                .setPositiveButton("Send") { dialog, _ ->

                    val input =
                        (dialog as AlertDialog).findViewById<TextView>(
                            android.R.id.text1
                        )
                    Toast.makeText(context, input!!.text, Toast.LENGTH_LONG).show()

                }
                .setNegativeButton("Cancel") { _, _ ->
                    Toast.makeText(requireContext(), "Clicked cancel", Toast.LENGTH_SHORT).show()
                }
                .show()

Style:

  <style name="MyAlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
  
        <item name="android:textAppearanceSmall">@style/MyTextAppearance</item>
        <item name="android:textAppearanceMedium">@style/MyTextAppearance</item>
        <item name="android:textAppearanceLarge">@style/MyTextAppearance</item>

        <item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
        <item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
        <item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>

        <item name="android:backgroundDimEnabled">true</item>

        <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded
        </item>

    </style>




    <style name="MyTextAppearance" parent="TextAppearance.AppCompat">
        <item name="android:fontFamily">@font/rosarivo</item>
    </style>


        <style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
   <!--     <item name="backgroundTint">@color/colorPrimaryDark</item>-->
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
       <!-- <item name="android:textColor">@android:color/white</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


    <style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
        <!--<item name="android:textColor">@android:color/darker_gray</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


  <style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
        <item name="cornerFamily">rounded</item>
        <item name="cornerSize">8dp</item>
    </style>

Output: enter image description here

`IF` statement with 3 possible answers each based on 3 different ranges

This is what I did:

Very simply put:

=IF(C7>100,"Profit",IF(C7=100,"Quota Met","Loss"))

The first IF Statement, if true will input Profit, and if false will lead on to the next IF statement and so forth :)

I only have basic formula knowledge but it's working so I will accept I am right!

Basic HTTP authentication with Node and Express 4

There seems to be multiple modules to do that, some are deprecated.

This one looks active:
https://github.com/jshttp/basic-auth

Here's a use example:

// auth.js

var auth = require('basic-auth');

var admins = {
  '[email protected]': { password: 'pa$$w0rd!' },
};


module.exports = function(req, res, next) {

  var user = auth(req);
  if (!user || !admins[user.name] || admins[user.name].password !== user.pass) {
    res.set('WWW-Authenticate', 'Basic realm="example"');
    return res.status(401).send();
  }
  return next();
};




// app.js

var auth = require('./auth');
var express = require('express');

var app = express();

// ... some not authenticated middlewares

app.use(auth);

// ... some authenticated middlewares

Make sure you put the auth middleware in the correct place, any middleware before that will not be authenticated.

Java 8 lambda Void argument

You can create a sub-interface for that special case:

interface Command extends Action<Void, Void> {
  default Void execute(Void v) {
    execute();
    return null;
  }
  void execute();
}

It uses a default method to override the inherited parameterized method Void execute(Void), delegating the call to the simpler method void execute().

The result is that it's much simpler to use:

Command c = () -> System.out.println("Do nothing!");

What's the difference between session.persist() and session.save() in Hibernate?

save()- As the method name suggests, hibernate save() can be used to save entity to database. We can invoke this method outside a transaction. If we use this without transaction and we have cascading between entities, then only the primary entity gets saved unless we flush the session.

persist()-Hibernate persist is similar to save (with transaction) and it adds the entity object to the persistent context, so any further changes are tracked. If the object properties are changed before the transaction is committed or session is flushed, it will also be saved into database. Also, we can use persist() method only within the boundary of a transaction, so it’s safe and takes care of any cascaded objects. Finally, persist doesn't return anything so we need to use the persisted object to get the generated identifier value.

Programmatically close aspx page from code behind

You can close a window by simply pasting the window closing code in the button's OnClientClick event in the markup

Assigning multiple styles on an HTML element

The way you have used the HTML syntax is problematic.

This is how the syntax should be

style="property1:value1;property2:value2"

In your case, this will be the way to do

<h2 style="text-align :center; font-family :tahoma" >TITLE</h2>

A further example would be as follows

<div class ="row">
    <button type="button" style= "margin-top : 20px; border-radius: 15px" 
    class="btn btn-primary">View Full Profile</button>
</div>

Python function as a function argument?

  1. Yes. By including the function call in your input argument/s, you can call two (or more) functions at once.

For example:

def anotherfunc(inputarg1, inputarg2):
    pass
def myfunc(func = anotherfunc):
    print func

When you call myfunc, you do this:

myfunc(anotherfunc(inputarg1, inputarg2))

This will print the return value of anotherfunc.

Hope this helps!

Is there a shortcut to make a block comment in Xcode?

I modified the code of Nikola Milicevic a little bit so it also remove comment block if code is already commented:

on run {input, parameters}
    repeat with anInput in input
        if "/*" is in anInput then
            set input to replaceText("/*", "", input as string)
            set input to replaceText("*/", "", input as string)

            return input
            exit repeat
        end if
    end repeat
    return "/*" & (input as string) & "*/"
end run

on replaceText(find, replace, textString)
    set prevTIDs to AppleScript's text item delimiters
    set AppleScript's text item delimiters to find
    set textString to text items of textString
    set AppleScript's text item delimiters to replace
    set textString to "" & textString
    set AppleScript's text item delimiters to prevTIDs
    return textString
end replaceText

Hope this will help someone.enter image description here

How do we count rows using older versions of Hibernate (~2009)?

For older versions of Hibernate (<5.2):

Assuming the class name is Book:

return (Number) session.createCriteria("Book")
                  .setProjection(Projections.rowCount())
                  .uniqueResult();

It is at least a Number, most likely a Long.

How can I pass a username/password in the header to a SOAP WCF Service

Suppose you have service reference of the name localhost in your web.config so you can go as follows

localhost.Service objWebService = newlocalhost.Service();
localhost.AuthSoapHd objAuthSoapHeader = newlocalhost.AuthSoapHd();
string strUsrName =ConfigurationManager.AppSettings["UserName"];
string strPassword =ConfigurationManager.AppSettings["Password"];

objAuthSoapHeader.strUserName = strUsrName;
objAuthSoapHeader.strPassword = strPassword;

objWebService.AuthSoapHdValue =objAuthSoapHeader;
string str = objWebService.HelloWorld();

Response.Write(str);

Unable to find velocity template resources

While using embedded jetty the property webapp.resource.loader.path should starts with slash:

webapp.resource.loader.path=/templates

otherwise templates will not be found in ../webapp/templates

Finding all possible combinations of numbers to reach a given sum

This problem can be solved with a recursive combinations of all possible sums filtering out those that reach the target. Here is the algorithm in Python:

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target: 
        print "sum(%s)=%s" % (partial, target)
    if s >= target:
        return  # if we reach the number why bother to continue

    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i+1:]
        subset_sum(remaining, target, partial + [n]) 


if __name__ == "__main__":
    subset_sum([3,9,8,4,5,7,10],15)

    #Outputs:
    #sum([3, 8, 4])=15
    #sum([3, 5, 7])=15
    #sum([8, 7])=15
    #sum([5, 10])=15

This type of algorithms are very well explained in the following Standford's Abstract Programming lecture - this video is very recommendable to understand how recursion works to generate permutations of solutions.

Edit

The above as a generator function, making it a bit more useful. Requires Python 3.3+ because of yield from.

def subset_sum(numbers, target, partial=[], partial_sum=0):
    if partial_sum == target:
        yield partial
    if partial_sum >= target:
        return
    for i, n in enumerate(numbers):
        remaining = numbers[i + 1:]
        yield from subset_sum(remaining, target, partial + [n], partial_sum + n)

Here is the Java version of the same algorithm:

package tmp;

import java.util.ArrayList;
import java.util.Arrays;

class SumSet {
    static void sum_up_recursive(ArrayList<Integer> numbers, int target, ArrayList<Integer> partial) {
       int s = 0;
       for (int x: partial) s += x;
       if (s == target)
            System.out.println("sum("+Arrays.toString(partial.toArray())+")="+target);
       if (s >= target)
            return;
       for(int i=0;i<numbers.size();i++) {
             ArrayList<Integer> remaining = new ArrayList<Integer>();
             int n = numbers.get(i);
             for (int j=i+1; j<numbers.size();j++) remaining.add(numbers.get(j));
             ArrayList<Integer> partial_rec = new ArrayList<Integer>(partial);
             partial_rec.add(n);
             sum_up_recursive(remaining,target,partial_rec);
       }
    }
    static void sum_up(ArrayList<Integer> numbers, int target) {
        sum_up_recursive(numbers,target,new ArrayList<Integer>());
    }
    public static void main(String args[]) {
        Integer[] numbers = {3,9,8,4,5,7,10};
        int target = 15;
        sum_up(new ArrayList<Integer>(Arrays.asList(numbers)),target);
    }
}

It is exactly the same heuristic. My Java is a bit rusty but I think is easy to understand.

C# conversion of Java solution: (by @JeremyThompson)

public static void Main(string[] args)
{
    List<int> numbers = new List<int>() { 3, 9, 8, 4, 5, 7, 10 };
    int target = 15;
    sum_up(numbers, target);
}

private static void sum_up(List<int> numbers, int target)
{
    sum_up_recursive(numbers, target, new List<int>());
}

private static void sum_up_recursive(List<int> numbers, int target, List<int> partial)
{
    int s = 0;
    foreach (int x in partial) s += x;

    if (s == target)
        Console.WriteLine("sum(" + string.Join(",", partial.ToArray()) + ")=" + target);

    if (s >= target)
        return;

    for (int i = 0; i < numbers.Count; i++)
    {
        List<int> remaining = new List<int>();
        int n = numbers[i];
        for (int j = i + 1; j < numbers.Count; j++) remaining.Add(numbers[j]);

        List<int> partial_rec = new List<int>(partial);
        partial_rec.Add(n);
        sum_up_recursive(remaining, target, partial_rec);
    }
}

Ruby solution: (by @emaillenin)

def subset_sum(numbers, target, partial=[])
  s = partial.inject 0, :+
# check if the partial sum is equals to target

  puts "sum(#{partial})=#{target}" if s == target

  return if s >= target # if we reach the number why bother to continue

  (0..(numbers.length - 1)).each do |i|
    n = numbers[i]
    remaining = numbers.drop(i+1)
    subset_sum(remaining, target, partial + [n])
  end
end

subset_sum([3,9,8,4,5,7,10],15)

Edit: complexity discussion

As others mention this is an NP-hard problem. It can be solved in exponential time O(2^n), for instance for n=10 there will be 1024 possible solutions. If the targets you are trying to reach are in a low range then this algorithm works. So for instance:

subset_sum([1,2,3,4,5,6,7,8,9,10],100000) generates 1024 branches because the target never gets to filter out possible solutions.

On the other hand subset_sum([1,2,3,4,5,6,7,8,9,10],10) generates only 175 branches, because the target to reach 10 gets to filter out many combinations.

If N and Target are big numbers one should move into an approximate version of the solution.

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

SQL Server: converting UniqueIdentifier to string in a case statement

In my opinion, uniqueidentifier / GUID is neither a varchar nor an nvarchar but a char(36). Therefore I use:

CAST(xyz AS char(36))

Python strip() multiple characters?

Because that's not what strip() does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.

You could do:

name= name.replace('(', '').replace(')', '').replace ...

or:

name= ''.join(c for c in name if c not in '(){}<>')

or maybe use a regex:

import re
name= re.sub('[(){}<>]', '', name)

ReactJS: "Uncaught SyntaxError: Unexpected token <"

UPDATE -- use this instead:

<script type="text/babel" src="./lander.js"></script>

Add type="text/jsx" as an attribute of the script tag used to include the JavaScript file that must be transformed by JSX Transformer, like that:

<script type="text/jsx" src="./lander.js"></script>

Then you can use MAMP or some other service to host the page on localhost so that all of the inclusions work, as discussed here.

Thanks for all the help everyone!

Where can I find the error logs of nginx, using FastCGI and Django?

My ngninx logs are located here:

/usr/local/var/log/nginx/*

You can also check your nginx.conf to see if you have any directives dumping to custom log.

run nginx -t to locate your nginx.conf.

# in ngingx.conf
error_log  /usr/local/var/log/nginx/error.log;
error_log  /usr/local/var/log/nginx/error.log  notice;
error_log  /usr/local/var/log/nginx/error.log  info;

Nginx is usually set up in /usr/local or /etc/. The server could be configured to dump logs to /var/log as well.

If you have an alternate location for your nginx install and all else fails, you could use the find command to locate your file of choice.

find /usr/ -path "*/nginx/*" -type f -name '*.log', where /usr/ is the folder you wish to start searching from.

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

Remove Elements from a HashSet while Iterating

An other possible solution:

for(Object it : set.toArray()) { /* Create a copy */
    Integer element = (Integer)it;
    if(element % 2 == 0)
        set.remove(element);
}

Or:

Integer[] copy = new Integer[set.size()];
set.toArray(copy);

for(Integer element : copy) {
    if(element % 2 == 0)
        set.remove(element);
}

What is a lambda expression in C++11?

What is a lambda function?

The C++ concept of a lambda function originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming.

In C++ a lambda function is defined like this

[]() { } // barebone lambda

or in all its glory

[]() mutable -> T { } // T is the return type, still lacking throw()

[] is the capture list, () the argument list and {} the function body.

The capture list

The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either:

  1. a value: [x]
  2. a reference [&x]
  3. any variable currently in scope by reference [&]
  4. same as 3, but by value [=]

You can mix any of the above in a comma separated list [x, &y].

The argument list

The argument list is the same as in any other C++ function.

The function body

The code that will be executed when the lambda is actually called.

Return type deduction

If a lambda has only one return statement, the return type can be omitted and has the implicit type of decltype(return_statement).

Mutable

If a lambda is marked mutable (e.g. []() mutable { }) it is allowed to mutate the values that have been captured by value.

Use cases

The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope.

C++14

In C++14 lambdas have been extended by various proposals.

Initialized Lambda Captures

An element of the capture list can now be initialized with =. This allows renaming of variables and to capture by moving. An example taken from the standard:

int x = 4;
auto y = [&r = x, x = x+1]()->int {
            r += 2;
            return x+2;
         }();  // Updates ::x to 6, and initializes y to 7.

and one taken from Wikipedia showing how to capture with std::move:

auto ptr = std::make_unique<int>(10); // See below for std::make_unique
auto lambda = [ptr = std::move(ptr)] {return *ptr;};

Generic Lambdas

Lambdas can now be generic (auto would be equivalent to T here if T were a type template argument somewhere in the surrounding scope):

auto lambda = [](auto x, auto y) {return x + y;};

Improved Return Type Deduction

C++14 allows deduced return types for every function and does not restrict it to functions of the form return expression;. This is also extended to lambdas.

Is multiplication and division using shift operators in C actually faster?

Just a concrete point of measure: many years back, I benchmarked two versions of my hashing algorithm:

unsigned
hash( char const* s )
{
    unsigned h = 0;
    while ( *s != '\0' ) {
        h = 127 * h + (unsigned char)*s;
        ++ s;
    }
    return h;
}

and

unsigned
hash( char const* s )
{
    unsigned h = 0;
    while ( *s != '\0' ) {
        h = (h << 7) - h + (unsigned char)*s;
        ++ s;
    }
    return h;
}

On every machine I benchmarked it on, the first was at least as fast as the second. Somewhat surprisingly, it was sometimes faster (e.g. on a Sun Sparc). When the hardware didn't support fast multiplication (and most didn't back then), the compiler would convert the multiplication into the appropriate combinations of shifts and add/sub. And because it knew the final goal, it could sometimes do so in less instructions than when you explicitly wrote the shifts and the add/subs.

Note that this was something like 15 years ago. Hopefully, compilers have only gotten better since then, so you can pretty much count on the compiler doing the right thing, probably better than you could. (Also, the reason the code looks so C'ish is because it was over 15 years ago. I'd obviously use std::string and iterators today.)

Replace a string in a file with nodejs

On Linux or Mac, keep is simple and just use sed with the shell. No external libraries required. The following code works on Linux.

const shell = require('child_process').execSync
shell(`sed -i "s!oldString!newString!g" ./yourFile.js`)

The sed syntax is a little different on Mac. I can't test it right now, but I believe you just need to add an empty string after the "-i":

const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)

The "g" after the final "!" makes sed replace all instances on a line. Remove it, and only the first occurrence per line will be replaced.

How to convert char* to wchar_t*?

Your problem has nothing to do with encodings, it's a simple matter of understanding basic C++. You are returning a pointer to a local variable from your function, which will have gone out of scope by the time anyone can use it, thus creating undefined behaviour (i.e. a programming error).

Follow this Golden Rule: "If you are using naked char pointers, you're Doing It Wrong. (Except for when you aren't.)"

I've previously posted some code to do the conversion and communicating the input and output in C++ std::string and std::wstring objects.

Does return stop a loop?

This code will exit the loop after the first iteration in a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
  if (iterator.name == 2) {
    return;
  }
  console.log(iterator.name);// 1
}

the below code will jump on the condition and continue on a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];

for (const iterator of objc) {
  if (iterator.name == 2) {
    continue;
  }
  console.log(iterator.name); // 1  , 3
}

How to pass dictionary items as function arguments in python?

If you want to use them like that, define the function with the variable names as normal:

def my_function(school, standard, city, name):
    schoolName  = school
    cityName = city
    standardName = standard
    studentName = name

Now you can use ** when you call the function:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}

my_function(**data)

and it will work as you want.

P.S. Don't use reserved words such as class.(e.g., use klass instead)

How to deserialize a JObject to .NET object

From the documentation I found this

JObject o = new JObject(
   new JProperty("Name", "John Smith"),
   new JProperty("BirthDate", new DateTime(1983, 3, 20))
);

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);

The class definition for Person should be compatible to the following:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}

Edit

If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.

Need to install urllib2 for Python 3.5.1

WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will 'phone home' when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

You can't, and you don't need to.

urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don't need to install it.

If you are following a tutorial that tells you to use urllib2 then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2 comes with that version.

Alternatively, install the requests library for a higher-level and easier to use API. It'll work on both Python 2 and 3.

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

There is a special security expression in spring security:

hasAnyRole(list of roles) - true if the user has been granted any of the roles specified (given as a comma-separated list of strings).

I have never used it but I think it is exactly what you are looking for.

Example usage:

<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
    ...
</security:authorize>

Here is a link to the reference documentation where the standard spring security expressions are described. Also, here is a discussion where I described how to create custom expression if you need it.

MySQL joins and COUNT(*) from another table

Your groups_main table has a key column named id. I believe you can only use the USING syntax for the join if the groups_fans table has a key column with the same name, which it probably does not. So instead, try this:

LEFT JOIN groups_fans AS m ON m.group_id = g.id

Or replace group_id with whatever the appropriate column name is in the groups_fans table.

How to find a user's home directory on linux or unix?

Can you parse /etc/passwd?

e.g.:

 cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'

Running conda with proxy

You can configure a proxy with conda by adding it to the .condarc, like

proxy_servers:
    http: http://user:[email protected]:8080
    https: https://user:[email protected]:8080

or set the HTTP_PROXY and HTTPS_PROXY environment variables. Note that in your case you need to add the scheme to the proxy url, like https://proxy-us.bla.com:123.

See http://conda.pydata.org/docs/config.html#configure-conda-for-use-behind-a-proxy-server.

How to listen for a WebView finishing loading a URL?

Extend WebViewClient and call onPageFinished() as follows:

mWebView.setWebViewClient(new WebViewClient() {

   public void onPageFinished(WebView view, String url) {
        // do your stuff here
    }
});

What should be the values of GOPATH and GOROOT?

As of 2020 and Go version 1.13+, in Windows the best way for updating GOPATH is just typing in command prompt:

setx GOPATH C:\mynewgopath

How to hide the Google Invisible reCAPTCHA badge

Recaptcha contact form 7 and Recaptcha v3 solution.

body:not(.page-id-20) .grecaptcha-badge {
    display: none;
}

More Than One Contact Form Page?

body:not(.page-id-12):not(.page-id-43) .grecaptcha-badge {
    display: none;
}

You can add more “nots” if you have more contact form pages.

body:not(.page-id-45):not(.page-id-78):not(.page-id-98) .grecaptcha-badge {
    display: none;
}

Make sure that your body section will like this:

<body>

Change it so that it looks like this:

 <body <?php body_class(); ?>>

Image re-size to 50% of original size in HTML

You can use the x descriptor of the srcset attribute as such:

_x000D_
_x000D_
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />

<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />

<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
_x000D_
_x000D_

Currently supported by all browsers except IE. (caniuse)

MDN documentation

Using parameters in batch files at Windows command line

As others have already said, parameters passed through the command line can be accessed in batch files with the notation %1 to %9. There are also two other tokens that you can use:

  • %0 is the executable (batch file) name as specified in the command line.
  • %* is all parameters specified in the command line -- this is very useful if you want to forward the parameters to another program.

There are also lots of important techniques to be aware of in addition to simply how to access the parameters.

Checking if a parameter was passed

This is done with constructs like IF "%~1"=="", which is true if and only if no arguments were passed at all. Note the tilde character which causes any surrounding quotes to be removed from the value of %1; without a tilde you will get unexpected results if that value includes double quotes, including the possibility of syntax errors.

Handling more than 9 arguments (or just making life easier)

If you need to access more than 9 arguments you have to use the command SHIFT. This command shifts the values of all arguments one place, so that %0 takes the value of %1, %1 takes the value of %2, etc. %9 takes the value of the tenth argument (if one is present), which was not available through any variable before calling SHIFT (enter command SHIFT /? for more options).

SHIFT is also useful when you want to easily process parameters without requiring that they are presented in a specific order. For example, a script may recognize the flags -a and -b in any order. A good way to parse the command line in such cases is

:parse
IF "%~1"=="" GOTO endparse
IF "%~1"=="-a" REM do something
IF "%~1"=="-b" REM do something else
SHIFT
GOTO parse
:endparse
REM ready for action!

This scheme allows you to parse pretty complex command lines without going insane.

Substitution of batch parameters

For parameters that represent file names the shell provides lots of functionality related to working with files that is not accessible in any other way. This functionality is accessed with constructs that begin with %~.

For example, to get the size of the file passed in as an argument use

ECHO %~z1

To get the path of the directory where the batch file was launched from (very useful!) you can use

ECHO %~dp0

You can view the full range of these capabilities by typing CALL /? in the command prompt.