Programs & Examples On #Random

This tag is for questions pertaining to random numbers and their generators, whether pseudo-random or truly random.

How do I create a list of random numbers without duplicates?

import random

sourcelist=[]
resultlist=[]

for x in range(100):
    sourcelist.append(x)

for y in sourcelist:
    resultlist.insert(random.randint(0,len(resultlist)),y)

print (resultlist)

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

Generating unique random numbers (integers) between 0 and 'x'

/**
 * Generates an array with numbers between
 * min and max randomly positioned.
 */
function genArr(min, max, numOfSwaps){
  var size = (max-min) + 1;
  numOfSwaps = numOfSwaps || size;
  var arr = Array.apply(null, Array(size));

  for(var i = 0, j = min; i < size & j <= max; i++, j++) {
    arr[i] = j;
  }

  for(var i = 0; i < numOfSwaps; i++) {
    var idx1 = Math.round(Math.random() * (size - 1));
    var idx2 = Math.round(Math.random() * (size - 1));

    var temp = arr[idx1];
    arr[idx1] = arr[idx2];
    arr[idx2] = temp;
  }

  return arr;
}

/* generating the array and using it to get 3 uniques numbers */
var arr = genArr(1, 10);
for(var i = 0; i < 3; i++) {
  console.log(arr.pop());
}

How can I generate random alphanumeric strings?

not 100% sure, as I didn't test EVERY option here, but of the ones I did test, this one is the fastest. timed it with stopwatch and it showed 9-10 ticks so if speed is more important than security, try this:

 private static Random random = new Random(); 
 public static string Random(int length)
     {   
          var stringChars = new char[length];

          for (int i = 0; i < length; i++)
              {
                  stringChars[i] = (char)random.Next(0x30, 0x7a);                  
                  return new string(stringChars);
              }
     }

What's an easy way to read random line from a file in Unix command line?

A solution that also works on MacOSX, and should also works on Linux(?):

N=5
awk 'NR==FNR {lineN[$1]; next}(FNR in lineN)' <(jot -r $N 1 $(wc -l < $file)) $file 

Where:

  • N is the number of random lines you want

  • NR==FNR {lineN[$1]; next}(FNR in lineN) file1 file2 --> save line numbers written in file1 and then print corresponding line in file2

  • jot -r $N 1 $(wc -l < $file) --> draw N numbers randomly (-r) in range (1, number_of_line_in_file) with jot. The process substitution <() will make it look like a file for the interpreter, so file1 in previous example.

Generate random number between two numbers in JavaScript

I discovered a great new way to do this using ES6 default parameters. It is very nifty since it allows either one argument or two arguments. Here it is:

function random(n, b = 0) {
    return Math.random() * (b-n) + n;
}

MySQL ORDER BY rand(), name ASC

Use a subquery:

SELECT * FROM 
(
    SELECT * FROM users ORDER BY rand() LIMIT 20
) T1
ORDER BY name 

The inner query selects 20 users at random and the outer query orders the selected users by name.

Get a random item from a JavaScript array

jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,

var randomItem = items[Math.floor(Math.random()*items.length)]

How do I generate random numbers in Dart?

An alternative solution could be using the following code DRandom. This class should be used with a seed. It provides a familiar interface to what you would expect in .NET, it was ported from mono's Random.cs. This code may not be cryptography safe and has not been statistically tested.

Random date in C#

Start with a fixed date object (Jan 1, 1995), and add a random number of days with AddDays (obviusly, pay attention not surpassing the current date).

How to create an array of 20 random bytes?

If you are already using Apache Commons Lang, the RandomUtils makes this a one-liner:

byte[] randomBytes = RandomUtils.nextBytes(20);

Note: this does not produce cryptographically-secure bytes.

Java random numbers using a seed

If you'd want to generate multiple numbers using one seed you can do something like this:

public double[] GenerateNumbers(long seed, int amount) {
    double[] randomList = new double[amount];
    for (int i=0;i<amount;i++) {
        Random generator = new Random(seed);
        randomList[i] = Math.abs((double) (generator.nextLong() % 0.001) * 10000);
        seed--;
    }
    return randomList;
}

It will display the same list if you use the same seed.

Why do I always get the same sequence of random numbers with rand()?

This is from http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand:

Declaration:

void srand(unsigned int seed); 

This function seeds the random number generator used by the function rand. Seeding srand with the same seed will cause rand to return the same sequence of pseudo-random numbers. If srand is not called, rand acts as if srand(1) has been called.

Random string generation with upper case letters and digits

I have gone though almost all of the answers but none of them looks easier. I would suggest you to try the passgen library which is generally used to create random passwords.

You can generate random strings of your choice of length, punctuation, digits, letters and case.

Here's the code for your case:

from passgen import passgen
string_length = int(input())
random_string = passgen(length=string_length, punctuation=False, digits=True, letters=True, case='upper')

Produce a random number in a range using C#

You can try

Random r = new Random();
int rInt = r.Next(0, 100); //for ints
int range = 100;
double rDouble = r.NextDouble()* range; //for doubles

Have a look at

Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method

How to randomly select an item from a list?

You could just:

from random import randint

foo = ["a", "b", "c", "d", "e"]

print(foo[randint(0,4)])

Random number generator only generating one random number

I would rather use the following class to generate random numbers:

byte[] random;
System.Security.Cryptography.RNGCryptoServiceProvider prov = new System.Security.Cryptography.RNGCryptoServiceProvider();
prov.GetBytes(random);

rand() between 0 and 1

No, because RAND_MAX is typically expanded to MAX_INT. So adding one (apparently) puts it at MIN_INT (although it should be undefined behavior as I'm told), hence the reversal of sign.

To get what you want you will need to move the +1 outside the computation:

r = ((double) rand() / (RAND_MAX)) + 1;

Select n random rows from SQL Server table

I was using it in subquery and it returned me same rows in subquery

 SELECT  ID ,
            ( SELECT TOP 1
                        ImageURL
              FROM      SubTable 
              ORDER BY  NEWID()
            ) AS ImageURL,
            GETUTCDATE() ,
            1
    FROM    Mytable

then i solved with including parent table variable in where

SELECT  ID ,
            ( SELECT TOP 1
                        ImageURL
              FROM      SubTable 
              Where Mytable.ID>0
              ORDER BY  NEWID()
            ) AS ImageURL,
            GETUTCDATE() ,
            1
    FROM    Mytable

Note the where condtition

Postgres FOR LOOP

Procedural elements like loops are not part of the SQL language and can only be used inside the body of a procedural language function, procedure (Postgres 11 or later) or a DO statement, where such additional elements are defined by the respective procedural language. The default is PL/pgSQL, but there are others.

Example with plpgsql:

DO
$do$
BEGIN 
   FOR i IN 1..25 LOOP
      INSERT INTO playtime.meta_random_sample
         (col_i, col_id)                       -- declare target columns!
      SELECT  i,     id
      FROM   tbl
      ORDER  BY random()
      LIMIT  15000;
   END LOOP;
END
$do$;

For many tasks that can be solved with a loop, there is a shorter and faster set-based solution around the corner. Pure SQL equivalent for your example:

INSERT INTO playtime.meta_random_sample (col_i, col_id)
SELECT t.*
FROM   generate_series(1,25) i
CROSS  JOIN LATERAL (
   SELECT i, id
   FROM   tbl
   ORDER  BY random()
   LIMIT  15000
   ) t;

About generate_series():

About optimizing performance of random selections:

Generate random numbers following a normal distribution in C/C++

I created a C++ open source project for normally distributed random number generation benchmark.

It compares several algorithms, including

  • Central limit theorem method
  • Box-Muller transform
  • Marsaglia polar method
  • Ziggurat algorithm
  • Inverse transform sampling method.
  • cpp11random uses C++11 std::normal_distribution with std::minstd_rand (it is actually Box-Muller transform in clang).

The results of single-precision (float) version on iMac [email protected] , clang 6.1, 64-bit:

normaldistf

For correctness, the program verifies the mean, standard deviation, skewness and kurtosis of the samples. It was found that CLT method by summing 4, 8 or 16 uniform numbers do not have good kurtosis as the other methods.

Ziggurat algorithm has better performance than the others. However, it does not suitable for SIMD parallelism as it needs table lookup and branches. Box-Muller with SSE2/AVX instruction set is much faster (x1.79, x2.99) than non-SIMD version of ziggurat algorithm.

Therefore, I will suggest using Box-Muller for architecture with SIMD instruction sets, and may be ziggurat otherwise.


P.S. the benchmark uses a simplest LCG PRNG for generating uniform distributed random numbers. So it may not be sufficient for some applications. But the performance comparison should be fair because all implementations uses the same PRNG, so the benchmark mainly tests the performance of the transformation.

How to generate a random String in Java

This is very nice:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7).

There are 10^7 equiprobable (if java.util.Random is not broken) distinct values so uniqueness may be a concern.

How can I generate a random number in a certain range?

Random r = new Random();
int i1 = r.nextInt(45 - 28) + 28;

This gives a random integer between 28 (inclusive) and 45 (exclusive), one of 28,29,...,43,44.

Laravel - Eloquent or Fluent random row

This works just fine,

$model=Model::all()->random(1)->first();

you can also change argument in random function to get more than one record.

Note: not recommended if you have huge data as this will fetch all rows first and then returns random value.

Generate a random number in the range 1 - 10

The correct version of hythlodayr's answer.

-- ERROR:  operator does not exist: double precision % integer
-- LINE 1: select (trunc(random() * 10) % 10) + 1

The output from trunc has to be converted to INTEGER. But it can be done without trunc. So it turns out to be simple.

select (random() * 9)::INTEGER + 1

Generates an INTEGER output in range [1, 10] i.e. both 1 & 10 inclusive.

For any number (floats), see user80168's answer. i.e just don't convert it to INTEGER.

How do you generate a random double uniformly distributed between 0 and 1 from C++?

If speed is your primary concern, then I'd simply go with

double r = (double)rand() / (double)RAND_MAX;

random.seed(): What does it do?

>>> random.seed(9001)   
>>> random.randint(1, 10)  
1     
>>> random.seed(9001)     
>>> random.randint(1, 10)    
1           
>>> random.seed(9001)          
>>> random.randint(1, 10)                 
1                  
>>> random.seed(9001)         
>>> random.randint(1, 10)          
1     
>>> random.seed(9002)                
>>> random.randint(1, 10)             
3

You try this.

Let's say 'random.seed' gives a value to random value generator ('random.randint()') which generates these values on the basis of this seed. One of the must properties of random numbers is that they should be reproducible. When you put same seed, you get the same pattern of random numbers. This way you are generating them right from the start. You give a different seed- it starts with a different initial (above 3).

Given a seed, it will generate random numbers between 1 and 10 one after another. So you assume one set of numbers for one seed value.

Generating random whole numbers in JavaScript in a specific range?

Ionu? G. Stan wrote a great answer but it was a bit too complex for me to grasp. So, I found an even simpler explanation of the same concepts at https://teamtreehouse.com/community/mathfloor-mathrandom-max-min-1-min-explanation by Jason Anello.

NOTE: The only important thing you should know before reading Jason's explanation is a definition of "truncate". He uses that term when describing Math.floor(). Oxford dictionary defines "truncate" as:

Shorten (something) by cutting off the top or end.

Generate unique random numbers between 1 and 100

This solution uses the hash which is much more performant O(1) than checking if the resides in the array. It has extra safe checks too. Hope it helps.

function uniqueArray(minRange, maxRange, arrayLength) {
  var arrayLength = (arrayLength) ? arrayLength : 10
  var minRange = (minRange !== undefined) ? minRange : 1
  var maxRange = (maxRange !== undefined) ? maxRange : 100
  var numberOfItemsInArray = 0
  var hash = {}
  var array = []

  if ( arrayLength > (maxRange - minRange) ) throw new Error('Cannot generate unique array: Array length too high')

  while(numberOfItemsInArray < arrayLength){
    // var randomNumber = Math.floor(Math.random() * (maxRange - minRange + 1) + minRange)
    // following line used for performance benefits
    var randomNumber = (Math.random() * (maxRange - minRange + 1) + minRange) << 0

    if (!hash[randomNumber]) {
      hash[randomNumber] = true
      array.push(randomNumber)
      numberOfItemsInArray++
    }
  }
  return array
}
document.write(uniqueArray(1, 100, 8))

Best way to randomize an array with .NET

private ArrayList ShuffleArrayList(ArrayList source)
{
    ArrayList sortedList = new ArrayList();
    Random generator = new Random();

    while (source.Count > 0)
    {
        int position = generator.Next(source.Count);
        sortedList.Add(source[position]);
        source.RemoveAt(position);
    }  
    return sortedList;
}

Random Number Between 2 Double Numbers

If you need a random number in the range [double.MinValue; double.MaxValue]

// Because of:
double.MaxValue - double.MinValue == double.PositiveInfinity

// This will be equals to NaN or PositiveInfinity
random.NextDouble() * (double.MaxValue - double.MinValue)

Use instead:

public static class RandomExtensions
{
    public static double NextDoubleInMinMaxRange(this Random random)
    {
        var bytes = new byte[sizeof(double)];
        var value = default(double);
        while (true)
        {
            random.NextBytes(bytes);
            value = BitConverter.ToDouble(bytes, 0);
            if (!double.IsNaN(value) && !double.IsInfinity(value))
                return value;
        }
    }
}

Get random boolean in Java

You can use the following for an unbiased result:

Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!

If you want to give more probability to your result to be true (or false) you can adjust the above as following!

Random random = new Random();

//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;

//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;

What does random.sample() method in python do?

random.sample(population, k)

It is used for randomly sampling a sample of length 'k' from a population. returns a 'k' length list of unique elements chosen from the population sequence or set

it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples

I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population) as an argument and return indices of 60% of the data as D_test.

import random

def randomly_select_70_percent_of_data_from_1_to_length(x_train):
    return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))

Best way to generate a random float in C#

Here is another way that I came up with: Let's say you want to get a float between 5.5 and 7, with 3 decimals.

float myFloat;
int myInt;
System.Random rnd = new System.Random();

void GenerateFloat()
{
myInt = rnd.Next(1, 2000);
myFloat = (myInt / 1000) + 5.5f;
}

That way you will always get a bigger number than 5.5 and a smaller number than 7.

How to randomize (or permute) a dataframe rowwise and columnwise?

Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations

Get random sample from list while maintaining ordering of items?

random.sample implement it.

>>> random.sample([1, 2, 3, 4, 5],  3)   # Three samples without replacement
[4, 1, 5]

How to generate a random integer number from within a range

Here is a formula if you know the max and min values of a range, and you want to generate numbers inclusive in between the range:

r = (rand() % (max + 1 - min)) + min

How to generate a random number in C++?

Generate a different random number each time, not the same one six times in a row.

Use case scenario

I likened Predictability's problem to a bag of six bits of paper, each with a value from 0 to 5 written on it. A piece of paper is drawn from the bag each time a new value is required. If the bag is empty, then the numbers are put back into the bag.

...from this, I can create an algorithm of sorts.

Algorithm

A bag is usually a Collection. I chose a bool[] (otherwise known as a boolean array, bit plane or bit map) to take the role of the bag.

The reason I chose a bool[] is because the index of each item is already the value of each piece of paper. If the papers required anything else written on them then I would have used a Dictionary<string, bool> in its place. The boolean value is used to keep track of whether the number has been drawn yet or not.

A counter called RemainingNumberCount is initialised to 5 that counts down as a random number is chosen. This saves us from having to count how many pieces of paper are left each time we wish to draw a new number.

To select the next random value I'm using a for..loop to scan through the bag of indexes, and a counter to count off when an index is false called NumberOfMoves.

NumberOfMoves is used to choose the next available number. NumberOfMoves is first set to be a random value between 0 and 5, because there are 0..5 available steps we can make through the bag. On the next iteration NumberOfMoves is set to be a random value between 0 and 4, because there are now 0..4 steps we can make through the bag. As the numbers are used, the available numbers reduce so we instead use rand() % (RemainingNumberCount + 1) to calculate the next value for NumberOfMoves.

When the NumberOfMoves counter reaches zero, the for..loop should as follows:

  1. Set the current Value to be the same as for..loop's index.
  2. Set all the numbers in the bag to false.
  3. Break from the for..loop.

Code

The code for the above solution is as follows:

(put the following three blocks into the main .cpp file one after the other)

#include "stdafx.h"
#include <ctime> 
#include <iostream>
#include <string>

