dimanche 31 mars 2019

Difference between these two methods to generate number

I'm a beginner on python. Here is the problem I need to solve:

Generate 10000 random numbers by uniform distribution. Randomly select 10 numbers from these 10000 numbers 20 times. Compute the sample mean and sample standard deviation.

I found that there are two ways to generate 10000 numbers by uniform distribution.

The first one is

import numpy as np
x = np.random.uniform(0,1,10000)

sample1 = []

for i in range(20):
    s1 = np.random.choice(a = x, size = 10, replace = True)
    m1 = np.mean(s1)
    sample1.append(m1)

smean1 = np.mean(sample1)
sstd1 = np.std(sample1)

The second one is

import numpy as np
x = np.random.random_sample((10000,))

sample1 = []

for i in range(20):
    s1 = np.random.choice(a = x, size = 10, replace = True)
    m1 = np.mean(s1)
    sample1.append(m1)

smean1 = np.mean(sample1)
sstd1 = np.std(sample1)

I don't know what's the difference between these two.




Get the drawable's name after setting it on ImageView

I'am Actually setting an image to the ImageView Dynamically from the Drawable folder. I got the working code to set the image dynamically but I can't get the name of the image/drawable which gets set on the image view at the moment. Either I should get the drawable name or any code to get the instance of each drawable with a name which I can set on the ImageView. Any help is Much Appreciated!!

I searched and tried all answers on StackOverflow.

Set the image dynamically to the imageview and also get that image's name.




Javascript: generating and storing random draws without replacement

I am trying to use Javascript to create an array, take two unique random draws from the array, then assign the drawn values to an HTML table. My approach has been to create an array, take a random, create a new array without the drawn value, then take a random draw from the new array as a way of taking two random draws without replacement.

I have provided a minimal example of what I've done to accomplish this, but it's not working. I would like the values assigned to the HTML table to ultimately be two unique values (e.g. "a", "b") from the foo array. Is this not working because value == bar_a below won't remove the value assigned to the bar_a array because bar_a is an array and not the value of the array?

While this post has addressed drawing without replacement, it doesn't provide an example when using strings or explain how to save both numbers and it's unclear why they're using splice() rather than filter()

    // Define array containing the set of values we'll randomly assign to A or B
    var foo = ["a", "b", "c", "d"];

    // Initialize variables to hold the value for A and B
    var bar_a=  [""];
    var bar_b=  [""];

    // Randomly draw from foo, save for A
    bar_a =foo[Math.floor(Math.random()*foo.length)];

    // Remove the drawn value from the array, create new array
    var foo_filtered = array.filter(function(value, index, arr){
        return value == bar_a;
        });

    // Randomly draw from foo_filtered, save for B
    bar_b = foo_filtered[Math.floor(Math.random()*foo_filtered.length)];

    // Assign attributes and values to their placeholders (a1, b1) in a HTML table
     document.getElementById("a1").innerHTML = bar_a;
     document.getElementById("b1").innerHTML = bar_b;




How to pass request for random xml generation?

I want to provide a method (let's call it --> generateXml(?);)which generates the xml fields of a xsd. There should be the option to generate a random value for all xml fields. The is another method (let's call it --> buildXml();). This method includes a generation of xml but it is hardcoded and I want to change this by providing generateXml(?);.

So generateXml(?); generates a xml (e.g. with JAXB) and the content of the xml fields can be randomized if it is desired.

What I am searching for is a proper data structure (the ? in the method above) which should be passed to the generateXml method.

So my approach would be to pass every xml field and another parameter for every xml field like a boolean randomize; to inform that this field should have a random content.

But how? Should I pass a file which contains every field and the random parameter?

What is recommeded here?




cumulative weights in random.choices

Apologies if this has been asked before but I am new to Python and confused using the new 'random.choices' in python 3.7(?).

Here is the doc. https://docs.python.org/3/library/random.html

random.choices(population, weights=None, *, cum_weights=None, k=1)

-- Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

2 questions:

  1. Where can I find full documentation (similar to Matlab's mathworks.com) instead of just the single line given above?

  2. They give an example: weights=[10, 5, 30, 5] and I don't know what this means? Why don't they sum to 100? If my population is [1, 2, 3, 4] -- does this mean that a choice of '10' occurs with probability 0.1?

Thank you. And I apologies again for breaking any of the posting/asking etiquettes here.

Best,

HP




How to send turtle to random position?

I have been trying to use goto() to send turtles to a random position but I get an error when running the programme.

I am lost on how else to do this and not sure of other ways. My current code is:

t1.shape('turtle')

t1.penup()

t1.goto((randint(-100,0)),(randint(100,0)))#this is the line with the error

I want the turtle to go to random co ordinates in a box between-100,100 and 0,100 but I get the error:

Traceback (most recent call last):

File "C:\Users\samdu_000\OneDrive\Documents\python\battle turtles.py",    line 18, in <module>

t1.goto((randint(-100,0)),(randint(100,0)))

File "C:\Users\samdu_000\AppData\Local\Programs\Python\Python3732\lib\random.py", line 222, in randint

return self.randrange(a, b+1)

File "C:\Users\samdu_000\AppData\Local\Programs\Python\Python37-
32\lib\random.py", line 200, in randrange

raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, 
istop, width))

 ValueError: empty range for randrange() (100,1, -99)




samedi 30 mars 2019

Javascript/Qualtrics: randomly drawing unique pairs of unique elements from an array

I am designing a custom conjoint experiment and have a Javascript issue. Participants repeatedly choose between two options distinguished by one of twelve randomly assigned levels of a single attribute. I am having difficulties with the Javascript necessary for two changes from a standard design: (a) preventing the random selection of identical levels for the two options and (b) preventing the random selection of identical options across choices. The former happens because I am currently randomly drawing two elements with replacement from an array of values. My approach to this is to randomly draw the elements without replacement by creating a new, filtered array. However, this doesn't seem to work:

\\ Define array of attribute levels, randomly draw an element
var foo = ["a", "b", "c", "d"];
bar_a = [ foo[Math.floor(Math.random()*foo.length)] ];

\\ Define a new array without the drawn element
var filtered = array.filter(function(value, index, arr){
    return value != bar; });

\\ Randomly draw an element from smaller array
bar_b = [ filtered[Math.floor(Math.random()*filtered.length)] ];

\\ Save values to embedded data fields to be piped into HTML table
Qualtrics.SurveyEngine.setEmbeddedData('bar_a1', bar_a);
Qualtrics.SurveyEngine.setEmbeddedData('bar_b1', bar_b);

The latter problem entails checking whether the result of the above matches the values of earlier sets of draws. I'd like to repeat the above process (presumably in a loop) until the pair of values drawn are not identical to earlier pairs (i.e. respondents don't face identical choice options ever). Is there a loop perhaps for this? Psuedo-code below:

\\ Take a new set of random draws repeating above
\\ Define array of attribute levels, randomly draw an element
var foo = ["a", "b", "c", "d"];
bar_a = [ foo[Math.floor(Math.random()*foo.length)] ];

\\ Define a new array without the drawn element
var filtered = array.filter(function(value, index, arr){
    return value != bar; });

\\ Randomly draw an element from smaller array
bar_b = [ filtered[Math.floor(Math.random()*filtered.length)] ];

