mercredi 31 janvier 2018

How to get a random number each time the code is executed for replace?

I apologize if this is a repeat question - I've been sifting through "random" questions but none of the answers I've found have helped.

I'm writing a javascript function that looks at a webpage and replaces every instance of a price with a random string from an array I made. Each time I run my script on a webpage a different string is chosen from the array, but it chooses the same string for every instance of the replace method. How can I have each replace pick a random number? I actually had this working at one point but I had to change my code and now it repeats the same string.

Here is my code:

$("*").each( function() { //go through each paragraph
    var curr = $(this).html();

    var price = Math.floor(Math.random() * pricesArray.length);
    curr = curr.replace(/(\$[0-9]+\.[0-9]{2})+/g, pricesArray[price]);
    console.log(curr);
    $(this).html(curr); //update paragraph text
});

Thank you!




Is it really to use str_replace with new generated value?

I tried to replace a certain word with difference generated keys

This is my code, that replace all 1 with one similar key:

function generate($qtd){
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $qtd; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$text = "nksn 1 kn ksn1dfub fui b 1uwbq k1m;lml1nfsbfjbj susksfk b1woub js sl m;sn1fjs";
$le = 10;

echo str_replace('sn', generate($le), $text);

Help please, Thanks




Php check exist have how many random int numbers in string

I have rand function like;

$mynumbers = rand(1111,9999);
echo $mynumbers;

Example output is 3582

and I have another strings

$mystring = "Ja9Js78I4PhXiF464R6s7ov8IUF";  (Have 1 number, must be turn 1 (only 8 have))
$mystring2 = "Ja3Js73I4P1X5iF564R8s2ov8IUF"; (Have 4 numbers, must be turn 4 (have all of them))

And i want to know this with function ;

$mystring is have, how many numbers ? inside $mynumbers and how many time ? passed when this process ? How can i do it ?




Compare elements in two arrays and return True when one value is greater than the other using python

I'm trying to write a for loop in python that compares each ith element in one array px to the ith element in another array py. If the element in px is greater than or equal to that of py than I want to note that value as True or 1.

Here's some code.

import pandas as pd
import random

px = np.random.normal(loc=0, scale=1, size=1000)
py = np.random.normal(loc=0, scale=1, size=1000)

for x, y in zip(px, py):
    print("{}% {}".format(x, y))
    if px[i] >= py[i]:
       px['status'] = True
    if px[i] < py[i]:
       px['status'] = False

The final dataframe should look something like this:

px                py                status
-2.24239571e-01   -1.83834445e+00   False
1.20102447e+00    5.01755172e-03    False    
8.82060986e-02    -2.55639665e-02   True

I know I have some problems with my for loop.




Random Jagged Array issues

For a class I need to make a jagged array that randomly has anywhere between 3-15 lines with each of those lines randomly having anywhere between 1-20 numbers between 1-20 in them. Then I need to type out the array, type out the sum and average of each line and finally type out the sum and average of the entire array. This is what I made:

using System;
class zigzag
{
    class jagged
    {
        public int many;
        public int total;
        public double mo;
    }
    static void Main()
    {
        Random rnd = new Random();
        int N = rnd.Next(3, 16);
        int i, j;
        int[][] P = new int[N][];
        jagged[] hold = new jagged[N];
        for (i=0; i<N; i++)
        {
            hold[i].total = 0;
            hold[i].many =rnd.Next(1, 21);
            P[i] = new int[hold[i].many];
            for (j = 0; j < hold[i].many; i++)
            {
                P[i][j] = rnd.Next(10, 21);
                hold[i].total += P[i][j];
            }
            hold[i].mo = (double) hold[i].total / hold[i].many;
        }
        for (i=0; i<N; i++)
        {
            Console.Write(P[i][hold[i].many]);
            for (j=1; j<hold[i].many; j++)
            {
                Console.Write(",");
                Console.Write(P[i][j]);
            }
            Console.WriteLine();
        }
        int ttotal=0;
        double mmo=0.0;
        for (i=0; i<N; i++)
        {
            Console.WriteLine("Line {0} has a total of {1} and an average of {2}", i, hold[i].total, hold[i].mo);
            ttotal += hold[i].total;
            mmo += hold[i].mo;
        }
        mmo = mmo / N;
        Console.WriteLine("The total of all the lines is {0} and the average of all the lines is {1}",ttotal, mmo);
        Console.ReadKey();
    }
}

Whenever I try to run the program it crashes at line 19

hold[i].total = 0;

What am I doing wrong?




why HashSet is returning my element sorted?

I'm using Strings (long sentences) with HashSet and I'm trying to shuffle them to get a random sentence every time the program runs but this is not happening

public class testshuffle {

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            run();
        }
    }

    public static void run() {
        ArrayList<String> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        list.add("Alexandria And Mimy are good people");
        list.add("Bob And Alexandria are better than Mimy");
        list.add("Camelia And Johanness are better than Bob And Alexandria");

        shuffle(list, ThreadLocalRandom.current());
        set.addAll(list);
        System.out.println(set);
    }
}

I know HashSet order is not guaranteed, but when using Integer or Double, the hashCode returned would likely cause the element to be sorted.

But here I'm using Strings and the output is:

[Alexandria And Mimy are good people, Bob And Alexandria are better than Mimy, Camelia And Johanness are better than Bob And Alexandria]
[Alexandria And Mimy are good people, Bob And Alexandria are better than Mimy, Camelia And Johanness are better than Bob And Alexandria]
[Alexandria And Mimy are good people, Bob And Alexandria are better than Mimy, Camelia And Johanness are better than Bob And Alexandria]
[Alexandria And Mimy are good people, Bob And Alexandria are better than Mimy, Camelia And Johanness are better than Bob And Alexandria]
[Alexandria And Mimy are good people, Bob And Alexandria are better than Mimy, Camelia And Johanness are better than Bob And Alexandria]
[Alexandria And Mimy are good people, Bob And Alexandria are better than Mimy, Camelia And Johanness are better than Bob And Alexandria]
[Alexandria And Mimy are good people, Bob And Alexandria are better than Mimy, Camelia And Johanness are better than Bob And Alexandria]
.
.
.
[Alexandria And Mimy are good people, Bob And Alexandria are better than Mimy, Camelia And Johanness are better than Bob And Alexandria]

Please don't mark this as duplicate because this is different from the cases I found here




mardi 30 janvier 2018

Create a computer system which mimics the functionality of lottery?

I’m a beginner in programming and started in python language. I need some help to create a computer system which mimics the functionality of lottery. Each lottery draw requires six balls, numbered between 1 and 49 to be drawn, plus one “bonus ball” making a total of seven.
The balls are not replaced after each selection, so each number may only be selected once.

The following requirements specification was created for the application: - Seven random numbers should be selected – six regular numbers plus the bonus ball. - The numbers must be displayed to the user. - No randomly selected number should be repeated.




3 digit hexadecimal generator for Access Database

I am trying to figure out how to create a hexadecimal generator that always spits out 3 digits in C# and sends it to my access database. Here is the code that I found an example of on here and changed a little bit, but the generator sometimes only gives me 2 digits. What am I doing wrong?

Thank you,

        var r = new Random();
        int A = r.Next(100, 500);
        string hexValue1 = A.ToString("X");
        MessageBox.Show(hexValue1);




Comparisons in Multiple Sorting Algorithms

Currently this program will generate 10 random numbers and either sort (from least to greatest), reverse sort, or shuffle them. However, when trying to list the number of comparisons made, the number of comparisons printed out are completely incorrect. For example, it prints that there were 44 comparisons with bubble sort (this is the one that varies every time but is usually around 40), 45 with selection sort, and 9 with insertion sort. For now I'm only running the program with numbersSorted() just to make sure the comparisons work. How can I print the correct number of comparisons made with each sorting method?

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int count1 = 0; //bubble
int count2 = 0; //selection
int count3 = 0; //insertion

vector<int> numbersSorted(int n);
vector<int> numbersReversed(int n);
vector<int> numbersShuffled(int n);

int main() {
srand(time(0));



    numbersSorted(10);
  //numbersReversed(10);
  //numbersShuffled(10);


return 0;
}

vector<int> numbersSorted(int n)
{

vector <int> v(n);

for (auto &x : v)
    x = rand() % 100;

cout << "Original list to be sorted: ";
for (auto x : v)
    cout  << x << " ";
cout << "\n\n";

// bubble sort
bool swapped = true;
for (int pass = 0; pass <= n - 2 && swapped; ++pass)
{
    swapped = false;
    for (int i = 0; i <= n - pass - 2; ++i)
    {
        ++count1;
        if (v.at(i) > v.at(i + 1))
        {
            swap(v[i], v[i + 1]);
            swapped = true;
        }
    }
}
cout << "Bubble sort sorted: ";
for (auto x : v)
    cout << x << " ";
cout << "\n";
cout << "There were " << count1 << " comparisons with bubble sort.\n" << 
endl;

// selection sort
for (int pass = 0; pass <= n - 2; ++pass)
{
    // Find least element remaining in the list starting at index pass
    int minIndex = pass;
    // i = minIndex + 1, minIndex + 1, ..., n - 1
    for (int i = minIndex + 1; i < n; i++)
    {
        ++count2;

        if (v[i] < v[minIndex])
        {
            minIndex = i;

        }
            // The element at index i is smaller than what I thought was the 
min
    }

    swap(v[pass], v[minIndex]);
}
cout << "Selection sort sorted: ";
for (auto x : v)
    cout << x << " ";
cout << "\n";
cout << "There were " << count2 << " comparisons with selection sort.\n" << 
endl;


//insertion sort
for (int pass = 0; pass <= n - 2; ++pass) {
    // Take the element at pass+1 and move it to the left until it's in the
    // right spot (i.e., as long as it's in the wrong spot).

    // for i = pass, pass-1, ..., 0 while L[i] > L[i+1]
    ++count3;
    for (int i = pass; i >= 0 && v[i] > v[i + 1]; --i) {
        swap(v[i], v[i + 1]);
    }
}
cout << "Insertion sort sorted: ";
for (auto x : v)
    cout << x << " ";
cout << "\n";
cout << "There were " << count3 << " comparisons with insertion sort.\n" << 
endl;
//return v;
}
vector<int> numbersReversed(int n)
{
vector <int> v(n);

for (auto &x : v)
    x = rand() % 100;

cout << "Original list to be reversed: ";
for (auto x : v)
    cout << x << " ";
cout << "\n\n";


// bubble sort
bool swapped = true;
for (int pass = 0; pass <= n - 2 && swapped; ++pass)
{
    swapped = false;
    for (int i = 0; i <= n - pass - 2; ++i)
    {
        ++count1;
        if (v.at(i) > v.at(i + 1))
        {
            swap(v[i], v[i + 1]);
            swapped = true;
        }
    }
}

//reverse the content of the vector
reverse(v.begin(),v.end());

cout << "Bubble sort reversed: ";
for (auto x : v)
    cout << x << " ";
cout << "\n";
cout << "There were " << count1 << " comparisons with bubble sort.\n" << 
endl;


// selection sort
for (int pass = 0; pass <= n - 2; ++pass)
{
    // Find least element remaining in the list starting at index pass
    int minIndex = pass;
    // i = minIndex + 1, minIndex + 1, ..., n - 1
    for (int i = minIndex + 1; i < n; i++)
    {
        ++count2;
        if (v[i] < v[minIndex])
            // The element at index i is smaller than what I thought was the 
min
            minIndex = i;
    }

    swap(v[pass], v[minIndex]);
}

reverse(v.begin(),v.end());

cout << "Selection sort reversed: ";
for (auto x : v)
    cout << x << " ";
cout << "\n";
cout << "There were " << count2 << " comparisons with selection sort.\n" << 
endl;



// insertion sort
for (int pass = 0; pass <= n - 2; ++pass) {
    // Take the element at pass+1 and move it to the left until it's in the
    // right spot (i.e., as long as it's in the wrong spot).

    // for i = pass, pass-1, ..., 0 while L[i] > L[i+1]
    ++count3;
    for (int i = pass; i >= 0 && v[i] > v[i + 1]; --i) {
        swap(v[i], v[i + 1]);
    }
}

reverse(v.begin(),v.end());
cout << "Insertion sort reversed: ";
for (auto x : v)
    cout << x << " ";
cout << "\n";
cout << "There were " << count3 << " comparisons with insertion sort.\n" << 
endl;

}