class RandomBag {
public:
    int Value = -1;

    RandomBag() {
        ResetBag();

    }

    void NextValue() {
        int BagOfNumbersLength = sizeof(BagOfNumbers) / sizeof(*BagOfNumbers);

        int NumberOfMoves = rand() % (RemainingNumberCount + 1);

        for (int i = 0; i < BagOfNumbersLength; i++)            
            if (BagOfNumbers[i] == 0) {
                NumberOfMoves--;

                if (NumberOfMoves == -1)
                {
                    Value = i;

                    BagOfNumbers[i] = 1;

                    break;

                }

            }



        if (RemainingNumberCount == 0) {
            RemainingNumberCount = 5;

            ResetBag();

        }
        else            
            RemainingNumberCount--; 

    }

    std::string ToString() {
        return std::to_string(Value);

    }

private:
    bool BagOfNumbers[6]; 

    int RemainingNumberCount;

    int NumberOfMoves;

    void ResetBag() {
        RemainingNumberCount = 5;

        NumberOfMoves = rand() % 6;

        int BagOfNumbersLength = sizeof(BagOfNumbers) / sizeof(*BagOfNumbers);

        for (int i = 0; i < BagOfNumbersLength; i++)            
            BagOfNumbers[i] = 0;

    }

};

A Console class

I create this Console class because it makes it easy to redirect output.

Below in the code...

Console::WriteLine("The next value is " + randomBag.ToString());

...can be replaced by...

std::cout << "The next value is " + randomBag.ToString() << std::endl; 

...and then this Console class can be deleted if desired.

class Console {
public:
    static void WriteLine(std::string s) {
        std::cout << s << std::endl;

    }

};

Main method

Example usage as follows:

int main() {
    srand((unsigned)time(0)); // Initialise random seed based on current time

    RandomBag randomBag;

    Console::WriteLine("First set of six...\n");

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    Console::WriteLine("\nSecond set of six...\n");

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    Console::WriteLine("\nThird set of six...\n");

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    randomBag.NextValue();

    Console::WriteLine("The next value is " + randomBag.ToString());

    Console::WriteLine("\nProcess complete.\n");

    system("pause");

}

Example output

When I ran the program, I got the following output:

First set of six...

The next value is 2
The next value is 3
The next value is 4
The next value is 5
The next value is 0
The next value is 1

Second set of six...

The next value is 3
The next value is 4
The next value is 2
The next value is 0
The next value is 1
The next value is 5

Third set of six...

The next value is 4
The next value is 5
The next value is 2
The next value is 0
The next value is 3
The next value is 1

Process complete.

Press any key to continue . . .

Closing statement

This program was written using Visual Studio 2017, and I chose to make it a Visual C++ Windows Console Application project using .Net 4.6.1.

I'm not doing anything particularly special here, so the code should work on earlier versions of Visual Studio too.

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

Why does this code using random strings print "hello world"?

I'll just leave it here. Whoever has a lot of (CPU) time to spare, feel free to experiment :) Also, if you have mastered some fork-join-fu to make this thing burn all CPU cores (just threads are boring, right?), please share your code. I would greatly appreciate it.

public static void main(String[] args) {
    long time = System.currentTimeMillis();
    generate("stack");
    generate("over");
    generate("flow");
    generate("rulez");

    System.out.println("Took " + (System.currentTimeMillis() - time) + " ms");
}

private static void generate(String goal) {
    long[] seed = generateSeed(goal, Long.MIN_VALUE, Long.MAX_VALUE);
    System.out.println(seed[0]);
    System.out.println(randomString(seed[0], (char) seed[1]));
}

public static long[] generateSeed(String goal, long start, long finish) {
    char[] input = goal.toCharArray();
    char[] pool = new char[input.length];
    label:
    for (long seed = start; seed < finish; seed++) {
        Random random = new Random(seed);

        for (int i = 0; i < input.length; i++)
            pool[i] = (char) random.nextInt(27);

        if (random.nextInt(27) == 0) {
            int base = input[0] - pool[0];
            for (int i = 1; i < input.length; i++) {
                if (input[i] - pool[i] != base)
                    continue label;
            }
            return new long[]{seed, base};
        }

    }

    throw new NoSuchElementException("Sorry :/");
}

public static String randomString(long i, char base) {
    System.out.println("Using base: '" + base + "'");
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    for (int n = 0; ; n++) {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char) (base + k));
    }

    return sb.toString();
}

Output:

-9223372036808280701
Using base: 'Z'
stack
-9223372036853943469
Using base: 'b'
over
-9223372036852834412
Using base: 'e'
flow
-9223372036838149518
Using base: 'd'
rulez
Took 7087 ms

Expand a random range from 1–5 to 1–7

int rand7()
{
    int zero_one_or_two = ( rand5() + rand5() - 1 ) % 3 ;
    return rand5() + zero_one_or_two ;
}

How does C#'s random number generator work?

I was just wondering how the random number generator in C# works.

That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.

I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

You can use Random.Next(int, int):

Random rng = new Random();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(rng.Next(1, 101));
}

Note that the upper bound is exclusive - which is why I've used 101 here.

You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.

How to randomize (shuffle) a JavaScript array?

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

See https://github.com/coolaj86/knuth-shuffle

You can see a great visualization here (and the original post linked to this)

_x000D_
_x000D_
function shuffle(array) {_x000D_
  var currentIndex = array.length, temporaryValue, randomIndex;_x000D_
_x000D_
  // While there remain elements to shuffle..._x000D_
  while (0 !== currentIndex) {_x000D_
_x000D_
    // Pick a remaining element..._x000D_
    randomIndex = Math.floor(Math.random() * currentIndex);_x000D_
    currentIndex -= 1;_x000D_
_x000D_
    // And swap it with the current element._x000D_
    temporaryValue = array[currentIndex];_x000D_
    array[currentIndex] = array[randomIndex];_x000D_
    array[randomIndex] = temporaryValue;_x000D_
  }_x000D_
_x000D_
  return array;_x000D_
}_x000D_
_x000D_
// Used like so_x000D_
var arr = [2, 11, 37, 42];_x000D_
shuffle(arr);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Some more info about the algorithm used.

How to properly seed random number generator

I don't understand why people are seeding with a time value. This has in my experience never been a good idea. For example, while the system clock is maybe represented in nanoseconds, the system's clock precision isn't nanoseconds.

This program should not be run on the Go playground but if you run it on your machine you get a rough estimate on what type of precision you can expect. I see increments of about 1000000 ns, so 1 ms increments. That's 20 bits of entropy that are not used. All the while the high bits are mostly constant!? Roughly ~24 bits of entropy over a day which is very brute forceable (which can create vulnerabilities).

The degree that this matters to you will vary but you can avoid pitfalls of clock based seed values by simply using the crypto/rand.Read as source for your seed. It will give you that non-deterministic quality that you are probably looking for in your random numbers (even if the actual implementation itself is limited to a set of distinct and deterministic random sequences).

import (
    crypto_rand "crypto/rand"
    "encoding/binary"
    math_rand "math/rand"
)

func init() {
    var b [8]byte
    _, err := crypto_rand.Read(b[:])
    if err != nil {
        panic("cannot seed math/rand package with cryptographically secure random number generator")
    }
    math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}

As a side note but in relation to your question. You can create your own rand.Source using this method to avoid the cost of having locks protecting the source. The rand package utility functions are convenient but they also use locks under the hood to prevent the source from being used concurrently. If you don't need that you can avoid it by creating your own Source and use that in a non-concurrent way. Regardless, you should NOT be reseeding your random number generator between iterations, it was never designed to be used that way.

Python: Random numbers into a list

import random
my_randoms = [random.randrange(1, 101, 1) for _ in range(10)]

Generating random integer from a range

Notice that in most suggestions the initial random value that you have got from rand() function, which is typically from 0 to RAND_MAX, is simply wasted. You are creating only one random number out of it, while there is a sound procedure that can give you more.

Assume that you want [min,max] region of integer random numbers. We start from [0, max-min]

Take base b=max-min+1

Start from representing a number you got from rand() in base b.

That way you have got floor(log(b,RAND_MAX)) because each digit in base b, except possibly the last one, represents a random number in the range [0, max-min].

Of course the final shift to [min,max] is simple for each random number r+min.

int n = NUM_DIGIT-1;
while(n >= 0)
{
    r[n] = res % b;
    res -= r[n];
    res /= b;
    n--;
}

If NUM_DIGIT is the number of digit in base b that you can extract and that is

NUM_DIGIT = floor(log(b,RAND_MAX))

then the above is as a simple implementation of extracting NUM_DIGIT random numbers from 0 to b-1 out of one RAND_MAX random number providing b < RAND_MAX.

Generate a random letter in Python

well, this is my answer! It works well. Just put the number of random letters you want in 'number'... (Python 3)

import random

def key_gen():
    keylist = random.choice('abcdefghijklmnopqrstuvwxyz')
    return keylist

number = 0
list_item = ''
while number < 20:
    number = number + 1
    list_item = list_item + key_gen()

print(list_item)

Random number between 0 and 1 in python

RTM

From the docs for the Python random module:

Functions for integers:

random.randrange(stop)
random.randrange(start, stop[, step])

    Return a randomly selected element from range(start, stop, step).
    This is equivalent to choice(range(start, stop, step)), but doesn’t
    actually build a range object.

That explains why it only gives you 0, doesn't it. range(0,1) is [0]. It is choosing from a list consisting of only that value.

Also from those docs:

random.random()    
    Return the next random floating point number in the range [0.0, 1.0).

But if your inclusion of the numpy tag is intentional, you can generate many random floats in that range with one call using a np.random function.

Sample random rows in dataframe

First make some data:

> df = data.frame(matrix(rnorm(20), nrow=10))
> df
           X1         X2
1   0.7091409 -1.4061361
2  -1.1334614 -0.1973846
3   2.3343391 -0.4385071
4  -0.9040278 -0.6593677
5   0.4180331 -1.2592415
6   0.7572246 -0.5463655
7  -0.8996483  0.4231117
8  -1.0356774 -0.1640883
9  -0.3983045  0.7157506
10 -0.9060305  2.3234110

Then select some rows at random:

> df[sample(nrow(df), 3), ]
           X1         X2
9  -0.3983045  0.7157506
2  -1.1334614 -0.1973846
10 -0.9060305  2.3234110

Generate random array of floats between a range

This is the simplest way

np.random.uniform(start,stop,(rows,columns))

How do I seed a random class to avoid getting duplicate random values

In case you can't for some reason use the same Random again and again, try initializing it with something that changes all the time, like the time itself.

new Random(new System.DateTime().Millisecond).Next();

Remember this is bad practice though.

EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN:

Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.

The code below is probably your best option:

new Random().Next();

How to generate a random int in C?

This is hopefully a bit more random than just using srand(time(NULL)).

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

int main(int argc, char **argv)
{
    srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL));
    srand(rand());

    for (int i = 0; i < 10; i++)
        printf("%d\n", rand());
}

How to randomly select rows in SQL?

SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()

That said, everybody seems to come to this page for the more general answer to your question:

Selecting a random row in SQL

Select a random row with MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

Select a random row with PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

Select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

Select a random row with IBM DB2

SELECT column, RAND() as IDX 
FROM table 
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Select a random record with Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

Select a random row with sqlite:

SELECT column FROM table 
ORDER BY RANDOM() LIMIT 1

Generate random numbers using C++11 random library

You've got two common situations. The first is that you want random numbers and aren't too fussed about the quality or execution speed. In that case, use the following macro

#define uniform() (rand()/(RAND_MAX + 1.0))

that gives you p in the range 0 to 1 - epsilon (unless RAND_MAX is bigger than the precision of a double, but worry about that when you come to it).

int x = (int) (uniform() * N);

Now gives a random integer on 0 to N -1.

If you need other distributions, you have to transform p. Or sometimes it's easier to call uniform() several times.

If you want repeatable behaviour, seed with a constant, otherwise seed with a call to time().

Now if you are bothered about quality or run time performance, rewrite uniform(). But otherwise don't touch the code. Always keep uniform() on 0 to 1 minus epsilon. Now you can wrap the C++ random number library to create a better uniform(), but that's a sort of medium-level option. If you are bothered about the characteristics of the RNG, then it's also worth investing a bit of time to understand how the underlying methods work, then provide one. So you've got complete control of the code, and you can guarantee that with the same seed, the sequence will always be exactly the same, regardless of platform or which version of C++ you are linking to.

How to generate a random string in Ruby

I was doing something like this recently to generate an 8 byte random string from 62 characters. The characters were 0-9,a-z,A-Z. I had an array of them as was looping 8 times and picking a random value out of the array. This was inside a Rails app.

str = ''
8.times {|i| str << ARRAY_OF_POSSIBLE_VALUES[rand(SIZE_OF_ARRAY_OF_POSSIBLE_VALUES)] }

The weird thing is that I got good number of duplicates. Now randomly this should pretty much never happen. 62^8 is huge, but out of 1200 or so codes in the db i had a good number of duplicates. I noticed them happening on hour boundaries of each other. In other words I might see a duple at 12:12:23 and 2:12:22 or something like that...not sure if time is the issue or not.

This code was in the before create of an ActiveRecord object. Before the record was created this code would run and generate the 'unique' code. Entries in the DB were always produced reliably, but the code (str in the above line) was being duplicated much too often.

I created a script to run through 100000 iterations of this above line with small delay so it would take 3-4 hours hoping to see some kind of repeat pattern on an hourly basis, but saw nothing. I have no idea why this was happening in my Rails app.

Generating (pseudo)random alpha-numeric strings

Generate cryptographically strong, random (potentially) 8-character string using the openssl_random_pseudo_bytes function:

echo bin2hex(openssl_random_pseudo_bytes(4));

Procedural way:

function randomString(int $length): string
{
    return bin2hex(openssl_random_pseudo_bytes($length));
}

Update:

PHP7 introduced the random_x() functions which should be even better. If you come from PHP 5.X, use excellent paragonie/random_compat library which is a polyfill for random_bytes() and random_int() from PHP 7.

function randomString($length)
{
    return bin2hex(random_bytes($length));
}

Seedable JavaScript random number generator

One option is http://davidbau.com/seedrandom which is a seedable RC4-based Math.random() drop-in replacement with nice properties.

Generating a Random Number between 1 and 10 Java

This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.

import java.util.Random;

If you want to test it out try something like this.

Random rn = new Random();

for(int i =0; i < 100; i++)
{
    int answer = rn.nextInt(10) + 1;
    System.out.println(answer);
}

Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).

How can I generate a 6 digit unique number?

This will generate random 6 digit number

_x000D_
_x000D_
<?php_x000D_
    mt_rand(100000,999999);_x000D_
?>
_x000D_
_x000D_
_x000D_

Generate random string/characters in JavaScript

You can loop through an array of items and recursively add them to a string variable, for instance if you wanted a random DNA sequence:

_x000D_
_x000D_
function randomDNA(len) {_x000D_
  len = len || 100_x000D_
  var nuc = new Array("A", "T", "C", "G")_x000D_
  var i = 0_x000D_
  var n = 0_x000D_
  s = ''_x000D_
  while (i <= len - 1) {_x000D_
    n = Math.floor(Math.random() * 4)_x000D_
    s += nuc[n]_x000D_
    i++_x000D_
  }_x000D_
  return s_x000D_
}_x000D_
_x000D_
console.log(randomDNA(5));
_x000D_
_x000D_
_x000D_

Generating random numbers with normal distribution in Excel

Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.

How to use random in BATCH script?

If you will divide by some large value you will get a huge amount of duplicates one after other. What you need to do is to take modulo of the %RANDOM% value:

@echo off
REM 
SET maxvalue=10
SET minvalue=1

SETLOCAL 
SET /A tmpRandom=((%RANDOM%)%%(%maxvalue%))+(%minvalue%)
echo "Tmp random: %tmpRandom%"
echo "Random:  %RANDOM%"
ENDLOCAL

How do I generate random integers within a specific range in Java?

I think this code will work for it. Please try this:

import java.util.Random;
public final class RandomNumber {

    public static final void main(String... aArgs) {
        log("Generating 10 random integers in range 1..10.");
        int START = 1;
        int END = 10;
        Random randomGenerator = new Random();
        for (int idx=1; idx<=10; ++idx) {

            // int randomInt=randomGenerator.nextInt(100);
            // log("Generated : " + randomInt);
            showRandomInteger(START,END,randomGenerator);
        }
        log("Done");
    }