\\ Check if the numbers are different
bar_a == ${e://Field/bar_a1} &&  bar_b == ${e://Field/bar_b1}

\\ If above is TRUE, repeat the above until FALSE




How does Ruby generate random numbers using

So when using, for example, rand(10), how does ruby generate the random number? I have very little knowlege about random number generation techniques, so I would like to get to know them better.




need a random number generator

i need to generate a random number between -0.5 and 0.5.

ive tried a solution on stack overflow by the user anthony pegram. i have modifyed it a bit ( i need the method to be called and used in a console.write line)

public static float nextfloat()
        {
            Random random = new Random();
            double val = random.NextDouble();
            val -= 0.5;

            return float.MaxValue * (float)val;
        }

by trying this i get numbers which are beyond -0.5 and 0.5 i get things like

1.7 1.005 etc




RANDOM OBJECTS AT THE SAME TIME

I am trying to create 5 objects at the same time. However, I want it to stop after creating 5 objects at the same time. I tried to use COUNT variable to count the targets. However, it does not work.

void drawTarget(target_t arr[]){

srand(time(NULL));


int i;

 r = rand() % 256;
 g = rand() % 256;
 b = rand() % 256;


for(i=0; i<MAX; i++){


    tX = rand() % 256;
    tY = rand() % 256;

    arr[i].xTarget = tX;
    arr[i].yTarget = tY;
    glColor3ub(r,g,b);
    glBegin(GL_TRIANGLES);
    glVertex2f(arr[i].xTarget + 20, arr[i].yTarget = tY+ 50);
    glVertex2f(arr[i].xTarget + 40,arr[i].yTarget = tY + -180);
    glVertex2f(arr[i].xTarget + 100, arr[i].yTarget = tY + -20);
    glEnd();

    count++;

}



while(count < MAX)
count++;



glColor3f(0,0,1);

}




how can I draw rectangles with random height and color?

I'm building app that shows random histogram by clicking on button. All rectangles of histogram should have different random colors and values from -100 to 100, for example.

I already have Y and X axis and some variables for the future.


Pen coord = new Pen(Color.Black);


private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            width = 350;
            g.TranslateTransform(50, 200);
            g.DrawLine(coord, 0, -200, 0, 210); //Y axis
            g.DrawLine(coord, 0, 0, 700, 0); //X axis

tried to add generation of random colors and draw rectangles like that. I understand that I need to add loop, but it doesn't work properly, because rectangles are drawn upside down when I generate Y axis coordinates for them. Also they are all the same and when I'm trying to change their color or height I'm getting some errors.

Random randcolor = new Random(); 
randcolor.Next(0, 256); 
SolidBrush painter = new SolidBrush(Color.FromArgb(randcolor.Next(256), randcolor.Next(256), randcolor.Next(256))); 
Rectangle rect = new Rectangle(0, 0, 50, 100); 
e.Graphics.FillRectangle(painter, rect); 

Probably I need to create List for rectangles and store them there. I need some parts of code to make this program work properly because i still have some problems with syntax and understanding with work of Lists.




How would be `function x = y` in R?

Consider the following code (Matlab)

function counter = ross_fpt_uniform
%ROSS_FPT_UNIFORM generates the first passage time of the sum of uniform
% random variables exceeding level 1.
s = 0;
counter = 0;
while (s <= 1)
s = s + rand(1,1);
counter = counter + 1;
end
end %ross_fpt_uniform

I am having problems translating function counter = ross_fpt_uniform in R

Confuses me how should I treat the counter because here counter = counter + 1; seems like it's a variable. Is it a function or a variable and how do I write on R?

Could someone please help ?




Using a Randomly Selected Long as the Database Primary Key

Is it reasonable to use a randomly selected long integer as the primary key value when storing new rows in a database (i.e. PostgreSQL or SQL Server)?

I am doing some maintenance work on an existing code base and this is how the code currently works when new items are added. I brought this up with the main developer, they maintain that this "works well" and has "never caused a problem". Still, I have to say, it makes me uncomfortable and I am hoping for either a reason to leave the code the same or an excuse to switch to GUIDs.




Type 'Double' has no member 'random'

I am fairly new to IOS development, I am trying to use the swift double.random(in:).

this is the example from the documentation:

for _ in 1...3 {
    print(Double.random(in: 10.0 ..< 20.0))
}
// Prints "18.1900709259179"
// Prints "14.2286325689993"
// Prints "13.1485686260762"

Here is my code, I am trying to generate random colors:

UIColor(red: Double.random(in: 1.0 ..< 251.0),
        green: Double.random(in: 1.0 ..< 251.0),
        blue: Double.random(in: 1.0 ..< 251.0),
        aplha: 1);

But I keep getting the Error

Type 'Double' has no member 'random'




Pseudo-randomly selecting and generating a permutation in O(1) space

I have a piece of code where I have to look in a bunch of vectors for the first element which satisfies a given predicate. I have to do this multiple times, and as there are multiple elements which satisfy my predicate, I'd like to somewhat randomize the order in which I check, so to give everybody a fair chance of being discovered.

At the same time, I'd like this to be as performant as possible, so I really don't want to shuffle/allocate or anything of the sort.

This requirements have sent me into a spiral of random number generation, linear congruential generators, LFSRs, Xorshifts, criptography, but I'm having a hard time figuring a good solution out.

I realize that picking a permutation truly randomly is impossible. What I'm looking for is a generator which I can pass

  • N
  • a seed
  • some number of random bits (in the form of number parameters generated from a separate PRNG)

and it will cycle through one of the permutations of N elements (picked pseudo-randomly).

This answer provides what I think could be a good starting point; a generator for 16 bits in the form of

P(x) = ((x ^ 0xf) ^ (x << 2) + 3) & 0xf 

Which one can iterate over discarding any number < N. I like this since it does not require me to find a prime number, only the next highest power of 2 which is fast with bit-fiddling. I have played with this and I have a generator of the form

P(x) = ((x ^ (next_pow2 - 1)) ^ (x << z) + y) & (next_pow2 - 1)

Picking z and y randomly gives me different permutations. However, I don't understand exactly how this works, whether it can be improved, and in what range y and z should be to be as fair as possible (since changing parameters will result in duplicating some permutations).

Could anyone point me out whether there's a better solution, and what to read exactly to learn more? This field looks terribly complicated for a novice, and I don't know where to start.




Why does this piece of code write/print all 0.0 instead of different random numbers?

I'm trying to generate random numbers and write them to a file, then print them. Instead all zeros such as this 0.0 are printed by line in the console and in the file its written in ASCII code.

I have already tied using different java input classes and using the random number generator.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.Random;


    public static void main(String[] args) throws IOException {
        makefile(10, "inputHW02.txt");

        double[] sizearray0 = new double[10];
        int i = 0;
        Scanner inFile;

        inFile = new Scanner(new File("inputHW02.txt"));

        while (inFile.hasNextDouble()) {
            sizearray0[i] = inFile.nextDouble();
            i++;
        }

        for (int r = 0; r < sizearray0.length; r++)
            System.out.println(sizearray0[r]);

        inFile.close();
    }

    public static void makefile(double n, String filename) throws IOException {

        FileOutputStream writer = new FileOutputStream(filename);
        DataOutputStream dos = new DataOutputStream(writer);
        Random rand = new Random();

        for (int i = 0; i < n; i++) {
            dos.writeInt((int) 60);
            ;

        }
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }

I expect the file and output console should have random numbers separated on a new line such as 10.0 23.0 1.0 and so forth.




vendredi 29 mars 2019

Assigning random rgb values for each vert in Maya with Python through polyColorPerVertex command

I am creating an object in Maya as well as a new colorSet for it. Then I'm trying to assign random rgb values for each vert inside that colorSet.

Here is my initial setup for spawning an object and assigning colorSet with color

import maya.cmds as cmds
import functools
import random

colorList =cmds.ls('colorSet*' )
sphereList = cmds.ls( 'mySphere*' )
if len( sphereList ) > 0:
    cmds.delete( sphereList)

result = cmds.polySphere ( r=50, sx=random.randrange(10, 100), sy=random.randrange(10,100), name='mySphere#' )
result = cmds.polyColorSet ( create=True, colorSet='colorSet1')
cmds.polyColorPerVertex('mySphere*',clamped=False, rgb=(1,0,0))

The code runs fine and the ColorSet is created but it doesn't fill the object with color. i.e. the sphere is not red secondly I don't really know how to grab all verts of an object and assign color through the polyColorPerVertex

Each vert should receive a random rgb value and not just be filled with a uniform color across the whole mesh.




Adjusting the mean and standard deviation of a list of random numbers?

I have to create a list of random numbers (with decimals) in the range between -3 and 3. The problem is that the list must have a mean of 0 and a standard deviation of 1. How can I adjust the mean and standard deviation parameters? Is there a function I can use?

I was already able to create a list of random numbers between -3 and 3.

import random


def lista_aleatorios(n):
    lista = [0] * n
    for i in range(n):
        lista[i] = random.uniform(-3, 3)
    return lista

print("\nHow many numbers do you want?: ")
n = int(input())

print (lista_aleatorios(n))




let vs do in monadic values

What's the difference in using let or do when trying to work with monadic values? (not sure if this is the right way to phrase it)

For example:

*Main> dupRand = let i = randomRIO (1, 10) in sequence [i, i]
*Main> :t dupRand
dupRand :: (Random a, Num a) => IO [a]
*Main> dupRand
[8,3]
*Main> dupRand
[2,9]
*Main> dupRand
[9,5]

*Main> dupRand2 = do i <- randomRIO (1, 10); sequence [i, i]
*Main> :t dupRand2
dupRand2 :: (Random a, Num a) => IO [a]
*Main> dupRand2
[6,6]
*Main> dupRand2
[9,9]
*Main> dupRand2
[5,5]

why is it that in dupRand2, the function successfully duplicates a random value, whereas in dupRand, the function just seems like it generates two random values?




Generate a 9 digit number with no more than 3 duplicate numbers

I'm trying to create a scratch card like system in php that displays a winner or loser based on random generate numbers.

I know i can create a random number using mt_rand or rand ranging from 0-9 but the issue i have is making sure there is no more than one duplicate of 3

9 digit number is out put with 100% no matching digits or a 9 digit number with one number appearing a maximum of 3 times like so 2948410427

the reason i am doing it this way is i have a lot of themed cards each theme has 10 small icons these icons are numbered 0-9 web the user opens my application it will randomly select a theme and then send a request to my server with this theme

the server will then generate the numbers and then these numbers will be output in json like so

{
    "Theme": "Space",
    "one": 3,
    "two": 6,
    "three": 0,
    "four": 7,
    "five": 1,
    "six": 3,
    "seven": 2,
    "eight": 9,
    "nine": 3,
    "winner": true
}

my application will then use these numbers to link to the images

1.png
2.png
3.png

and so on filling up the scratched grid.

this is the best way i can think todo it wile also allowing for random theme selection and random winners.

if anyone else can think of a better way i would be happy to hear it.




Generating a URL friendly, unguessable, Unique ID in PHP or MySQL

I'm trying to create a unique id for a MySQL database table that can be used in a URL


It should be

  • URL friendly - preferably alphanumeric
  • Unguessable - it should be difficult to randomly find another ID by manipulating the value in the URL
  • Unique - very unlikely to collide with an existing number

I toyed with using UUID() or UUID_SHORT() from MySQL but while these are unique, other values may be guessable from a known ID

The same could be said for PHP's uniqid() function


I'm currently looking at generating a 33 character hex string using

uniqid(bin2hex(random_bytes(10))) 

But I'm wondering if that is more or less likely to be unique than a random 33 character hex string using

dechex(random_int(0,15)).bin2hex(random_bytes(16))




How to create a random number generator function using JavaScript without using the Math.random() function?

I want to create a random number generator function using JavaScript that will return a random number between 0 and 1. Is it possible to create a custom random number generator function without using the Math.random() function?

I tried this approach. It works but I don't know if it is really random or there is any pattern?

var lastRand = 0.5;
function rand(){
    var x = new Date().getTime()*Math.PI*lastRand;
    var randNum = x%1;
    lastRand = randNum;

    return randNum;
}

// Output
for(var n = 0; n < 50; n++){
    console.log(rand());
}

This function depends on the variable lastRand to generate the number. But I want more efficient way to do it.




Why does the quick sort algorithm duration increase when the range of integers in an array is narrow?

I am trying to measure the duration for both Merge Sort and Quick Sort functions using std::chrono time calculations and using randomly generated arrays of integers within some range [A, B], the sizes of the arrays vary from 5000 to 100,000 integers.

The goal of my code is to prove that when the method of picking the (pivot) in quick sort is improved, the quick sort function ends up taking less time to process the array than merge sort, the way I pick the pivot is using the random index method to minimize the probability of having a complexity of (n^2), However in some cases which I will describe below, the quick sort ends up taking more time than merge sort and I would like to know why this occurs.

case 1: The range of the numbers in the array is small which increases the probability of having duplicate numbers in the array.

case 2: When I use a local IDE like clion, the quick sort function takes a lot more time than merge sort, however an online compiler like IDEONE.com gives similar results in both sorting algorithms (even when the range of the generated integers is small)

here are the results I got in the mentioned cases(the first row of numbers is merge sort results, the second row is quick sort results):

1-clion results narrow range of numbers (-100, 600) https://i.ibb.co/fNJ9yt1/CLION-GRAPH.png

2-clion results with a wide range of numbers (INT_MIN, INT_MAX) https://i.ibb.co/PwGDq8Y/CLION-RESULTS-WIDERANGE.png

3-IDEONE results with a narrow range of numbers (-100, 600) https://i.ibb.co/SRW20cM/IDEONE-GRAPH.png

4- IDEONE results with a wide range of numbers (INT_MIN, INT_MAX) https://i.ibb.co/rHyDf5f/IDEONE-RESULTS-WIDERANGE.jpg

#include <bits/stdc++.h>
#include <chrono>
#include <random>

using namespace std;

mt19937 gen(chrono::steady_clock::now().time_since_epoch().count());
int* generateArray(int size)
{
    int* arr = new int[size];
    uniform_int_distribution<> distribution(INT_MIN, INT_MAX);
    for (int i=0; i < size; ++i)
    {
        arr[i] = distribution(gen);
    }
    return arr;
}
void merge(int* leftArr, int nL, int* rightArr, int nR, int* mainArr)
{
    int i=0, j=0, k=0;
    while (i < nL && j < nR)
    {
        if (leftArr[i] < rightArr[j]) { mainArr[k++] = leftArr[i++]; }
        else { mainArr[k++] = rightArr[j++]; }
    }
    while (i < nL){ mainArr[k++] = leftArr[i++]; }
    while (j < nR){ mainArr[k++] = rightArr[j++]; }
}
void mergeSort (int* mainArray, int arrayLength)
{
    if (arrayLength < 2) { return; }
    int mid = arrayLength/2;
    int* leftArray = new int[mid];
    int* rightArray = new int[arrayLength - mid];
    for (int i=0; i<mid; ++i) {leftArray[i] = mainArray[i];}
    for (int i = mid; i<arrayLength; ++i) {rightArray[i - mid] = mainArray[i];}
    mergeSort(leftArray, mid);
    mergeSort(rightArray, arrayLength-mid);
    merge(leftArray, mid, rightArray, arrayLength-mid, mainArray);
    delete[] leftArray;
    delete[] rightArray;
}


int partition (int* arr, int left, int right)
{
    uniform_int_distribution<> distribution(left, right);
    int idx = distribution(gen);
    swap(arr[right], arr[idx]);
    int pivot = arr[right];
    int partitionIndex = left;
    for (int i = left; i < right; ++i)
    {
        if (arr[i] <= pivot)
        {
            swap(arr[i], arr[partitionIndex]);
            partitionIndex++;
        }
    }
    swap(arr[right], arr[partitionIndex]);
    return partitionIndex;
}
void quickSort (int* arr, int left, int right)
{
    if(left < right)
    {
        int partitionIndex = partition(arr, left, right);
        quickSort(arr, left, partitionIndex-1);
        quickSort(arr, partitionIndex+1, right);
    }
}

int main()
{
    vector <long long> mergeDuration;
    vector <long long> quickDuration;
    for (int i = 5000; i<= 100000; i += 5000)
    {
        int* arr = generateArray(i);
        auto startTime = chrono::high_resolution_clock::now();
        quickSort(arr, 0, i - 1);
        auto endTime = chrono::high_resolution_clock::now();
        long long duration = chrono::duration_cast<chrono::milliseconds>(endTime - startTime).count();
        quickDuration.push_back(duration);
        delete[] arr;
    }
    for (int i = 5000; i <= 100000; i += 5000 )
    {
        int* arr = generateArray(i);
        auto startTime = chrono::high_resolution_clock::now();
        mergeSort(arr, i);
        auto endTime = chrono::high_resolution_clock::now();
        long long duration = chrono::duration_cast<chrono::milliseconds>(endTime - startTime).count();
        mergeDuration.push_back(duration);
        delete[] arr;
    }
    for (int i = 0; i<mergeDuration.size(); ++i)
    {
        cout << mergeDuration[i] << " ";
    }
    cout  << endl;
    for (int i = 0; i<quickDuration.size(); ++i)
    {
        cout << quickDuration[i] << " ";
    }
}




Random number generator in Python when the mean is known

In Python, I am trying to get a list 50 random numbers between [0,100] that have a mean of 25. All the information I have is below.

Total = 250
Number_of_users = 10
Average_score = 25

In the past i have used the Gaussian function in random but without the standard deviation i am a bit stuck. Is there another way of doing it?

My output would be something like:

[20, 30, 18, 21, 27, 30, 15, 24, 31, 30]




Need explanation about random function swift

Got a question about my random function: why is it giving this error?

'4294967295' is not exactly representable as 'Float'; it becomes '4294967296'

-

my code is

func random() ->CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func  random(min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

it doesn't change the functionality of the application but it just appeared out of nowhere.

thanks in advance!




jeudi 28 mars 2019

How do I make 3 random numbers in C# as a row of 3 in an array and assign each to 3 variables?

I'm trying to generate 3 random numbers and output it onto a label as an array with 3 in a row. I am just unsure about doing so. So far, I initialized my randomValue as

Random valueRandom = new Random();

private void Main()
    {
        for (int i = 1; i <= gameAmountInteger; i++)
            DoNextNumber(valueRandom);
    }


private void DoNextNumber(Random valueRandom)
    {
        int int1;

        int1 = valueRandom.Next(0, 1);

        displayLabel.Text = valueRandom.ToString();
    }

It should be (range of 0 - 10) 3, 5, 2




Can I save a RandStream and load it at a later time to continue a simulation?

My question is whether a RandStream in matlab can be saved to a file and loaded at a later time to continue a simulation picking up the random number sequence from it's last point. All I can find is that one can save a RandStream e.g:

s1 = RandStream('mt19937ar','Seed',1); savedState = s1.State;

nothing about saving a stream to a file and loading it at another run

Thanks!




How to show all of possible result from random.shuffle() [duplicate]

This question already has an answer here:

If I have a = [ 1, 2, 3] So it has 6 ways possible results if i use random.shuffle(a) right?

I want all of possible results so how I can do that?

Ps.I'm sorry for my English or everything this is my first time




SQLite random nested query sometimes doesn't return result

I have two tables, a and b, connected by a many-to-many relational table, c. For the needs of my program, I need 5 unique, random results.

First, I create a temporary table by randomly selecting one of the rows (varA) from table a. I create another temporary table by randomly selecting from table b one of the rows that is related to varA by table c (var1). I create a third temporary table by randomly selecting another row from table b related to varA that isn't var1 (var2). I then want to randomly select a row from table a that's related to var1 by table c that isn't varA (varZ). Finally, I want to randomly select a row from table a that's related to var2 by table c that is neither varA or varZ (varY).

Hopefully that was followable.

With what I have, sometimes it only returns once or even zero results. How do I always ensure that there's a result?

Alternatively, if there's a more elegant way to do this, I'm all ears. Or eyes, because I'll be reading it...




Convergence to different results for an optimization

i am using the PyOpt module to solve a problem of convex optimization. The optimization always gives me a result and the value to which it converges looks like it is minimizing my target function, but for different runs of my code i get different solutions. My problem is convex but not strictly convex, so I'd expect the existence of different solutions, but since the starting point of my algorithm is basically the same for the two runs I was wondering if this could be due to some random procedure in the algorithm I am using. I am using the slsqp algorithm, does anybody know if it uses any random procedure?




How to random number with length 10 and not duplicate [on hold]

I using java 8 and i want random value with length equal 10 and it not duplicate value random. Example:

  1. 6379797797

  2. 2213213123

  3. 2222222222

All element after random not duplicate value before random. How to do that ? Thank you




unique vector with random numbers

My program is to write a c++ program initializes an integer vector v of size SIZE with distinct random integers each in a range [0,2*SIZE], how can I ensure allof my numbers in the vector are unique how can I edit my initialize vector so that it works properly, something in my logic is flawed.

#include <iostream>
#include <ctime>
#include <vector>
#include <iomanip>
#include<algorithm>

const int SIZE =10;
unsigned int seed = (unsigned)time(0);
using namespace std;

double random (unsigned int &seed);
void print_vector (vector<int> :: iterator b,
                   vector<int> :: iterator e );
void initialize_vector(vector<int> &v);
vector<int>v;

int main()
{
    cout << endl;
    initialize_vector(v);
    cout << "Vector : " << endl;
    print_vector(v.begin(), v.end());
    return 0;
}

double random(unsigned int &seed)
{
    const int MODULUS = 15749;
    const int MULTIPLIER = 69069;
    const int INCREMENT = 1;
    seed = ((MULTIPLIER*seed)+INCREMENT)%MODULUS;
    return double (seed)/MODULUS;
}

void initialize_vector(vector<int> &v)
{
    vector<int> used;
    int count_unused, k;
    for (int i=0; i<2*SIZE; i++)
    {
        used.push_back(0);
    }
    for (int i=0; i<SIZE; i++)
    {
        int j= (random(seed)*(2*SIZE+1-i)) + 1;
        count_unused = 0;
        k = 0;
        while (count_unused != j)
        {
            if (used[k] == 0)
                count_unused++;
            k++;
        }
        used[k] = 1;
        v.push_back(j);
    }

}

void print_vector (vector<int> :: iterator b,
                   vector<int> :: iterator e )
{
    vector<int> :: iterator p =b;
    while(p<e)
        cout << setw(3) << (*p++);
    cout << endl;
}




Generating a random bit stream in Rcpp efficiently

I have an auxiliary function in the R package I'm currently building named rbinom01. Note that it calls random(3).

int rbinom01(int size) {
  if (!size) {
    return 0;
  }

  int64_t result = 0;
  while (size >= 32) {
    result += __builtin_popcount(random());
    size -= 32;
  }

  result += __builtin_popcount(random() & ~(LONG_MAX << size));

  return result;
}

When R CMD check my_package, I got the following warning:

* checking compiled code ... NOTE
File ‘ my_package/libs/my_package.so’:
  Found ‘_random’, possibly from ‘random’ (C)
    Object: ‘ my_function.o’

Compiled code should not call entry points which might terminate R nor
write to stdout/stderr instead of to the console, nor use Fortran I/O
nor system RNGs.

See ‘Writing portable packages’ in the ‘Writing R Extensions’ manual.

I headed to the Document, and it says I can use one of the *_rand function, along with a family of distribution functions. Well that's cool, but my package simply needs a stream of random bits rather than a random double. The easiest way I can have it is by using random(3) or maybe reading from /dev/urandom, but that makes my package "unportable".

This post suggests using sample, but unfortunately it doesn't fit into my use case. For my application, generating random bits is apparently critical to the performance, so I don't want it waste any time calling unif_rand, multiply the result by N and round it. Anyway, the reason I'm using C++ is to exploit bit-level parallelism.

Surely I can hand-roll my own PRNG or copy and paste the code of a state-of-the-art PRNG like xoshiro256**, but before doing that I would like to see if there are any easier alternatives.

Incidentally, could someone please link a nice short tutorial of Rcpp to me? Writing R Extensions is comprehensive and awesome but it would take my weeks to finish. I'm looking for a more concise version, but preferably it should be more informative than a call to Rcpp.package.skeleton.




Generate number by groovy X and Y with range

I want to create a keyword that following method to generate two value X and Y with limitation starting the value X = from 120 -200 and Y = from 140 to 200

Thank you

@Keyword
def generatorNumber(int number, int n) {
    return new Random().with({
        (1..n).collect({
            number[nextInt(number.length())]
        }).join()
    })
}

enter image description here enter image description here




mercredi 27 mars 2019

How can I return a new non-repeating item from a list in Django while keeping track of previous items?

I'm working on an app where a user can select a category, which will return a random selection from that category. The main functionality I'm trying to implement is once an item is selected, it can no longer be randomly selected in session.

For example, we have 3 categories of photos: landscape, urban, and portraits, each with 5 photos. A user selects urban, is then redirected to a details page with a random photo from urban category. He can either refresh the page or click a button to get a new photo from that category. When that category is out of new photos, he is redirected home.

I am able to get my random item from the selected category through converting a queryset to a list, but the data isn't persisting. On every refresh the list I have resets, thus a previously selected photo can come up again, ignoring the the fact that I removed the item from the list after it was selected.

Here's the views.py with the function responsible for this:

def randomPhoto(request, pk, **kwargs):

    # queryset to get all photos from selected category
    gallery = list(Photos.objects.filter(id=pk)
    .values_list("partof__category", flat=True))

    # select random photo from list
    last = len(gallery) -1
    randomInt = random.randint(0, last)
    randomPic = gallery[randomInt]

    gallery.remove(randomPic)

    if len(gallery) == 0:
        return render(request, 'gallery/category_select.html')

        photoDetails = {
        'category' : Category.objects.get(id=pk),
        'author' : Author.objects.get(tookin__category=randomPic),
        'uploadedPhoto' : 'http://localhost:8000/media/' + 
    str(Photo.objects.get(category=randomPic).photoUpload),
        'randomPic' : randomPic,
        }

        return render(request, 'gallery/random_photo.html', {'photoDetails': photoDetails})

The functionality I'm looking for is (where each number is an object/item in list):

  • User selects urban category:
    • urban has the following items: [1, 2, 3, 4, 5]
    • random [3] selected from urban
    • urban now has [1, 2, 4, 5]
  • User refreshes:
    • random [4] selected
    • urban now has [1, 2, 5]
  • User refreshes:
    • random [2] selected
    • urban now has [1, 5]
  • User refreshes:
    • random [5] selected
    • urban now has [1]
  • User refreshes:
    • random [1] selected
    • urban now has []
  • User is redirected home

I believe my problem lies in having to configure either sessions or cookies to have the data persist in an anonymous session. Eventually I will be adding a Users module so each user will have their browsing history saved but for now I want it to work just as an anonymous user.

I've tried adding SESSION_SAVE_EVERY_REQUEST = True to settings.py and placing request.session.modified = True in my views.py, though I doubt I'm implementing them properly. I've read some SO questions on sessions and cookies but wasn't able to find something to work with my issue. The Django Sessions Doc seemed interesting but overwhelming. I'm not sure where to begin trying to experiment with wiring the sessions aspect together.

I've been stuck on this issue for a few days now and am wondering if there's an easy/Pythonic way to achieve having my web app give me a non-repeating item from a list until none are left within the session.




Generate list of floats where each number is inferior to the number of another list of floats

I am using the following code to get a random list of floats:

random_A = np.random.uniform(low=0, high=10, size=(50,))

So I get a list of 50 floats

[0.35664866 4.76750599 2.05083389 9.53811567 5.36920383 8.91679955
 2.19965617 2.62523134 6.55224616 9.35766331 5.79652488 4.23194067
 2.72168337 5.31431884 8.3975979  9.29497168 5.42797236 5.64302212
 2.91821098 5.06305922 1.88212402 0.24593891 9.45021432 0.95423611
 9.36860165 2.46100709 3.80709829 1.08442665 3.28513088 9.75743916
 5.36187267 4.61001088 0.17912406 6.52406152 3.26927165 4.40187936
 6.79600876 8.10418648 1.06927133 5.3087785  1.85829928 2.20111922
 1.6910625  6.25714944 0.29338196 5.73195802 0.73971446 3.62506435
 9.0166149  3.90316395]

What I would like to get now is another list of 50 floats let us call it random_B where each float of that list is inferior to the number compared in the first list (random_A). Could you please help me?

Regards




How to generate random and lattice points inside of an irregular object?

I have an irregular 3d object and want to know the surface of this object. The object can be both convex or non convex type. I can get the surface of this object applying any method like marching cube, surface contour, or isosurface.

All this methods give me triangulated mesh which is basically contains edges and vertex.

My task is to generate random and lattice points inside the object.

How should i check whether my point is inside or outside?

Any suggestion? Thanks a lot.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

from skimage import measure, io
from skimage.draw import ellipsoid
import skimage as sk 
import random 

I=np.zeros((50,50,50),dtype=np.float)

for i in range(50):
  for j in range(50):
    for k in range(50):
        dist=np.linalg.norm([i,j,k]-O)
        if dist<8:
            I[i,j,k]=0.8#random.random()  
        dist=np.linalg.norm([i,j,k]-O2)
        if dist<16:
            I[i,j,k]=1#random.random()  

verts, faces, normals, values = measure.marching_cubes_lewiner(I,0.7)

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
mesh = Poly3DCollection(verts[faces])
mesh.set_edgecolor('k')
ax.add_collection3d(mesh)
plt.show()

%now forget the above code and suppose i have only verts and
%faces information. Now how to generate random points inside this Data

Data=verts[faces]
???????




How and Why the last 8 bytes MUST be overwritten in TLS 1.3 as described below if negotiating TLS 1.2 or TLS 1.1?

In RFC 8446. About the random in ServerHello send by Server.

In 4.1.3. Server Hello

32 bytes generated by a secure random number generator. See Appendix C for additional information. The last 8 bytes MUST be overwritten as described below if negotiating TLS 1.2 or TLS 1.1, but the remaining bytes MUST be random. This structure is generated by the server and MUST be generated independently of the ClientHello.random.

Why and How ?

The last 8 bytes MUST be overwritten as described below if negotiating TLS 1.2 or TLS 1.1




Script to display image1, and after (random ms) show image2 and stop

I've been looking around, and there are a lot of questions (and answers) about changing image after a few seconds, but I didn't find anything that works for me.

What I want;

A script, PHP or Java (prefer PHP to hide function from users) that displays an image1 and after a few milliseconds (500-5000) it changes it to image 2, and stops there.

I have no idea how to create this, so any help would be appreciated..




How to randomly split data into three equal sizes?

I have a dataset with 9558 rows from three different projects. I want to randomly split this dataset in three equal groups and assigning a unique ID for each group, so that Project1_Project_2_Project3 becomes Project1, Project2 and Project3.

I have tried many things, and googled codes from people with similar problem as I have. I have used sample_n() and sample_frac(), but unfortunately I can't solve this issue myself :/

I have made an example of my dataset looking like this:


ProjectName <- c("Project1_Project2_Project3")
data <- data.frame(replicate(10,sample(0:1,9558,rep=TRUE)))
data <- data.frame(ProjectName, data)

And the output should be randomly splitted in three equals group of nrow=3186 and then assigned it to the values

ProjectName Count of rows
Project1     3186
Project2     3186
Project3     3186





Player 1 always wins. Is this because random.shuffle isn' truely random or have I made a logic error?

The code always shows player 1 as the winner despite random.shuffle supposedly making the odds random every time. There isn't any straight forward pattern I have been able to see in how the cards are shuffled or how player 1 always wins the game, as they don't always win each round. Regardless they always win the whole game.

I want to know if this is a problem with me using sudo-random shuffling or have I made a logic error at some point that I failed to notice.

I have tried putting prints in at various points to try and see if I am getting unforeseen/undesired outcomes at different point but haven't noticed any weird outputs.

I tried double shuffling the values to see if that changed anything but the outcome was still always player 1.

Player 2 does win when I don't shuffle so I assume all the maths and checks are right.

#cardShuffler
def cardShuffler(cards):
    from random import shuffle
    shuffle(cards)
    print(cards)
    return(cards)


#cardArrayDeciphers
#colour
def cardColour(selectedCard):
    colour = selectedCard[0] #takes the letter on the card intidacting colour
    return colour
#number
def cardNum(selectedCard):
    number = int(selectedCard[1]) #takes number in a card and convert str to int
    return number

#winnerCalc
def winnerCalc(p1Card, p2Card):
    colour1 = cardColour(p1Card)
    colour2 = cardColour(p2Card)
    num1 = cardNum(p1Card)
    num2 = cardNum(p2Card)
    #pattern should go red > black > yellow > red
    if(colour1 == "r")and(colour2 == "b"):
        winner = ("p1")
    elif(colour1 == "b")and(colour2 == "y"):
        winner = ("p1")
    elif(colour1 == "y")and(colour2 == "r"):
        winner = ("p1")
    elif num1 > num2:
        winner = ("p1")
    else:
        winner = ("p2")
    print("winner "+str(winner)) #debug
    return winner

#gameVals
searchVal = -1
p1WinCards = []
p2WinCards = []
cards = cardShuffler(cards) #function = cardShuffle

#gameLoop [player 1 always wins!]
while (searchVal != 29):
    p1Given = searchVal + 1 #where the code looks for p1 card
    p2Given = searchVal + 2
    p1Card = cards[p1Given]
    p2Card = cards[p2Given]
    searchVal = p2Given
    winner = winnerCalc(p1Card, p2Card) #function = winnerCalc
    if winner == "p1": #giving the winner all the cards
        p1WinCards.append(p1Card)
        p1WinCards.append(p2Card)
    else:
        p2WinCards.append(p1Card)
        p2WinCards.append(p2Card)
    print("p1 " +str(len(p1WinCards))) #debug
    print("p2 " +str(len(p2WinCards))) #debug
if len(p1WinCards) > len(p2WinCards): #finding the final winner by the length of win cards
     winnerAbsolute = p1WinCards
     winnerName = input("Player 1 won! Please enter your name: ")
else:
    winnerAbsolute = p2WinCards
    winnerName = input("Player 2 won! Please enter your name: ")

I expect the output for winnerAbsolute to be sudo_random but the result is always player 1.




Is there a way to call the MS Excel =RAND() function from an external programme, like a c++ programme, for example?

I am trying to find a more reliable Random Number Generator than the c++ rand(). I am writing an encryption programme that, of course, needs random prime numbers to function properly. I have found that excel does a decent job in generating random numbers (at least it seems that way, at a first glace, in comparison to the standard c++ rand()). Any pointers, suggestions?




mardi 26 mars 2019

Unique Random Id using all 62 characters

I am looking for a way to generate unique random ids that will be as short as possible (similar to url shorteners) either through code or using MSSQL (preferable).

I know this can be done using NEWID or CRYPT_GEN_RANDOM(), but these methods only use A-F and 0-9, while I am looking for a solution that will use all 62 characters (A-Z,a-z,0-9) and therefore obtain a much shorter id.




How to generate different random number between 0 and 1 [duplicate]

This question already has an answer here:

I want to generate random Number every time I call the

   double Rand(){
srand ( time(NULL) );

double number=(double)rand()/((double)RAND_MAX+
return number;
}
cout<<Rand()<<endl;
cout<<Rand()<<endl;
cout<<Rand()<<endl;

the result is same for all of them. However I want them to be different. Could you please Help me??




C++ computing a probability for an event

I'm trying to simulate a Wild Pokemon encounter. As stated in the formula:

The rate of Pokémon encounter is determined from a simple mathematical formula:
1 in (187.5 / ( x )) per step.

Let x equal the a value which determines how rare the Pokémon is. The higher the encounter rate, 
the more common the Pokémon is.

Encounter-rate Table
Encounter type Encounter rate
Very common     10
Common          8.5
Semi-rare       6.75
Rare            3.33
Very rare       1.25

I want to run this probability after every press of a button. How do I simulate this with rand()?




Need help fixing random number

I'm learning python and was working on the random dice throw and when I run it it repeats the same number that is first shown after asked if you want to play again. Need help finding where im going wrong here. Thanks!

I've tried moving code around and also putting different varieties of the code. I'm just stumped.

import sys
import random
import time


greeting = "Welcome to my Dice Game!"
roll = "Lets roll this die!"
die = random.randint(0, 6)

print(greeting)
time.sleep(2)

answer = input("Want to play?")

while answer == "yes" or answer == "y":
    print(roll)
    time.sleep(2)
    print(die)
    answer = input("Want to play again?")
print("Thanks for playing!")

Welcome to my Dice Game! Want to play?yes Lets roll this die! 5 Want to play again?yes Lets roll this die! 5 Want to play again?y Lets roll this die! 5

This is what I get.




Why is my C code only generating every third random number?

I am trying to simulate the propagation of a worm across a network made of 100,000 computers. The simulation itself is very simple and I don't need any help except that for some reason, I am only getting every third random number.

Only the computers whose index modulo 1000 is less than 10 can be infected so when 1000 computers are infected, the program should be done. For some reason, my program only gets 329. When I lower the goal number and check the contents of the array, only every third computer has been changed and it is a consistent pattern. For example at the end of the array, only computers 98001, 98004, 98007, 99002, 99005, 99008 are changed even though the computers in between (98002, 98003, etc.) should be changed as well. The pattern holds all the way to the beginning of the array. When I try to get all 1000 changed, the program goes into an infinite loop and is stuck at 329.


#define NETSIZE 100000

double rand01();
void initNetwork();

unsigned char network[NETSIZE];
int scanrate = 3;
int infectedCount;
int scans;
int ind;
int time;

initNetwork();
time = 0;
infectedCount = 1;

while (infectedCount < 1000) { //changing 1000 to 329 stops the infinite loop
    scans = infectedCount * scanrate;
    for (int j = 0; j < scans; j++) {
        ind = (int) (rand01() * NETSIZE);
        if (network[ind] == 0) {
            network[ind] = 1;
            infectedCount++;
        }
    }
    time++;
}

double rand01() {
    double temp;
    temp = (rand() + 0.1) / (RAND_MAX + 1.0); 
    return temp;
}

void initNetwork() {
    for (int i = 0; i < NETSIZE; i++) {
        if (i % 1000 < 10) {
            network[i] = 0;
        } else  {
            network[i] = 2;
        }
    }
    // Patient 0
    network[1000] = 1;
}

In the above code, I expect the code to run until the 1000 vulnerable indexes are changed from 0 to 1.




How to find a random item from a C# list that has a specific value?

I'm trying to find an item from a list that has a field with a specific value; some entries will have the same value for this field, and in that case, I would like to return one of those at random. Does the List.Find function return one randomly if there are multiple entries that satisfy the criteria? The code below is what I currently have; if used on the same list multiple times, will it return the same entry every time if multiple satisfy the criteria? The list is large enough that I would prefer not to foreach through, build a list of everything that meets the criteria, and then randomly return one of those; I'm hoping to find a more efficient way. If that's not feasible for a List, is there another data structure more suited to this?

public List<Category> Categories {get; set;}

public Category CatByName(string nm)
        {
            string name = nm.ToUpper();
            return Categories.Find(x => x.CategoryName.Contains(name));
        }




randomize values within multiple columns of a data.frame

I'm trying to randomize the values in multiple columns but keep the row and column orders. Also, I only want to randomize values within each column. I basically want to use the function below on multiple columns of a data frame (not just column A).

sample(myDF$A)




How do I capture the minimum and maximum for 1000 random integers?

enter image description hereThe problem asks for 1000 iteration of the code.It must allow for whole numbers from 0-100000 and show how many odd numbers were generated during the iterations then show the highest number and lowest numbers generated. The first part of my code works and shows how many odd numbers were generated however I can not figure out how to capture/edit the smallest and largest numbers that were generated while the code was running.

I have tried many different methods including while loops and my if, else if, conditions. I have placed them through out my program however I am stuck. I know the problem is with the randNum going into the variables and staying there through each iterations without going back to zero.(when I run my code it displays zero for the smallNum and LargeNum.)

here is my work so far

using System;
using System.Windows.Forms;

namespace BissonnetteMessageBox

{
  class Program
    {
      static void Main(string[] args)

      {

        int oddNumCount = 0;
        int smallNum = 0;
        int largeNum = 0;
            Random randNum = new Random();


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

                int num = randNum.Next(100000);
                int remain = num % 2;

                if (remain != 0)
                {
                    oddNumCount++;


                }
                if (num < smallNum)
                {
                    num = smallNum;
                }
                else if (num > largeNum)
                {
                    num = largeNum;
                }

            }

            MessageBox.Show("the Number of odd numbers generated: " + oddNumCount +
                "\nSmallest number was: " + smallNum +
                "\nLargerst number was: "+ largeNum , "random number generation results");
        }
    }
}

Here is what the result is when I run my program.




Mergesort Sometimes Returning Wrong List- Java

I am writing a mergesort in Java. However, it is currently not always printing the correct order of passed integers in the List. Where did I go wrong exactly?

I have tried changing the size of the List (currently at 10 - variable arrayLength). Seemed to be fine for length 2, but I need very large sorted lists (n > 1000).

public class MergeSort {

static LinkedList<Integer> list = new LinkedList<>();

private static LinkedList<Integer> sortedList;
static int randomInt;

public static void main(String[] args) {


    fillArray();
    sortedList = mergeSort(list);
    printSortedList();
}

private static void fillArray() {

    int arrayLength = 10;
    for(int i = 0; i < arrayLength; i++ ) {
        randomInt = (int) (Math.random()*arrayLength);
        list.add(i, randomInt);
    }
}

private static LinkedList mergeSort(LinkedList<Integer> list) {


    int middle;
    LinkedList<Integer> leftHalf = new LinkedList<Integer>();
    LinkedList<Integer> rightHalf = new LinkedList<Integer>();


    if(list.size() == 1) {
        return list;
    }
    else {
        //split list in half (round if uneven).
        //Then, add the left half of the array to a new sub-array
        middle = list.size()/2;
        for(int k = 0; k < middle; k++) {
            leftHalf.add(list.get(k));
        }
        //repeat for right side but with total size
        for(int j = middle; j < list.size(); j++) {
            rightHalf.add(list.get(j));
        }

        //Recursively call mergeSort to split even further
        //Set new values of left + right
        leftHalf = mergeSort(leftHalf);
        rightHalf = mergeSort(rightHalf);

        //Now, with obtained current arrays, sort them
        mergeAll(leftHalf, rightHalf, list);
    }
    return list;
}

private static void mergeAll(LinkedList<Integer> leftHalf, LinkedList<Integer> rightHalf, LinkedList<Integer> list) {

    //Initialize to be used indices

    int left = 0;
    LinkedList<Integer> remainderArray;
    int remainderIndex;
    int indexList = 0; //index for whole list
    int right = 0;

    //Change index elements depending on size
    while (left < leftHalf.size() && right < rightHalf.size()) {
        if ( (leftHalf.get(left).compareTo(rightHalf.get(right))) < 0) {
            list.set(indexList, leftHalf.get(left));
            left++;
        } else {
            list.set(indexList, rightHalf.get(right));
            right++;
        }
        indexList++;
    }
    //Now we check if there are any elements left to be checked
    //in the left and right arrays respectively
    if(left >= leftHalf.size()) {
        remainderArray = rightHalf;
        remainderIndex = right;
    }
    else {
        remainderArray = leftHalf;
        remainderIndex = left;
    }

    //Now, either left or right is empty with one still containing elements
    for(int k = remainderIndex; k < remainderArray.size(); k++) {
        list.set(indexList, remainderArray.get(k));
        remainderIndex++;
    }
}

public static void printSortedList() {
    for(int i=0; i< sortedList.size(); i++ ) {
        System.out.println(sortedList.get(i));
    }
}
}

I want to print the array, ascending. Current output would be something like:

0 0 1 5 6 6 7 0 6

Which is clearly wrong, because of the 0 before the last element.

Thanks!




In C++, why can't I generate independent random integer samples using two default random engines

I want to have to independent random distributions of integers in a configurable range. What I had originally is illustrated by the following program:

#include <random>
#include <cstdio>
#include <cstdlib>
using namespace std;

int main(int argc, char* argv[])
{
    default_random_engine generator1;
    default_random_engine generator2;
    uniform_int_distribution<int> dist1(0,atoi(argv[1]));
    uniform_int_distribution<int> dist2(0,atoi(argv[2]));

    generator1.seed(0);
    generator2.seed(1);
    for (int i = 0; i < 60; i++)
        printf("(%d, %d)\n", dist1(generator1), dist2(generator2));
    return 0;
}

This turns out to always generate equal values when argv[1] and argv[2] are equal, and has less obvious dependencies when they are different as well. For in case I used different engine instances, and even seeded them differently.

What is going on here? I noticed that the problem goes away if I replace the default_random_engine by the mt19937, but that is something I never would have guessed. Also, is the other engine supposed to be able to produce independent samples?




Is there a function in Python which gives an output based on a probability distribution?

I have an array of numbers, say from 0 to 8, which may appear repetedly in the array. I need to choose a number among those, and the probability of a number coming out should be proportional to the number of times it appears in that array.

This is the original array: ([7, 0, 7, 8, 4, 4, 6, 5, 2, 6, 0, 1, 2, 3, 4, 5, 6, 7, 8])

This is the array containing the number of times each number appears in the array:
array([ 2., 1., 3., 1., 1., 4., 1., 5., 1.])

This is the code in which I tried to get one index (of deg) in the way I described before

        n = np.random.uniform(0, tot)
        for i in range(len(deg)):
            if n < deg[i]:
                return i
            n = n - deg[i]
        return i

I get an index, 2, but I don't know if the process is probabilitistically correct. What do you say?




Generating same random unique number every time for a given number

We are having a set of groups and each group will have billions of records. Each group will uniquely identified by an id and each record in a group will be uniquely identified by an id. By combining these two ids(concat(groupid, recordid)) we can identify a record across the groups.

Now we are trying to change these id (concatenated) values, in our reports we don't want to share the direct ids with the customers that we are maintaining, rather we want to convert the ids to some other uniqueid and share that with the customers, so that it will be difficult for them to identify the group.

We have tried generating hash (hmac256 hashing) values for this, but that didn't work for our customer as it has increased their storage drastically. If the current id is of 20 digit length, and generating 45 characters hash is not working. So looking for a better option in generating 20 digit/string or at least 25 digit/string unique value which will not be having collisions.

Looking for some inputs on this.

We have tried generating hash (hmac256 hashing) values for this, but that didn't work for our customer as it has increased their storage drastically. If the current id is of 20 digit length, and generating 45 characters hash is not working.

Example: groupId=910612349078 recordId=6234091234

for the above two values, the unique id that system generates as of today will be looking like as below: uniqueId=9106123490786234091234 (concat(groupId, recordId))

The expected behavior for unique id will be some random/hash value: newUniqueId = some hash or some random number




lundi 25 mars 2019

Use of random in C++

Are these codes equivalent in terms of "randomness" ?

1)

std::vector<int> counts(20);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 19);