vector<int> numbersShuffled(int n)
{
vector<int> v(n);

for (auto &x : v)
{
    x = rand() % 100;
    ++count1;
}


cout << "Numbers Shuffled: ";
for (auto x : v)
    cout << x << " ";
cout << "\n";
cout << "There were " << count1 << " comparisons made. " << endl;
}




Sum from random list in python

I have created a random list of 30 numbers, I don't know the numbers contained in the list. I'm asked to find any combination of three numbers from the list that sum to zero. What can I do?




how to interpret cuda performance

I have the following very simple code to test the performance of the standard curand library function. There are two kernels in the code: "init_rand" to initialize the random number generators for each threads and "generate_rand" to generate random numbers on each thread. The GPU I have is NVIDIA Tesla P100-PCIE-12GB. In the code, each thread generates 100*1024 random numbers (but does not write it into any array). By varying the number of blocks and threads per block, I timed the following performance.

  • 112 blocks, 1024 threads per block, time 22ms
  • 224 blocks, 512 threads per block, time 22ms
  • 448 blocks, 256 threads per block, time 22ms
  • 112 blocks, 512 threads per block, time 11ms

T think the first three results are reasonable as the total number of threads used are the same. However, I don't see why in the fourth row the time is reduced to half. The workload for each thread remains the same in these four tests (each thread generates 1024 * 100 numbers). But why the time is reduced when fewer numbers of thread are used? Does this have something to do with the memory?


#include<stdio.h>
#include"RNG.h"

#define BLOCK 56
#define THREAD 1024
#define SIZE (100 * 1024)

int main()
{
    /*SET UP RNG*/
    curandState_t *streams;
    cudaMalloc((void**)&streams, sizeof(curandState_t) * THREAD * BLOCK);
    init_rand<<<BLOCK, THREAD>>>(time(0), streams);

    /*Performance measure*/
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    cudaEventRecord(start, 0);

    /*The kernel*/
    generate_rand<<<BLOCK, THREAD>>>(streams, SIZE);

    /*Performance measure*/
    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    float elapsed_time;
    cudaEventElapsedTime(&elapsed_time, start, stop);
    printf("Time to generate: %3.1f micro-seconds\n", elapsed_time);
    cudaEventDestroy(start);
    cudaEventDestroy(stop);

    cudaFree(streams);
    return 0;
}

#include"RNG.h"
__global__ void init_rand(unsigned int seed, curandState_t* streams)
{
    int id = threadIdx.x + blockDim.x * blockIdx.x;
    curand_init(seed, id, 0, &streams[id]);
}

__global__ void generate_rand(curandState_t *streams, long size)
{
    int id = threadIdx.x + blockIdx.x * blockDim.x;
    int i = 0;
    while (i < size) {
            /*generate random numbers*/
            gen_single_rand(streams, id);
            i++;
    }
}

__device__ double gen_single_rand(curandState_t *streams, int id)
{
    double num;
    curandState_t local_state;
    local_state = streams[id];
    num = curand_uniform(&local_state);
    streams[id] = local_state;
    return num;
}




I can't select a random variable from a list [on hold]

For some reason I can't seem to select a variable from a list. I know my syntax is right, so any help would be appreciated. Here is the error

random.choice(Board)='X'

SyntaxError: can't assign to function call

Thanks!

import random
Board1 ='|'
Board2 ='|'
Board3 ='|'
Board4 ='|'
Board5 ='|'
Board6 ='|'
Board7 ='|'
Board8 ='|'
Board9 ='|'
Board=[Board1,Board2,Board3,Board4,Board5,Board6,Board7,Board8,Board9]
turn_count = 1
def printBoard():
    print(Board1 + ' ' + Board2 + ' ' + Board3)
    print(Board4 + ' ' + Board5 + ' ' + Board6)
    print(Board7 + ' ' + Board8 + ' ' + Board9)

print('The computer will go first, you are O')
if turn_count == 1:
    random.choice(Board)='X'
    printBoard()




lundi 29 janvier 2018

FCMP function giving unexpected results in PROC SQL

I wanted to take Rick Wicklin's macro (https://blogs.sas.com/content/iml/2015/10/05/random-integers-sas.html) that generates random numbers and convert it into an FCMP function. The FCMP function works as expected when called using %sysfunc(randbetween(1,100)); or via a data step, but from proc sql it always returns a value of 1.

proc fcmp outlib=work.funcs.funcs;
  function randbetween(min,max);
    return ( min + floor( ( 1 + max - min ) * rand("uniform") ) );
  endsub;
run;

Working example:

data example;
  do cnt=1 to 1000;
    x = randbetween(1,100);
    output;
  end;
run;

Broken SQL example:

proc sql noprint;
  create table have as
  select randbetween(1,100)
  from sashelp.class
  ;
quit;

Is this a bug? Or am I mis-using something?

SAS version is SAS9.4TS1M5. Windows 10x64.

EDIT: When I subsitute the formula directly into the SQL statement it works as expected, so it seems unrelated to the call to rand("uniform").




random.range not working in a variable

I am trying to make an intager a random number between 1 and the length of a list