    private static void log(String aMessage) {
        System.out.println(aMessage);
    }

    private static void showRandomInteger(int aStart, int aEnd, Random aRandom) {
        if (aStart > aEnd) {
            throw new IllegalArgumentException("Start cannot exceed End.");
        }
        long range = (long)aEnd - (long)aStart + 1;
        long fraction = (long) (range * aRandom.nextDouble());
        int randomNumber = (int) (fraction + aStart);
        log("Generated" + randomNumber);
    }
}

How to generate random float number in C

Try:

float x = (float)rand()/(float)(RAND_MAX/a);

To understand how this works consider the following.

N = a random value in [0..RAND_MAX] inclusively.

The above equation (removing the casts for clarity) becomes:

N/(RAND_MAX/a)

But division by a fraction is the equivalent to multiplying by said fraction's reciprocal, so this is equivalent to:

N * (a/RAND_MAX)

which can be rewritten as:

a * (N/RAND_MAX)

Considering N/RAND_MAX is always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a.

Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):

float x = ((float)rand()/(float)(RAND_MAX)) * a;

Note: the floating point representation of a must be exact or this will never hit your absolute edge case of a (it will get close). See this article for the gritty details about why.

Sample

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

int main(int argc, char *argv[])
{
    srand((unsigned int)time(NULL));

    float a = 5.0;
    for (int i=0;i<20;i++)
        printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
    return 0;
}

Output

1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Generating random numbers in C

You first need to seed the generator because it doesn't generate real random numbers!

Try this:

#include <stdlib.h>
#include <time.h>
int main()
{
    // random seed, time!
    srand( time(NULL) ); // hackish but gets the job done.
    int x;
    x = rand(); // everytime it is different because the seed is different.
    printf("%d", x);
}

How does one generate a random number in Apple's Swift language?

In Swift 4.2 you can generate random numbers by calling the random() method on whatever numeric type you want, providing the range you want to work with. For example, this generates a random number in the range 1 through 9, inclusive on both sides

let randInt = Int.random(in: 1..<10)

Also with other types

let randFloat = Float.random(in: 1..<20)
let randDouble = Double.random(in: 1...30)
let randCGFloat = CGFloat.random(in: 1...40)

Creating a random string with A-Z and 0-9 in Java

You can easily do that with a for loop,

public static void main(String[] args) {
  String aToZ="ABCD.....1234"; // 36 letter.
  String randomStr=generateRandom(aToZ);

}

private static String generateRandom(String aToZ) {
    Random rand=new Random();
    StringBuilder res=new StringBuilder();
    for (int i = 0; i < 17; i++) {
       int randIndex=rand.nextInt(aToZ.length()); 
       res.append(aToZ.charAt(randIndex));            
    }
    return res.toString();
}

Generate random 5 characters string

If it's fine that you'll get only letters A-F, then here's my solution:

str_pad(dechex(mt_rand(0, 0xFFFFF)), 5, '0', STR_PAD_LEFT);

I believe that using hash functions is an overkill for such a simple task as generating a sequence of random hexadecimal digits. dechex + mt_rand will do the same job, but without unnecessary cryptographic work. str_pad guarantees 5-character length of the output string (if the random number is less than 0x10000).

Duplicate probability depends on mt_rand's reliability. Mersenne Twister is known for high-quality randomness, so it should fit the task well.

How can I generate a unique ID in Python?

Maybe this work for u

str(uuid.uuid4().fields[-1])[:5]

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

/*this code is written in Turbo C++
 For Visual Studio, code is in comment*/

int a[10],ct=0,x=10,y=10;    //x,y can be any value, but within the range of 
                             //array declared
randomize();                 //there is no need to use this Visual Studio
for(int i=0;i<10;i++)
{   a[i]=random(10);         //use a[i]=rand()%10 for Visual Studio
}
cout<<"\n\n";
do
{   ct=0;
    for(i=0;i<x;i++)
    {   for(int j=0;j<y;j++)
        {   if(a[i]==a[j]&&i!=j)
            {   a[j]=random(10);    //use a[i]=rand()%10 for Visual Studio
            }
            else
            {   ct++;
            }
        }
    }
}while(!(ct==(x*y)));

Well I'm not a pro in C++, but learnt it in school. I am using this algo for past 1 year to store different random values in a 1D array, but this will also work in 2D array after some changes. Any suggestions about the code are welcome.

Generate GUID in MySQL for existing Data?

Just a minor addition to make as I ended up with a weird result when trying to modify the UUIDs as they were generated. I found the answer by Rakesh to be the simplest that worked well, except in cases where you want to strip the dashes.

For reference:

UPDATE some_table SET some_field=(SELECT uuid());

This worked perfectly on its own. But when I tried this:

UPDATE some_table SET some_field=(REPLACE((SELECT uuid()), '-', ''));

Then all the resulting values were the same (not subtly different - I quadruple checked with a GROUP BY some_field query). Doesn't matter how I situated the parentheses, the same thing happens.

UPDATE some_table SET some_field=(REPLACE(SELECT uuid(), '-', ''));

It seems when surrounding the subquery to generate a UUID with REPLACE, it only runs the UUID query once, which probably makes perfect sense as an optimization to much smarter developers than I, but it didn't to me.

To resolve this, I just split it into two queries:

UPDATE some_table SET some_field=(SELECT uuid());
UPDATE some_table SET some_field=REPLACE(some_field, '-', '');

Simple solution, obviously, but hopefully this will save someone the time that I just lost.

Generating a random password in php

Security warning: rand() is not a cryptographically secure pseudorandom number generator. Look elsewhere for generating a cryptographically secure pseudorandom string in PHP.

Try this (use strlen instead of count, because count on a string is always 1):

function randomPassword() {
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

Demo

How to generate a random alpha-numeric string

static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static SecureRandom rnd = new SecureRandom();

String randomString(int len){
   StringBuilder sb = new StringBuilder(len);
   for(int i = 0; i < len; i++)
      sb.append(AB.charAt(rnd.nextInt(AB.length())));
   return sb.toString();
}

How to get random value out of an array?

$value = $array[array_rand($array)];

PHP random string generator

Finally I have found a solution to get random and unique values.

My solution is:

substr(md5(time()), 0, 12)

time always return a timestamp, and it is always unique. You can use it with MD5 to make it better.

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

How to generate a random number between a and b in Ruby?

Random.new.rand(a..b) 

Where a is your lowest value and b is your highest value.

Generate random numbers uniformly over an entire range

By their nature, a small sample of random numbers doesn't have to be uniformly distributed. They're random, after all. I agree that if a random number generator is generating numbers that consistently appear to be grouped, then there is probably something wrong with it.

But keep in mind that randomness isn't necessarily uniform.

Edit: I added "small sample" to clarify.

Creating random numbers with no duplicates

Following code create a sequence random number between [1,m] that was not generated before.

public class NewClass {

    public List<Integer> keys = new ArrayList<Integer>();

    public int rand(int m) {
        int n = (int) (Math.random() * m + 1);
        if (!keys.contains(n)) {
            keys.add(n);
            return n;
        } else {
            return rand(m);
        }
    }

    public static void main(String[] args) {
        int m = 4;
        NewClass ne = new NewClass();
        for (int i = 0; i < 4; i++) {
            System.out.println(ne.rand(m));
        }
        System.out.println("list: " + ne.keys);
    }
}

Random row selection in Pandas dataframe

sample

As of v0.20.0, you can use pd.DataFrame.sample, which can be used to return a random sample of a fixed number rows, or a percentage of rows:

df = df.sample(n=k)     # k rows
df = df.sample(frac=k)  # int(len(df.index) * k) rows

For reproducibility, you can specify an integer random_state, equivalent to using np.ramdom.seed. So, instead of setting, for example, np.random.seed = 0, you can:

df = df.sample(n=k, random_state=0)

How do I pick randomly from an array?

myArray.sample

will return 1 random value.

myArray.shuffle.first

will also return 1 random value.

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

Java generating non-repeating random numbers

Integer[] arr = {...};
Collections.shuffle(Arrays.asList(arr));

For example:

public static void main(String[] args) {
    Integer[] arr = new Integer[1000];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i;
    }
    Collections.shuffle(Arrays.asList(arr));
    System.out.println(Arrays.toString(arr));

}

Python: Generate random number between x and y which is a multiple of 5

Create an integer random between e.g. 1-11 and multiply it by 5. Simple math.

import random
for x in range(20):
  print random.randint(1,11)*5,
print

produces e.g.

5 40 50 55 5 15 40 45 15 20 25 40 15 50 25 40 20 15 50 10

Generate random password string with requirements in javascript

Here's a way to create a flexible generator that allows you to add some rules:

function generatePassword(length, rules) {
    if (!length || length == undefined) {
        length = 8;
    }

    if (!rules || rules == undefined) {
        rules = [
            {chars: "abcdefghijklmnopqrstuvwxyz", min: 3},  // As least 3 lowercase letters
            {chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 2},  // At least 2 uppercase letters
            {chars: "0123456789", min: 2},                  // At least 2 digits
            {chars: "!@#$&*?|%+-_./:;=()[]{}", min: 1}      // At least 1 special char
        ];
    }

    var allChars = "", allMin = 0;
    rules.forEach(function(rule) {
        allChars += rule.chars;
        allMin += rule.min;
    });
    if (length < allMin) {
        length = allMin;
    }
    rules.push({chars: allChars, min: length - allMin});
    
    var pswd = "";
    rules.forEach(function(rule) {
        if (rule.min > 0) {
            pswd += shuffleString(rule.chars, rule.min);
        }
    });
    
    return shuffleString(pswd);
}

function shuffleString(str, maxlength) {
    var shuffledString = str.split('').sort(function(){return 0.5-Math.random()}).join('');
    if (maxlength > 0) {
        shuffledString = shuffledString.substr(0, maxlength);
    }
    return shuffledString;
}

var pswd = generatePassword(15, [
  {chars: "abcdefghijklmnopqrstuvwxyz", min: 4},  // As least 4 lowercase letters
  {chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 1},  // At least 1 uppercase letters
  {chars: "0123456789", min: 3},                  // At least 3 digits
  {chars: "!@#$&*?|%+-_./:;=()[]{}", min: 2}      // At least 2 special chars
]);

console.log(pswd, pswd.length);

How to randomize Excel rows

Use Excel Online (Google Sheets).. And install Power Tools for Google Sheets.. Then in Google Sheets go to Addons tab and start Power Tools. Then choose Randomize from Power Tools menu. Select Shuffle. Then select choices of your test in excel sheet. Then select Cells in each row and click Shuffle from Power Tools menu. This will shuffle each row's selected cells independently from one another.

Generating random numbers in Objective-C

I thought I could add a method I use in many projects.

- (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {
    return (NSInteger)(min + arc4random_uniform(max - min + 1));
}

If I end up using it in many files I usually declare a macro as

#define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))

E.g.

NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74

Note: Only for iOS 4.3/OS X v10.7 (Lion) and later

Random number c++ in some range

Since nobody posted the modern C++ approach yet,

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(gen) << ' '; // generate numbers
}

Random record from MongoDB

You can pick a random timestamp and search for the first object that was created afterwards. It will only scan a single document, though it doesn't necessarily give you a uniform distribution.

var randRec = function() {
    // replace with your collection
    var coll = db.collection
    // get unixtime of first and last record
    var min = coll.find().sort({_id: 1}).limit(1)[0]._id.getTimestamp() - 0;
    var max = coll.find().sort({_id: -1}).limit(1)[0]._id.getTimestamp() - 0;

    // allow to pass additional query params
    return function(query) {
        if (typeof query === 'undefined') query = {}
        var randTime = Math.round(Math.random() * (max - min)) + min;
        var hexSeconds = Math.floor(randTime / 1000).toString(16);
        var id = ObjectId(hexSeconds + "0000000000000000");
        query._id = {$gte: id}
        return coll.find(query).limit(1)
    };
}();

Simple way to create matrix of random numbers

Take a look at numpy.random.rand:

Docstring: rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1).


>>> import numpy as np
>>> np.random.rand(2,3)
array([[ 0.22568268,  0.0053246 ,  0.41282024],
       [ 0.68824936,  0.68086462,  0.6854153 ]])

How do you use math.random to generate random ints?

You can also use this way for getting random number between 1 and 100 as:

SecureRandom src=new SecureRandom();
int random=1 + src.nextInt(100);

Random alpha-numeric string in JavaScript?

This function should give a random string in any length.

function randString(length) {
    var l = length > 25 ? 25 : length;
    var str = Math.random().toString(36).substr(2, l);
    if(str.length >= length){
        return str;
    }
    return str.concat(this.randString(length - str.length));
}

I've tested it with the following test that succeeded.

function test(){
    for(var x = 0; x < 300000; x++){
        if(randString(x).length != x){
            throw new Error('invalid result for len ' + x);
        }
    }
}

The reason i have chosen 25 is since that in practice the length of the string returned from Math.random().toString(36).substr(2, 25) has length 25. This number can be changed as you wish.

This function is recursive and hence calling the function with very large values can result with Maximum call stack size exceeded. From my testing i was able to get string in the length of 300,000 characters.

This function can be converted to a tail recursion by sending the string to the function as a second parameter. I'm not sure if JS uses Tail call optimization

generate random double numbers in c++

This should be performant, thread-safe and flexible enough for many uses:

#include <random>
#include <iostream>

template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
    thread_local static Generator gen(std::random_device{}());

    using dist_type = typename std::conditional
    <
        std::is_integral<Numeric>::value
        , std::uniform_int_distribution<Numeric>
        , std::uniform_real_distribution<Numeric>
    >::type;

    thread_local static dist_type dist;

    return dist(gen, typename dist_type::param_type{from, to});
}

int main(int, char*[])
{
    for(auto i = 0U; i < 20; ++i)
        std::cout << random<double>(0.0, 0.3) << '\n';
}

Random numbers with Math.random() in Java

A better approach is:

int x = rand.nextInt(max - min + 1) + min;

Your formula generates numbers between min and min + max.

Random random = new Random(1234567);
int min = 5;
int max = 20;
while (true) {
    int x = (int)(Math.random() * max) + min;
    System.out.println(x);
    if (x < min || x >= max) { break; }
}       

Result:

10
16
13
21 // Oops!!

See it online here: ideone

mysql: get record count between two date-time

May be with:

SELECT count(*) FROM `table` 
where 
    created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 07:42:50';

or use between:

SELECT count(*) FROM `table` 
where 
    created_at between '2011-03-17 06:42:10' and '2011-03-17 07:42:50';

You can change the datetime as per your need. May be use curdate() or now() to get the desired dates.

How to add include and lib paths to configure/make cycle?

This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf

Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.

After successfully running autogen.sh/configure, compile with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make

The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.

I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.

Can you change a path without reloading the controller in AngularJS?

Here's my fuller solution which solves a few things @Vigrond and @rahilwazir missed:

  • When search params were changed, it would prevent broadcasting a $routeUpdate.
  • When the route is actually left unchanged, $locationChangeSuccess is never triggered which causes the next route update to be prevented.
  • If in the same digest cycle there was another update request, this time wishing to reload, the event handler would cancel that reload.

    app.run(['$rootScope', '$route', '$location', '$timeout', function ($rootScope, $route, $location, $timeout) {
        ['url', 'path'].forEach(function (method) {
            var original = $location[method];
            var requestId = 0;
            $location[method] = function (param, reload) {
                // getter
                if (!param) return original.call($location);
    
                # only last call allowed to do things in one digest cycle
                var currentRequestId = ++requestId;
                if (reload === false) {
                    var lastRoute = $route.current;
                    // intercept ONLY the next $locateChangeSuccess
                    var un = $rootScope.$on('$locationChangeSuccess', function () {
                        un();
                        if (requestId !== currentRequestId) return;
    
                        if (!angular.equals($route.current.params, lastRoute.params)) {
                            // this should always be broadcast when params change
                            $rootScope.$broadcast('$routeUpdate');
                        }
                        var current = $route.current;
                        $route.current = lastRoute;
                        // make a route change to the previous route work
                        $timeout(function() {
                            if (requestId !== currentRequestId) return;
                            $route.current = current;
                        });
                    });
                    // if it didn't fire for some reason, don't intercept the next one
                    $timeout(un);
                }
                return original.call($location, param);
            };
        });
    }]);
    

What should main() return in C and C++?

I believe that main() should return either EXIT_SUCCESS or EXIT_FAILURE. They are defined in stdlib.h

Matplotlib: "Unknown projection '3d'" error