for (int i = 0; i < 10000; ++i) {
    ++counts[dis(gen)];
}

2)

std::vector<int> counts(20);
std::random_device rd;
std::mt19937 gen(rd());

for (int i = 0; i < 10000; ++i) {
    std::uniform_int_distribution<> dis(0, 19);
    ++counts[dis(gen)];
}

3)

std::vector<int> counts(20);
std::random_device rd;

for (int i = 0; i < 10000; ++i) {
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 19);
    ++counts[dis(gen)];
}

4)

std::vector<int> counts(20);

for (int i = 0; i < 10000; ++i) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 19);
    ++counts[dis(gen)];
}

In the documentation of std::random_device, it is says that multiple std::random_device object may generate the same number sequence so the code 4 is bad, isn't it ?

And for the other codes ?

If I need to generate random values for multiple stuffs unrelated, must I need to create differents generators or can I keep the same ? :

1)

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> disInt(0, 10);
std::uniform_float_distribution<> disFloat(0, 1.0f);

// Use for one stuff
disInt(gen);

// Use same gen for another unrelated stuff
disFloat(gen);

2)

std::random_device rd1, rd2;
std::mt19937 gen1(rd1()), gen2(rd2());
std::uniform_int_distribution<> disInt(0, 10);

// Use for one stuff
disInt(gen1);