code can be found here:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameControllerScript : MonoBehaviour {
public static List <int> Cards = new List <int>();
public int RndCard;
public static int CardNo;
public static bool Active = true;

void Start()
{
    Cards.Add(1);
    Cards.Add(2);
    Cards.Add(3);
}

void Update()
{
    print(Random.Range(1,Cards.Count));
    if(Active == false)
    {
        Active = true;
        RndCard = Random.Range(1,Cards.Count);
        CardNo = Cards[RndCard];
        Cards.RemoveAt(CardNo);
    }
}

the print statement works but the "RndCard" variable dosent even though they are neer enough the same statement




How to randomly sample web pages from a domain?

This may be the wrong place for this question and if so, please let me know and I'll delete it.

I'm trying to randomly sample x number of pages from a given domain. Say, for example, I'm looking at PubMed. Given just the URL https://www.ncbi.nlm.nih.gov/pubmed/, is there any way to grab subpages randomly?

I typically use Python for this sort of thing, but I'm up for any tools in any language to look into this further!




Best way to create a list with random int numbers with some criteria

I'd like to know what is the best way to create a list with random integer numbers, without repetition, and defining: how many even/odd, how many primer and how many multiple of 3 the list can have.

Exemple: I want a list with 20 numbers, between 1 to 100, with 5 odds and 5 primers and 4 multiple of 3.

Thank you for the help.




sample() in R unpredictable when vector length is one

I am trying to debug a short program, and I get a disconcerting result towards the end of sampling from the elements of a vector under some conditions. It happens as the elements of the vector that remain draw down to a single value.

In the specific case I'm referring to the vector is called remaining and contains a single element, the number 2. I would expect that any sampling of size 1 from this vector would stubbornly return 2, since 2 is the only element in the vector, but this is not the case:

Browse[2]> is.vector(remaining)
[1] TRUE
Browse[2]> sample(remaining,1)
[1] 2
Browse[2]> sample(remaining,1)
[1] 2
Browse[2]> sample(remaining,1)
[1] 1
Browse[2]> sample(x=remaining, size=1)
[1] 1
Browse[2]> sample(x=remaining, size=1)
[1] 2
Browse[2]> sample(x=remaining, size=1)
[1] 1
Browse[2]> sample(x=remaining, size=1)
[1] 1
Browse[2]> sample(x=remaining, size=1)
[1] 1

As you can see, sometimes the return is 1 and some others, 2.

What am I misunderstanding about the function sample()?




Problems testing a PRNG on NIST statistical test sp 800 - 22

I'm having problems with to understand the result of NIST statistical test sp 800 - 22. Acording to the user guide the results are available at finalAnalysisReport, but it diverges with others guides which tell us to access each one of the tests folders individually. Can anyone, please , enlighten me about this ?




python random.getstate() and random.setstate()

Learning the module random here, in the very beginning there are book-keeping functions, I understand that to set a specific seed is to make sure obtaining same random number.

but, what about the getstate() and setsate()? link In the documentation, it has no introduction for what this state means, and if I don't know what it means, how could I set it right?

random.getstate()

Return an object capturing the current internal state of the generator. This object can be passed to setstate() to restore the state.

random.setstate(state)

state should have been obtained from a previous call to getstate(), and setstate() restores the internal state of the generator to what it was at the time getstate() was called.

Thanks,




Is there a maximum character limit to random seed?

Is there a maximum number of characters (and therfore value) to the seed in Python?

import random
random.seed(13) # fine
random.seed(1234567890) # also fine
random.seed(31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989)
# also fine

I'm not sure why someone would pick such a high value, but I just want to know if has a limit.




Is it possible to generate random number?

I wonder if there is any way to generate a pseudo random number without using any system API in C? By without system API, I mean without using any Random generator API provided by framework or system APIs like currentMilliseconds etc.

int random(){

    // generate a random number R
    // how to generate R here?

    return R;
}




dimanche 28 janvier 2018

How to generate random salts that are differents on each application reboot JAVA

I'm currently trying to implement a password hash manager in Java. Looking for the best way to achieve this, I learned about salts.

This is the generateSalt function I've found :

public static byte[] generateSalt() throws NoSuchAlgorithmException {
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    byte[] salt = new byte[8];
    random.nextBytes(salt);
    return salt;
}

Then I simply tried this :

public class Application {
    public static void main(String[] args) {
        try {
            for(int i = 0; i < 10; i++) {
                System.out.println(PasswordHash.generateSalt());
            }
        }
        catch(Exception e) {
            System.out.println(e.getStackTrace());
        }
    }
}

Output is : B@135fbaa4 B@45ee12a7 B@330bedb4 B@2503dbd3 B@4b67cf4d B@7ea987ac B@12a3a380 B@29453f44 B@5cad8086 B@6e0be858 All of these are preceed by '['

So, first, I want a 8 bytes salt. It seems to work, but what are the first 3 bytes returned by the function ?

Second, if I restart my application, results remains the same. I've seen salt are unique for each users. So let's imagine I want to be able to create database users in my application. I create user 1, and generated salt is B@135fbaa4.

Then I restart my application and create user 2, so generated salt will be B@135fbaa4 too, right ?

Documentation said :

public void nextBytes(byte[] bytes)

Generates a user-specified number of random bytes.

If a call to setSeed had not occurred previously, the first call to this method forces this SecureRandom object to seed itself. This self-seeding will not occur if setSeed was previously called.

Is this seed the problem ? Feel like I've missed something.




Getting a c++11 library on an older version of c++?

A remote machine that I don't own uses gcc 4.1.2 (2007 or so). I'd like to use the random library and its functions, which comes with the c++11 standard. Is there some way I can use the contents of ? Can I dump all of into a custom header?

I lack understanding of libraries and wonder if there's a reasonable workaround for this situation.




How to take a list of strings randomly select one, and change it

I have this list in python, in each has a integer,

listofarea=[a1,a2,a3,a4,a5]

I need to take one then change one... but when I do,

area=random.choice(listofarea)

All you get is the number. hich means I can change the number but I cant change the string so...

if it picked a2 I would just get,

231

but I need it to say,

a2

Thanks in advance, O1lec1




I want a RNG to repeat itself if the number is false

I'm just testing around with C# and Random Number Generators (RNGs) and I want the RNG to repeat itself if the number isn't 1 but it won't work properly.

Random random = new Random();
        label1.Text = random.Next(0, 10).ToString();           

        if (label1.Text == "1")
            {
            label3.Text = "Positiv";
            }
        else
            {
            label1.Text = random.Next(0, 10).ToString();
            };




please help me with the following random code mysql:

I want to write random code. I have the following code, but I do not know how random the "id" variable is to be random variable. Please help me, I thank you.

{if $related neq 0}
<div class="media-meta">
<ul>
<li data-toggle="tooltip" data-placement="bottom"><i class="fa fa-reorder"></i>Danh sách Video liên quan</li></ul></div>
<div class="related">
<ul>
{section name=x loop=$related}
<li>
<a href="./media/{$related[x].id}/{$related[x].title|html_decode|slug}">
<div class="related-item-image">
<div class="related-duration">
{if isset($theme_display_media_video_site) AND $theme_display_media_video_site eq 1}<span class="{$related[x].video_site}-span related-site-span">{$lang_{$related[x].video_site}_select}</span>{/if}
<span class="related-time">{$related[x].duration|SecToMin}</span>
</div>
<img data-src="upload/media/{$related[x].thumbnail}" />
</div>
<div class="related-title">{$related[x].title|html_decode}</div>
</a>
</li>
{/section}
</ul>
</div>
{/if}



How to generate many random numbers in c++?

I just started learning C++ and SFML, and I'm writing game like doodle jump. I have three different platforms. My platforms are set randomly but... overlapped. Here's a screenshot. ---> 1

Here's part of my code. Plese by patient.

int main()
{

srand(time(NULL));

RenderWindow app(VideoMode(600, 600), "Doodle Game!");
app.setFramerateLimit(60);

Texture t1,t2,t3,t4,t5;
t1.loadFromFile("4.png");
t2.loadFromFile("platform.png");
t3.loadFromFile("cartoon.png");
t4.loadFromFile("rock.png");
t5.loadFromFile("wood.png");


Sprite sBackground(t1), sPlat(t2), sPlat1(t4), sPlat2(t5), sPers(t3);
sPers.setScale(0.3f, 0.3f);
sPlat.setScale(0.06f, 0.06f);
sPlat1.setScale(0.06f, 0.06f);
sPlat2.setScale(0.06f, 0.06f);

point plat[20];
point plat1[20];
point plat2[20];

for (int i=0;i<10;i++)
  {
   plat[i].x=rand()%600;
   plat[i].y=rand()%600;
   plat1[i].x=rand()%600;
   plat1[i].y=rand()%600;
   plat2[i].x=rand()%600;
   plat2[i].y=rand()%600;
  }




I'm trying to make a simple script that says two different two phrase lines(Python)

So, I'm just starting to program Python and I wanted to make a very simple script that will say something like "Gabe- Hello, my name is Gabe (Just an example of a sentence" + "Jerry- Hello Gabe, I'm Jerry" OR "Gabe- Goodbye, Jerry" + "Jerry- Goodbye, Gabe". Here's pretty much what I wrote.

 answers1 = [
"James-Hello, my name is James!"
]
answers2 = [
    "Jerry-Hello James, my name is Jerry!"
    ]
answers3 = [
    "Gabe-Goodbye, Samuel."
        ]
 answers4 = [
    "Samuel-Goodbye, Gabe"
    ]
Jack1 = (answers1 + answers2)
Jack2 = (answers3 + answers4)
Jacks = ([Jack1,Jack2])
import random
for x in range(2):
    a = random.randint(0,2)
    print (random.sample([Jacks, a]))

I'm quite sure it's a very simple fix, but as I have just started Python (Like, literally 2-3 days ago) I don't quite know what the problem would be. Here's my error message

Traceback (most recent call last):
File "C:/Users/Owner/Documents/Test Python 3.py", line 19, in <module>
print (random.sample([Jacks, a]))
TypeError: sample() missing 1 required positional argument: 'k'

If anyone could help me with this, I would very much appreciate it! Other than that, I shall be searching on ways that may be relevant to fixing this.




samedi 27 janvier 2018

I have a "video_id" column with 100 rows in mysql. How do I select a random row in this column?

[PHP RANDOM] My database has lots of rows and columns in mysql. For example:

id    | title | video_id
========================
1       a1q     1200921
2       atw     1628993
3       trw     2344516
4       poo     9115082
5       a2o     4782181
6       ppq     3336611
7       ntz     8772006
8       ewq     9005678
9       qpp     7582219
.....................
1005    tkk     7223378
.....................
100001  hww     8924467

I want to choose randomly a row. For example, I choose row id is 1. What code do I need to write?




MySQL - Copy data from one table into another in a random order

I have created a new table identical to the original one and I would like to copy all the data to the new table in a random way.

I use:

INSERT INTO `new_table` ('id', 'value') 
    SELECT 'id', 'value' FROM `original_table` ORDER BY RAND();

But as result I get new table in the same order as original one. For some reason RAND() is not working.




Constrained Randomization of data frame in R

I have a data frame like this :

 Tem    Time
 10a      1
 10a      2
 10a      3 
 10a      4 
 20a      1
 20a      2
 20a      3
 20a      4 
 #(10a and 10b are different treatment under the same Tem) 
 10b      1
 10b      2
 10b      3 
 10b      4 
 20b      1
 20b      2
 20b      3
 20b      4 

Now I want to do randomization to reduce experimental errors like this

 Tem     Time
 10a      1
 10a      2
 10a      3 
 10a      4 
 20a      4 #( not the same sequence for Time in 10a)
 20a      2
 20a      3
 20a      1 
 #(for b, not same sequence for a in Tem)
 20b      3
 20b      1
 20b      2
 20b      4 
 10b      1 #(not the same sequence for 20b)
 10b      3
 10b      2 
 10b      4 

At the end, I need to randomize all the 12 samples together. I know it is very complicated. Could you help me to do this or give me some hints? Thanks in advance!




how to get an output of 16 cards value but in a random way in c++

Q hearts Q diamonds Q spades Q clubs J hearts J diamonds J spades J clubs A hearts A diamonds A spades A clubs K hearts K diamonds K spades k clubs




How can I manually generate entropy with a python program?

The most commonly cited source of randomness is CrypAPI in Windows systems. Can I generate my own entropy from different sources without using this API in python? Any such library? I want to tinker with the generation process and learn a bit about RNG.




Is this the correct way to generate password salt?

I searched and found something like this on the internet. I was wondering if this is the correct implementation of the salt. (?) And how can implement scrypt in javafx (?)

public class Main {
        public  static String generateSalt(int length, String pass) throws NoSuchAlgorithmException {
            StringBuffer buffer=null;
            try {
                 buffer = new StringBuffer();
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
                char[] characterMap;
                characterMap = pass.toCharArray();
                for (int i = 0; i <= length; i++) {
                    byte[] bytes = new byte[16]; // 16 bytes = 128 bits
                    secureRandom.nextBytes(bytes);
                    double number = secureRandom.nextDouble();
                    int b = ((int) (number * characterMap.length));
                    buffer.append(characterMap[b]);
                }
            }catch(NoSuchAlgorithmException e){
                e.printStackTrace();
            }
            System.out.println(buffer.length());
            return buffer.toString();
        }


        public static void main(String[] args) throws NoSuchAlgorithmException {
            System.out.print(generateSalt(32,"javid"));
        }
    }




vendredi 26 janvier 2018

sklearn PCA random_state parameter function

I am using PCA to visualize clusters and noticed Sklearn added "random_state" parameter to the PCA method (http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html), my question is what does the random_state parameter do there?

My understanding is that PCA should return the same principle components despite the random state, so, what is the purpose of having it built in?




Random numbers in function .click

I wrote this:

$("div[style='top: 0px; opacity: 0.5;']").click();  

I want to 0 in top: 0px be random compartment from 0 to 1 with one place after the coma and text behind this will be like using it *, I mean any text behind this will be true.

I'm sorry for my bad english.




Better way to randomize from text file in Powershell

I have a working Powershell function that uses the System.Speech to read-out a random line from a text file, using the Get-Random cmdlet.

Unfortunately, the randomizer cmdlet doesn't seem to be doing such a good job by itself, as it repeats the same lines way too many times.

My text file contains just sentences.

function suggestion{
    $suggestion=(Get-Random -InputObject (get-content C:\Tools\linesoftext.txt))
    Add-Type -AssemblyName System.Speech 
    $synth = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
    $synth.Speak($suggestion)
    }

I'm not sure if I can modify what I have, or rethink the way I'm trying to randomize the output--maybe by keeping track of what has been already played and loop? (I'm a bit stumped).




Random number return the same numbers c++ [duplicate]

I want a vector that is filled automatically with random letters without repeating any, but whenever I compile the program it generates the same letters in the same positions

this is my code:

string alphabet[27] = { "A","B","C","D","E","F","G","H","I","J","K","L","M","N","Ñ","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
string vector[20];
int pos[20];
int r;
bool rep = false;

int main() {

    cout << "Generate vector" << endl;

    for (int i = 0; i < 20; i++) {

        do {
        rep = false;
        r = rand() % 27;
        vector[i] = alphabet[r];
        pos[i] = r;

                for (int j = 0; j < i; j++) {
                if (r == pos[j])
                    rep= true;
            }
        } while (rep == true);
    }

    for (int i = 0; i < 20; i++) {
        cout << i << " . " << vector[i] << endl;
    }

    _getch();

    return 0;
}




How do I generate a positive long integer in C#?

This is for storing in a database which doesn't have auto-increment primary keys. I want it to be positive to match standard id conventions.




KISS algorithm for javascript

Anyone here know any implementation of the algorithm KISS in javascript? I found some solutions in fortran 90 and c ++, but nothing in javascript




Replace NA values in a column in dataframe based on probability of occurrence with non-NA values

I have to populate a set of 'Failure' values within a 'Bucket' randomly.

For instance,

| Bucket | Failure | Id |
|--------|---------|----|
| B1     | F1      | 1  |
| B1     | F2      | 2  |
| B1     | F1      | 3  |
| B1     | null    | 4  |
| B1     | null    | 5  |
| B2     | F3      | 6  |
| B2     | F4      | 7  |
| B2     | null    | 8  |

In table above, each Bucket can contain many records. Some of those records will contain Failure populated, but most will not. My goal is to randomly assign the Failure based on the proportion of Failures within a bucket. For instance, for combination - {B1, F1} as compared to the proportion of B1 records(with Failure populated) is 2/3 and for {B1, F2} the proportion of B1 records(with failure populated) is 1/3.

Therefore the records of B1 with null Failure column (Id=4,5) should get randomly either failure F1 or F2 but with the same proportion of F1 as 2/3 and F2 as 1/3. This logic needs to be applied for all buckets within the table.

I see that this is a complicated thing. I'm relatively a R noob, therefore, any code examples would be much appreciated.

In between, I see this question. But the solution doesn't run: Fill missing value based on probability of occurrence

See sample code:

test <- data.frame(
bucket = c(rep('B1', 5), rep('B2',3))
    , failure = c('F1', 'F2', 'F1', NA, NA, 'F3', 'F4', NA)
    , Id = seq(1:8)
)

test

sample_fill_na = function(x) {
    x_na = is.na(x)
    x[x_na] = sample(x[!x_na], size = sum(x_na), replace = TRUE)
    return(x)
}

test[, failure := sample_fill_na(failure), by = bucket]




Python behavior of default RNG across multiple consecutive executions

I have a program that does seem thing like this regarding random functionality.

import random
for I in range (10):
     myarray.append (random.randint (0,4))

My question is this:

I designed my program in such a way that I could run it multiple consecutive times, and each time it runs it saves it's results in a data file and picks up where you left off each time u run it (new results are appended to the old datafile)

So my compsci teacher told me this could be dangerous because I might disrupt the uniform random distribution by rerunning the program multiple consecutive times. Is this a problem in python? How can I fix it in an easy way?




segmentation fault using nested vectors

I stumbled upon the following code segment somewhere to create a list of random numbers in a certain interval:

#include <vector>
#include <iostream>
#include <math.h>
struct gen_rand_pos{
  double factor;
  public:
    gen_rand_pos(double r=1.0): factor(r/RAND_MAX)
    {}
    double operator()(){
        return rand()*factor;
    }
};

int main(){
  int N = 5;
  std::vector<double> result(N);
  std::generate_n(std::back_inserter(result), N, gen_rand_pos(1.0));
  std::cout << result[0] << std::endl;
}

It works perfectly fine. I tried to take this one step further and do the same, but this time creating a list(vector) of random unit vectors, uniformly distributed on the sphere. Here is my go at this:

double l2_norm(std::vector<double> const& u) {
    double accum = 0.;
    for (double x : u) {
        accum += x * x;
    }
    return sqrt(accum);
}

struct gen_rand_vec{
  double factor;
  public:
    gen_rand_vec(): factor(2.0/RAND_MAX)
    {}
  std::vector<double> operator()(){
    std::vector<double> result = {rand()*factor-1,rand()*factor-1,rand()*factor-1}; // uniform in each component
    double norm = l2_norm(result);
    std::transform(result.begin(), result.end(), result.begin(),
           std::bind1st(std::multiplies<float>(),1/norm)); // normalize the vector
    return result;
  }
};

However if I now try to construct it in the same manner:

int main(){
  int N = 5;
  std::vector<std::vector<double>> result2(N);
  std::generate_n(std::back_inserter(result2), N, gen_rand_vec());
  std::cout << result2[0][0] <<std::endl;
}

I get a segmentation error. Is the problem lying in the back_inserter or am I doing something completely wrong? I can't figure out. I checked the construction of the single vectors and they work just fine, so the mistake has to lie somewhere after that.

Thanks in advance.




jeudi 25 janvier 2018

Rails Select one random listings for premium users

In my rails app, I have Users and Listings. The Listings belong to a User. Listing has user_id and its filled with users id who is creating the listing.

A user can be a premium user, gold user or silver user.

What I want is for each premium user, select one random listing to show in premium listings.

I can do it in O(n**2) time or n+1 query as follow:

users_id = User.where(:role => "premium").pluck[:id]
final_array = Array.new
final_array << Listing.where(:user_id => users_id).sample(1)
final_array

Is there a better way of doing this?




What is the distribution for random() in stdlib?

The man page claims that the random function in the C standard library "returns a value between 0 and RAND_MAX."

Unfortunately, it does not say what the distribution is for this random function.

Is the distribution documented anywhere?




Exclude link from Javascript Random Generator

Trying to exclude specific links from the random_all javascript generator. I have tried limiting the script to only search certain sections, but did not have any luck. So, looking to try the opposite approach: excluding options.

    <script>
    function random_all(){
    var myrandom=Math.round(Math.random()*(document.links.length-1))
    window.location=document.links[myrandom].href
    } 
    //-->
    </script>

I would just create a seperate blank page for the links I want, but I am using this for a blog so the list of available links needs to be able to refresh in real time.

Any help is greatly appreciated.

-Eoin Thomas




Making a string to a part of the code Python

I want to programm a random genrator for mathtasks. I am at this point:

    first = random.randint(1,100)
    second = random.randint(1,100)
    third = random.randint(1,100)
    R1 = random.choice("+-/*")
    R2 = random.choice("+-/*")
    R3 = random.choice("+-/*")

    x= first + R1 + second + R2 + third + R3

But I know that this wont work, because the +-/* are sawn as a string, not as math actions. Any ideas how to solve this?




Pascall darts program

I would like to write a program in the programming language Pascall. It should be a program in a form project.

Its about darts and the program should keep up to 2 persons when they dart.

Detailled description: Its a program about darts where you will see the score that starts at 501, and there should be 3 columns where you can enter the points you play with a dart. And it should show all outs, if there are more than 5, then it should write the best 5 possible outs. It must end with a double. It cant go lower as 0, and on 1 you cant play double anymore so 1 isn't possible either. And the program should keep up to 2 persons.

I couldn't find any information on the internet how I could do this, so a friend told me I just could ask here.




New to matlab and need some help regarding lists/vectors and how to make them

I want to make a list/vector which is from say a to b and from there i would like to basically make another list and pick 100 numbers from my list for random numbers (it can repeat) and put it in that list.

So it is like i have a list

 A = [a,a+1,a+2 .... b]
 B = empty list
 for i=1:100
     B[i] = random element from A
 end

but i do not understand how to do this, i tried using rand(a,b) but that is giving me a matrix.




How to sample independently N times without replacement?

Numpy allows me to easily sample s numbers from a range of 0,...,M-1 without replacement, for example this way:

numpy.random.choice(5, 3, replace=False) # sampling for M=5 and s=3

However, how do I do this independently N times?

If I were to write a loop by hand in Python, it would look like this:

N = 10
res = []
for i in range (0, N):
    res.append(numpy.random.choice(5, 3, replace=False)

However, it is best to avoid writing any loops in Python in favor of vectorizing computations using numpy facilities, since this offers much better performance.

Therefore, how to independently sample s numbers without replacement N times from a range of 0,...,M-1 in numpy?




c, obtaining a special random number

I have a algorithm problem that I need to speed up :)

I need a 32bit random number, with exact 10 bits set to 1. But in the same time, patterns like 101 (5 dec) and 11 (3 dec) to be considered illegal.

Now the MCU is a 8051 (8 bit) and I tested all this in Keil uVision. My first attempt completes, giving the solution

0x48891249
1001000100010010001001001001001   // correct, 10 bits 1, no 101 or 11

The problem is that it completes in 97 Seconds or 1165570706 CPU cycles which is ridiculous!!!

Here is my code

// returns 1 if number is not good. ie. contains at leats one 101 bit sequence
bool checkFive(unsigned long num)
{
    unsigned char tmp;

    do {

            tmp = (unsigned char)num;

        if(
            (tmp & 7) == 5 
        || (tmp & 3) == 3
        ) // illegal pattern 11 or 101
                return true; // found 

            num >>= 1;
    }while(num);

    return false;
}

void main(void) {


    unsigned long v,num; // count the number of bits set in v
    unsigned long c; // c accumulates the total bits set in v

    do {
            num = (unsigned long)rand() << 16 | rand(); 
            v = num;

            // count all 1 bits, Kernigen style
            for (c = 0; v; c++)
                    v &= v - 1; // clear the least significant bit set

    }while(c != 10 || checkFive(num));

  while(1);
}

The big question for a brilliant mind :) Can be done faster? Seems that my approach is naive.

Thank you in advance,




How can I extract part of an element, and reuse this (numerical) value in javascript

Ok, so the background to what I would like to do overall is 'randomly select a car from the list of results'.

So far, what I've successfully done is randomly select a Car type from a simple list of possibilities.

var cartype = ['small-city', 'hatchback', 'saloon', 'estate', '4x4']
var selectedtype = cartype[Math.floor(Math.random() * cartype.length)]

What I'm also able to do is randomly select a resulting page from a static value (in this case, any page between 1 and 10);

var cfspageNumber = Math.floor(Math.random() * 11) + 1

I can then load the random page and it all works Ok

.url(`https://www.parkers.co.uk/cars-for-sale/type-${selectedtype}/?page=${cfspageNumber}`)

Upon loading the landing page of the resulting list of cars for sale with the (randomly) selected Car type, what I'd then like to do is randomly select a page so that (in theory) a different list of cars is displayed each time the test is run.

So, in the case below, I would like to randomly select any of the 1882 pages and load that page.

enter image description here

If the number of pages was always 1882, I'd be Ok as I can randomly select from a 'static' list.

However, depending on what Car type is randomly selected beforehand, the number of pages changes.

What I would like to do, is somehow 'extract' this value (in this case 1882 but is dynamic), and then use this value to randomly select a page.

var cfspageNumber = Math.floor(Math.random() * 1882, or whatever is listed as the final page) + 1




Nodejs & Mongo pagination random order

I am running an iOS app where I display a list of users that are currently online.
I have an API endpoint where I return 10 (or N) users randomly, so that you can keep scrolling and always see new users. Therefore I want to make sure I dont return a user that I already returned before.
I cannot use a cursor or a normal pagination as the users have to be returned randomly.

I tried 2 things, but I am sure there is a better way:

  • At first what I did was sending in the parameters of the request the IDs of the user that were already seen. ex: But if the user keeps scrolling and has gone through 200 profiles then the list is long and it doesnt look clean.
  • Then, in the database, I tried adding a field to each users "online_profiles_already_sent" where i would store an array of the IDs that were already sent to the user (I am using MongoDB)

I can't figure out how to do it in a better/cleaner way

Thank you :)




sampling data based on posterior joint-probabilities

I have a dataset and would like get a sample based on probabilities that I manually set.

Example: (id = user, score(sort by desc), b1-b6(dummy variable)), 1 represents users have this feature, 0 otherwise

id score b1 b2 b3 b4 b5 b6

1 0.99 1 0 0 0 1 0

2 0.98 1 0 0 0 0 0

3 0.97 1 1 1 0 1 1

4 0.96 0 1 0 0 0 0

A parameter set (p1,p2,p3,p4,p5,p6) is given that controls the proportion of users having this feature in columns (b1,b2,b3,b4,b5,b6) respectively

Let's see I set p1 = 0.1, p2 = 0.2, p3 = 0.9, p4 = 0.32, p5 = 0.2, p6 = 0.21 And it's expected to sample from the dataset whose distribution is approximately follow the p1-p6 values.

about 10% of users have 1 in b1, 20% users have 1 in b2 and so on)

Problem is the original dataset has its distributions across b1 to b6, and how to get a sample from it, which has the distributions that follows the p1-p6 values

Any thoughts would be appreciated

UPDATES It's to draw a sample from a large dataset (1k sample from 1000k) that follows the distributions (p1,p2 etc.),instead of simulating phony data

Approach 1: It may be solved by repeating random sample. and using the closest one(need resampling or iteration tricks).

Approach 2: using linear optimisation algorithm(may be complicated, as 2^6 possibilities, and needs to solve large equations)




Random function call from multiple threads in C++/QT

I have a multi-thread QT application that sometimes need a random alphanumeric string from one of its threads (some threads start at application startup, others start or die during lifetime), and I would like to obtain that by calling a function defined in a common header, to avoid code replication.

Here there's a code snippet:

QString generateRandomAlphanumericString(int length)
{
    qsrand(static_cast<uint>(QTime::currentTime().msec())); //bad
    QString randomAS = QString();

    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < length; ++i)
        randomAS[i] = alphanum[qrand() % (sizeof(alphanum) - 1)];

    return randomAS;
}

I initially did some mistakes.

At the beginning I called qsrand(static_cast<uint>(QTime::currentTime().msec())); in the main function, but I've learned that it should be done per-thread.

Then I put the qsrand call in the function above, but it's not correct.

Please consider that at program startup many threads start "together", so if I initialize the seed with current time in msec the seed is the same among them.

Is there a way to change that function accordingly without modify all points in my application where a thread starts its life? Any implementation done in pure C++ (without the use of QT) is fine. Could the new random C++11 library help in some way to achieve my task?




What's the equivalent of R sample function in Stata

I have a basic question about Stata. I have programming experience in R but I've started a new job where Stata is the main language. I'm currently diving into Stata on my own and sometimes it's hard to understand how to do simple things.

I've trying to get 5 random numbers between 3 and 50 but without success.

In R, any of these would work:

 floor(runif(5, min=3, max=50))

 sample(3:50, 5, replace=TRUE)

But I'm not sure how to do this in Stata, specifically how to return random numbers within the desired range (3:50). Any pointers would be appreciated. I found the runiform but I don't think I can get the same output.

Thank you!




mercredi 24 janvier 2018

Using Random in Parallel.For

My program performs many simulations, each of which calls for many random numbers to be generated. The serial method is straightforward and works. However, in my pursuit of parallelizing the work I believe I found a more straightforward method than what I could find. The other methods are somewhat dated.

Am I missing something that will make my method susceptible to any of the myriad of multithreading problems? I ask this because my software is not benefiting from my addition and I am wondering if I missed a problem. My method uses the ability of a Parallel.For to instantiate a variable for individual thread use. In this case each thread gets its own Random.

Timing:

My method: 4s

Stephen: 14s

Jon: 16s

Clearly I don't know as much as Stephen or Jon so I'm concerned I missed something.

My method:

Random rnd = new Random();
int trials = 1_000_000;

ParallelOptions po = new ParallelOptions();
po.MaxDegreeOfParallelism = 4;

await Task.Run(() =>
{
    Parallel.For<Random>(0, trials, po, () => new Random(rnd.Next()), (i, loop, local) =>
    {
        for (int work = 0; work < 1000; work++)
        {
            local.Next();
        }

        return local;
    },
        (x) => { }
    );
});

This next method is by Stephen Toub on the MSDN Blog:

public static class RandomGen2
{
    private static Random _global = new Random();
    [ThreadStatic]
    private static Random _local;

    public static int Next()
    {
        Random inst = _local;
        if (inst == null)
        {
            int seed;
            lock (_global) seed = _global.Next();
            _local = inst = new Random(seed);
        }
        return inst.Next();
     }
}

await Task.Run(() =>
{
    Parallel.For(0, trials, i =>
    {
        for (int work = 0; work < 1000; work++)
        {
            RandomGen2.Next();
        }
    });

});

This next method is by Jon Skeet on his blog:

public static class ThreadLocalRandom
{
    private static readonly Random globalRandom = new Random();
    private static readonly object globalLock = new object();

    private static readonly ThreadLocal<Random> threadRandom = new ThreadLocal<Random>(NewRandom);

    public static Random NewRandom()
    {
        lock (globalLock)
        {
            return new Random(globalRandom.Next());
        }
    }

    public static Random Instance { get { return threadRandom.Value; } }

    public static int Next()
    {
        return Instance.Next();
    }
}

await Task.Run(() =>
{
    Parallel.For(0, trials, i =>
    {
        for (int work = 0; work < 1000; work++)
        {
            ThreadLocalRandom.Instance.Next();
        }
    });
});




Getting a Random Sample of An Account's Twitter Followers

I am trying to get a random sample of an account's twitter followers. I found the following code: https://gist.github.com/aparrish/2910772

However, when I run it, I inevitably get sname = sys.argv[1] IndexError: list index out of range

What should I do? Any help would be greatly appreciated.




How to read random objects from a bucket with java?

I want to read random objects from a bucket . i do not want to store keys and pick with randomly a key and get the object because i think it is an expensive operation . thanks




Does runif() really have a range: 0<= runif(n) <= 1, as stated in the documentation?

I'm new to R, but the documentation surprised me by stating that runif(n) returns a number in the range 0 to 1 inclusive. I would expect 0 <= runif(n) < 1 -- including 0 and not including 1.

I tested it with n = 100,000,000, and found that it never produced 0 or 1. I realize that the probability of actually hitting specific values in floating point is really small, but still... (There are something like 2^53 values between 0 and 1 in double precision).

So I looked into the source code for R and found in r-source-trunk\src\nmath\runif.c

do 
{
    u = unif_rand();
} while (u <= 0 || u >= 1);
return a + (b - a) * u;

So by design, despite the documentation, it will never ever return a 0 or 1.
Isn't this a bug?

Or at least a problem with the documentation?




sample X examples from each class label

l have a dataset (numpy vector) with 50 classes and 9000 training examples.

x_train=(9000,2048)
y_train=(9000,)  # Classes are strings 
classes=list(set(y_train))

l would like to build a sub-dataset such that each class will have 5 examples

which means l get 5*50=250 training examples. Hence my sub-dataset will take this form :

sub_train_data=(250,2048)
sub_train_labels=(250,)

Remark : we take randomly 5 examples from each class (total number of classes = 50)

Thank you




Why does random() not work in windows?

Why does the C++ random() command not work on Windows? I made a running program with the random() command on Ubuntu. This command generates a random integer. Online there isn't much to find about this command. What confuses me is that the code is not altered in any way, and the same program is used on both operating systems to run the code.

Is there any structural difference in these 2 operating systems that prohibits the command from working on one of them?




Shuffle buttons game c#

I am a new programmer. I found this shuffle buttons game. I understand most of what is going on here but I don't get what is the role of "flag" and what does "i" do.. once it is i=1 but then it says "while(i<=8)".. and then what role does it have here: "a[i]". I would be grateful if someone could explain.

   namespace Shuffle_Numere
{
    public partial class Form1 : Form
    {
        int num;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button2.Text == "")
            {
                button2.Text = button1.Text;
                button1.Text = "";
            }
            if (button4.Text == "")
            {
                button4.Text = button1.Text;
                button1.Text = "";
            }
            ChekWin();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (button1.Text == "")
            {
                button1.Text = button2.Text;
                button2.Text = "";
            }
            if (button3.Text == "")
            {
                button3.Text = button2.Text;
                button2.Text = "";
            }
            if (button5.Text == "")
            {
                button5.Text = button2.Text;
                button2.Text = "";
            }
            ChekWin();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (button2.Text == "")
            {
                button2.Text = button3.Text;
                button3.Text = "";
            }
            if (button6.Text == "")
            {
                button6.Text = button3.Text;
                button3.Text = "";
            }
            ChekWin();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (button1.Text == "")
            {
                button1.Text = button4.Text;
                button4.Text = "";
            }
            if (button5.Text == "")
            {
                button5.Text = button4.Text;
                button4.Text = "";
            }
            if (button7.Text == "")
            {
                button7.Text = button4.Text;
                button4.Text = "";
            }
            ChekWin();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (button2.Text == "")
            {
                button2.Text = button5.Text;
                button5.Text = "";
            }
            if (button4.Text == "")
            {
                button4.Text = button5.Text;
                button5.Text = "";
            }
            if (button6.Text == "")
            {
                button6.Text = button5.Text;
                button5.Text = "";
            }
            if (button8.Text == "")
            {
                button8.Text = button5.Text;
                button5.Text = "";
            }
            ChekWin();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (button3.Text == "")
            {
                button3.Text = button6.Text;
                button6.Text = "";
            }
            if (button5.Text == "")
            {
                button5.Text = button6.Text;
                button6.Text = "";
            }
            if (button9.Text == "")
            {
                button9.Text = button6.Text;
                button6.Text = "";
            }
            ChekWin();
            timer1.Enabled = true;
            timer1.Start();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (button4.Text == "")
            {
                button4.Text = button7.Text;
                button7.Text = "";
            }
            if (button8.Text == "")
            {
                button8.Text = button7.Text;
                button7.Text = "";
            }
            ChekWin();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (button5.Text == "")
            {
                button5.Text = button8.Text;
                button8.Text = "";
            }
            if (button7.Text == "")
            {
                button7.Text = button8.Text;
                button8.Text = "";
            }
            if (button9.Text == "")
            {
                button9.Text = button8.Text;
                button8.Text = "";
            }
            ChekWin();
            timer1.Enabled = true;
            timer1.Start();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (button6.Text == "")
            {
                button6.Text = button9.Text;
                button9.Text = "";
            }
            if (button8.Text == "")
            {
                button8.Text = button9.Text;
                button9.Text = "";
            }
            ChekWin();
        }
        public void ChekWin()
        {
            num = num + 1;
            label2.Text = num.ToString();
            if (button1.Text == "1" && button2.Text == "2" && button3.Text == "3" && button4.Text == "4" && button5.Text == "5" && button6.Text == "6" && button7.Text == "7" && button8.Text == "8" && button9.Text == "")
            {
                if (MessageBox.Show("Congratulations! You won in "+num+" moves asnd "+timp+" seconds.", "Message text", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    label2.Text = "0";
                    timp = 0;
                    timer1.Stop();
                    label4.Text = "0";
                }
            }

        }

        private void button11_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        public void Shuffle()
        {
            int i, j, Rn;
            int[] a = new int[9];
            Boolean flag = false;
            i = 1;
            do
            {
                Random rnd = new Random();
                Rn = ((rnd.Next(0, 8)) + 1);
                for (j = 1; j <= i; j++)
                {
                    if (a[j] == Rn)
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag == true)
                {
                    flag = false;
                }
                else
                {
                    a[i] = Rn;
                    i = i+1;
                }
            }
            while (i <= 8);
            button1.Text =Convert.ToString(a[1]);
            button2.Text = Convert.ToString(a[2]);
            button3.Text = Convert.ToString(a[3]);
            button4.Text = Convert.ToString(a[4]);
            button5.Text = Convert.ToString(a[5]);
            button6.Text = Convert.ToString(a[6]);
            button7.Text = Convert.ToString(a[7]);
            button8.Text = Convert.ToString(a[8]);
            button9.Text = "";

            num = 0;
            label2.Text = "0";
            timer1.Stop();
            label4.Text = "0";
        }

        private void button10_Click(object sender, EventArgs e)
        {
            Shuffle();
        }

        int timp = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            timp++;
            label4.Text = timp.ToString();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Shuffle();
        }

    }
}




Generating random Int array of random count without repeated vars

Code first generates a random between 0-8, assigning it to var n. Then a 2nd randomNumber Generator func is looped n amount of times to generate n amount of ints between 0 and 10, all having different probabilities of occurring and ultimately put into an array. What I want is for none of those 10 possible numbers to repeat, so once one is chosen it can no longer be chosen by the other n-1 times the func is run. I'm thinking a repeat-while-loop or an if-statement or something involving an index but I don't know exactly how, nor within what brackets. Thanks for any help!

import UIKit

let n = Int(arc4random_uniform(8))

var a:Double = 0.2
var b:Double = 0.3
var c:Double = 0.2
var d:Double = 0.3
var e:Double = 0.2
var f:Double = 0.1
var g:Double = 0.2
var h:Double = 0.4
var i:Double = 0.2
var j:Double = 0.2
var k: [Int] = []

for _ in 0...n {
    func randomNumber(probabilities: [Double]) -> Int {
        let sum = probabilities.reduce(0, +)
        let rnd = sum * Double(arc4random_uniform(UInt32.max)) / Double(UInt32.max)
        var accum = 0.0
        for (i, p) in probabilities.enumerated() {
            accum += p
            if rnd < accum {
                return i
            }}
        return (probabilities.count - 1)
    }
    k.append(randomNumber(probabilities: [a, b, c, d, e, f, g, h, i, j]))
}
print(k)




Fastest way to generate a random-like unique string with random length in Python 3

I know how to create random string, like:

''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))

However, there should be no duplicates so what I am currently just checking if the key already exists in a list, like shown in the following code:

import secrets
import string
import numpy as np


amount_of_keys = 40000

keys = []

for i in range(0,amount_of_keys):
    N = np.random.randint(12,20)
    n_key = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
    if not n_key in keys:
        keys.append(n_key)

Which is okay for a small amount of keys like 40000, however the problem does not scale well the more keys there are. So I am wondering if there is a faster way to get to the result for even more keys, like 999999




Not repeating numbers within Random Number Generator that generates a Random amount of numbers itself

My code first generates a random number between 0 and 8 and assigns it to var n. Then I loop another randomNumber Generator n amount of times to generate n amount of ints between 0 and 10 (The amount of variables I have), all 10 vars having different probabilities of occurring and ultimately returning them in an array. What I want is for none of those 10 possible numbers to repeat, so once one int is chosen it can no longer be chosen in the other n-1 times the code repeats. Im a coding super noob so please talk to me in code baby talk. I'm thinking I need to have a repeat-while-loop in there or an if-statement or something involving an index but I don't know exactly how, nor within what brackets. Thanks for any help! (If you see something in my code and think "why would he include that?" or "well thats redundant" its probably because I don't understand, so let me know!)

import UIKit

let n = Int(arc4random_uniform(8))

var a:Double = 0.2
var b:Double = 0.3
var c:Double = 0.2
var d:Double = 0.3
var e:Double = 0.2
var f:Double = 0.1
var g:Double = 0.2
var h:Double = 0.4
var i:Double = 0.2
var j:Double = 0.2
var k: [Int] = []

for _ in 0...n {
    func randomNumber(probabilities: [Double]) -> Int {
        let sum = probabilities.reduce(0, +)
        let rnd = sum * Double(arc4random_uniform(UInt32.max)) / Double(UInt32.max)
        var accum = 0.0
        for (i, p) in probabilities.enumerated() {
            accum += p
            if rnd < accum {
                return i
            }}
        return (probabilities.count - 1)
    }
    k.append(randomNumber(probabilities: [a, b, c, d, e, f, g, h, i, j]))
}
print(k)




Generate array of N sample from a list of N means and N sigmas

I have a numpy array of size N which contains [x,y] pixel locations. I want to slightly move every pixel in both x and y directions. What I want to achieve is to use every x value as the mean and randomly select new value around it from a normal distribution with configurable sigma. Same will be done for new y values

My problem is that I have to loop for every pixel and tediously use the following:

for i in range(len(pixels)):
    pixel = pixels[i]
    x = pixel[0]
    y = pixel[1]
    new_x = numpy.random.normal(x, std_deviation_x)
    new_y = numpy.random.normal(y, std_deviation_y)
    pixel[i][0] = new_x
    pixel[i][1] = new_y

I wonder if there is a way or any random function implementation which accept list of means, and list of sigmas to return list of N samples where each sample is of corresponding mean and sigma in the list




Generation of Random numbers in binary with constraints in C

I am trying to find a way to generate a 32 bit number randomly : But with the certain constraints like only the lowest 4 bits and the upper 20 bits must be randomized in C

Can someone please guide me to proper direction




mardi 23 janvier 2018

Randomly sample from arbitrarily nested lists while maintaining structure

I am trying to write a function which chooses integers randomly from arbitrarily nested lists while maintaining order and the structure of the lists (though empty lists can be ignored).

For example, running listrand([1,2,3,[3,4],[65,[3]]]) 3 times might give:

[1, 3, [3], [65[3]]]
[1, 2, [[3]]]
[[3, 4], [65]]

The catch is I need it to be uniformly distributed, so I can't use something like

sample = [[random.sample(mylist)] for mylist in listoflists]

because that would be binomial.

At a minimum I need this to work for single-level nesting. I thought about sampling from a flattened list but then I'm not sure how to use those to construct the desired output.




Randomly generating two list, finding odd numbers and comparing the lists

I'm writing a function compare(list_a, list_b) that accepts two lists of integers.

The function does the following:

  1. Counts the number of odd numbers in the first list
  2. Counts the number of odd numbers in the second list
  3. Returns 1, if the first list has more odd numbers
  4. Returns -1, f the second list has more odd numbers,
  5. Returns 0, if both lists have the same amount of odd numbers.

I am writing a main program that testing the function and randomly generate the list of size 15, range of integers from -10 to 10.

Here is what I have so far:

def make_list(size):
        my_list=[]
        for i in range(size):
                my_list.append(int(input("enter integer ")))
        return my_list

def compare(list_a,list_b):
        flist=[]
        slist=[]


        fcount=0


        for i in my_list:
                if(i%2!=0):
                        flist.append(i)
                                fcount+=1

def main():
        size=random.randint(15, -10,10)

main()




Non repeating elements from array

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

int main()
{
    srand(time(NULL)); //initialize the random seed

    while (true) {
        const char arrayNum[4] = { '1', '3', '7', '9' };
        int RandIndex = rand() % 4; //generates a random number between 0 and 3
        cout << arrayNum[RandIndex];
    }
}

When generating this numbers some of them are repeating and i don't want this.Is a way for this?




Trying to pull a random string array element after assigning values from user input

I am working on an AI project and am trying to build a Video Game Selector. The user would input what genre, mode, rating and platform of a game they would like to play. Then the program would take that input, and then select games within the gameList array that match that criteria. Then, it would randomly select a game from the gameList array matching the criteria and output the randomly selected game as a suggestion for the user to play. I'm not as experienced in Java, done more C++ coding before, but my professor suggested we do this project in Java so figured I'd give it a go since I'm graduating at the end of this semester and wanted more experience in Java when applying for jobs/internships.

I'm having an issue trying to come up with the best way to use the user input to assign or check it against elements within each array (I have an array for genre, mode, rating and platform) to then have games that would match that criteria be able to be randomly selected to suggest to the user of which game to play.

If anyone has any ideas on a better approach then I currently have or a better and easier way to go about doing this that would be hugely helpful!

Here is the code I currently have (some of from a previous assignment so ignore the printPeas() and other stuff that isn't revenant to the arrays. The code currently isn't working unfortunately:

package Games;

import java.util.Scanner;

public class Games
{
    String _gameType;
    String _genreType;
    String _gameMode;
    String _gameRating;
    String _tType;

    public static Scanner input = new Scanner(System.in);

    public Games(String type)
    {
        _gameType = type;
        System.out.println("Suggested type of game is: " + _gameType);
    }
    public Games()
    {
        _gameType = "Sports";
        System.out.println("Suggested type of game is: " + _gameType);
    }
    public void typeInput(String tType)
    {
        _tType = tType;
        System.out.println("Type of Game selected: " + _tType);
    }
    public void genreInput(String gType)
    {
        _genreType = gType;
        System.out.println("Type of Genre selected: " + _genreType);
    }
    public void modeInput(String gMode)
    {
        _gameMode = gMode;
        System.out.println("Type of Game Mode selected: " + _gameMode);
    }
    public void ratingInput(String gRating)
    {
         _gameRating = gRating;
         System.out.println("Type of Rating selected: " + _gameRating);
    }
    public void printPeas()
    {
        String agent = "Agent = Video Game Seletor.";
        String perfmeasure = "P = If it meets the users information being input.";
        String environment = "E = All games within a certain location.";
        String actuators = "A = Library of games to select from, and the display of which game was selected.";
        String sensors = "S = Keyboard input.";
        System.out.println(agent);
        System.out.println(perfmeasure);
        System.out.println(environment);
        System.out.println(actuators);
        System.out.println(sensors);
    }
}


package Games;

import java.util.ArrayList;
import java.util.Random;

public class Game
{
    public static String _genreType;
    public static String _gameMode;
    public static String _gameRating;
    public static String _gameName;

    public void setGame(String genre, String mode, String rating)
    {
        _genreType = genre;
        _gameMode = mode;
        _gameRating = rating;
        _gameName = "";

        Random random = new Random();
        String gameList[] = {"NHL '18", "Madden '18", "Call of Duty: WW2", "GTA V", "Counter-Strike: Global Offsnsive",
            "World of Warcrat", "PUBG", "Assassin's Creed Origins", "Hearthstone", "Battlefield 4"};
        String genreList[] = {"Action", "Sports", "Racing", "MMORPG", "Strategy", "Fighting", "Fantasy"};
        String modeList[] = {"Multiplayer", "Online", "Campaign"};
        String ratingList[] = {"Everyone", "E10+", "Teen", "Mature"};
        String platformList[] = {"PC", "PS4", "Xbox"};
        for(int i=0; i<gameList.length; i++) //trying to have it pull a random game name matching type, genre, mode and rating
        {
            if(genre == genreList[i])
            {
                _genreType = genre;
            }
            if(mode == modeList[i])
            {
                _gameMode = mode;
            }
                System.out.println(gameList[random.nextInt(gameList.length)]);
        }
    }
}

package Games;

import java.util.Scanner;

public class StartSelector
{
    public static String _gameType;
    public static String _genreType;
    public static String _gameMode;
    public static String _gameRating;
    public static Scanner userInput = new Scanner(System.in);
    public static void main(String[] args)
    {
        String gameType = _gameType, genreType = _genreType, gameMode = _gameMode, gameRating = _gameRating;
        Games gameType1 = new Games();
        gameType1.printPeas();
        Games gameType2 = new Games("Action");
        gameType2.printPeas();
        Games gameSelect = new Games();
        System.out.println("Please enter the Genre Type: ");
        genreType = userInput.next();
        gameSelect.genreInput(genreType);
        System.out.println("Please enter the Game Type: ");
        gameType = userInput.next();
        gameSelect.typeInput(gameType);
        System.out.println("Please enter the Game Mode: ");
        gameMode = userInput.next();
        gameSelect.modeInput(gameMode);
        System.out.println("Please enter the Game Rating: ");
        gameRating = userInput.next();
        gameSelect.ratingInput(gameRating);
        userInput.close();
        System.out.println("You have selected a " + genreType + " " 
        + gameType + " " + gameMode + " " + gameRating 
        + " game to play.");
        gameType1.setGame("Action", "Online", "Mature", "GTA V");
    }
}




Same function with different random results - jquery part 2

i already posted one similar question but with different issue here Same functions, different random results - jQuery

I have other bigger issue, because i need to load all the content from js array's, and make one of the word inside that array clickable, and obtain random result from another array:

///  simple arrays with link in the middle

var listArray1 = [
  "<a class='linkLoadIam' href='javascript: loadIam();'>I am</a> engulfed",
  "This is how <a class='linkLoadIam' href='javascript: loadIam();'>I am</a> angry",
   "Just some <a class='linkLoadIam' href='javascript: loadIam();'>I am</a> sentimental",
];

var listArray2 = [
  "Phrase without links",
  "Phrase without links2",
  "Phrase without links3",
];

var listArray3 = [
  "Why <a class='linkLoadIam' href='javascript: loadIam();'>I am</a> hungry",
  "This is how <a class='linkLoadIam' href='javascript: loadIam();'>I am</a> eating",
   "Just some <a class='linkLoadIam' href='javascript: loadIam();'>I am</a> food phrase",
];

/////// starting functions
$('#js-random').click(function() {
        // get random array's
getRandomArray1 = listArray1[Math.floor(Math.random() * listArray1.length)];
getRandomArray2 = listArray2[Math.floor(Math.random() * listArray2.length)];
getRandomArray3 = listArray3[Math.floor(Math.random() * listArray3.length)];


// loading into div
 $('.getRandomArray1div').html(getRandomArray1);
 $('.getRandomArray2div').html(getRandomArray2);
 $('.getRandomArray3div').html(getRandomArray3);
 
   }); //end click function

 

///array that i want to call randomly with I am link
var listIam = [
  "<a class='linkLoadIam' href='javascript: loadIam();'>I am</a> the substitute",
  "This is how <a class='linkLoadIam' href='javascript: loadIam();'>I am</a> the phrase is changing",
   "Just some <a class='linkLoadIam' href='javascript: loadIam();'>I am</a> random project.",
];


/// function to load this phrase instead of actual phrase

function loadIam() {
    var randomIam = listIam[Math.floor(Math.random() * listIam.length)];
    $('.linkLoadIam').parent('div').html(randomIam);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<div id="results">
     <div class="getRandomArray1div"></div>
     <div class="getRandomArray2div"></div>
     <div class="getRandomArray3div"></div>
</div>

<div id="js-random"> <a href="#">RANDOM</a> </div>

It works perfectly, but functions are repeating the same string, and i want one string in a time when i click on the word.

Can anyone tell me another way? The previous post didn't solved this problem. Thank you




How do I generate a Cryptographically secure number in Classic ASP?

What's the best way to generate a cryptographically secure random number in classic ASP?




How to set .Count function to exclude headers?

I am trying to make a sub where the macro counts all the rows containing data (it isn't a set amount, it varies) and then picks a random number between 6 (to exclude headers) and the number of counted rows and highlights the corresponding row. Unfortunately the code I've been working on doesn't do what I need it to do. It does select and highlight a random row, but it selects empty rows too, not only the ones with data. Any ideas where I went wrong?

Sub RandomRow()
Dim mrg As Worksheet
Dim Count As Integer, myRange As Range
Set mrg = ActiveWorkbook.Sheets("Merged")


    mrg.Range("A6:K200000").Interior.Color = RGB(255, 255, 255) 'reset cell colours

        Set myRange = mrg.Columns("A:A")
        Count = Application.WorksheetFunction.CountA(myRange)

myValue = Int((Count * Rnd) + 6)    ' Generate random value between 6 and the number of filled rows'.

mrg.Range("A" & myValue).EntireRow.Interior.Color = RGB(255, 255, 153) 'highlight a random row

End Sub




lundi 22 janvier 2018

Why is this Javascript/Ajax function using a random number?

I'm helping maintain a Javascript-based web site that was written by someone else. In their Javascript code, I came across this function, which downloads a file from the specified URL and calls a callback when the download is complete:

// ajax wrapper
function getServerData(command, command_label, success_callback)
{
   $.ajax({
     url: command,
     type: 'POST',
     data: { rand: (Math.floor(Math.random()*1000)) },
     success: function(data) { success_callback(data); },
     error: function(error) {if (handleError(error, command_label)) {getServerData(command, command_label, success_callback);}}
   });
}

The above makes sense to me, except for this line:

     data: { rand: (Math.floor(Math.random()*1000)) },

Why is there a random number assigned to the data attribute? Is this some attempt to defeat a cacheing mechanism, that will fail to work about 0.1% of the time? Or is it a copy-and-paste-from-an-example detail that wasn't removed even though it's no longer relevant? Or has it some other (even more obscure) purpose?

Simply removing that line doesn't seem to hurt anything, but I'm worried about removing code whose purpose I don't understand.




Same functions, different random results - jQuery

Let's suppose i have an array of words

JS

var fruit = [banana, apple, watermelon, mango];

function loadFruit() {
    var randomFruit = fruit[Math.floor(Math.random() * fruit.length)];
    $('.divLoadFruit').parent('div').html(randomFruit);
};

I need to trigger function on click of the middle word of the sentence, to obtain different random matches

HTML

"You need to eat <a href='javascript: loadFruit();'>just_some_fruit</a>: it is good for your health."

"My son doesn´t like <a href='javascript: loadFruit();'>another_fruit_here</a>."

When you click on one of the links, it triggers the same function (obviously) but gets me the same fruit in that spaces. Is there any way to make it random without repeating?




Img added by Javascript showing 0x0 pixels

I'm trying to add the same small image multiple times to a canvass. It shows in Inspect Elements correctly, except that the images have 0x0 pixels (natural is 200x45 or something).

Here's the code:

function addbgd1(){
    this.obj = document.createElement('img');
    this.obj.src = 'img/bgd1.png';
    this.obj.classList.add('bgd1img');
    //this.obj.width = 100;
    //this.obj.height = 22;
    this.obj.style.top = Math.floor((window.innerHeight * Math.random())) + 'px';
    this.obj.style.left = Math.floor((window.innerWidth * Math.random())) + 'px';
    bgd1.appendChild(this.obj);
}


function drawbgd1(){
    nbgd1 = Math.floor(WIDTH / 50);
    for(var i=0; i<nbgd1 ; i++){
        bgd1imgs.push(new addbgd1());
    }
}

I have var bgd1 as the canvas (screen sized); WIDTH is the screen width.

Completely lost here. I've tried several variations of CSS but there's no difference.

Thanks!




How does Trezor hardware wallet generate random seed?

Wouldn't all wallets generate the same seed (first private key) if all the wallets had the same hardware. Does the wallet use time or some sensor (like temperature) to generate a random seed. Can you specify the code where this is generated.




R: generating a discrete random probability distribution, by perturbating an existing one

If I wanted to efficiently generate a random discrete probability distribution of N probabilities which sum up to 1, I could go with Hadley's comment here:

prop.table(runif(N))

If I repeat this many times, the average probability for each of the N elements should be ~1/N.

What if I want the average probability for each of the N elements not to be 1/N but a specified number apriori?

E.g. N = 4 elements, I have the apriori distribution:

apriori <- c(0.2, 0.3, 0.1, 0.4)

And I would like random distributions based on this apriori, e.g.:

c(0.21, 0.29, 0.12, 0.38)
c(0.19, 0.29, 0.08, 0.44)
c(0.19, 0.33, 0.1, 0.38)

Etc.

Where we go by either of these rules:

1) On average each of the elements probabilities would be (approx.) its probability in the apriori distribution

2) There's a "perturbation" parameter, say perturbation = 0.05 which means either: (a) we're letting each of the probabilities i to be in the apriori[i] +- perturbation range or (b) we're letting each of the probabilities i to be in the apriori[i] +- perturbation * apriori[i] range (i.e. plus/minus 5% of that apriori probability, not absolute 5%)

I have no idea how to do this while keeping rule 1.

Regarding rule 2, my initial inefficient thought would be perturbating each of the first N - 1 elements by a random allowed amount, setting the last element to be 1 - sum(N-1_probs) and wrapping this with a while loop until the last element is also legitimate.

I didn't event implement it yet because that's very inefficient (say I want 100K of such distributions...). Ideas?




Generating random numbers in numpy with strict lower bounds

So according to numpy's documentation here: https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.random.uniform.html, they say that the random values generated belong to the set [lower, upper) i.e. all values are >= lower, and less than upper. Is there any way to make this a stricter bound, i.e. all values are > lower? I have a particular case in which I want to ensure that all random values lie between 0 and k, but should not be equal to 0, as that will cause my program to crash. Any workarounds/other libraries which can help me?




MySQL: select random individual from available to populate new table

I am trying to automate production of a roster based on leave dates and working preferences. I have generated some data to work with, and I now have two tables, one with a list of individuals and their preferences for working on particular days of the week(e.g. some prefer to work on a Tuesday, others only every other Wednesday etc and another with leave dates for individuals. That looks like this, where firstpref and secondpref represent weekdays with Mon = 1, Sun = 7 and firstprefclw represents a marker for which week of a 2 week pattern someone prefers (0 = no pref, 1 = wk 1 preferred, 2 = wk2 preferred)

initials | firstpref | firstprefclw | secondpref | secondprefclw KP | 3 | 0 | 1 | 0 BD | 2 | 1 | 1 | 0 LW | 3 | 0 | 4 | 1

Then there is atable leave_entries, which basically has the intials, a start date and an end date for each leave request.

Finally there is a pre-calculated clwdates table, which contains a marker (a 1 or 2) for each day in one of its columns as to what week of the roster pattern it is.

I have run this query:

SELECT @tdate, DATE_FORMAT(@tdate,'%W') AS whatDay, GROUP_CONCAT(t1.initials separator ',') AS available
FROM people AS t1
WHERE ((t1.firstpref = (DAYOFWEEK(@tdate))-1 
AND (t1.firstprefclw = 0 OR (t1.firstprefclw = (SELECT c_dates.clw from clwdates AS c_dates LIMIT i,1)))) 
OR (t1.secondpref = (DAYOFWEEK(@tdate))-1 
AND (t1.secondprefclw = 0 OR (t1.secondprefclw = (SELECT c_dates.clw from clwdates AS c_dates LIMIT i,1)))
OR ((DAYOFWEEK(@tdate))-1 IN (0,5,6))
AND t1.initials NOT IN (SELECT initials FROM leave_entries WHERE @tdate BETWEEN leave_entries.start_date and leave_entries.end_date) 
);

My output from that is a list of dates with initials of the pattern:

2018-01-03;Wednesday;KP,LW,TH

My desired output is

2018-01-03;Wednesday;KP

where the initials of the person have been randomly selected from the list of available people generated by the first set of SELECTs.

My question: how can I randomly select an individual's initials from the available ones and create a table which is basically date ; random_person?




Python : numpy.random.choice() without Numpy

For my program I need to select random strings stored in a list, with given weights. numpy.random.choice() is perfect for this situation, but unfortunately I'm stuck with Python 2.6.6, which does not support Numpy 1.7.0 and newer versions. random.choice is a Numpy 1.7.0 feature. Thus, I am looking for a simple function like this :

get_random_weighted(["foo1","foo2"],[0.7,0.3])
"foo1"

Thanks!




JavaScript random slider with table list

The exam consists of creating a slider containing images of flags. When the visitor clicks on the radio button of a country, the slide slider until the corresponding flag.

Here are 2 contents of JavaScript arrays that you will need:

('Flag_USA_small.png', 'flag-au.png', 'flag-nz.png', 'flags_0000_vietnam.png', 'flags_0001_unitedkingdom.png', 'flags_0002_unitedarabemirates.png', 'flags_0003_turkey.png', 'flags_0004_thailand. png ', 'flags_0005_taiwan.png', 'flags_0006_sweden.png', 'flags_0007_spain.png', 'flags_0008_southafrica.png', 'flags_0009_singapore.png', 'flags_0010_saudiarabia.png', 'flags_0012_portugal.png', 'flags_0013_poland.png', 'flags_0014_phillipines.png', 'flags_0015_norway.png', 'flags_0016_mexico.png', 'flags_0017_malaysia.png', 'flags_0018_lebanon.png', 'flags_0019_korea.png', 'flags_0020_italy.png', 'flags_0021_israel.png', 'flags_0022_ireland.png', 'flags_0023_indonesia.png', 'flags_0024_india.png', 'flags_0025_hongkong.png', 'flags_0026_greece.png', 'flags_0027_germany.png', 'flags_0028_france.png', 'flags_0029_finland.png', 'flags_0030_denmark.png', 'flags_0031_croatia.png', 'flags_0032_china.png', 'flags_0033_canada.png', 'flags_0034_brazil.png', 'flags_0035_belgium.png', 'flags_0036_austria.png', 'flags_0037_switzerland.png');

('USA', 'Australia', 'New Zealand', 'Vietnam', 'United Kingdom', 'United Arab Emirates', 'Turkey', 'Thailand', 'Taiwan', 'Sweden', 'Spain' , 'South Africa', 'Singapore', 'Saudi Arabia', 'Portugal', 'Poland', Philippines, Norway, Mexico, Malaysia, Lebanon, South Korea, Italy, Israel, Ireland, Indonesia, India, Hong Kong Greece, Germany, France, Finland, Denmark, Croatia, China, Canada, 'Brazil', 'Belgium', 'Austria', 'Switzerland');

When loading the page, dynamically from the 2 contents of tables provided above:

  • Draw a random number N between the number of elements in the arrays and the number of elements-10.
  • The slider is completed by N images of flags arranged side by side horizontally.
  • The radio buttons are arranged in 3 columns: N country with for each, a radio button next to the name of the country.
  • The Belgian radio button is ticked by default and its flag is visible

When clicking on a radio button, the slider changes position to the target flag. His movement is visible.

Please can you help me ? I can't resolve that.




dimanche 21 janvier 2018

Determing length of a random list being altered

I have a list being accessed randomly within a list, to which I am adding an element. (note that the element has to be inserted randomly inside of the list, i.e. I don't want to insert at the end or start) For example:

myList = [[0, 1, 4, 7],[0, 3, 2, 7]]
toinsert = [5, 6]

for item in toinsert:
    random.choice(myList).insert(random.randint(1,len(`the list that got chosen`)-2), item)

I have tried using

choicelist = random.choice(myList)
choicelist.insert(randint(1,len(choicelist)))

but then I'm not sure how to put that back in where the original list was - considering it's a random list.

I know I could randomly choose an index for myList and use that method, but I was looking for a hopefully more Pythonic - and shorter - way of doing so.




Shifting elements and printing each step

Im trying to shift elements in an array and print each step until they are back to their original positions. The array has to be filled with random numbers and must not be over the size of 15. I approached the task by creating a new array when the shifting occurs. If anyone has any better suggestions let me know. Ive done the array and the shifting part once, but cant seem to figure out how to repeat it. Here is what I came up with:

public static void main(String[] args) {

    System.out.println("Enter size: ");
    Scanner s = new Scanner(System.in);
    int p = s.nextInt();
    if (p > 15) {
        System.out.println("Too much to handle!");
    }
    int oldArray[] = new int [p];
for (int i = 0; i<oldArray.length;i++) {
        oldArray[i]=(int)(Math.random()*10);
    }
    int newArray[] = moveA(oldArray);
    printA(oldArray);
    printA(newArray);
}

public static int[] moveA(int[] array1) {
int[] array2 = new int[array1.length];

 for (int i = 0; i < array2.length - 1; i++) {
    array2[i+1] = array1[i];
}
array2[0] = array1[array1.length - 1];
return array2;
}

public static void printA(int[] arr) {
    System.out.println(Arrays.toString(arr));
}

The code prints like this:

Enter size: 
4
[1, 5, 9, 3]
[3, 1, 5, 9]

Ive tried doing a for loop at:

for ( int b = 0; b <= oldArray.length; b++)
int newArray[] = moveA(oldArray);
printA(oldArray);
printA(newArray)

but all it does is print it 4 times.