First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib.

Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")

I'm guessing you're running version 0.99, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib.

If you're running version 0.99, try doing this instead of using using the projection keyword argument:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization! 
fig = plt.figure()

ax = Axes3D(fig) #<-- Note the difference from your original code...

X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()

This should work in matplotlib 1.0.x, as well, not just 0.99.

How to pass a PHP variable using the URL

just put

$a='Link1';
$b='Link2';

in your pass.php and you will get your answer and do a double quotation in your link.php:

echo '<a href="pass.php?link=' . $a . '">Link 1</a>';

How to use external ".js" files

I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script> </script> tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body> tag and bingo every part of the script started to respond fine again.

How to automatically generate unique id in SQL like UID12345678?

CREATE TABLE dbo.tblUsers
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED, 
    [Name] VARCHAR(50) NOT NULL,
)

marc_s's Answer Snap

marc_s's Answer Snap

Difference between MongoDB and Mongoose

I assume you already know that MongoDB is a NoSQL database system which stores data in the form of BSON documents. Your question, however is about the packages for Node.js.

In terms of Node.js, mongodb is the native driver for interacting with a mongodb instance and mongoose is an Object modeling tool for MongoDB.

Mongoose is built on top of the MongoDB driver to provide programmers with a way to model their data.

EDIT: I do not want to comment on which is better, as this would make this answer opinionated. However I will list some advantages and disadvantages of using both approaches.

Using Mongoose, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB. On the downside, learning mongoose can take some time, and has some limitations in handling schemas that are quite complex.

However, if your collection schema is unpredictable, or you want a Mongo-shell like experience inside Node.js, then go ahead and use the MongoDB driver. It is the simplest to pick up. The downside here is that you will have to write larger amounts of code for validating the data, and the risk of errors is higher.

AssertNull should be used or AssertNotNull

I just want to add that if you want to write special text if It null than you make it like that

  Assert.assertNotNull("The object you enter return null", str1)

Is it possible to see more than 65536 rows in Excel 2007?

Here is an interesting blog entry about numbers / limitations of Excel 2007. According to the author the new limit is approximately one million rows.

Sounds like you have a pre-Excel 2007 workbook open in Excel 2007 in compatibility mode (look in the title bar and see if it says compatibility mode). If so, the workbook has 65,536 rows, not 1,048,576. You can save the workbook as an Excel workbook which will be in Excel 2007 format, close the workbook and re-open it.

Make first letter of a string upper case (with maximum performance)

public string FirstLetterToUpper(string str)
{
    if (str == null)
        return null;

    if (str.Length > 1)
        return char.ToUpper(str[0]) + str.Substring(1);

    return str.ToUpper();
}

Old answer: This makes every first letter to upper case

public string ToTitleCase(string str)
{
    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}

How to get thread id of a pthread in linux c program?

Platform-independent way (starting from c++11) is:

#include <thread>

std::this_thread::get_id();

Use -notlike to filter out multiple strings in PowerShell

V2 at least contains the -username parameter that takes a string[], and supports globbing.

V1 you want to expand your test like so:

Get-EventLog Security | ?{$_.UserName -notlike "user1" -and $_.UserName -notlike "*user2"}

Or you could use "-notcontains" on the inline array but this would only work if you can do exact matching on the usernames.

... | ?{@("user1","user2") -notcontains $_.username}

How do I create a batch file timer to execute / call another batch throughout the day

I would use the scheduler (control panel) rather than a cmd line or other application.

Control Panel -> Scheduled tasks

How can I calculate the difference between two ArrayLists?

You already have the right answer. And if you want to make more complicated and interesting operations between Lists (collections) use apache commons collections (CollectionUtils) It allows you to make conjuction/disjunction, find intersection, check if one collection is a subset of another and other nice things.

psql: could not connect to server: No such file or directory (Mac OS X)

I'm not entirely sure why, but my Postgres installation got a little bit screwed and some files were deleted resulting in the error OP is showing.

Despite the fact that I am able to run commands like brew service retart postgres and see the proper messages, this error persisted.

I went through the postgres documentation and found that my file /usr/local/var/postgres was totally empty. So I ran the following:

initdb /usr/local/var/postgres

It seems some configurations took place with that command.

Then it asked me to run this:

postgres -D /usr/local/var/postgres

And that told me a postmaster.pid file already exists.

I just needed to know if brew would be able to pick up the configs I just ran, so I tested it out.

ls /usr/local/var/postgres

That showed me a postmaster.pid file. I then did brew services stop postgresql, and the postmaster.pid file disappeared. Then I did brew services start postgresql, and VIOLA, the file reappeared.

Then I went ahead and ran my app, which did in fact find the server, however my databases seem to be gone.

Although I know that they may not be gone at all - the new initialization I did may have created a new data_area, and the old one isn't being pointed to. I'd have to look at where that's at and point it back over or just create my databases again.

Hope this helps! Reading the postgres docs helped me a lot. I hate reading answers that are like "Paste this in it works!" because I don't know what the hell is happening and why.

HowTo Generate List of SQL Server Jobs and their owners

A colleague told me about this stored procedure...

USE msdb

EXEC dbo.sp_help_job

Java Reflection: How to get the name of a variable?

see this example :

PersonneTest pt=new PersonneTest();
System.out.println(pt.getClass().getDeclaredFields().length);
Field[]x=pt.getClass().getDeclaredFields();
System.out.println(x[1].getName());

Display number always with 2 decimal places in <input>

Use currency filter with empty symbol ($)

{{val | currency:''}}

Javascript change Div style

A simple switch statement should do the trick:

function abc() {
    var elem=document.getElementById('test'),color;
    switch(elem.style.color) {
        case('red'):
            color='black';
            break;
        case('black'):
        default:
            color='red';
    }
    elem.style.color=color;
}

Removing the title text of an iOS UIBarButtonItem

Non of the answers helped me. But a trick did - I just cleared the title of the view controller that pushed (where the back button is going to) just before pushing it.

So when the previous view doesn't have a title, on iOS 7 the back button will only have an arrow, without text.

On viewWillAppear of the pushing view, I placed back the original title.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

UIAlertController custom font, size, color

To change the color of one button like CANCEL to the red color you can use this style property called UIAlertActionStyle.destructive :

let prompt = UIAlertController.init(title: "Reset Password", message: "Enter Your E-mail :", preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: "Submit", style: .default) { (action) in
              //your code
}

let cancelAction = UIAlertAction.init(title: "Cancel", style: UIAlertActionStyle.destructive) { (action) in
                //your code
        }
        prompt.addTextField(configurationHandler: nil)
        prompt.addAction(okAction)
        prompt.addAction(cancelAction)
        present(prompt, animated: true, completion: nil);

Escaping backslash in string - javascript

I think this is closer to the answer you're looking for:

<input type="file">

$file = $(file);
var filename = fileElement[0].files[0].name;

Dynamically change color to lighter or darker by percentage CSS (Javascript)

As far as I know, there's no way you can do this in CSS.

But I think that a little server-side logic could easily do as you suggest. CSS stylesheets are normally static assets, but there is no reason they couldn't be dynamically generated by server-side code. Your server-side script would:

  1. Check a URL parameter to determine the user and therefore the user's chosen colour. Use a URL parameter rather than a session variable so that you can still cache the CSS.
  2. Break up the colour into its red, green and blue components
  3. Increment each of the three components by a set amount. Experiment with this to get the results you are after.
  4. Generate CSS incorporating the new colour

Links to this CSS-generating page would look something like:

<link rel="stylesheet" href="http://yoursite.com/custom.ashx?user=1231">

If you don't use the .css extension be sure to set the MIME-type correctly so that the browser knows to interpret the file as CSS.

(Note that to make colours lighter you have to raise each of the RGB values)

How many socket connections possible?

Realistically for an application, more then 4000-5000 open sockets on a single machine becomes impractical. Just checking for activity on all the sockets and managing them starts to become a performance issue - especially in real-time environments.

How to create image slideshow in html?

Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.

Here is the one I most liked.

http://www.zurb.com/playground/orbit-jquery-image-slider

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

Why is there no String.Empty in Java?

Don't just say "memory pool of strings is reused in the literal form, case closed". What compilers do under the hood is not the point here. The question is reasonable, specially given the number of up-votes it received.

It's about the symmetry, without it APIs are harder to use for humans. Early Java SDKs notoriously ignored the rule and now it's kind of too late. Here are a few examples on top of my head, feel free to chip in your "favorite" example:

  • BigDecimal.ZERO, but no AbstractCollection.EMPTY, String.EMPTY
  • Array.length but List.size()
  • List.add(), Set.add() but Map.put(), ByteBuffer.put() and let's not forget StringBuilder.append(), Stack.push()

How to change the locale in chrome browser

The easiest way I found, summarized in a few pictures:

Adding Language

Changing Language

Relaunch

You could skip a few steps (up to step 4) by simply navigating to chrome://settings/languages right away.

Quick Way to Implement Dictionary in C

I am surprised no one mentioned hsearch/hcreate set of libraries which although is not available on windows, but is mandated by POSIX, and therefore available in Linux / GNU systems.

The link has a simple and complete basic example that very well explains its usage.

It even has thread safe variant, is easy to use and very performant.

How to customize listview using baseadapter

I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
    <ImageView
        android:id="@+id/image"
        android:layout_alignParentRight="true"
        android:paddingRight="4dp" />
    <TextView
        android:id="@+id/title"
        android:layout_toLeftOf="@id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="23sp"
        android:maxLines="1" />
    <TextView
        android:id="@+id/subtitle"
        android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 
</RelativeLayout>

Assuming you have a custom class like this

public class CustomClass {

    private long id;
    private String title, subtitle, picture;

    public CustomClass () {
    }

    public CustomClass (long id, String title, String subtitle, String picture) {
        this.id = id;
        this.title= title;
        this.subtitle= subtitle;
        this.picture= picture;
    }
    //add getters and setters
}

And a CustomAdapter.java uses the xml-layout

public class CustomAdapter extends ArrayAdapter {

private Context context;
private int resource;
private LayoutInflater inflater;

public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever

    super(context, R.layout.customlistviewitem, values);

    this.context = context;
    this.resource = R.layout.customlistview;
    this.inflater = LayoutInflater.from(context);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    convertView = (RelativeLayout) inflater.inflate(resource, null);

    CustomClass item = (CustomClass) getItem(position);

    TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
    TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
    ImageView imageview = (ImageView) convertView.findViewById(R.id.image);

    //fill the textviews and imageview with the values
    textviewTitle = item.getTtile();
    textviewSubtitle = item.getSubtitle();

    if (item.getAfbeelding() != null) {
        int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
        Drawable image = context.getResources().getDrawable(imageResource);
    }
    imageview.setImageDrawable(image);

    return convertView;
    }
}

Did you manage to do it? Feel free to ask if you want more info on something :)

EDIT: Changed the adapter to suit a List instead of just a List

Remove part of string in Java

If you just need to remove everything after the "(", try this. Does nothing if no parentheses.

StringUtils.substringBefore(str, "(");

If there may be content after the end parentheses, try this.

String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")"); 

To remove end spaces, use str.trim()

Apache StringUtils functions are null-, empty-, and no match- safe

How to call Base Class's __init__ method from the child class?

You could use super(ChildClass, self).__init__()

class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

class ChildClass(BaseClass):
    def __init__(self, *args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)

Your indentation is incorrect, here's the modified code:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Here's the output:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}

How can I install pip on Windows?

Updated at 2016 : Pip should already be included in Python 2.7.9+ or 3.4+, but if for whatever reason it is not there, you can use the following one-liner.

PS:

  1. This should already be satisfied in most cases but, if necessary, be sure that your environment variable PATH includes Python's folders (for example, Python 2.7.x on Windows default install: C:\Python27 and C:\Python27\Scripts, for Python 3.3x: C:\Python33 and C:\Python33\Scripts, etc)

  2. I encounter same problem and then found such perhaps easiest way (one liner!) mentioned on official website here: http://www.pip-installer.org/en/latest/installing.html

Can't believe there are so many lengthy (perhaps outdated?) answers out there. Feeling thankful to them but, please up-vote this short answer to help more new comers!

How to declare string constants in JavaScript?

Just declare variable outside of scope of any js function. Such variables will be global.

Print text in Oracle SQL Developer SQL Worksheet window

You could put your text in a select statement such as...

SELECT 'Querying Table1' FROM dual;

Remove last character of a StringBuilder?

With Java-8 you can use static method of String class,

String#join(CharSequence delimiter,Iterable<? extends CharSequence> elements).


public class Test {

    public static void main(String[] args) {

        List<String> names = new ArrayList<>();
        names.add("James");
        names.add("Harry");
        names.add("Roy");
        System.out.println(String.join(",", names));
    }
}

OUTPUT

James,Harry,Roy

MongoDB: How to update multiple documents with a single command?

I had the same problem , and i found the solution , and it works like a charm

just set the flag multi to true like this :

 db.Collection.update(
                {_id_receiver: id_receiver},
               {$set: {is_showed: true}},
                {multi: true}   /* --> multiple update */
            , function (err, updated) {...});

i hope that helps :)

Iterate through Nested JavaScript Objects

var findObjectByLabel = function(objs, label) {
  if(objs.label === label) { 
    return objs; 
    }
  else{
    if(objs.subs){
      for(var i in objs.subs){
        let found = findObjectByLabel(objs.subs[i],label)
        if(found) return found
      }
    }
  }
};

findObjectByLabel(cars, "Ford");

Auto margins don't center image in page

img{display: flex; max-width: 80%; margin: auto;}

This is working for me. You can also use display: table in this case. Moreover, if you don't want to stick to this approach you can use the following:

img{position: relative; left: 50%;}

Enum Naming Convention - Plural

This is one of the few places that I disagree with the convention enough to go against it. TBH, I HATE that the definition of an enum and the instance of it can have the same name. I postfix all of my Enums with "Enum" specifically because it makes it clear what the context of it is in any given usage. IMO it makes the code much more readable.

public enum PersonTypesEnum {
    smart,
    sad,
    funny,
    angry
}


public class Person {   
    public PersonTypesEnum PersonType {get; set;}
}

Nobody will ever confuse what is the enum and what is the instance of it.

Global Angular CLI version greater than local version

Run the following Command: npm install --save-dev @angular/cli@latest

After running the above command the console might popup the below message

The Angular CLI configuration format has been changed, and your existing configuration can be updated automatically by running the following command: ng update @angular/cli

Best way to do a split pane in HTML

Hmm, I came across this property in CSS 3. This might be easier to use.

CSS resize Property

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I used a combination of the answers from rohancragg, Mukul Goel, and NullSoulException from above. However I had an additional error:

ORA-01157: cannot identify/lock data file string - see DBWR trace file

To which I found the answer here: http://nimishgarg.blogspot.com/2014/01/ora-01157-cannot-identifylock-data-file.html

Incase the above post gets deleted I am including the commands here as well.

C:\>sqlplus sys/sys as sysdba
SQL*Plus: Release 11.2.0.3.0 Production on Tue Apr 30 19:07:16 2013
Copyright (c) 1982, 2011, Oracle.  All rights reserved.
Connected to an idle instance.

SQL> startup
ORACLE instance started.
Total System Global Area  778387456 bytes
Fixed Size                  1384856 bytes
Variable Size             520097384 bytes
Database Buffers          251658240 bytes
Redo Buffers                5246976 bytes
Database mounted.
ORA-01157: cannot identify/lock data file 11 – see DBWR trace file
ORA-01110: data file 16: 'E:\oracle\app\nimish.garg\oradata\orcl\test_ts.dbf'

SQL> select NAME from v$datafile where file#=16;
NAME
--------------------------------------------------------------------------------
E:\ORACLE\APP\NIMISH.GARG\ORADATA\ORCL\TEST_TS.DBF

SQL> alter database datafile 16 OFFLINE DROP;
Database altered.

SQL> alter database open;
Database altered.

Thanks everyone you saved my day!

Fissh

How to change active class while click to another link in bootstrap use jquery?

I am using bootstrap navigation

This did the job for me including active main dropdown's and the active children

$(document).ready(function () {
        var url = window.location;
    // Will only work if string in href matches with location
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');

    // Will also work for relative and absolute hrefs
        $('ul.nav a').filter(function () {
            return this.href == url;
        }).parent().addClass('active').parent().parent().addClass('active');
    });

What is the difference between lower bound and tight bound?