// Use another gen for another unrelated stuff
disFloat(gen2);




Generate random number for each rows of grid view at onClick of single button in asp.net

I want to generate a random number for each row(w.r.t ID column) of grid view in asp.net on a single click of a button(placed outside of the grid)and insert that ID and the random number in the database.




random sqrt string generation

i need to generate 4 numbers between 20 to 100 and to print all of them . after that i need to print and to know who the random number that his sqrt the closet one to the number that my ''man'' chose on the start . i know what i want to do but i didnt succeed. help thanks hi , i need to generate 4 numbers between 20 to 100 and to print all of them . after that i need to print and to know who the random number that his sqrt the closet one to the number that my ''man'' chose on the start . i know what i want to do but i didnt succeed. help thanks

public class RandomNumbers {

public static void main(String[] args){
    for(int i = 0; i < 5; i++){
        System.out.println((int)((Math.random() * 81) + 20));

    }
}




is there any other function (in c or c++) to generate random numbers?

I know a bit of rand() and how to use it; I know also that srand give the seed to rand, in order not to generate the same number, but is there any other function apart from that? The languages are C and C++




how to generate list of 5 random numbers between 10 and 100 in java and to print the biggest random

how to generate list of 5 random numbers between 10 and 100 in java and to print the biggest random number . how i do that and chose that( with no array) and i dont knot how to continue. help !

public class Random {

    public static void main(String[] args){

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

            System.out.println((int)((Math.random() * 91) + 10));
        }
    }
}




How to check to see if a random piece of an array is equal to specific array part?

I'm trying to get my string array to get a random string from it and if it is a certain string then it needs to print an outcome in my text area.

String[] items = new String[]{"nothing useful", "trash", "a fork"};

Said array.

Random rand = new Random();
String outcome = items[rand.nextInt(items.length)];

getting a random string from the array as a string named outcome.

if(outcome.equals(items[2])){
  textArea2.append("a fork" + "\n");
}

my attempt at getting it to put a "a fork" in a text area. All of my text areas work so that's not my problem.

I've tried to use .equals, ==, if(outcome=="a fork"), and various things like that without any of them working.

I need it to add 'a fork" to the text area named textArea2.




Problem loading application dependencies on heroku

I am trying to download a program on heroku, but when installing multiple dependencies I get an error.

'No matching distribution found for random'

Also for "time" and "pickle" dependencies. On the Internet I found that this is due to the fact that they have not been updated, but did not find how to fix it.




RAND gives #n/a

in excel I have

Sex   Probability     Cumulative Prob
M     80%             80%
F     20%             100%

These are in a sheet called probability of Client and run from cells E1:G3.

In another worksheet i have put the below formula in. Most of the time the result is #N/A with the occasional 'M'. How can i choose this so either M or F is picked in line with the probability above.