Big O is the upper bound, while Omega is the lower bound. Theta requires both Big O and Omega, so that's why it's referred to as a tight bound (it must be both the upper and lower bound).

For example, an algorithm taking Omega(n log n) takes at least n log n time, but has no upper limit. An algorithm taking Theta(n log n) is far preferential since it takes at least n log n (Omega n log n) and no more than n log n (Big O n log n).

How to fill 100% of remaining height?

I added this for pages that were too short.

html:

<section id="secondary-foot"></section>

css:

section#secondary-foot {
    height: 100%;
    background-color: #000000;
    position: fixed;
    width: 100%;
}

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

The 'packages' element is not declared

Taken from this answer.

  1. Close your packages.config file.
  2. Build
  3. Warning is gone!

This is the first time I see ignoring a problem actually makes it go away...

Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

Get host domain from URL?

Try this

Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));

It will output support.domain.com

Or try

Uri.GetLeftPart( UriPartial.Authority )

Ruby 'require' error: cannot load such file

This will work nicely if it is in a gem lib directory and this is the tokenizer.rb

require_relative 'tokenizer/main'

C#: Converting byte array to string and printing out to console

This is just an updated version of Jesse Webbs code that doesn't append the unnecessary trailing , character.

public static string PrintBytes(this byte[] byteArray)
{
    var sb = new StringBuilder("new byte[] { ");
    for(var i = 0; i < byteArray.Length;i++)
    {
        var b = byteArray[i];
        sb.Append(b);
        if (i < byteArray.Length -1)
        {
            sb.Append(", ");
        }
    }
    sb.Append(" }");
    return sb.ToString();
}

The output from this method would be:

new byte[] { 48, ... 135, 31, 178, 7, 157 }

What's the difference between using "let" and "var"?

Here's an explanation of the let keyword with some examples.

let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function

This table on Wikipedia shows which browsers support Javascript 1.7.

Note that only Mozilla and Chrome browsers support it. IE, Safari, and potentially others don't.

Convert a string into an int

This is the simple solution for converting string to int

NSString *strNum = @"10";
int num = [strNum intValue];

but when you are getting value from the textfield then,

int num = [txtField.text intValue];

where txtField is an outlet of UITextField

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).

Typical symptoms:

[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100

[root@host /]# netstat -plant | grep 25
tcp        0      0 :::25                       :::*                        LISTEN      1082/exim           

If this happens, make sure that you don't have two entries for localhost in /etc/hosts with different IP addresses, like this (bad) example:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1       localhost localhost.localdomain localhost6 localhost6.localdomain6

To avoid confusion, make sure you only have one entry for localhost, preferably an IPv4 address, like this:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost  localhost.localdomain   localhost4.localdomain4 localhost4
::1       localhost6 localhost6.localdomain6

PPT to PNG with transparent background

Import To Google Slides

Select desired slide and set background to solid transparent

the click "File->Download as PNG"

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

I got this error When upgrading Google play services to 9.0 from 7.5

Having error with below one:

compile 'com.google.android.gms:play-services:9.0.0'

When I changed to

compile 'com.google.android.gms:play-services:7.5.0'

There is no error. Try this

Can I have onScrollListener for a ScrollView?

This might be very useful. Use NestedScrollView instead of ScrollView. Support Library 23.1 introduced an OnScrollChangeListener to NestedScrollView. So you can do something like this.

 myScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
        @Override
        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            Log.d("ScrollView","scrollX_"+scrollX+"_scrollY_"+scrollY+"_oldScrollX_"+oldScrollX+"_oldScrollY_"+oldScrollY);
            //Do something
        }
    });

How to set a tkinter window to a constant size

There are 2 solutions for your problem:

  1. Either you set a fixed size of the Tkinter window; mw.geometry('500x500')

OR

  1. Make the Frame adjust to the size of the window automatically;back.place(x = 0, y = 0, relwidth = 1, relheight = 1)

*The second option should be used in place of back.pack()

What is the best way to find the users home directory in Java?

Actually with Java 8 the right way is to use:

System.getProperty("user.home");

The bug JDK-6519127 has been fixed and the "Incompatibilities between JDK 8 and JDK 7" section of the release notes states:

Area: Core Libs / java.lang

Synopsis

The steps used to determine the user's home directory on Windows have changed to follow the Microsoft recommended approach. This change might be observable on older editions of Windows or where registry settings or environment variables are set to other directories. Nature of Incompatibility

behavioral RFE

6519127

Despite the question being old I leave this for future reference.

C++ Dynamic Shared Library on Linux

On top of previous answers, I'd like to raise awareness about the fact that you should use the RAII (Resource Acquisition Is Initialisation) idiom to be safe about handler destruction.

Here is a complete working example:

Interface declaration: Interface.hpp:

class Base {
public:
    virtual ~Base() {}
    virtual void foo() const = 0;
};

using Base_creator_t = Base *(*)();

Shared library content:

#include "Interface.hpp"

class Derived: public Base {
public:
    void foo() const override {}
};

extern "C" {
Base * create() {
    return new Derived;
}
}

Dynamic shared library handler: Derived_factory.hpp:

#include "Interface.hpp"
#include <dlfcn.h>

class Derived_factory {
public:
    Derived_factory() {
        handler = dlopen("libderived.so", RTLD_NOW);
        if (! handler) {
            throw std::runtime_error(dlerror());
        }
        Reset_dlerror();
        creator = reinterpret_cast<Base_creator_t>(dlsym(handler, "create"));
        Check_dlerror();
    }

    std::unique_ptr<Base> create() const {
        return std::unique_ptr<Base>(creator());
    }

    ~Derived_factory() {
        if (handler) {
            dlclose(handler);
        }
    }

private:
    void * handler = nullptr;
    Base_creator_t creator = nullptr;

    static void Reset_dlerror() {
        dlerror();
    }

    static void Check_dlerror() {
        const char * dlsym_error = dlerror();
        if (dlsym_error) {
            throw std::runtime_error(dlsym_error);
        }
    }
};

Client code:

#include "Derived_factory.hpp"

{
    Derived_factory factory;
    std::unique_ptr<Base> base = factory.create();
    base->foo();
}

Note:

  • I put everything in header files for conciseness. In real life you should of course split your code between .hpp and .cpp files.
  • To simplify, I ignored the case where you want to handle a new/delete overload.

Two clear articles to get more details:

How to install a Notepad++ plugin offline?

Notepad++ address has changed, so many of the links above are broken. The up to date link for this question is here: https://npp-user-manual.org/docs/plugins/

Just in case the address changes again, here is what we have there today:

How to install a plugin

Install plugin manually

If the plugin you want to install is not listed in the Plugins Admin, you may still install it manually. The plugin (in the DLL form) should be placed in the plugins subfolder of the Notepad++ Install Folder, under the subfolder with the same name of plugin binary name without file extension. For example, if the plugin you want to install named myAwesomePlugin.dll, you should install it with the following path: %PROGRAMFILES(x86)%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll

Once you installed the plugin, you can use (and you may configure) it via the menu “Plugins”.

How to find GCD, LCM on a set of numbers

There are no build in function for it. You can find the GCD of two numbers using Euclid's algorithm.

For a set of number

GCD(a_1,a_2,a_3,...,a_n) = GCD( GCD(a_1, a_2), a_3, a_4,..., a_n )

Apply it recursively.

Same for LCM:

LCM(a,b) = a * b / GCD(a,b)
LCM(a_1,a_2,a_3,...,a_n) = LCM( LCM(a_1, a_2), a_3, a_4,..., a_n )

SQL Update with row_number()

If table does not have relation, just copy all in new table with row number and remove old and rename new one with old one.

Select   RowNum = ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) , * INTO cdm.dbo.SALES2018 from 
(
select * from SALE2018) as SalesSource

How are software license keys generated?

There are also DRM behaviors that incorporate multiple steps to the process. One of the most well known examples is one of Adobe's methods for verifying an installation of their Creative Suite. The traditional CD Key method discussed here is used, then Adobe's support line is called. The CD key is given to the Adobe representative and they give back an activation number to be used by the user.

However, despite being broken up into steps, this falls prey to the same methods of cracking used for the normal process. The process used to create an activation key that is checked against the original CD key was quickly discovered, and generators that incorporate both of the keys were made.

However, this method still exists as a way for users with no internet connection to verify the product. Going forward, it's easy to see how these methods would be eliminated as internet access becomes ubiquitous.

how to create Socket connection in Android?

Simple socket server app example

I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.

This example app runs a server that returns a ROT-1 cypher of the input.

You would then need to add an Exit button + some sleep delays, but this should get you started.

To play with it:

Android sockets are the same as Java's, except we have to deal with some permission issues.

src/com/cirosantilli/android_cheat/socket/Main.java

package com.cirosantilli.android_cheat.socket;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main extends Activity {
    static final String TAG = "AndroidCheatSocket";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(Main.TAG, "onCreate");
        Main.this.startService(new Intent(Main.this, MyService.class));
    }

    public static class MyService extends IntentService {
        public MyService() {
            super("MyService");
        }
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(Main.TAG, "onHandleIntent");
            final int port = 12345;
            ServerSocket listener = null;
            try {
                listener = new ServerSocket(port);
                Log.d(Main.TAG, String.format("listening on port = %d", port));
                while (true) {
                    Log.d(Main.TAG, "waiting for client");
                    Socket socket = listener.accept();
                    Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    for (String inputLine; (inputLine = in.readLine()) != null;) {
                        Log.d(Main.TAG, "received");
                        Log.d(Main.TAG, inputLine);
                        StringBuilder outputStringBuilder = new StringBuilder("");
                        char inputLineChars[] = inputLine.toCharArray();
                        for (char c : inputLineChars)
                            outputStringBuilder.append(Character.toChars(c + 1));
                        out.println(outputStringBuilder);
                    }
                }
            } catch(IOException e) {
                Log.d(Main.TAG, e.toString());
            }
        }
    }
}

We need a Service or other background method or else: How do I fix android.os.NetworkOnMainThreadException?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cirosantilli.android_cheat.socket"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="22" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="AndroidCheatsocket">
        <activity android:name="Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".Main$MyService" />
    </application>
</manifest>

We must add: <uses-permission android:name="android.permission.INTERNET" /> or else: Java socket IOException - permission denied

On GitHub with a build.xml: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket

insert data into database with codeigniter

function order_summary_insert()
$OrderLines=$this->input->post('orderlines');
$CustomerName=$this->input->post('customer');
$data = array(
'OrderLines'=>$OrderLines,
'CustomerName'=>$CustomerName
);

$this->db->insert('Customer_Orders',$data);
}

CKEditor, Image Upload (filebrowserUploadUrl)

May be it's too late. Your code is correct so please check again your url in filebrowserUploadUrl

CKEDITOR.replace( 'editor1', {
    filebrowserUploadUrl: "upload/upload.php" 
} );

And the Upload.php file

if (file_exists("images/" . $_FILES["upload"]["name"]))
{
 echo $_FILES["upload"]["name"] . " already exists. ";
}
else
{
 move_uploaded_file($_FILES["upload"]["tmp_name"],
 "images/" . $_FILES["upload"]["name"]);
 echo "Stored in: " . "images/" . $_FILES["upload"]["name"];
}

ImportError: numpy.core.multiarray failed to import

I used Anaconda environment and had the same issue. I tried all the aforementioned approaches and, alas, it didn't help me. Accumulated the suggestions, here the way which helped me:

  1. Delete all NumPy folders in the virtual environment or in the system if you don't use a virtual environment, for example in my case:

    ~/home/anaconda3/envs//lib/python/site-packages/numpy

    ~/home/anaconda3/envs//lib/python/site-packages/numpy.libs

    ~/home/anaconda3/envs//lib/python/site-packages/numpy-.dist-info

  2. Install new Numpy with:

    pip install numpy -U

Hope, it could help in the same case

How to hide Android soft keyboard on EditText

The soft keyboard kept rising even though I set EditorInfo.TYPE_NULL to the view. None of the answers worked for me, except the idea I got from nik431's answer:

editText.setCursorVisible(false);
editText.setFocusableInTouchMode(false);
editText.setFocusable(false);

Fitting a density curve to a histogram in R

Such thing is easy with ggplot2

library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5), 
                            rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..)) + 
  geom_density()

or to mimic the result from Dirk's solution

ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..), binwidth = 5) + 
  geom_density()

How to replace multiple white spaces with one white space

string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");

Initialising an array of fixed size in python

One thing I find easy to do is i set an array of empty strings for the size I prefer, for example

Code:

import numpy as np

x= np.zeros(5,str)
print x

Output:

['' '' '' '' '']

Hope this is helpful :)

How do I set hostname in docker-compose?

The simplest way I have found is to just set the container name in the docker-compose.yml See container_name documentation. It is applicable to docker-compose v1+. It works for container to container, not from the host machine to container.

services:
  dns:
    image: phensley/docker-dns
    container_name: affy

Now you should be able to access affy from other containers using the container name. I had to do this for multiple redis servers in a development environment.

NOTE The solution works so long as you don't need to scale. Such as consistant individual developer environments.

How to create a timer using tkinter?

from tkinter import *

from tkinter import messagebox

root = Tk()

root.geometry("400x400")

root.resizable(0, 0)

root.title("Timer")

seconds = 21

def timer():

    global seconds
    if seconds > 0:
        seconds = seconds - 1
        mins = seconds // 60
        m = str(mins)

        if mins < 10:
            m = '0' + str(mins)
        se = seconds - (mins * 60)
        s = str(se)

        if se < 10:
            s = '0' + str(se)
        time.set(m + ':' + s)
        timer_display.config(textvariable=time)
        # call this function again in 1,000 milliseconds
        root.after(1000, timer)

    elif seconds == 0:
        messagebox.showinfo('Message', 'Time is completed')
        root.quit()


frames = Frame(root, width=500, height=500)

frames.pack()

time = StringVar()

timer_display = Label(root, font=('Trebuchet MS', 30, 'bold'))

timer_display.place(x=145, y=100)

timer()  # start the timer

root.mainloop()

What is the difference between Hibernate and Spring Data JPA

There are 3 different things we are using here :

  1. JPA : Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
  2. Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
  3. Spring Data JPA : This is another layer on top of jpa which spring provide to make your life easy.

So lets understand how spring data jpa and spring + hibernate works-


Spring Data JPA:

Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.

Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.

Rmi connection refused with localhost

It seems to work when I replace the

Runtime.getRuntime().exec("rmiregistry 2020");

by

LocateRegistry.createRegistry(2020);

anyone an idea why? What's the difference?

Hide div element when screen size is smaller than a specific size

You can do this with CSS:

@media only screen and (max-width: 1026px) {
    #fadeshow1 {
        display: none;
    }
}

We're using max-width, because we want to make an exception to the CSS, when a screen is smaller than the 1026px. min-width would make the CSS rule count for all screens of 1026px width and larger.

Something to keep in mind is that @media queries are not supported on IE8 and lower.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

If you are working with Source safe then make a new directory and take the latest there, this solved my issue...thanks

Including another class in SCSS

Combine Mixin with Extend

I just stumbled upon a combination of Mixin and Extend:

reused blocks:

.block1 { box-shadow: 0 5px 10px #000; }

.block2 { box-shadow: 5px 0 10px #000; }

.block3 { box-shadow: 0 0 1px #000; }

dynamic mixin:

@mixin customExtend($class){ @extend .#{$class}; }

use mixin:

like: @include customExtend(block1);

h1 {color: fff; @include customExtend(block2);}

Sass will compile only the mixins content to the extended blocks, which makes it able to combine blocks without generating duplicate code. The Extend logic only puts the classname of the Mixin import location in the block1, ..., ... {box-shadow: 0 5px 10px #000;}

How to use a switch case 'or' in PHP

Match expression (PHP 8)

PHP 8 RFC introduced a new match expression that is similar to switch but with the shorter syntax:

  • doesn't require break statements
  • combine conditions using a comma
  • returns a value

Example:

match ($value) {
  0 => '0',
  1, 2 => "1 or 2",
  default => "3",
}

What is a handle in C++?

A handle is a sort of pointer in that it is typically a way of referencing some entity.

It would be more accurate to say that a pointer is one type of handle, but not all handles are pointers.

For example, a handle may also be some index into an in memory table, which corresponds to an entry that itself contains a pointer to some object.

The key thing is that when you have a "handle", you neither know nor care how that handle actually ends up identifying the thing that it identifies, all you need to know is that it does.

It should also be obvious that there is no single answer to "what exactly is a handle", because handles to different things, even in the same system, may be implemented in different ways "under the hood". But you shouldn't need to be concerned with those differences.

Escape double quote character in XML

Here are the common characters which need to be escaped in XML, starting with double quotes:

  1. double quotes (") are escaped to &quot;
  2. ampersand (&) is escaped to &amp;
  3. single quotes (') are escaped to &apos;
  4. less than (<) is escaped to &lt;
  5. greater than (>) is escaped to &gt;

android : Error converting byte to dex

I've noticed this can happen (sometimes) when editing java files while Android Studio is building.

I solved this by manually deleting the build folder and running agin.

ASP.NET MVC: What is the purpose of @section?

A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.

How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?

You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.

What is the cleanest way to get the progress of JQuery ajax request?

http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html

I was searching for a similar solution and found this one use full.

var es;

function startTask() {
    es = new EventSource('yourphpfile.php');

//a message is received
es.addEventListener('message', function(e) {
    var result = JSON.parse( e.data );

    console.log(result.message);       

    if(e.lastEventId == 'CLOSE') {
        console.log('closed');
        es.close();
        var pBar = document.getElementById('progressor');
        pBar.value = pBar.max; //max out the progress bar
    }
    else {

        console.log(response); //your progress bar action
    }
});

es.addEventListener('error', function(e) {
    console.log('error');
    es.close();
});

}

and your server outputs

header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache'); 

function send_message($id, $message, $progress) {
    $d = array('message' => $message , 'progress' => $progress); //prepare json

    echo "id: $id" . PHP_EOL;
    echo "data: " . json_encode($d) . PHP_EOL;
    echo PHP_EOL;

   ob_flush();
   flush();
}


//LONG RUNNING TASK
 for($i = 1; $i <= 10; $i++) {
    send_message($i, 'on iteration ' . $i . ' of 10' , $i*10); 

    sleep(1);
 }

send_message('CLOSE', 'Process complete');

jQuery 'input' event

As claustrofob said, oninput is supported for IE9+.

However, "The oninput event is buggy in Internet Explorer 9. It is not fired when characters are deleted from a text field through the user interface only when characters are inserted. Although the onpropertychange event is supported in Internet Explorer 9, but similarly to the oninput event, it is also buggy, it is not fired on deletion.

Since characters can be deleted in several ways (Backspace and Delete keys, CTRL + X, Cut and Delete command in context menu), there is no good solution to detect all changes. If characters are deleted by the Delete command of the context menu, the modification cannot be detected in JavaScript in Internet Explorer 9."

I have good results binding to both input and keyup (and keydown, if you want it to fire in IE while holding down the Backspace key).

How do I store an array in localStorage?

localStorage only supports strings. Use JSON.stringify() and JSON.parse().

var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));

//...
var storedNames = JSON.parse(localStorage.getItem("names"));

How to export table as CSV with headings on Postgresql?

For version 9.5 I use, it would be like this:

COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);

How to take the first N items from a generator or list?

Do you mean the first N items, or the N largest items?

If you want the first:

top5 = sequence[:5]

This also works for the largest N items, assuming that your sequence is sorted in descending order. (Your LINQ example seems to assume this as well.)

If you want the largest, and it isn't sorted, the most obvious solution is to sort it first:

l = list(sequence)
l.sort(reverse=True)
top5 = l[:5]

For a more performant solution, use a min-heap (thanks Thijs):

import heapq
top5 = heapq.nlargest(5, sequence)

How do I delete everything below row X in VBA/Excel?

It sounds like something like the below will suit your needs:

With Sheets("Sheet1")
    .Rows( X & ":" & .Rows.Count).Delete
End With

Where X is a variable that = the row number ( 415 )

How to use the start command in a batch file?

I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?

Basically, you use the /B and /C options:

START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1

Maven: How to change path to target directory from command line?

Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:

    <profile>
        <id>alternateBuildDir</id>
        <activation>
            <property>
                <name>alt.build.dir</name>
            </property>
        </activation>
        <build>
            <directory>${alt.build.dir}</directory>
        </build>
    </profile>

Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

Refer to openpyxl document, you can do changes as followings.

from openpyxl import Workbook
from openpyxl.drawing.image import Image

wb = Workbook()
ws = wb.active
ws['A1'] = 'Insert a xxx.PNG'
# Reload an image
img = Image(**r**'x:\xxx\xxx\xxx.png')
# Insert to worksheet and anchor next to cells
ws.add_image(img, 'A2')
wb.save(**r**'x:\xxx\xxx.xlsx')

How to reverse apply a stash?

I had a similar issue myself, I think all you need to do is git reset --hard and you will not lose your changes or any untracked changes.

If you read the docs in git stash --help it states that apply is "Like pop, but do not remove the state from the stash list" so the state still resides there, you can get it back.

Alternatively, if you have no conflicts, you can just git stash again after testing your changes.

If you do have conflicts, don't worry, git reset --hard won't lose them, as "Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards."

how to clear JTable

This is the fastest and easiest way that I have found;

while (tableModel.getRowCount()>0)
          {
             tableModel.removeRow(0);
          }

This clears the table lickety split and leaves it ready for new data.

How to generate a QR Code for an Android application?

Maybe this old topic but i found this library is very helpful and easy to use

QRGen

example for using it in android

 Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);

Simple way to get element by id within a div tag?

A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.

You could change your HTML to this:

<div id="div1" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>
<div id="div2" >
    <input type="text" class="edit1" />
    <input type="text" class="edit2" />
</div>

Then, you could get the first item in div1 with a CSS selector like this:

#div1 .edit1

On in jQuery:

$("#div1 .edit1")

Or, if you want to iterate the items in one of your divs, you can do it like this:

$("#div1 input").each(function(index) {
    // do something with one of the input objects
});

If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.

If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.

You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

MySQLi count(*) always returns 1

Always try to do an associative fetch, that way you can easy get what you want in multiple case result

Here's an example

$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";

how to read value from string.xml in android?

Update

  • You can use getString(R.string.some_string_id) in both Activity or Fragment.
  • You can use Context.getString(R.string.some_string_id) where you don't have direct access to getString() method. Like Dialog.

Problem is where you don't have Context access, like a method in your Util class.

Assume below method without Context.

public void someMethod(){
    ...
    // can't use getResource() or getString() without Context.
}

Now you will pass Context as a parameter in this method and use getString().

public void someMethod(Context context){
    ...
    context.getString(R.string.some_id);
}

What i do is

public void someMethod(){
    ...
    App.getRes().getString(R.string.some_id)
}

What? It is very simple to use anywhere in your app!

So here is a Bonus unique solution by which you can access resources from anywhere like Util class .

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getResourses() {
        return res;
    }

}

Add name field to your manifest.xml <application tag.

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go.

SQL multiple columns in IN clause

It often ends up being easier to load your data into the database, even if it is only to run a quick query. Hard-coded data seems quick to enter, but it quickly becomes a pain if you start having to make changes.

However, if you want to code the names directly into your query, here is a cleaner way to do it:

with names (fname,lname) as (
    values
        ('John','Smith'),
        ('Mary','Jones')
)
select city from user
    inner join names on
        fname=firstName and
        lname=lastName;

The advantage of this is that it separates your data out of the query somewhat.

(This is DB2 syntax; it may need a bit of tweaking on your system).

Android: Go back to previous activity

All new activities/intents by default have back/previous behavior, unless you have coded a finish() on the calling activity.

How to compile Tensorflow with SSE4.2 and AVX instructions?

I just ran into this same problem, it seems like Yaroslav Bulatov's suggestion doesn't cover SSE4.2 support, adding --copt=-msse4.2 would suffice. In the end, I successfully built with

bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.2 --config=cuda -k //tensorflow/tools/pip_package:build_pip_package

without getting any warning or errors.

Probably the best choice for any system is:

bazel build -c opt --copt=-march=native --copt=-mfpmath=both --config=cuda -k //tensorflow/tools/pip_package:build_pip_package

(Update: the build scripts may be eating -march=native, possibly because it contains an =.)

-mfpmath=both only works with gcc, not clang. -mfpmath=sse is probably just as good, if not better, and is the default for x86-64. 32-bit builds default to -mfpmath=387, so changing that will help for 32-bit. (But if you want high-performance for number crunching, you should build 64-bit binaries.)

I'm not sure what TensorFlow's default for -O2 or -O3 is. gcc -O3 enables full optimization including auto-vectorization, but that sometimes can make code slower.


What this does: --copt for bazel build passes an option directly to gcc for compiling C and C++ files (but not linking, so you need a different option for cross-file link-time-optimization)

x86-64 gcc defaults to using only SSE2 or older SIMD instructions, so you can run the binaries on any x86-64 system. (See https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html). That's not what you want. You want to make a binary that takes advantage of all the instructions your CPU can run, because you're only running this binary on the system where you built it.

-march=native enables all the options your CPU supports, so it makes -mavx512f -mavx2 -mavx -mfma -msse4.2 redundant. (Also, -mavx2 already enables -mavx and -msse4.2, so Yaroslav's command should have been fine). Also if you're using a CPU that doesn't support one of these options (like FMA), using -mfma would make a binary that faults with illegal instructions.

TensorFlow's ./configure defaults to enabling -march=native, so using that should avoid needing to specify compiler options manually.

-march=native enables -mtune=native, so it optimizes for your CPU for things like which sequence of AVX instructions is best for unaligned loads.

This all applies to gcc, clang, or ICC. (For ICC, you can use -xHOST instead of -march=native.)

How to send an email with Gmail as provider using Python?

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("fromaddress", "password")
msg = "HI!"
server.sendmail("fromaddress", "receiveraddress", msg)
server.quit()

How to fix missing dependency warning when using useEffect React Hook?

You can set it directly as the useEffect callback:

useEffect(fetchBusinesses, [])

It will trigger only once, so make sure all the function's dependencies are correctly set (same as using componentDidMount/componentWillMount...)


Edit 02/21/2020

Just for completeness:

1. Use function as useEffect callback (as above)

useEffect(fetchBusinesses, [])

2. Declare function inside useEffect()

useEffect(() => {
  function fetchBusinesses() {
    ...
  }
  fetchBusinesses()
}, [])

3. Memoize with useCallback()

In this case, if you have dependencies in your function, you will have to include them in the useCallback dependencies array and this will trigger the useEffect again if the function's params change. Besides, it is a lot of boilerplate... So just pass the function directly to useEffect as in 1. useEffect(fetchBusinesses, []).

const fetchBusinesses = useCallback(() => {
  ...
}, [])
useEffect(() => {
  fetchBusinesses()
}, [fetchBusinesses])

4. Disable eslint's warning

useEffect(() => {
  fetchBusinesses()
}, []) // eslint-disable-line react-hooks/exhaustive-deps

Bootstrap 3 scrollable div for table

Well one way to do it is set the height of your body to the height that you want your page to be. In this example I did 600px.

Then set your wrapper height to a percentage of the body here I did 70% This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.

body {
   padding-top: 70px;
   border:1px solid black;
   height:600px;
}

.mygrid-wrapper-div {
   border: solid red 5px;
   overflow: scroll;
   height: 70%;
}

http://jsfiddle.net/4NB2N/7/

Update How about a jQuery approach.

$(function() {  
   var window_height = $(window).height(),
   content_height = window_height - 200;
   $('.mygrid-wrapper-div').height(content_height);
});

$( window ).resize(function() {
   var window_height = $(window).height(),
   content_height = window_height - 200;
   $('.mygrid-wrapper-div').height(content_height);
});

http://jsfiddle.net/4NB2N/11/

mysql: SOURCE error 2?

Remove spaces in the folder names of the path, It worked for my mac path.

(Eg: change the folder name MySQL Server 5.1 to MySQLServer5.1)

Passing enum or object through an intent (the best solution)

I like simple.

  • The Fred activity has two modes -- HAPPY and SAD.
  • Create a static IntentFactory that creates your Intent for you. Pass it the Mode you want.
  • The IntentFactory uses the name of the Mode class as the name of the extra.
  • The IntentFactory converts the Mode to a String using name()
  • Upon entry into onCreate use this info to convert back to a Mode.
  • You could use ordinal() and Mode.values() as well. I like strings because I can see them in the debugger.

    public class Fred extends Activity {
    
        public static enum Mode {
            HAPPY,
            SAD,
            ;
        }
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.betting);
            Intent intent = getIntent();
            Mode mode = Mode.valueOf(getIntent().getStringExtra(Mode.class.getName()));
            Toast.makeText(this, "mode="+mode.toString(), Toast.LENGTH_LONG).show();
        }
    
        public static Intent IntentFactory(Context context, Mode mode){
            Intent intent = new Intent();
            intent.setClass(context,Fred.class);
            intent.putExtra(Mode.class.getName(),mode.name());
    
            return intent;
        }
    }
    

Generate a sequence of numbers in Python

Write a function that takes a number as an argument and prints the Fibonacci series till that number

def Series(n):  
    a = 0  
    b = 1  
    print(a)  
    print(b)  
    S = 0  
    for i in range(0,n):  
        if S <= n-1:  
            S = a + b  
            print(S)  
            a = b  
            b = S

How can I delete all cookies with JavaScript?

On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.

Try this:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

All of this with the following caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.

window.onload vs document.onload

According to Parsing HTML documents - The end,

  1. The browser parses the HTML source and runs deferred scripts.

  2. A DOMContentLoaded is dispatched at the document when all the HTML has been parsed and have run. The event bubbles to the window.

  3. The browser loads resources (like images) that delay the load event.

  4. A load event is dispatched at the window.

Therefore, the order of execution will be

  1. DOMContentLoaded event listeners of window in the capture phase
  2. DOMContentLoaded event listeners of document
  3. DOMContentLoaded event listeners of window in the bubble phase
  4. load event listeners (including onload event handler) of window

A bubble load event listener (including onload event handler) in document should never be invoked. Only capture load listeners might be invoked, but due to the load of a sub-resource like a stylesheet, not due to the load of the document itself.

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('window - DOMContentLoaded - capture'); // 1st_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('document - DOMContentLoaded - capture'); // 2nd_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('document - DOMContentLoaded - bubble'); // 2nd_x000D_
});_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('window - DOMContentLoaded - bubble'); // 3rd_x000D_
});_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
  console.log('window - load - capture'); // 4th_x000D_
}, true);_x000D_
document.addEventListener('load', function(e) {_x000D_
  /* Filter out load events not related to the document */_x000D_
  if(['style','script'].indexOf(e.target.tagName.toLowerCase()) < 0)_x000D_
    console.log('document - load - capture'); // DOES NOT HAPPEN_x000D_
}, true);_x000D_
document.addEventListener('load', function() {_x000D_
  console.log('document - load - bubble'); // DOES NOT HAPPEN_x000D_
});_x000D_
window.addEventListener('load', function() {_x000D_
  console.log('window - load - bubble'); // 4th_x000D_
});_x000D_
_x000D_
window.onload = function() {_x000D_
  console.log('window - onload'); // 4th_x000D_
};_x000D_
document.onload = function() {_x000D_
  console.log('document - onload'); // DOES NOT HAPPEN_x000D_
};
_x000D_
_x000D_
_x000D_

Oracle copy data to another table

Creating a table and copying the data in a single command:

create table T_NEW as
  select * from T;

* This will not copy PKs, FKs, Triggers, etc.

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

Unfortunately MyApp has stopped. How can I solve this?

This answer describes the process of retrieving the stack trace. Already have the stack trace? Read up on stack traces in "What is a stack trace, and how can I use it to debug my application errors?"

The Problem

Your application quit because an uncaught RuntimeException was thrown.
The most common of these is the NullPointerException.

How to solve it?

Every time an Android application crashes (or any Java application for that matter), a Stack trace is written to the console (in this case, logcat). This stack trace contains vital information for solving your problem.

Android Studio

Finding the stack trace in Android Studio

In the bottom bar of the window, click on the Logcat button. Alternatively, you can press alt+6. Make sure your emulator or device is selected in the Devices panel. Next, try to find the stack trace, which is shown in red. There may be a lot of stuff logged into logcat, so you may need to scroll a bit. An easy way to find the stack trace is to clear the logcat (using the recycle bin on the right), and let the app crash again.

I have found the stack trace, now what?

Yay! You're halfway to solving your problem.
You only need to find out what exactly made your application crash, by analyzing the stack trace.

Read up on stack traces in "What is a stack trace, and how can I use it to debug my application errors?"

I still can't solve my problem!

If you've found your Exception and the line where it occurred, and still cannot figure out how to fix it, don't hesitate to ask a question on StackOverflow.