=INDEX('Probability of client'!$E$2:$E$3,MATCH(RAND(),'Probability of client'!$G$2:$G$3))

thanks




how to split the .text file using Stratified Sampling or Referral sampling technique

I have .txt file

This .txt file may contain 1000 of records with features ,I want apply the Sampling techniques (Stratified Sampling and Multistage sampling)to read & fetch to 5 employee_ID records write this into (output) another file.

Employee ID First Name  last name   State   Country
123            Arti          G          NY  USA
456            Sona          S          NY  USA
789            Geetha        R          NY  USA
256            Keerthi       T          NY  USA
213            Tam           U          NY  USA
321            Sam           I          NY  USA
354            Beta          E          NY  USA
216            Tag           U          NY  USA
327            Sat           I          NY  USA
358            Beti          E          NY  USA
214            Taa           U          NY  USA
325            Sau           I          NY  USA
357            ketti         E          NY  USA

I have counted the number of records and now i want apply the sampling techniques to fetch only 5 employee_ID records

with open("XXXX.txt", "r") as f: counter = 0 for line in f: #print line counter += 1 if counter == 0: break else: print(counter)

Apply Stratified Sampling and Multistage sampling to fetch 5 empoloyee_IDrecords write this into (output) another file




How to compute (negative binomial) distribution PDF and CDF in C++?

STD has many distributions, that apparently are used to generate pseudo random variables, see e.g. below code that generates and outputs some negative binomial distributed numbers.

Now this might mean that internally, there is code that computes the CDF and or PDF of the negative binomial distribution, i.e. the probability that the random variable takes on a certain value, e.g. 6. Is there a way to output that probability? If yes, how? I know I could run my own code for that, but I'd rather not do that if it there is some way to get the probabilities from std.

If possible, same question for other distributions, e.g. CDF of gamma distribution.

int main()
{
   std::negative_binomial_distribution<int> negBin{ 5,0.5 };//Negative binomial distribution
   std::mt19937 RNG(260783);//Random generator
   for (size_t i = 0; i < 4; i++)
   {
        std::cout << negBin(RNG) << std::endl;
   }
   return 0;
}




dimanche 24 mars 2019

Why the output has different column order on different runs?

I have a piece of code in R. Every time I run it on a cluster, I get an answer where the order of columns are different. (It seems to be OK on my laptop). If I order the column so they have the same order, answers are identical, the only problem is ordering of the columns.

{NNs_loc_year <- Reduce(cbind, 
                      split(NNs_loc_year, 
                            rep(1:n_neighbors, each=(nrow(NNs_loc_year)/n_neighbors)))) %>%
               data.table()

# rename columns 
NN_dist <- NN_dist %>% data.table()
names(NN_dist) <- paste0("NN_", c(1:n_neighbors))
names(NNs_loc_year) <- paste0(names(NNs_loc_year), paste0("_NN_", rep(1:n_neighbors, each=2)))

NN_chi <- pchi(as.vector(NN_list$nn.dist), PCs)

NN_sigma <- qchi(NN_chi, 1)

NN_sigma_df = Reduce(cbind, 
                      split(NN_sigma, 
                            rep(1:n_neighbors, each=(length(NN_sigma)/n_neighbors)))) %>%
               data.table()

names(NN_sigma_df) <- paste0("sigma_NN_", c(1:n_neighbors))

NN_dist_tb = rbind(NN_dist_tb, NN_dist)
NNs_loc_year_tb =  rbind(NNs_loc_year_tb, NNs_loc_year)
NN_sigma_tb =  rbind(NN_sigma_tb, NN_sigma_df)}




TypeError: object of type 'int' has no len() *subtraction*

I'm trying to figure out if there's a way to make a small calculation by subtracting a variables number from 4

number_1_raw = random.randrange(1, 1000) number_1_len = len(number_1_raw) number_of_zeros = 4 - number_1_len print("0" * number_of_zeros + number_1_raw)

I wanted the script to give me an answer that ranged from 1-3, however the code isn't executing properly.

The desired output would be something like this: 0617 or 0071 or 0008, etc.

Please help with this issue, thanks!




What does the replace mean in sample function?

I try to figure out how dose the sample function work when I try to random select 10 samples in each group from the data frame.

I have a data frame with 5 columns and 7000 rows. I split the dataset into around 200 groups. Then I want to random select 10 samples from each group. Some groups have less 10 samples. So when I try to sample them, I set replace=T. However, when I check the output, I found out some groups which were more then 10 sample in the group have repeat samples.

I am not sure how to fix this?

  mydata2<- split(mydf,mydf$Group)
  names(mydata2)<-paste0("mydata2",1:length(levels(mydf$Group))) 
  mysample<-Map(function(x) x[sample((1:nrow(x)),size=10,replace=T),], 
  mydata2)




How can I get a random animated image in b.html when button in a.html is clicked?

I'm making a website where a pizza can be personalized. When the button "Deliver pizza" is clicked, the user get redirected to a new html where an animation will be played that lets them know the pizza is on the way.

What I have now just keeps playing the same animation instead of a random one everytime.

Html where the animation will be played: (playAnimation.html)

<img src="img/pizzadeliverer1.png" alt="pizza deliverer" id='pizzaDeliverer' class="letTheDelivererDrive">

CSS:

.letTheDelivererDrive {
visibility: visible;
animation: animationFrames ease-in-out 4s;
animation-iteration-count: infinite;
transform-origin: 50% 50%;
animation-fill-mode: forwards;
/*when the spec is finished*/
-webkit-animation: animationFrames ease-in-out 7s;
-webkit-animation-iteration-count: infinite;
-webkit-transform-origin: 50% 50%;
-webkit-animation-fill-mode: forwards;
/*Chrome 16+, Safari 4+*/
-moz-animation: animationFrames ease-in-out 4s;
-moz-animation-iteration-count: infinite;
-moz-transform-origin: 50% 50%;
-moz-animation-fill-mode: forwards;
/*FF 5+*/
-o-animation: animationFrames ease-in-out 4s;
-o-animation-iteration-count: infinite;
-o-transform-origin: 50% 50%;
-o-animation-fill-mode: forwards;
/*Not implemented yet*/
-ms-animation: animationFrames ease-in-out 4s;
-ms-animation-iteration-count: infinite;
-ms-transform-origin: 50% 50%;
-ms-animation-fill-mode: forwards;
/*IE 10+*/

}

JS:

    function changeHTML() {
        if (deliverPizzaButton.classList.contains('readyToDeliver')) { // if every step is filled in
            window.location.href = 'playAnimation.html'; // 
        }
    }


    var pizzaDeliverGuys = ["img/pizzadeliverer1.png", "img/pizzadeliverer2.png", "img/pizzadeliverer3.png"];


    function playAnimation() {
        var chosenDeliveryGuy = Math.floor((Math.random() * pizzaDeliverGuys.length));
chosenDeliveryGuy.classlist.add('letTheDelivererDrive');
    }


    deliverPizzaButton.addEventListener('click', changeHTML, playAnimation); // this button is on the index.html


    if (window.location.href == 'playAnimation.html') {
        playAnimation();
    }




C++ How to generate 10,000 UNIQUE random integers to store in a BST?

I am trying to generate 10,000 unique random integers in the range of 1 to 20,000 to store in a BST, but not sure the best way to do this.

I saw some good suggestions on how to do it with an array or a vector, but not for a BST. I have a contains method but I don't believe it will work in this scenario as it is used to search and return results on how many tries it took to find the desired number. Below is the closest I've gotten but it doesn't like my == operator. Would it be better to use an array and just store the array in the BST? Or is there a better way to use the below code so that while it's generating the numbers it's just storing them right in the tree?

for (int i = 0; i < 10000; i++) 
{
    int random = rand() % 20000;
    tree1Ptr->add(random);
    for (int j = 0; j < i; j++) {
        if (tree1Ptr[j]==random) i--;
        }
    }




WordPress custom random avatar based on user email

I'm using this snippet to replace default gravatars for users on my WordPress installation.

add_filter( 'pre_option_avatar_default', 'space_default_avatar' );

function space_default_avatar ( $value )
{
    $upload_dir = wp_get_upload_dir();
    return trailingslashit( $upload_dir['baseurl'] ) . '/custom-images/avatares-espacio/avatar-espacio'.rand( 0 , 31 ).'.jpg';
}

But this randomizes the images on every page load.

I need to define an image based on the user email, so it will always look the after reloading the page.

I also tried this other code, but it's not working: https://shibashake.com/wordpress-theme/wordpress-gravatars-use-your-own-default-avatar




How to sample from CDF in Python

Could you please advise how to sample from distribution with define probabilities (or better solution of my problem below):

I wrote simple script to test myself in other language. Inputs are pair of words in 2 languages. So I receive a question (one word in Eng) and provide answer (in other language and perform checks). To pick the word I use simple rand_word = randint(0, overall), where overall is number of words. But I would like the later (more recently added to my csv) words to appear more often. I can write few conditions, but probably there is much simpler solution to sample from words. For example: I have 3000 word pairs. I would like words from first 20% of space to appear with probability of 10% or 20%, and last 20% of words with 50-60% of prob. This is just example. It could be linear solution, but I want to avoid situation, when first words appear super rarely and latest too often. Thus left tail and right tail preferable should be adjustable.




If two divs have a class added. All the classes have to remove

I have a little problem with my code. If I click 2 divs they show a random Number, but if I click a third div. All my numbers have to remove but it isn't working. Can someone help me?

let mijnDivs = document.querySelectorAll("div")
let i = 0
while (i<mijnDivs.length) {
  mijnDivs[i].addEventListener("click", toevoegen)
  i++
}
function toevoegen(event) {
  console.log("het werkt")
  let nummer = randomNumber(1,9)
  this.innerHTML = nummer
  this.classList.toggle("zichtbaar")
  if (this.classList.contains("zichtbaar").length === 2) {
    console.log("yay")
  }
}
function randomNumber (min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}




samedi 23 mars 2019

mt19937 can't set random_device

My code is failing as to not recognize "generator", but I declare it at the top of my C++ file. I need it to be thread-safe, so I declared it with "thread_local":

#include <windows.h>
#include <iostream>
#include <random>

using namespace std;
thread_local mt19937 generator;

DWORD GenerateRandomNumber(DWORD dwMin, DWORD dwMax)
{
uniform_int_distribution <DWORD> distribution(dwMin, dwMax);
return distribution(generator);
}

int main() 
{
random_device rd;
generator(rd());
}




How to seed mt19937 once per app in C and use it multiple times?

I can get the mt19937 rng seeded in a simple app. Now I am trying to get it seeded once per app and use it multiple times whenever it's needed. Here is my code. I can't get it to compile. I'm sure it's something simple I'm overlooking?

And maybe a better way to seed the mt19937?

main.cpp

#include <iostream>
#include "general.h"

int main() {

CallOncePerApp();

// Loop for output testing
// Ultimately, GenerateRandomNumber can be called from anywhere in any CPP file
for (int i=0;i<10;i++)  {
    int dwGen = GenerateRandomNumber(1, 1000);
    cout << dwGen; // print the raw output of the generator.
    cout << endl;
    }
}

general.h:

#include <random>

using namespace std;

extern random_device rd;
extern void CallOncePerApp();
extern mt19937 gen;

extern unsigned int GenerateRandomNumber(unsigned int dwMin, unsigned int dwMax);

general.cpp:

#include <random>

using namespace std;
random_device rd;
mt19937 gen;

void CallOncePerApp() 
{
    gen(rd); // Perform the seed once per app
}

unsigned int GenerateRandomNumber(unsigned int dwMin, unsigned int dwMax) 
{
    uniform_int_distribution <int> dist(dwMin, dwMax); // distribute results between dwMin and dwMax inclusive.
    return dist(gen);
}




vendredi 22 mars 2019

In Twilio, can you

Using Twilio for an interactive art exhibition where you call the number and listen to the audio in the gallery. I'd like for incoming callers to not always hear the same 20-30 seconds of audio at the beginning of the audio file. Is it possible to provide 3-4 different audio files and one of them is randomly selected to Play for an incoming call. Or even to randomize the start time on the single audio file would work too.

I've searched everyone without much luck.

Code I'm using for the basic function is below.

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Play> https://dl.dropboxusercontent.com/s/qt0l2zjrlssj3nv/CMCA-PHONE-01.mp3 </Play>
</Response>




Random Number Generation C++

I'm trying to learn from this code I found online, it has two functions that generates a random integer but I'm having a hard time understanding them. Could these just be substituted for a normal random int generation instead? Here's the code, thanks in advance!

namespace {
    std::random_device rd;
    std::mt19937 mt(rd());

    int generateRandNumber(int exclusiveMax) {
        std::uniform_int_distribution<> length(0, exclusiveMax - 1);
        return length(mt);
    }

    int generateRandNumber(int min, int max) { // inclusive min/max
        std::uniform_int_distribution<> length(0, max - min);
        return length(mt) + min;
    }

  bool randTrueFalse() {
    static const int random = static_cast<int>(std::log2(RAND_MAX));
    return (rand() >> random) & 1;
  }
}




Storing all the results from a FOR LOOP in an array

I have created an array called Player1_Cards. Each card needs to have a number and a colour. Player1 should have 15 cards, which can be numbered from 1 to 30.

I have used a for loop to do this:

using random.randint (1,30), I have found the number of the card.

using random.randint(1,3), I allocate number 1,2 or 3 to colours RED, YELLOW or BLACK.

How do I store all my results from the for loop as an array?

Here is my code:

Player1_Cards = [0]

import random
for i in range(1,16):
    i = random.randint(1,30)
    i_colour = random.randint(1,3)
    i_colour = str(i_colour)

    if i_colour == "1":
        i_colour = "RED"

    if i_colour == "2":
        i_colour = "YELLOW"

    if i_colour == "3":
        i_colour = "BLACK"



    Player1_Cards[i,i_colour]

If I print(i,i_colour), ignoring the array, examples of what it may execute is:

6 YELLOW
28 YELLOW
8 RED
3 BLACK
22 RED
2 BLACK
26 RED
25 YELLOW
8 RED
20 RED
16 BLACK
12 YELLOW
4 RED
20 BLACK
1 YELLOW




jeudi 21 mars 2019

How to create completely random size image grid?

In my site, there are lot's of image and are completely random size. i want to show all image in grid line below image (please consider one stone as one image).

I already try masonry-grid, but it take fix sized column like 4 or 5 but i want to sort image according to their size.

I don't know how this is possible, if possible, please help me.

enter image description here




Random number generator with boolean & array

I'm trying to create a generator that prints 1 to 4 from an array as well as a corresponding background color. How do I phrase it so that a specific number is tied to a color?

Here is just the number gen setup so far:

void setup() {

size(500, 500);

}

void draw() {

background(100);

int myArray[] = {1, 2, 3, 4};

int rand = (int)random(myArray.length);

println(myArray[rand]);

}

Thanks!




representing distribution tables in c++ and random number generators

Ok so Im trying to write a simulation where a base ball player is at bat and im given a probability distribution table where the likelihood of getting a hit, out etc is listed in percentages here

im going to be using a while loop to simulate it at Bat 1000 times and use all those values to calculate the players batting percentage.

what i dont quite understand is how to represent the percentages and how to differentiate between the different types. Like i cant use an if(atBat<=5) to decide for homeruns because you have a 9 percent chance of getting a triple so doing if(atBat<=9) or doing an if(atBat>=5 && atBat<=9) cant work because your numeric probability is now 4 percent and not 9 percent. yall know what i mean or am i just overthinking this way too much.

Here's the prompt too.




SQL Generate a Different Value for Each Output Row

I am running a query in which i need the SCORE to have a different output for each row. I am able to do it per execution but I have had no luck with RAND as I get a convert from varchar to int error. I need variable number per executrion within a range with no decimals. Is there anyway to do this? Any help is appreciated.

SELECT 'Row_Number^FEED_date^database_id^station_id^Form_Type^FBCS_CLAIM_ID^FBCS_LINE_ID^Pay^SCORE^score_date^reason_code^reason_description'
UNION ALL
SELECT
CAST(ROW_NUMBER() OVER ( ORDER BY ( SELECT 1 ) ) AS VARCHAR(20))  + '^' + 
          CONVERT(VARCHAR, getdate(), 112)+ '^' +  
          'FBCSTrans'+ '^' +  ---took off the 1 so if problems put it back
          stationnumber+ '^' +  
          case when claimtype = 0 then 'HCFA 1500' else 'UB 1450' end+ '^' + 
          CAST(Claims.claimid AS VARCHAR(50)) + '^' + 
          CAST(LineID AS VARCHAR(50)) + '^' + 
          'Y'+ '^' + 
          **RAND() * 100000 AS random_number** + '^' + 
          CONVERT(VARCHAR, getdate(), 112)+ '^' + 
          '' + '^' + ''
FROM Claims 
        JOIN ClaimLines on Claims.Claimid = Claimlines.Claimid 
        JOIN Facilities ON Claims.FacilityID = Facilities.FacilityID
WHERE  Claims.ClaimId IN (SELECT TOP(100000)ClaimId FROM CLAIMS WHERE Claims.RecordStatus = 55 and facilityid=40)




C++ equivalent to R's set.seed() function

I would like to do the equivalent of R's set.seed() inside of a C++ function. How do I do this?

Note that I make this C++ function available in R via the Rcpp package. I would like myfun(seed=42) to return the same result each time it is called in R. I do not want to set the rng seed in R via set.seed() prior to calling myfun every time.

C++ file:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double myfun(double seed) {
  std::srand(seed); // <-- this doesn't do what i want
  return R::rnorm(0,1);
}

/*** R
myfun(42)
myfun(42)
*/

This currently returns:

> myfun(42)
[1] 0.737397

> myfun(42)
[1] -0.02764103

What I want is:

> myfun(42)
[1] 0.737397

> myfun(42)
[1] 0.737397




Weighted Random Sampling with CUDA

I am writing an algorithm that involves

  • Having a list of values on the GPU
  • Sampling from these values based on probabilities.

For example, the probabilities are calculated directly from the values on the GPU.

However, I want to avoid cloning the values on the GPU, as they are quite large.