Try to be as concise as possible: post the stack trace, and the relevant code (e.g. a few lines up to the line which threw the Exception).

How to plot a function curve in R

plot has a plot.function method

plot(eq, 1, 1000)

Or

curve(eq, 1, 1000)

C/C++ macro string concatenation

If they're both strings you can just do:

#define STR3 STR1 STR2

This then expands to:

#define STR3 "s" "1"

and in the C language, separating two strings with space as in "s" "1" is exactly equivalent to having a single string "s1".

Render Partial View Using jQuery in ASP.NET MVC

You'll need to create an Action on your Controller that returns the rendered result of the "UserDetails" partial view or control. Then just use an Http Get or Post from jQuery to call the Action to get the rendered html to be displayed.

Is there a way to disable initial sorting for jquery DataTables?

Try this:

$(document).ready( function () {
  $('#example').dataTable({
    "order": []
  });
});

this will solve your problem.

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

I have 2 accounts on my windows machine and I was experiencing this problem with one of them. I did not want to use the sa account, I wanted to use Windows login. It was not immediately obvious to me that I needed to simply sign into the other account that I used to install SQL Server, and add the permissions for the new account from there

(SSMS > Security > Logins > Add a login there)

Easy way to get the full domain name you need to add there open cmd echo each one.

echo %userdomain%\%username%

Add a login for that user and give it all the permissons for master db and other databases you want. When I say "all permissions" make sure NOT to check of any of the "deny" permissions since that will do the opposite.

JQuery .hasClass for multiple values in an if statement

You just had some messed up parentheses in your 2nd attempt.

var $html = $("html");

if ($html.hasClass('m320') || $html.hasClass('m768')) {

  // do stuff 

}

PHP "pretty print" json_encode

Here's a function to pretty up your json: pretty_json

String contains - ignore case

If you won't go with regex:

"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())

Sending email from Azure

If you're looking for some ESP alternatives, you should have a look at Mailjet for Microsoft Azure too! As a global email service and infrastructure provider, they enable you to send, deliver and track transactional and marketing emails via their APIs, SMTP Relay or UI all from one single platform, thought both for developers and emails owners.

Disclaimer: I’m working at Mailjet as a Developer Evangelist.

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.

Changing password with Oracle SQL Developer

The built-in reset password option may not work for user. In this case the password can be reset using following SQL statement:

ALTER user "user" identified by "NewPassword" replace "OldPassword";

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

How to hide a div after some time period?

In older versions of jquery you'll have to do it the "javascript way" using settimeout

setTimeout( function(){$('div').hide();} , 4000);

or

setTimeout( "$('div').hide();", 4000);

Recently with jquery 1.4 this solution has been added:

$("div").delay(4000).hide();

Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

How to get the last value of an ArrayList

If you modify your list, then use listIterator() and iterate from last index (that is size()-1 respectively). If you fail again, check your list structure.

Correct way to work with vector of arrays

Use:

vector<vector<float>> vecArray; //both dimensions are open!

How to serialize Object to JSON?

You make the http request

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

import org.json.JSONObject;

Running java with JAVA_OPTS env variable has no effect

I don't know of any JVM that actually checks the JAVA_OPTS environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java command-line.

The key thing to understand here is that arguments to java that come before the -jar analyse.jar bit will only affect the JVM and won't be passed along to your program. So, modifying the java line in your script to:

java $JAVA_OPTS -jar analyse.jar $*

Should "just work".

What is the difference between PUT, POST and PATCH?

Difference between PUT, POST, GET, DELETE and PATCH IN HTTP Verbs:

The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them.

  1. create - POST
  2. read - GET
  3. update - PUT
  4. delete - DELETE

PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.

Note:
Since POST, PUT, DELETE modifies the content, the tests with Fiddler for the below url just mimicks the updations. It doesn't delete or modify actually. We can just see the status codes to check whether insertions, updations, deletions occur.

URL: http://jsonplaceholder.typicode.com/posts/

1) GET:

GET is the simplest type of HTTP request method; the one that browsers use each time you click a link or type a URL into the address bar. It instructs the server to transmit the data identified by the URL to the client. Data should never be modified on the server side as a result of a GET request. In this sense, a GET request is read-only.

Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.

Verb: GET

url: http://jsonplaceholder.typicode.com/posts/

Response: You will get the response as:

"userId": 1, "id": 1, "title": "sunt aut...", "body": "quia et suscipit..."

In the “happy” (or non-error) path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).

2) POST:

The POST verb is mostly utilized to create new resources. In particular, it's used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource.

On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.

Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.

Verb: POST

url: http://jsonplaceholder.typicode.com/posts/

Request Body:

data: { title: 'foo', body: 'bar', userId: 1000, Id : 1000 }

Response: You would receive the response code as 201.

If we want to check the inserted record with Id = 1000 change the verb to Get and use the same url and click Execute.

As said earlier, the above url only allows reads (GET), we cannot read the updated data in real.

3) PUT:

PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.

Verb: PUT

url: http://jsonplaceholder.typicode.com/posts/1

Request Body:

data: { title: 'foo', body: 'bar', userId: 1, Id : 1 }

Response: On successful update it returns 200 (or 204 if not returning any content in the body) from a PUT.

4) DELETE:

DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.

On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.

Checking with Fiddler or PostMan: We can use Fiddler for checking the response. Open Fiddler and select the Compose tab. Specify the verb and url as shown below and click Execute to check the response.

Verb: DELETE

url: http://jsonplaceholder.typicode.com/posts/1

Response: On successful deletion it returns HTTP status 200 (OK) along with a response body.

Example between PUT and PATCH

PUT

If I had to change my firstname then send PUT request for Update:

{ "first": "Nazmul", "last": "hasan" } So, here in order to update the first name we need to send all the parameters of the data again.

PATCH:

Patch request says that we would only send the data that we need to modify without modifying or effecting other parts of the data. Ex: if we need to update only the first name, we pass only the first name.

Please refer the below links for more information:

https://jsonplaceholder.typicode.com/

https://github.com/typicode/jsonplaceholder#how-to

What is the main difference between PATCH and PUT request?

http://www.restapitutorial.com/lessons/httpmethods.html

Any way to make plot points in scatterplot more transparent in R?

If you are using the hex codes, you can add two more digits at the end of the code to represent the alpha channel:

E.g. half-transparency red:

plot(1:100, main="Example of Plot With Transparency")
lines(1:100 + sin(1:100*2*pi/(20)), col='#FF000088', lwd=4)
mtext("use `col='#FF000088'` for the lines() function")

example plot of color with transparency

Test process.env with Jest

In test file:

const APP_PORT = process.env.APP_PORT || 8080;

In the test script of ./package.json:

"scripts": {
   "test": "jest --setupFiles dotenv/config",
 }

In ./env:

APP_PORT=8080

Force git stash to overwrite added files

Use git checkout instead of git stash apply:

$ git checkout stash -- .
$ git commit

This will restore all the files in the current directory to their stashed version.


If there are changes to other files in the working directory that should be kept, here is a less heavy-handed alternative:

$ git merge --squash --strategy-option=theirs stash

If there are changes in the index, or the merge will touch files with local changes, git will refuse to merge. Individual files can be checked out from the stash using

$ git checkout stash -- <paths...>

or interactively with

$ git checkout -p stash

How to Configure SSL for Amazon S3 bucket

If you really need it, consider redirections.

For example, on request to assets.my-domain.example.com/path/to/file you could perform a 301 or 302 redirection to my-bucket-name.s3.amazonaws.com/path/to/file or s3.amazonaws.com/my-bucket-name/path/to/file (please remember that in the first case my-bucket-name cannot contain any dots, otherwise it won't match *.s3.amazonaws.com, s3.amazonaws.com stated in S3 certificate).

Not tested, but I believe it would work. I see few gotchas, however.

The first one is pretty obvious, an additional request to get this redirection. And I doubt you could use redirection server provided by your domain name registrar — you'd have to upload proper certificate there somehow — so you have to use your own server for this.

The second one is that you can have urls with your domain name in page source code, but when for example user opens the pic in separate tab, then address bar will display the target url.

Why does modulus division (%) only work with integers?

You're looking for fmod().

I guess to more specifically answer your question, in older languages the % operator was just defined as integer modular division and in newer languages they decided to expand the definition of the operator.

EDIT: If I were to wager a guess why, I would say it's because the idea of modular arithmetic originates in number theory and deals specifically with integers.

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

Don't worry. Just uninstall jdk as well as jdk updates Before re installing jdk ,delete the oracle folder inside programData hidden folder in C:\ Then reinstall. Set the following,

JAVA_HOME
CLASSPATH
PATH
JRE_HOME ( is optional)

How to completely hide the navigation bar in iPhone / HTML5

Try the following:

  1. Add this meta tag in the head of your HTML file:

    <meta name="apple-mobile-web-app-capable" content="yes" />
    
  2. Open your site with Safari on iPhone, and use the bookmark feature to add your site to the home screen.

  3. Go back to home screen and open the bookmarked site. The URL and status bar will be gone.

As long as you only need to work with the iPhone, you should be fine with this solution.

In addition, your sample on the warnerbros.com site uses the Sencha touch framework. You can Google it for more information or check out their demos.

get the value of DisplayName attribute

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(foo);

foreach (PropertyDescriptor property in properties)
{
    if (property.Name == "Name")
    {
        Console.WriteLine(property.DisplayName); // Something To Name
    }
}

where foo is an instance of Class1

window.location.href and window.open () methods in JavaScript

  • window.open will open a new browser with the specified URL.

  • window.location.href will open the URL in the window in which the code is called.

Note also that window.open() is a function on the window object itself whereas window.location is an object that exposes a variety of other methods and properties.

How to select records from last 24 hours using SQL?

In Oracle (For last 24 hours):

SELECT  *
FROM    my_table
WHERE   date_column >= SYSDATE - 24/24

In case, for any reason, you have rows with future dates, you can use between, like this:

SELECT  *
FROM    my_table
WHERE   date_column BETWEEN (SYSDATE - 24/24) AND SYSDATE

How to convert a NumPy array to PIL image applying matplotlib colormap

  • input = numpy_image
  • np.unit8 -> converts to integers
  • convert('RGB') -> converts to RGB
  • Image.fromarray -> returns an image object

    from PIL import Image
    import numpy as np
    
    PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
    
    PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
    

Removing duplicates in the lists

You can use the following function:

def rem_dupes(dup_list): 
    yooneeks = [] 
    for elem in dup_list: 
        if elem not in yooneeks: 
            yooneeks.append(elem) 
    return yooneeks

Example:

my_list = ['this','is','a','list','with','dupicates','in', 'the', 'list']

Usage:

rem_dupes(my_list)

['this', 'is', 'a', 'list', 'with', 'dupicates', 'in', 'the']

Converting a date in MySQL from string field

Yes, there's str_to_date

mysql> select str_to_date("03/02/2009","%d/%m/%Y");
+--------------------------------------+
| str_to_date("03/02/2009","%d/%m/%Y") |
+--------------------------------------+
| 2009-02-03                           |
+--------------------------------------+
1 row in set (0.00 sec)

Initializing an Array of Structs in C#

Firstly, do you really have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with ValueTuple) but they're pretty rare in my experience.

Other than that, I'd just create a constructor taking the two bits of data:

class SomeClass
{

    struct MyStruct
    {
        private readonly string label;
        private readonly int id;

        public MyStruct (string label, int id)
        {
            this.label = label;
            this.id = id;
        }

        public string Label { get { return label; } }
        public string Id { get { return id; } }

    }

    static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
        (new[] {
             new MyStruct ("a", 1),
             new MyStruct ("b", 5),
             new MyStruct ("q", 29)
        });
}

Note the use of ReadOnlyCollection instead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs - it then just passes the reference to the constructor of ReadOnlyCollection<>.)

How to handle the `onKeyPress` event in ReactJS?

There are some challenges when it comes to keypress event. Jan Wolter's article on key events is a bit old but explains well why key event detection can be hard.

A few things to note:

  1. keyCode, which, charCode have different value/meaning in keypress from keyup and keydown. They are all deprecated, however supported in major browsers.
  2. Operating system, physical keyboards, browsers(versions) could all have impact on key code/values.
  3. key and code are the recent standard. However, they are not well supported by browsers at the time of writing.

To tackle keyboard events in react apps, I implemented react-keyboard-event-handler. Please have a look.

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

.htaccess not working on localhost with XAMPP

I've setup xampp for my localhost as well, I've not done anything with the files created by xampp during or after setup.

But in the '.htaccess' file, make sure you've set it to something like this. Works for me, and this should not make any difference for you.

RewriteEngine On
RewriteRule ^filename/?$ filename.html

Change .html to whatever format you're using.

Make sure your install is clean, and just make the .htaccess file. Also remember to put one .htaccess file for each directory (don't really know if you can use ONE file for all folders, but to be safe, just do this and it will always work.

Python pandas: how to specify data types when reading an Excel file?

Starting with v0.20.0, the dtype keyword argument in read_excel() function could be used to specify the data types that needs to be applied to the columns just like it exists for read_csv() case.

Using converters and dtype arguments together on the same column name would lead to the latter getting shadowed and the former gaining preferance.


1) Inorder for it to not interpret the dtypes but rather pass all the contents of it's columns as they were originally in the file before, we could set this arg to str or object so that we don't mess up our data. (one such case would be leading zeros in numbers which would be lost otherwise)

pd.read_excel('file_name.xlsx', dtype=str)            # (or) dtype=object

2) It even supports a dict mapping wherein the keys constitute the column names and values it's respective data type to be set especially when you want to alter the dtype for a subset of all the columns.

# Assuming data types for `a` and `b` columns to be altered
pd.read_excel('file_name.xlsx', dtype={'a': np.float64, 'b': np.int32})

Java random number with given length

For the follow-up question, you can get a number between 36^5 and 36^6 and convert it in base 36

UPDATED:

using this code

http://javaconfessions.com/2008/09/convert-between-base-10-and-base-62-in_28.html

It's written BaseConverterUtil.toBase36(60466176+r.nextInt(2116316160))

but in your use case, it can be optimized by using a StringBuilder and having the number in the reverse order ie 71 should be converted in Z1 instead of 1Z

EDITED:

How do I access my SSH public key?

cat ~/.ssh/id_rsa.pub or cat ~/.ssh/id_dsa.pub

You can list all the public keys you have by doing:

$ ls ~/.ssh/*.pub

How do I populate a JComboBox with an ArrayList?

Use the toArray() method of the ArrayList class and pass it into the constructor of the JComboBox

See the JavaDoc and tutorial for more info.

How to reset a form using jQuery with .reset() method

you may try using trigger() Reference Link

$('#form_id').trigger("reset");

jQuery vs. javascript?

"I actually tried to had a normal objective discusssion over pros and cons of 1., using framework over pure javascript and 2., jquery vs. others, since jQuery seems to be easiest to work with with quickest learning curve."

Using any framework because you don't want to actually learn the underlying language is absolutely wrong not only for JavaScript, but for any other programming language.

"Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?"

Most of the hate agains it comes from the exaggerated fanboyism which pollutes forums with "use jQuery" as an answer for every single JavaScript question and the overuse which produces code in which simple statements such as declaring a variable are done through library calls.

Nevertheless, there are also some legit technical issues such as the shared guilt in producing illegible code and overhead. Of course those two are aggravated by the lack of developer proficiency rather than the library itself.

Which characters are valid in CSS class names/selectors?

We can use all characters as class name. Even like # and . Just we have to escape it with \.

_x000D_
_x000D_
.test\.123 {
  color: red;
}

.test\#123 {
  color: blue;
}

.test\@123 {
  color: green;
}

.test\<123 {
  color: brown;
}

.test\`123 {
  color: purple;
}

.test\~123 {
  color: tomato;
}
_x000D_
<div class="test.123">test.123</div>
<div class="test#123">test#123</div>
<div class="test@123">test@123</div>
<div class="test<123">test<123</div>
<div class="test`123">test`123</div>
<div class="test~123">test~123</div>
_x000D_
_x000D_
_x000D_

Azure SQL Database "DTU percentage" metric

From this document, this DTU percent is determined by this query:

SELECT end_time,   
  (SELECT Max(v)    
   FROM (VALUES (avg_cpu_percent), (avg_data_io_percent), 
(avg_log_write_percent)) AS    
   value(v)) AS [avg_DTU_percent]   
FROM sys.dm_db_resource_stats;  

looks like the max of avg_cpu_percent, avg_data_io_percent and avg_log_write_percent

Reference:

https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-resource-stats-azure-sql-database

How to configure a HTTP proxy for svn

In TortoiseSVN you can configure the proxy server under Settings=> Network

When do I need a fb:app_id or fb:admins?

Including the fb:app_id tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.

The fb:admins tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.

You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.

fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>

and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>

php codeigniter count rows

You could use the helper function $query->num_rows()

It returns the number of rows returned by the query. You can use like this:

$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();

getting the difference between date in days in java

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }

Authenticating in PHP using LDAP through Active Directory

For those looking for a complete example check out http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/.

I have tested this connecting to both Windows Server 2003 and Windows Server 2008 R2 domain controllers from a Windows Server 2003 Web Server (IIS6) and from a windows server 2012 enterprise running IIS 8.

php - get numeric index of associative array


  $a = array(
      'blue' => 'nice',
      'car' => 'fast',
      'number' => 'none'
  );  
var_dump(array_search('car', array_keys($a)));
var_dump(array_search('blue', array_keys($a)));
var_dump(array_search('number', array_keys($a)));

What uses are there for "placement new"?

Head Geek: BINGO! You got it totally - that's exactly what it's perfect for. In many embedded environments, external constraints and/or the overall use scenario forces the programmer to separate the allocation of an object from its initialization. Lumped together, C++ calls this "instantiation"; but whenever the constructor's action must be explicitly invoked WITHOUT dynamic or automatic allocation, placement new is the way to do it. It's also the perfect way to locate a global C++ object that is pinned to the address of a hardware component (memory-mapped I/O), or for any static object that, for whatever reason, must reside at a fixed address.

What is perm space?

What exists under PremGen : Class Area comes under PremGen area. Static fields are also developed at class loading time, so they also exist in PremGen. Constant Pool area having all immutable fields that are pooled like String are kept here. In addition to that, class data loaded by class loaders, Object arrays, internal objects used by jvm are also located.

Reminder - \r\n or \n\r?

\r\n for Windows will do just fine.

How to copy a file to multiple directories using the gnu cp command

You can't do this with cp alone but you can combine cp with xargs:

echo dir1 dir2 dir3 | xargs -n 1 cp file1

Will copy file1 to dir1, dir2, and dir3. xargs will call cp 3 times to do this, see the man page for xargs for details.

How to send email using simple SMTP commands via Gmail?

Unfortunately as I am forced to use a windows server I have been unable to get openssl working in the way the above answer suggests.

However I was able to get a similar program called stunnel (which can be downloaded from here) to work. I got the idea from www.tech-and-dev.com but I had to change the instructions slightly. Here is what I did:

  1. Install telnet client on the windows box.
  2. Download stunnel. (I downloaded and installed a file called stunnel-4.56-installer.exe).
  3. Once installed you then needed to locate the stunnel.conf config file, which in my case I installed to C:\Program Files (x86)\stunnel
  4. Then, you need to open this file in a text viewer such as notepad. Look for [gmail-smtp] and remove the semicolon on the client line below (in the stunnel.conf file, every line that starts with a semicolon is a comment). You should end up with something like:

    [gmail-smtp]
    client = yes
    accept = 127.0.0.1:25
    connect = smtp.gmail.com:465
    

    Once you have done this save the stunnel.conf file and reload the config (to do this use the stunnel GUI program, and click on configuration=>Reload).

Now you should be ready to send email in the windows telnet client!
Go to Start=>run=>cmd.

Once cmd is open type in the following and press Enter:

telnet localhost 25

You should then see something similar to the following:

220 mx.google.com ESMTP f14sm1400408wbe.2

You will then need to reply by typing the following and pressing enter:

helo google

This should give you the following response:

250 mx.google.com at your service

If you get this you then need to type the following and press enter:

ehlo google

This should then give you the following response:

250-mx.google.com at your service, [212.28.228.49]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES

Now you should be ready to authenticate with your Gmail details. To do this type the following and press enter:

AUTH LOGIN

This should then give you the following response:

334 VXNlcm5hbWU6

This means that we are ready to authenticate by using our gmail address and password.

However since this is an encrypted session, we're going to have to send the email and password encoded in base64. To encode your email and password, you can use a converter program or an online website to encode it (for example base64 or search on google for ’base64 online encoding’). I reccomend you do not touch the cmd/telnet session again until you have done this.

For example [email protected] would become dGVzdEBnbWFpbC5jb20= and password would become cGFzc3dvcmQ=

Once you have done this copy and paste your converted base64 username into the cmd/telnet session and press enter. This should give you following response:

334 UGFzc3dvcmQ6

Now copy and paste your converted base64 password into the cmd/telnet session and press enter. This should give you following response if both login credentials are correct:

235 2.7.0 Accepted

You should now enter the sender email (should be the same as the username) in the following format and press enter:

MAIL FROM:<[email protected]>

This should give you the following response:

250 2.1.0 OK x23sm1104292weq.10

You can now enter the recipient email address in a similar format and press enter:

RCPT TO:<[email protected]>

This should give you the following response:

250 2.1.5 OK x23sm1104292weq.10

Now you will need to type the following and press enter:

DATA

Which should give you the following response:

354  Go ahead x23sm1104292weq.10

Now we can start to compose the message! To do this enter your message in the following format (Tip: do this in notepad and copy the entire message into the cmd/telnet session):

From: Test <[email protected]>
To: Me <[email protected]>
Subject: Testing email from telnet
This is the body

Adding more lines to the body message.

When you have finished the email enter a dot:

.

This should give you the following response:

250 2.0.0 OK 1288307376 x23sm1104292weq.10

And now you need to end your session by typing the following and pressing enter:

QUIT

This should give you the following response:

221 2.0.0 closing connection x23sm1104292weq.10
Connection to host lost.

And your email should now be in the recipient’s mailbox!

Working with TIFFs (import, export) in Python using numpy

You can also use pytiff of which I'm the author.

    import pytiff

    with pytiff.Tiff("filename.tif") as handle:
        part = handle[100:200, 200:400]

    # multipage tif
    with pytiff.Tiff("multipage.tif") as handle:
        for page in handle:
            part = page[100:200, 200:400]

It's a fairly small module and may not have as many features as other modules, but it supports tiled tiffs and bigtiff, so you can read parts of large images.

What is the maximum length of data I can put in a BLOB column in MySQL?

May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.

BLOB A string with a maximum length of 65535 characters.

The MySQL manual says:

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers

I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html

How to set adaptive learning rate for GradientDescentOptimizer?

Gradient descent algorithm uses the constant learning rate which you can provide in during the initialization. You can pass various learning rates in a way showed by Mrry.

But instead of it you can also use more advanced optimizers which have faster convergence rate and adapts to the situation.

Here is a brief explanation based on my understanding:

  • momentum helps SGD to navigate along the relevant directions and softens the oscillations in the irrelevant. It simply adds a fraction of the direction of the previous step to a current step. This achieves amplification of speed in the correct dirrection and softens oscillation in wrong directions. This fraction is usually in the (0, 1) range. It also makes sense to use adaptive momentum. In the beginning of learning a big momentum will only hinder your progress, so it makse sense to use something like 0.01 and once all the high gradients disappeared you can use a bigger momentom. There is one problem with momentum: when we are very close to the goal, our momentum in most of the cases is very high and it does not know that it should slow down. This can cause it to miss or oscillate around the minima
  • nesterov accelerated gradient overcomes this problem by starting to slow down early. In momentum we first compute gradient and then make a jump in that direction amplified by whatever momentum we had previously. NAG does the same thing but in another order: at first we make a big jump based on our stored information, and then we calculate the gradient and make a small correction. This seemingly irrelevant change gives significant practical speedups.
  • AdaGrad or adaptive gradient allows the learning rate to adapt based on parameters. It performs larger updates for infrequent parameters and smaller updates for frequent one. Because of this it is well suited for sparse data (NLP or image recognition). Another advantage is that it basically illiminates the need to tune the learning rate. Each parameter has its own learning rate and due to the peculiarities of the algorithm the learning rate is monotonically decreasing. This causes the biggest problem: at some point of time the learning rate is so small that the system stops learning
  • AdaDelta resolves the problem of monotonically decreasing learning rate in AdaGrad. In AdaGrad the learning rate was calculated approximately as one divided by the sum of square roots. At each stage you add another square root to the sum, which causes denominator to constantly decrease. In AdaDelta instead of summing all past square roots it uses sliding window which allows the sum to decrease. RMSprop is very similar to AdaDelta
  • Adam or adaptive momentum is an algorithm similar to AdaDelta. But in addition to storing learning rates for each of the parameters it also stores momentum changes for each of them separately

    A few visualizations: enter image description here enter image description here

How can I convert JSON to CSV?

This code should work for you, assuming that your JSON data is in a file called data.json.

import json
import csv

with open("data.json") as file:
    data = json.load(file)

with open("data.csv", "w") as file:
    csv_file = csv.writer(file)
    for item in data:
        fields = list(item['fields'].values())
        csv_file.writerow([item['pk'], item['model']] + fields)

split string in two on given index and return both parts

Try this

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

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

Caesar Cipher Function in Python

Using some ascii number tricks:

# See http://ascii.cl/
upper = {ascii:chr(ascii) for ascii in range(65,91)}
lower = {ascii:chr(ascii) for ascii in range(97,123)}
digit = {ascii:chr(ascii) for ascii in range(48,58)}


def ceasar(s, k):
    for c in s:
        o = ord(c)
        # Do not change symbols and digits
        if (o not in upper and o not in lower) or o in digit:
            yield o
        else:
            # If it's in the upper case and
            # that the rotation is within the uppercase
            if o in upper and o + k % 26 in upper:
                yield o + k % 26
            # If it's in the lower case and
            # that the rotation is within the lowercase
            elif o in lower and o + k % 26 in lower:
                yield o + k % 26
            # Otherwise move back 26 spaces after rotation.
            else: # alphabet.
                yield o + k % 26 -26

x = (''.join(map(chr, ceasar(s, k))))
print (x)

Programmatically Install Certificate into Mozilla

Firefox now (since 58) uses a SQLite database cert9.db instead of legacy cert8.db. I have made a fix to a solution presented here to make it work with new versions of Firefox:

certificateFile="MyCa.cert.pem"
certificateName="MyCA Name" 
for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert9.db")
do
  certDir=$(dirname ${certDB});
  #log "mozilla certificate" "install '${certificateName}' in ${certDir}"
  certutil -A -n "${certificateName}" -t "TCu,Cuw,Tuw" -i ${certificateFile} -d sql:${certDir}
done

Get a filtered list of files in a directory

Filenames with "jpg" and "png" extensions in "path/to/images":

import os
accepted_extensions = ["jpg", "png"]
filenames = [fn for fn in os.listdir("path/to/images") if fn.split(".")[-1] in accepted_extensions]

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

How do you remove a Cookie in a Java Servlet

Cookie[] cookies = request.getCookies();
if(cookies!=null)
for (int i = 0; i < cookies.length; i++) {
 cookies[i].setMaxAge(0);
}

did that not worked? This removes all cookies if response is send back.

Passing event and argument to v-on in Vue.js

If you want to access event object as well as data passed, you have to pass event and ticket.id both as parameters, like following:

HTML

<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">

Javascript

methods: {
  addToCart: function (event, id) {
    // use event here as well as id
    console.log('In addToCart')
    console.log(id)
  }
}

See working fiddle: https://jsfiddle.net/nee5nszL/

Edited: case with vue-router

In case you are using vue-router, you may have to use $event in your v-on:input method like following:

<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">

Here is working fiddle.

What is the best way to concatenate two vectors?

All the solutions are correct, but I found it easier just write a function to implement this. like this:

template <class T1, class T2>
void ContainerInsert(T1 t1, T2 t2)
{
    t1->insert(t1->end(), t2->begin(), t2->end());
}

That way you can avoid the temporary placement like this:

ContainerInsert(vec, GetSomeVector());

How to study design patterns?

For books, I would recommend Design Patterns Explained, and Head First Design patterns. To really learn these patterns, you should look at your existing code. Look for what patterns you are already using. Look at code smells and what patterns might solve them.

Correct way to detach from a container without stopping it

If you do "docker attach "container id" you get into the container. To exit from the container without stopping the container you need to enter Ctrl+P+Q

Do I need a content-type header for HTTP GET requests?

The problem with not passing over the content-type on a GET message is that sure the content-type is irrelevant because the server side determines the content anyway. The problem that I have encountered is that there are now a lot of places that set up their webservices to be smart enough to pick up the content-type that you pass and return the response in the 'type' that you request. Eg. we are currently messaging with a place that defaults to JSON, however, they have set their webservice up so that if you pass a content-type of xml they will then return xml rather than their JSON default. Which I think going forward is a great idea

What is the difference between "expose" and "publish" in Docker?

Most people use docker compose with networks. The documentation states:

The Docker network feature supports creating networks without the need to expose ports within the network, for detailed information see the overview of this feature).

Which means that if you use networks for communication between containers you don't need to worry about exposing ports.

VBA code to set date format for a specific column as "yyyy-mm-dd"

It works, when you use both lines:

Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"

Replace a value in a data frame based on a conditional (`if`) statement

The easiest way to do this in one command is to use which command and also need not to change the factors into character by doing this:

junk$nm[which(junk$nm=="B")]<-"b"

How do I add a simple jQuery script to WordPress?

Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever. You just need to make sure the path is correct. I suggest using something like this (assuming you are in your theme's directory).

<script type="javascript" href="<?php echo get_template_directory_uri();?>/your-file.js"></script>

A good practice is to include this right before the closing body tag or at least just prior to your footer. You can also use php includes, or several other methods of pulling this file in.

<script type="javascript"><?php include('your-file.js');?></script>

How to solve SyntaxError on autogenerated manage.py?

Have you entered the virtual environment for django? Run python -m venv myvenv if you have not yet installed.

Laravel Redirect Back with() Message

For Laravel 5.5+

Controller:

return redirect()->back()->with('success', 'your message here');

Blade:

@if (Session::has('success'))
    <div class="alert alert-success">
        <ul>
            <li>{{ Session::get('success') }}</li>
        </ul>
    </div>
@endif

How can I use async/await at the top level?

I can't seem to wrap my head around why this does not work.

Because main returns a promise; all async functions do.

At the top level, you must either:

  1. Use a top-level async function that never rejects (unless you want "unhandled rejection" errors), or

  2. Use then and catch, or

  3. (Coming soon!) Use top-level await, a proposal that has reached Stage 3 in the process that allows top-level use of await in a module.

#1 - Top-level async function that never rejects

(async () => {
    try {
        var text = await main();
        console.log(text);
    } catch (e) {
        // Deal with the fact the chain failed
    }
})();

Notice the catch; you must handle promise rejections / async exceptions, since nothing else is going to; you have no caller to pass them on to. If you prefer, you could do that on the result of calling it via the catch function (rather than try/catch syntax):

(async () => {
    var text = await main();
    console.log(text);
})().catch(e => {
    // Deal with the fact the chain failed
});

...which is a bit more concise (I like it for that reason).

Or, of course, don't handle errors and just allow the "unhandled rejection" error.

#2 - then and catch

main()
    .then(text => {
        console.log(text);
    })
    .catch(err => {
        // Deal with the fact the chain failed
    });

The catch handler will be called if errors occur in the chain or in your then handler. (Be sure your catch handler doesn't throw errors, as nothing is registered to handle them.)

Or both arguments to then:

main().then(
    text => {
        console.log(text);
    },
    err => {
        // Deal with the fact the chain failed
    }
);

Again notice we're registering a rejection handler. But in this form, be sure that neither of your then callbacks doesn't throw any errors, nothing is registered to handle them.

#3 top-level await in a module

You can't use await at the top level of a non-module script, but the top-level await proposal (Stage 3) allows you to use it at the top level of a module. It's similar to using a top-level async function wrapper (#1 above) in that you don't want your top-level code to reject (throw an error) because that will result in an unhandled rejection error. So unless you want to have that unhandled rejection when things go wrong, as with #1, you'd want to wrap your code in an error handler:

// In a module, once the top-level `await` proposal lands
try {
    var text = await main();
    console.log(text);
} catch (e) {
    // Deal with the fact the chain failed
}

Note that if you do this, any module that imports from your module will wait until the promise you're awaiting settles; when a module using top-level await is evaluated, it basically returns a promise to the module loader (like an async function does), which waits until that promise is settled before evaluating the bodies of any modules that depend on it.