Is there a way to implement something like numpy.random.choice with weights on a GPU using CUDA?




How to assign random 4 digit number for selenium port in jenkinsfile

Using Jenkinsfile for Pipeline as code, i want to create a random 4 digit Port number as follows:enter image description here This example i tried prefix of 47 + build number, which doesnt work if build number is single digit or more than 3 digits. But randomInt() hasnt worked in jenkinsfile before.




class 'int' instead of type 'int': string indices must be integers

I have a simple Python function where I'm swapping values in a string. I'm doing this by generating a pseudorandom integer, then swapping it with the next index or previous index to avoid out of bounds exceptions.

However, I am getting TypeError: string indices must be integers. When I add a print statement to check the type of the index that is generated by the secrets.randbelow() function, it returns class 'int', whereas I would expect type 'int'. Is this what's causing the error?

Function

import secrets as random


def shuffle_sequence(sequence):
    sequence_len = int(len(sequence))
    for x in range(0, sequence_len):
        swap_index = random.randbelow(sequence_len)
        next_index = 0
        if swap_index != sequence_len:
            next_index = swap_index + 1
        else:
            next_index = swap_index - 1
        sequence[swap_index, next_index] = sequence[next_index, swap_index]
        x += 1
    return sequence

I even adding an int conversion to the first line of the function hoping that would help, but it's returning the same class of int, which is expected.

To clarify, sequence is a string of letters, numbers, and symbols.




Why is the curve of my permutation test analysis not smooth?

I am using a permutation test (pulling random sub-samples) to test the difference between 2 experiments. Each experiment was carried out 100 times (=100 replicas of each). Each replica consists of 801 measurement points over time. Now I would like to perform a kind of permutation (or boot strapping) in order to test how many replicas per experiment (and how many (time) measurement points) I need to obtain a certain reliability level.

For this purpose I have written a code from which I have extracted the minimal working example (with lots of things hard-coded) (please see below). The input data is generated as random numbers. Here np.random.rand(100, 801) for 100 replicas and 801 time points.

This code works in principle however the produced curves are sometimes not smoothly falling as one would expect if choosing random sub-samples for 5000 times. Here is the output of the code below:

Result of the code below

It can be seen that at 2 of the x-axis there is a peak up which should not be there. If I change the random seed from 52389 to 324235 it is gone and the curve is smooth.

Why is this the case? I have the semantically similar code in Matlab and there the curves are completely smooth at already 1000 permutations (here 5000).

Do I have a coding mistake or is the numpy random number generator not good?

Does anyone see the problem here?

import matplotlib.pyplot as plt
import numpy as np
from multiprocessing import current_process, cpu_count, Process, Queue
import matplotlib.pylab as pl


def groupDiffsInParallel (queue, d1, d2, nrOfReplicas, nrOfPermuts, timesOfInterestFramesIter):

    allResults = np.zeros([nrOfReplicas, nrOfPermuts])  # e.g. 100 x 3000
    for repsPerGroupIdx in range(1, nrOfReplicas + 1):
        for permutIdx in range(nrOfPermuts):
            d1TimeCut = d1[:, 0:int(timesOfInterestFramesIter)]
            d1Idxs = np.random.randint(0, nrOfReplicas, size=repsPerGroupIdx)
            d1Sel = d1TimeCut[d1Idxs, :]
            d1Mean = np.mean(d1Sel.flatten())

            d2TimeCut = d2[:, 0:int(timesOfInterestFramesIter)]
            d2Idxs = np.random.randint(0, nrOfReplicas, size=repsPerGroupIdx)
            d2Sel = d2TimeCut[d2Idxs, :]
            d2Mean = np.mean(d2Sel.flatten())

            diff = d1Mean - d2Mean

            allResults[repsPerGroupIdx - 1, permutIdx] = np.abs(diff)

    queue.put(allResults)



def evalDifferences_parallel (d1, d2):
    # d1 and d2 are of size reps x time (e.g. 100x801)

    nrOfReplicas = d1.shape[0]
    nrOfFrames = d1.shape[1]
    timesOfInterestNs = [0.25, 0.5, 1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]  # 17
    nrOfTimesOfInterest = len(timesOfInterestNs)
    framesPerNs = (nrOfFrames-1)/100  # sim time == 100 ns
    timesOfInterestFrames = [x*framesPerNs for x in timesOfInterestNs]

    nrOfPermuts = 5000

    allResults = np.zeros([nrOfTimesOfInterest, nrOfReplicas, nrOfPermuts]) # e.g. 17 x 100 x 3000
    nrOfProcesses = cpu_count()
    print('{} cores available'.format(nrOfProcesses))
    queue = Queue()
    jobs = []
    print('Starting ...')

    # use one process for each time cut
    for timesOfInterestFramesIterIdx, timesOfInterestFramesIter in enumerate(timesOfInterestFrames):
        p = Process(target=groupDiffsInParallel, args=(queue, d1, d2, nrOfReplicas, nrOfPermuts, timesOfInterestFramesIter))
        p.start()
        jobs.append(p)
        print('Process {} started work on time \"{} ns\"'.format(timesOfInterestFramesIterIdx, timesOfInterestNs[timesOfInterestFramesIterIdx]), end='\n', flush=True)
    # collect the results
    for timesOfInterestFramesIterIdx, timesOfInterestFramesIter in enumerate(timesOfInterestFrames):
        oneResult = queue.get()
        allResults[timesOfInterestFramesIterIdx, :, :] = oneResult
        print('Process number {} returned the results.'.format(timesOfInterestFramesIterIdx), end='\n', flush=True)
    # hold main thread and wait for the child process to complete. then join back the resources in the main thread
    for proc in jobs:
        proc.join()
    print("All parallel done.")

    allResultsMeanOverPermuts = allResults.mean(axis=2)  # size: 17 x 100

    replicaNumbersToPlot = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
    replicaNumbersToPlot -= 1  # zero index!
    colors = pl.cm.jet(np.linspace(0, 1, len(replicaNumbersToPlot)))

    ctr = 0

    f, ax = plt.subplots(nrows=2, ncols=2, figsize=(12, 12))
    axId = (1, 0)
    for lineIdx in replicaNumbersToPlot:
        lineData = allResultsMeanOverPermuts[:, lineIdx]
        ax[axId].plot(lineData, ".-", color=colors[ctr], linewidth=0.5, label="nReps="+str(lineIdx+1))
        ctr+=1

    ax[axId].set_xticks(range(nrOfTimesOfInterest))  # careful: this is not the same as plt.xticks!!
    ax[axId].set_xticklabels(timesOfInterestNs)
    ax[axId].set_xlabel("simulation length taken into account")
    ax[axId].set_ylabel("average difference between mean values boot strapping samples")
    ax[axId].set_xlim([ax[axId].get_xlim()[0], ax[axId].get_xlim()[1]+1])  # increase x max by 2

    plt.show()


##### MAIN ####
np.random.seed(83737)  # some number for reproducibility
d1 = np.random.rand(100, 801)
d2 = np.random.rand(100, 801)

np.random.seed(52389)  # if changed to 324235 the peak is gone
evalDifferences_parallel(d1, d2)




Generate large dataset for a line chart

I need to test graphing application on a big data set. Data is in json format with the structure:

{
 "linechart":[
  {
   "x":[5,15,20,3],
   "y":[10,20,30,40]
  }
 ]
}

4 numbers represents 1 line, i.e. x[i] and y[i] is start point, while x[i+1] and y[i+1] is end point.

I want a chart to be inseparable (i.e. without "gaps"). By "big data set" i mean json of ~50mb as a perfect case, though it's not critical, the goal is to have at least a few thousand of points.

It is not possible to produce it manually and I can't think of any solution to this.




Emitting certain character from being outputted in a random password generator program

I'm writing a program that randomly generates a combination of any amount of ASCII characters.

import random
import string

string.printable
sP = string.printable

def random_pass(stringLength):
     x = sP
     return ''.join((random.choice(x)) for i in range(stringLength))
     if x == '<0x0c>' or '<0x0b>:
     print("Try again!")
print('You'\re password is: ', random_pass(12))

-What do '<0x0c>' and '<0x0b>' stand for? -During some iterations of the program, these character codes are printed out. -Do they represent white space? -My if statement in the random_pass() function doesn't omit the character codes from appearing in the output. Which is why I now seek help.




mercredi 20 mars 2019

Making full use of 256 random bits when you just need 1 bit

I am doing some Monte Carle simulations. A CSPRNG is too expensive, so I'm using the xoshiro256** generator instead, which as its name suggests fills four 64-bit unsigned integers with random bits.

In my use case, only one random bit is required each time, but only extracting the lowest bit seems a huge waste.

static uint64_t s[4] = { /* SEED */ };

static inline unsigned random_bernoulli(void) {
    next(s);
    return s[0] & 1U;
}

How can I make full use of the 256 bits, preferably in a not-so-CPU-intensive way? Or, is the lowest bit random enough so my current approach is good?




Generate a vector to conditionally separate equal values by specified intervals in R

Consider the vector of numbers below

c(8.29, 11.23, 11.23, 8.82, 8.82, 11.23, 7.4, 10.05, 10.05, 7.19, 
7.4, 10.05, 3.82, 4.34, 4.34, 4.11, 4.11, 4.34, 3.66, 4.25, 4.25, 
3.95, 3.95, 4.25, 112.6, 124.6, 124.6, 123.2060887, 123.2060887, 
124.6, 142.8, 142.8, 126.4, 149.1772336, 149.1772336, 149.1772336, 
12.33333333, 12.33333333, 10.5, 12.33333333, 10.5, 8.611, 13, 
8.833333333, 13, 6.166666667, 13, 8.833333333, 8.4934, 18.858, 
18.858, 18.93, 18.93, 18.93, 8.2369, 18.64, 18.64, 14.845, 14.845, 
18.64, 5.6405, 5.6405, 4.914, 5.6405, 4.914, 3.3356, 8.6466, 
8.6466, 6.3472, 8.6466, 6.8782, 6.8782, 234.8436611, 279.8109002, 
279.8109002, 240.7415593, 240.7415593, 279.8109002, 175.3816258, 
252.6242588, 252.6242588, 145.2245835, 175.3816258, 252.6242588, 
58.47020984, 81.85080837, 440.0126793, 641.6917085, 641.6917085, 
438.09328, 440.0126793, 641.6917085, 333.2871061, 461.7888531, 
461.7888531, 259.4327562, 333.2871061, 461.7888531, 72.80259873, 
42.76565047, 72.80259873, 74.72707421, 74.72707421, 74.72707421) 

These are max values of a series of comparisons. I want to use them to place significance bars in plots of all these comparisons at a specified y-value. Something like this, where the significance bar will be placed between groups at this y-value.

Something like this

I want to generate this y-value vector such that each of the values is higher by 2 - 3 than its corresponding max value when that value is 0-10, by 4-5 when 10-100, and by 10 when > 100.

Several values in the max value vector are the same, so just adding a certain number will not work, as I cannot obtain the separation I want to achieve. I can provide more details if that will help clarify the issue. Thanks.