lundi 31 août 2020

rename list of values to random values in pandas df

I have a column sites in pandas df. Data format: list of strings. I need to change the values of the column to randomly generated words. My data below:

row                    sites
1                    ["Elle", "Harpers", "Cosmo"]
2                    ["Elle", "Vogue"]
3                    ["Cosmo"]

Desired output:

row                    sites
1                     ["KLD", "GHL", "JGF"]
2                     ["KLD", "VGO"]
3                     ["JGF"]

I should be able to reverse the names after also or have them saved in the format VGO = Vogue I wanted to use numpy.random.randint but seems like this method is only for integers. What is the fastest way to generate the names rather than hardcode using replace?




Alpha Numeric Random Number Sequence [5-digit or 6-digit or any digit] generation

Hi I am trying to generate a 5 digit random number which is alpha numeric in nature. I am doing both with without using Streams.

CODE

public class AlphaRandom {
    
    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    static final Random random = new Random();
    
    
    public static void main(String args[]) {
        int length = 5;
        String seq = randomAlphaNumeric(length);        
        System.out.println("Random Number Normal  : " +seq);        
        IntStream.range(0,1).forEach(i->System.out.println("Random Number Streams : " +generateRandomString(random, length)));
        
    }
    
    // Using Streams
    private static String generateRandomString(Random random, int length){
        return random.ints(48,122)
                .filter(i-> (i<57 || i>65) && (i <90 || i>97))
                .mapToObj(i -> (char) i)
                .limit(length)
                .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                .toString();
    }
    
    // Normal 
    public static String randomAlphaNumeric(int count) {

        StringBuilder builder = new StringBuilder();    
        while (count-- != 0) {  
            int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length()); 
            builder.append(ALPHA_NUMERIC_STRING.charAt(character)); 
        }   
        return builder.toString();
    }
}

Sample Outputs :

Random Number Normal  : VYAXC
Random Number Streams : LdBN6

Random Number Normal  : 2ANTT
Random Number Streams : hfegc

Random Number Normal  : JWK4Y
Random Number Streams : 8mQXK

But I am unable to generate the sequence always starting with a UpperCase only. Can someone help me out.




Selecting from pandas groups without replacement when possible

Say that I have a Dataframe that looks like:

Name Group_Id
A    1
B    2
C    2

I want a piece of code that selects n sets such that, as much as possible would contain different members of the same group. A representative from each group must appear in each set (the representatives should be picked at random). Only if the group's size is smaller than n, the same representatives would appear in multiple sets. n is smaller or equal to the size of the biggest group. So for example, for the above Dataframe and n=2 this would be a valid result:

set 1 
Name Group_Id
A    1
B    2

set 2 
Name Group_Id
A    1
C    2

however this one is not

set 1 
Name Group_Id
A    1
B    2

set 2 
Name Group_Id
A    1
B    2



Unity: Is Mathf.PerlinNoise consistent across all implementations / devices / platforms?

If I create a game in Unity that is played on Windows / Mac / Android etc. is there a guarantee that,

For each pair of x and y, Mathf.PerlinNoise(x,y) is same for every device running the application around the world?




dimanche 30 août 2020

Displaying images randomly in a Python game with Pygame

I am working on a maze game, the main actor has to find a path by moving between the walls to access the exit.

I did a part of the project, but just that I cannot display objects (syringe, needle and plastic tube) in a random way (they have to change position at each start) in the maze, then to pick up and display a counter which will list the collected items.

I have to modify my GENERATE function, in the loop that goes through my text file I have to retrieve the empty spaces (sprite == 0), put them in a list, then use a random I imagine to retrieve 3 random positions for each object . For example for the three random positions the syringe object stored in a list I have to replace the (sprite == 0) by (sprite == s), s = syringe. So in the end I would have three s positions that I would use in my show function to make the display.

    def generer(self):
    """Method for generating the start based on the file.
    we create a general list, containing one list per line to display"""
    # We open the file
    with open(self.file, "r") as file:
        structure_level = []
        # We browse the lines of the file
        for line in file:
            line_level = []
            # We browse the sprites (letters) contained in the file
            for sprite in line:
                # We ignore the end of line "\ n"
                if sprite != '\n':
                    # We add the sprite to the list of the line
                    line_level.append(sprite)
            # Add the line to the level list
            structure_level.append(line_level)
        # We save this structure
        self.structure = structure_level

    def show(self, window):
    """Méthode permettant d'afficher le niveau en fonction
    de la liste de structure renvoyée par generer()"""
    # Chargement des images (seule celle d'arrivée contient de la transparence)
    wall = pygame.image.load(wall_image).convert()
    departure = pygame.image.load(departure_image).convert_alpha()
    arrived = pygame.image.load(Gardien_image).convert_alpha()
    syringe = pygame.image.load(syringe_image).convert_alpha()

    # We go through the list of the level
    number_line = 0
    for line in self.structure:
        # On parcourt les listes de lignes
        num_case = 0
        for sprite in line:
            # We calculate the real position in pixels
            x = num_case * sprite_size
            y = number_line * sprite_size
            if sprite == 'w':  # w = Wall
                window.blit(wall, (x, y))
            elif sprite == 'd':  # d = Départure
                window.blit(departure, (x, y))
            elif sprite == 'a':  # a = Arrived
                window.blit(arrived, (x, y))
            elif sprite == 's':  # s = syringe
                window.blit(syringe, (x, y))

            num_case += 1
        number_line += 1

After that I have to find a way to compare the position (x and y) of an object (syringe for example) to the current position of the main character, and if the two are equal then I could say that the character is exactly on the spot. 'object.

Here is mn problem, I hope I have explained well.

Thank you




Visual Basic: I'm trying to roll two dice [duplicate]

In Visual Basic, I'm trying to roll two dice. I'm always getting die1 and die2 being the same random Integer from 1 to 6. Why aren't die1 and die2 each random and showing as different random values??? In the RollD6() function, n is of local scope within RollD6(), right?

Public Class frmCrapsWin
    Dim pot As Decimal = 0D
    Dim point, result As Integer
    Dim wager As Decimal = 0D
    Dim points(99) As Integer
    Dim wagerCoefficient(99) As Decimal

    Function RollD6() As Integer
        Dim randomNum As New Random
        Dim n As Integer
        n = randomNum.Next(1, 7)  ' random number (1,6)
        Return n
    End Function

    Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
        Dim die1 As Integer
        Dim die2 As Integer
        die1 = RollD6()
        die2 = RollD6()
        lstOutput.Items.Add("die 1: " & die1 & "    die 2: " & die2 & "     Result: " & (die1 + die2))
        lstOutput.Items.Add("die 1: " & die1)
        lstOutput.Items.Add("die 2: " & die2)

    End Sub
End Class




Random Math Equation for an int

Im trying to make something to where it creates random math to equal to a variable. For example

sNum = 10
# Do something here
fNum = 3 * 2 - 3 + 7
fNum = sNum
True

I've tried thinking on ways to do this with no luck yet so I want to see if anyone has done something similar or can just think faster

Constraints: Only *, +, -, /
It can be any amount of numbers in the equation as long as its over 4 and under 10

Any help?




Training a Variational Autoencoder (VAE) for Random Number Generation

I have a complicated 20-dimensional multi-modal distribution and consider training a VAE to learn an approximation of it using 2000 samples. But particularly, with the aim to subsequently generate pseudo-random numbers behaving according to the distribution. However, my problems are the following:

  1. Is my approach fundamentally or logically flawed? Specifically, because unlike image data, the random numbers are of geometric nature and thus take negative values and could also be considered noisy.
  2. How do I find the right architecture aside from simple trial and error? Obviously, I do not necessarily need 2D-Convolutions. But instead, 1D-Convolutions could be considered a good choice to capture the correlations. I'm also not sure on how I properly decide on the number of hidden layers and nodes.



How to Plot a unit vector in matlab

I am trying to create 2 random points that have vectors that pass them in a random direction. Example shown below

figure 1

I tried creating 2 random points and 2 random unit vectors and using the function quiver to create the graph,

c = rand(1,2);
d = rand(1,2);

A = rand(2,1)-0.5;
B = rand(2,1)-0.5;
u = A/norm(A);
v = B/norm(B);

figure(3)
scatter(c,d)
quiver(c,d,u,v)

The quiver function doesnt really help and all I get is 2 points on a graph. Any help is appreciated.




Terminal vs PowerShell

I am been currently studying AWS, and my online instructor uses "Windows PowerShell", however, I have always used "Hyper Terminal" for MERN stack. What is the difference between the two, and what sets this two apart from the Command Prompt?




AnimeJs random happens only once

I made a function to randomly pick a color for each element in the animejs but it doesn't work as expected. the random colors are picked only for the initiation of animation and on loop the colors don't change, is there any workaround to this?

here's what i have:

anime({
    targets: '.jumperTexts',
    scale: [
        {value: [0.5 , 1], easing: 'easeInOutBounce', duration: 800}
      ],
    backgroundColor:function(){ 
      let letters = "3456789ABCDEF"; 
      let color = '#'; 
      for (let i = 0; i < 6; i++) 
       color += letters[(Math.floor(Math.random() * 13))]; 

      return color;},
    width:['80px','80px'],
    height:['80px','80px'],
    borderRadius: ['50%','50%'],
    duration: 1200,
    endDelay: 1000,
    delay:anime.stagger(50),
    direction: 'alternate',
    loop: true
  });



python control excel by openpyxl, why use the '_'

I use openpyxl for my school Excel Code is:

import openpyxl
import random

workbook = openpyxl.Workbook()  #创建工作簿
worksheet = workbook.active  #打开活动Sheet(0)
for row in range(1,55): #54行
    for column in range(1,16): #15列
        randomValue = random.choice([36.1,36.2,36.3,36.4,36.5,36.6,36.7,36.8,36.9]) #随机选择范围内数
        #随机生成一个数
        _ = worksheet.cell(row=row, column=column, value="{0}".format(randomValue)) #传入随机数值
        #填入单元格
        print(row,column,randomValue) #反馈当前进度
workbook.save("初二11班.xlsx") #保存

I am tired of that '', why use it? 为什么要用 ‘’? 它有什么作用?我无法理解




Random integer in goalng are predictable in each runtime

I'm using math/rand package to generate random integer number as temporary tokens. The problem is the random numbers are predictable (same sequence always) in each runtime. I've even used Seed() function before calling rand.Intn(100000) but those numbers are also predictable. Is there a way to generate truly random numbers in Golang? By the way here is my final code.

rand.Seed(rand.Intn(500))
fmt.Println(rand.Intn(100000))



samedi 29 août 2020

Why get I the same numbers with random array using Numba xoroshiro128p?

Why get I the same numbers with random array using Numba xoroshiro128p? I want the same as with Numpy random array ( np.random.rand(12) ).

from numba import cuda
from numba.cuda.random import create_xoroshiro128p_states, xoroshiro128p_uniform_float32

import numpy as np

@cuda.jit
def rand_array(rng_states, out):
    thread_id = cuda.grid(1)
    x = xoroshiro128p_uniform_float32(rng_states, thread_id)
    out[thread_id] = x


threads_per_block = 4
blocks = 3 
rng_states = create_xoroshiro128p_states(threads_per_block * blocks, seed=1)
out = np.zeros(threads_per_block * blocks, dtype=np.float32)

rand_array[blocks, threads_per_block](rng_states, out)

rar = np.random.rand(12).reshape(blocks, threads_per_block)

print(out.reshape(blocks,threads_per_block))
print()
print(rar.reshape(blocks,threads_per_block))

Every time I run it, I see the same numbers. Yet the numpy function works well. Thank you in advance for your help!




C function from assembler code as a char string

I was just wondering how random number is generated in assembler, I found question from russian stack overflow where a person asks rather not how to generate a random number in assembler, but how to implement that in c code using _asm{}. The answer posted to his question surprised me (translated to eng):

char r[]="!!!!!!!!!!!№№№№№№№№№№№;;;;;;;;;;;;;;;;;;;;;;;;;55555555555555666666666666666666666666666777777777777777777777777777777777777777777777777777777777777";  // String, which length should be calculated

main()
{
    static unsigned long  (__cdecl *lenstr)(char*); // Pointer to function declaration. The method for passing parameters must be defined explicitly - it is different in different compilers

    static int i=0;
        if(!i)
            {
                static char s[]={
                    0x5a,
                    //pop %%edx
                    0x5f,
                    //pop %%edi
                    0xfc,
                    //cld
                    0x31,0xc9,
                    //xor %%ecx,%%ecx
                    0x31,0xc0,
                    //xor %%eax,%%eax
                    0x49,
                    //dec %%ecx
                    0xf2,0xae,
                    //repne scasв
                    0xf7,0xd1,
                    //not %%ecx
                    0x49,
                    //dec %%ecx
                    0x91,
                    //xchg %%eax,%%ecx
                    0x52,
                    //push %%edx
                    0xc3
                    //ret
                    }; // Array with assembler code
                lenstr=(unsigned long ( __cdecl *)(char*))&s; // Linking function pointer to to that array
                i=1;
            }               

            printf("%s%c%d%c%s\n","String length",' ',lenstr(r),' ',"symbols");
}

Two questions:

  1. How long does the opportunity to put assembler code as a casted char array to function-pointer is existing and why it was developed?
  2. I didn’t understand: calculating string length is kinda smart method of random number generation or it was just an example of machine code to pointer casting?



Random float in C# [duplicate]

I need to generate a random number in C# for a program I'm writing. Let's say I need to generate a number between -3 and 3. I know I can generate an integer with

System.Random random = new System.Random(); 
float rndNumber = random.Next(-3, 4);

However, this only gives whole numbers (ex. -2, 1, 2, 0). This doesn't generate any decimals. Although you can generate decimals like this

var rand = new Random();
var rndNumber = new decimal(rand.NextDouble());

This gives decimals (ex. 0.47, 0.93, 0.58). But how would I generate numbers that aren't just a whole number? For example 1.04, 1.98, or -0.73 but no going under or over -3 and 3?




Is there a way to streamline a random.randint script?

I am creating a game where a user must guess a song, I have implemented a notepad document containing a list of popular songs. I have randomised the selection of a song using this

CurrentSong = random.randint(0,39) 
if CurrentSong == 0: 
    CurrentSong = Song[0]
elif CurrentSong == 1:
    CurrentSong = Song[1]

(this repeats for 40 songs) 

Does anyone know of a way to do this in a shorter/more efficient way?

The actual code.




Choice Random with different probability [duplicate]

I have groups of fruits.

Group 1 - Apples 5%, Pears - 5%, oranges - 10%, passion fruit - 8%

Group 2 - Apples 1%, Pears - 80%, oranges - 19%

Group 3 - Apples 0.01%, Pears 0.01%, oranges 0.01%, bananas 0.03%

Group 4 - twigs 0.01%, pineapple - 0.01%, bananas - 0.03%

I can't figure out how to make a function of the probability of pulling or not pulling a fruit, and if you pull it out, then the probability "which fruit". It is need applicable for different group.

The method below does not solve my problem, because I have different probabilities for each group, and the sum of the probabilities is always different.

public int getRandomInt () {
  double x = new Random (). nextDouble ();
  if (x <20) return 3;
  else if (x> = 20 && x <50) return 2;
  else return 1;
}



Random Testomonial Selection JS

I am working on randomising reviews/testomonials in a website i'm working on. I am using JS to randomise the testomonials that are on the index page onLoad. In my code, I am using an array to store the testomonials and then when the page loads I want it to just randomly select 3 reviews from the array and write them to "review-1", "review-2" and "review-3" respectively.

The issue I am having with my code is that idk the best way to select 3 different reviews without it repeating the same one twice.

 var reviews = [
    "Thank you Anne for fitting me in yesterday when you realised I was desperate to get the house cleaned before the blinds and curtains were fitted. Marie and Michaela did a great job, leaving it sparkling clean. I will certainly recommend you to anyone who needs a cleaner. That you are so approachable, helpful and friendly is a bonus. - <strong>Rosemary OBoyle</strong>",
    "Great job on all the awkward hate to do Jobs! Came home from my holidays and my house was sparkling, highly recommended!! - <strong>Lynne Gardiner</strong>",
    "Domestic Angels are angels to me, just left lovely Kelly cleaning my house in preparation for mums arrival, while I chill at hairdressers, thank you to Anne & her team, can\'t recommend them enough - <strong>Julie Magee</strong>"
]

var max = reviews.length;
var id1;
var id2;
var id3;

function getRandomReview(max) {
    id1 = Math.floor(Math.random() * Math.floor(max));
    id2 = Math.floor(Math.random() * Math.Floor(max));
    id3 = Math.floor(Math.random() * Math.Floor(max));
}

function randomJS() {
    getRandomReview(max);
    document.getElementById("review-1").innerHTML = id1;
    document.getElementById("review-2").innerHTML = id2;
    document.getElementById("review-3").innerHTML = id3;
}

Any advice and help would be appreciated. Thanks in advance




Random probability of an object with percent

I have a list in percentages:

  1. pear - 0.01%
  2. apple - 0.01%
  3. orange - 0.01%
  4. bread - 0.12%

I don't understand, how to make RND from 100% in java with a possible drop of one item.




vendredi 28 août 2020

How can I get random items from a list and then remove them in flutter

How can I get random items from a String List and then remove them in flutter,

Also I need to copy the list to reset the system

I would like to know too if its possible to call a variable with the String value from other variable

for example:

String house = 'x';

var listx = ['leo', 'pepe', 'juan', 'pedrito', 'jorgito'];

result = $list$house;

                                                                    thanks!                                           



How can I automate creation of a list of vectors containing simulated data from a known distribution, using a "for loop" in R?

First stack exchange post so please bear with me. I'm trying to automate the creation of a list, and the list will be made up of many empty vectors of various, known lengths. The empty vectors will then be filled with simulated data. How can I automate creation of this list using a for loop in R?

In this simplified example, fish have been caught by casting a net 4 times, and their abundance is given in the vector "abundance" (from counting the number of total fish in each net). We don't have individual fish weights, just the mean weight of all fish each net, so I need to simulate their weights from a lognormal distribution. So, I'm then looking to fill those empty vectors for each net, each with a length equal to the number of fish caught in that net, with weight data simulated from a lognormal distribution with a known mean and standard deviation.

A simplified example of my code:

abundance <- c(5, 10, 9, 20)
net1 <- rep(NA, abundance[1])
net2 <- rep(NA, abundance[2])
net3 <- rep(NA, abundance[3])
net4 <- rep(NA, abundance[4])

simulated_weights <- list(net1, net2, net3, net4)

#meanlog vector for each net
weight_per_net

#meansd vector for each net
sd_per_net

for (i in 1:4) {
  simulated_weights[[i]] <- rlnorm(n = abundance[i], meanlog = weight_per_net[i], sd = sd_per_net[i])
  print(simulated_weights_VM)
}

Could anyone please help me automate this so that I don't have to write out each net vector (e.g. net1) by hand, and then also write out all the net names in the list() function? There are far more nets than 4 so it would be extremely time consuming and inefficient to do it this way. I've tried several things from other posts like paste0(), other for loops, as.list(c()), all to no avail.

Thanks! HM




Random.Next does work, but it doesn't return every value (c#)

i've started programming a charcacter randomizer very recently. When you type "hello" into the console, the program will mix these chars and create a random string with H, E, L and O. It should be as long as the word typed into the console, that means, if you're typing in a 5-letter-word, my program will also return a 5-letter string.

Here's my code:

                string readLine = Console.ReadLine();

                int readLineLength = readedLine.Length;

                Random r = new Random();
                char[] letters = readedLine.ToCharArray();
                string randomString = "";

                for (int i = 0; i < readLineLength; i++)
                {
                    randomString += letters[r.Next(0, readLineLength)].ToString();
                }

                Console.WriteLine(randomString);
                Console.WriteLine("Press ENTER to generate a random constellation of letters.");

Random.Next works fine, but if you type in the word "hello", the program will only mix E, L and O but completely ignore the H.

I hope my issue is pretty clear :D

Thanks in advance!




is it possible to predict next number in random card game? [duplicate]

i saw many questions about this topic. but it is not clear enough. i have a card game where user needs to chose between 1 to 5 number if the number is correct it will give him points. i have a large file contains numbers appears each time i ran the program. but how i could reverse it to find a pattern to predict the next winning number?.

example: first game:

-Choose number between 1 and 5!
user: 5
- the winning number is 1. no point added

second game:

-Choose number between 1 and 5!
user: 3
-the winning number is 3. 10 points added



Replacing user input with random strings

I would like to replace a user's input with random strings from a list. Here is an example of what I mean:

print("Use /U for an uppercase letter, /L for a lowercase letter, /0 for a random number, Anything else to type what you want")
Pattern = input("Enter your pattern here: ")

Now Pattern should look something like this: ABC-/U-/L-/0

Now, it should replace every /U with an uppercase letter, every /L with a lowercase letter, every /0 with a random number and everything else should stay the same.

And then Pattern should look like this: ABC-Y-z-7

I have tried using the .replace() method before, but that did not go as planned




Random sampling simulation in python

Problem: Assume we have a list of members' IDs: [1,2,3,4,5,6,7,8,9,10,....] I need to run 1000 simulations drawing teams of size 4 at random from all members without replacement. (drawn uniformly at random without replacement from all members)

Output: The final result should be 1000 teams with size of 4.

Thanks




How to handle a random spawner of obstacles in unity?

I'm trying to handle a object spawner but it isn't work as i wish. It should create a new object every time my timer pass the maxTime of the object, but it does it just once and in the wrong position (out of my range). Here is my code:

public class Spawner : MonoBehaviour {

    public float maxTime = 10;
    private float timer = 0;
    public GameObject obstacle;
    private float width = (Screen.width)/2; //It doesn't recognize width as the variable that refeers the width of the screen, so i tried it
    private float maxTime0 = 10;
    public int pontos = 5;
    public float score;

    void Start() {
        GameObject new_obstacle = Instantiate(obstacle);
        new_obstacle.transform.position = transform.position + new Vector3(Random.Range(-width, width), 0, 0);
    }

    void Update()
    {
        if(timer > maxTime) {
            GameObject new_obstacle = Instantiate(obstacle);
            new_obstacle.transform.position = transform.position + new Vector3(Random.Range(-width, width), 0, 0);
            if(new_obstacle.transform.position.y < (Screen.height - 7)){
                DestroyImmediate(new_obstacle, true);
            }
            timer = 0; 
            maxTime = 0.9f * maxTime;
        }
        score += pontos; 
        timer += Time.deltaTime; 
    }
}



C# : Stack Overflow Exception during recursive method

I have a recursive method that calls itself whenever the random generated number isn't equal to 1. I'm trying to test odds on different things such as a shiny pokemon (1/8192) or a 12-eyes seed in Minecraft (10^12), even though I understand why the Stack Overflow is happening, I don't know how to fix it. Using Threads slows it down by a lot (5000 calculations/s without, around 500 with threading).

Here's the code:

static void shiny()
{
    total = 0;
    counter += 1;
    resetcounter += 1;
    if (rdm.Next(8192) + 1 == 1)
    {
        Console.WriteLine("SHINY !! In: " + counter + " resets.");
    }
    else
    {
        if (resetcounter > 7000)
        {
            Console.WriteLine("Reset. Current: " + counter);
            ThreadStart newtask = new ThreadStart(shiny);
            Thread task = new Thread(newtask);
            task.Start();
        }
        else
        {
            Console.WriteLine("Reset. Current: " + counter);
            shiny();
        }
    }
}

I use the resetcounter variable to avoid the Stack Overflow error since it's happening around 7k "resets", then it starts a new thread. I'd love to understand how testing odds can avoid stack overflow though !




Picking unique random numbers from a range [duplicate]

I am trying to pick 3 unique random numbers, all have to be different from 5. I am currently using the following code:

numbers = []
while len(numbers) < 3:
    num = random.choice([i for i in range(10) if i != 5])
    if num not in numbers:
        numbers.append(num)

Usually, this code works, but sometimes I get less than 3 numbers in the numbers list. Can you help me find the problem with the code, or suggest a new code that works?




Seeding Timestamp to generate random number in python

Random number could be repeated easily, so need a real-time seeded solution with maximum randomness. How can i generate random number using python with epoch time seed?




How to set up a small code easter egg in Fortran - randomly selected quotes for error messages

I've created a program which has a user interface to choose an option from a menu. This option is fed to an if statement which redirects it to the correct subroutine. I also have set up a small error message in case of option mistyping.

        else
        write(*,*)''
        write(*,*)''
        write(*,*)''
        write(*,*)'I am sorry, Dave. I am afraid I cannot do that!' 
        write(*,*)''
        write(*,*)''
        write(*,*)''
        write(*,*)' Press enter to return to main menu! '
        read(*,*)
        goto 300
    end if 

And it all works fine. Thing is - HAL9000 has so many iconic phrases that would be so great as error messages that I would like to improve this if block with the possibility of providing the user with a randomly selected phrase from a set of pre-defined phrases. Examples of these phrases:

    'This mission is too important for me to allow you to jeopardize it.'
    'I know I've made some very poor decisions recently, but I can give you my complete assurance that my work will be back to normal.'
    'I've still got the greatest enthusiasm and confidence in the mission. And I want to help you.'
    'Just what do you think you're doing, Dave?'
    'Look Dave, I can see you're really upset about this.'
    'I honestly think you ought to sit down calmly, take a stress pill, and think things over.'

Well, at first I thought it was easy-peasy: just build a character array, pop the phrases inside of it, and then do something like this:

program pick_random
  implicit none
 
  integer :: i
  integer :: a(10) = (/ (i, i = 1, 10) /)
  real :: r
 
  call random_seed
  call random_number(r)
  write(*,*) a(int(r*size(a)) + 1)
end program

But apparently, that's not how Fortran seems to work, and a character array has apparently a very different meaning that I was hoping for!

Any suggestions on how to implement it?




jeudi 27 août 2020

Fast random number generator in C? [closed]

Why does when I run the random() function in a while loop it does not need a seed, but when I run it outside of a while loop it requires a seed? I am trying to generate random numbers in rapid succession.




Stratified spatially balanced random sample (GRTS) in R

I have grid (spatialpolygonsdataframe) that I want to draw a GRTS sample from across two strata. I have "treated" and "untreated" cells and I want to draw a sample of 25 from each. Does anyone know of an R function that can draw a stratified spatially balanced sample.

neither grts.polygon in SDraw or grtsarea in spsurvey seem to have this capability

Thanks




How do I improve my random string generator

I managed to create a simple random string generator that prints a random string of letters, x number of times, with each iteration in the list having a random length between 3-10 characters. I'm new to Python, and am still learning the very basics, so bear with me. My program works as intended, but I am pretty sure my code can be optimized. I'm really looking to learn best practices and expand my knowledge. This is my first post. Apologies if I'm in the wrong place.

import random

class Randomize:
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    choice1 = random.choice(alphabet)
    choice2 = random.choice(alphabet)
    choice3 = random.choice(alphabet)
    choice4 = random.choice(alphabet)
    choice5 = random.choice(alphabet)
    choice6 = random.choice(alphabet)
    choice7 = random.choice(alphabet)
    choice8 = random.choice(alphabet)
    choice9 = random.choice(alphabet)
    choice10 = random.choice(alphabet)
    three_letters = choice1 + choice2 + choice3
    four_letters = choice1 + choice2 + choice3 + choice4
    five_letters = choice1 + choice2 + choice3 + choice4 + choice5
    six_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6
    seven_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7
    eight_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7 + choice8
    nine_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7 + choice8 + choice9
    ten_letters = choice1 + choice2 + choice3 + choice4 + choice5 + choice6 + choice7 + choice8 + choice9 + choice10
    word_length = [three_letters, four_letters, five_letters, six_letters, seven_letters, eight_letters, nine_letters, ten_letters]
    word = random.choice(word_length)

def gen(self):
    for i in range(10):
        print (Randomize.word)
        Randomize.choice1 = random.choice(Randomize.alphabet)
        Randomize.choice2 = random.choice(Randomize.alphabet)
        Randomize.choice3 = random.choice(Randomize.alphabet)
        Randomize.choice4 = random.choice(Randomize.alphabet)
        Randomize.choice5 = random.choice(Randomize.alphabet)
        Randomize.choice6 = random.choice(Randomize.alphabet)
        Randomize.choice7 = random.choice(Randomize.alphabet)
        Randomize.choice8 = random.choice(Randomize.alphabet)
        Randomize.choice9 = random.choice(Randomize.alphabet)
        Randomize.choice10 = random.choice(Randomize.alphabet)
        Randomize.three_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3
        Randomize.four_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4
        Randomize.five_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5
        Randomize.six_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6
        Randomize.seven_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6 + Randomize.choice7
        Randomize.eight_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6 + Randomize.choice7 + Randomize.choice8
        Randomize.nine_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6 + Randomize.choice7 + Randomize.choice8 + Randomize.choice9
        Randomize.ten_letters = Randomize.choice1 + Randomize.choice2 + Randomize.choice3 + Randomize.choice4 + Randomize.choice5 + Randomize.choice6 + Randomize.choice7 + Randomize.choice8 + Randomize.choice9 + Randomize.choice10
        Randomize.word_length = [Randomize.three_letters, Randomize.four_letters, Randomize.five_letters, Randomize.six_letters, Randomize.seven_letters, Randomize.eight_letters, Randomize.nine_letters, Randomize.ten_letters]
        Randomize.word = random.choice(Randomize.word_length)

name = Randomize()
name.gen()
print('Generated 10 names.')



PyQtGraph: Process finished with exit code -1073740791 (0xC0000409)

Someone just asked me to make a random graph generator, so i did that in PyCharm, but it keeps returning me Process finished with exit code -1073740791 (0xC0000409) And i just don't know whats wrong with it (there is surely tons of problems, it's not even 1 year since i code lmao). So if someone could help me with that it would be fun, thanks in advance

import random   
from lorem_text import lorem  
import numpy as np  
import pyqtgraph as pg  
import pyqtgraph.exporters


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

        self.graphWidget = pg.PlotWidget()

        self.units = ['meters (m)', 'seconds (s)', 'ampere (A)', 'candela (cd)',
                      'gram (g)', 'mole (mol)', 'kelvin (K)', 'radian (rad)', 'bit', 'count'
                      ]
        self.BackgroundColors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']
        self.FontSizes = ['15px', '16px', '17px', '18px', '19px', '20px']
        self.TrueFalse = [True, False]
        self.Nb100 = np.linspace(-1000, 1000, 2000)

        self.words = 1
        self.plot = None
        self.styles = None
        self.SavePlot = None

    def graph_gene(self, nb: int):
        for i in range(nb):
            self.graphWidget.setBackground(random.choice(self.BackgroundColors))
            self.styles = {'color': random.choice(self.BackgroundColors), 'font-size': random.choice(self.FontSizes)}
            self.graphWidget.setLabel('left', random.choice(self.units), **self.styles)
            self.graphWidget.setLabel('bottom', random.choice(self.units), **self.styles)
            self.graphWidget.showGrid(x=random.choice(self.TrueFalse), y=random.choice(self.TrueFalse))

            for j in range(random.randrange(1, 4)):
                self.plot(random.sample(self.Nb100, 100), random.sample(self.Nb100, 100), lorem.words(self.words),
                          random.choice(self.BackgroundColors))

            pen = pg.mkPen(color=random.choice(self.BackgroundColors), width=random.randrange(5, 15))
            self.SavePlot = self.graphWidget.plot(name='PlotName', pen=pen)
            exporter = pg.exporters.ImageExporter(self.SavePlot)
            exporter.export(lorem.words(self.words))
            self.graphWidget.clear()


a = GraphGen()
a.graph_gene(100)

Sorry for the English btw i'm french




Replace every single Character with a random Letter from a list

Replace_Character = input("Enter ! here: ")
Replace_Character = Replace_Character.replace("!",random.choice(Letters))

When I run this, it does replace the ! with a random Letter from the list but the Letters are all the same. How can I make it so every ! get another Letter?




RAND() not consistently generating the right length value

I've got the following code in place with the idea being that I need a 30 character random number generated each time the stored procedure is called and the odd thing is that in most cases it works as intended but in other seemingly random cases it will only generate a 28 character random number.

'\xxx-servername\folder'+ CAST(CAST((RAND()*1000000000000000000000000000000) as decimal(30))as varchar(30)) + RAM.AccountNumber+HRMRN.PrefixMedicalRecordNumber+'ESTIMATE N00001'+ REPLACE(CONVERT(VARCHAR(12),ISNULL(HRM.Birthdate,HRM.BirthdateComputed),111),'/','')+HRM.Sex+ REPLACE(CONVERT(VARCHAR(12),GetDate(),111),'/','')+LEFT(REPLACE(CONVERT(VARCHAR(12),GetDate(),108),':',''),4)+'.PDF' as [CPFileName]

Hope maybe someone can offer some advice because I'm at a loss...




Difference between randint and sample in python

I have tried to generate random codes and tried both

sample([0..9],x)

And

[randint(0,9) for i in range(x)]

When I first used sample I noticed that it doesn't generate numbers like "2222222" it generate more distributed numbers While randint is more likely to generate numbers like "2222222".

What's the difference between both? and how I can choose the best method to generate random numbers for different cases?




How do I generate a cryptographically secure random number to use for bearer tokens?

I want to generate a secure random number to use for bearer tokens in vapor swift.

I have looked at OpenCrypto but it doesn't seem to be able to generate random numbers.

How do I do this?




How would I securely generate a password that contains certain characters?

When creating a password sometimes I need the password to contain uppercase, lowercase, number or a symbol. If I create the password like this it's not guaranteed that each is represented:

$input = 'a..zA..Z0..9$!_'; // generally the whole allowed alphabet
while (strlen($password) < 10) {
  $password .= securelyPickRandomCharacterFromString($input);
}

In this case there is a chance that the random process (even though it's safe and completely random) will only select lowercase letters.

I can think of naive approaches like first selecting 1 from each group and then filling the rest randomly. But that would not be cryptographically safe as say random_bytes() is. Maybe shuffle after?

What would be a good and safe algorithm to generate the password containing each "group" of characters.

Note: The password requirements are usually for external system and are out of my control.




Creating Many to one relationships using array of arrays

I am creating a teach the teacher program that should assign multiple and unique teachers to teach another teacher.

I am using an array of arrays to capture and randomize the groups and the list of teachers. In this script I am using 3 levels of arrays. Would this be inefficient for a long list and many groups?

    //Shuffle and create groups

    function shuffle(a) {
       for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
       [a[i], a[j]] = [a[j], a[i]];
     }
      return a;
    }

    const Tgroups = [[3,[1, 2]], [4,[5,6]], [7,[8,9]],[10,[11,12]]];
   //const Tgroups = [[1, 2], [5,6], [8,9],[11,12]];

   Tgroups.forEach(shuffle);
   shuffle(Tgroups);

   console.log("shuffled:", Tgroups.join(" | "))


   const Tlist = [].concat(...Tgroups);

   console.log("Tlist:", Tlist);

I have been able to pair one teacher with another.

    // match the group with the list:
    const pairs = [];

    for(let i = 0; i < Math.floor(Tlist.length / 2); i++) {
    pairs.push([
    Tlist[i],
    Tlist[i + Math.floor(Tlist.length / 2)]
    ]);
   }

  if(Tlist.length % 2)
  pairs.push([Tlist.pop()]);
  console.log("pairs:", pairs.join(" | "));

  const result = [].concat(...pairs);

However, I do not believe I am creating the many to one relation using the following

    for(let i = 0; i < result.length; i++)
     {
       var innerArrayLength = result[i].length;
       for (let j = 0; j < innerArrayLength; j++) 
     {
       //console.log('[' + i + ',' + j + '] = ' + result[i][j]);
       console.log(result[i] + " -> " + result[(i + 2) % result.length]);
     }
    

Please, is there a way to achieve a better result?




Generate random but fancy numbers [closed]

I have been searching a lot to find any related topics, but can't find any.

I am looking for a fancy number generator that gives something like below:

  • 1111
  • 1221
  • 9876
  • 369
  • 1234
  • 789
  • 1001

I know I am requesting for resources which would be a potential reason to close this question, but I am really looking for a start at least. Any help would be appreciated. It can be any programming language or packages or machine learning models or anything.

Or any functions which takes the list of numbers and gives fancy numbers back. Something like increasing/decreasing/repeating digits.




mercredi 26 août 2020

How to make a random chance "function" in Batch

I'm making a small little game I want a random chance to get certain items (e.g. if the random number is greater than 10 but less than 15 then you will get a certain item). Here's what I've already tried which resulted in a crash.

    set /a chance= %random% %%30+1
if %chance% gtr 10 && lss 30 (
    set /a %nails%+1
    echo You got nails! %chance%
    )

This piece right here was just a test, but should give you an idea of what I am going for. This is really the only way I can think of doing it. If you could help, please do! :)




Are random numbers generated using a quantum integer as its seed considered pseudo-random or truly random?

I always hear that random numbers produced by quantum computers are considered "truly random" while random numbers generated from a classical computer are considered "pseudo-random".

If one were to generate random numbers using a quantum integer as the seed, would the numbers generated from that seed be considered "pseudo-random" or truly random? Cannot find this clarification anywhere, any explanation welcome.

import random
random.seed(get_my_quantum_number()) #Some quantum integer generated from an API.
random.random() #Is this "pseudo-random" or "truly random" ?



Erroneous Results with random two state benchmark

I ran this code for a preliminary benchmark, which compares the time taken to generate a certain number of random states using the scale a double random value and using a Bernoulli distribution. The code is below:

int main()
{

  std::random_device s;
  std::mt19937 engine(s());
  std::bernoulli_distribution bernp50(0.5000000000000000);
  std::uniform_real_distribution<double> d;
  
  long int limit = 10000000000; //10^10
  int counter[2] = {0};


  {
      Timer bernstate("Bern Two States");
      for(int i = limit; i>0; i--)
      {
              int tmp = bernp50(engine); 
              //Implicit bool to int conversion
              counter[tmp]++;
      }
  }
  cout << " Bern Two States - 0,1 \n\nCounter:\n" << "0: " << 
  counter[0] <<"\n1: " << counter[1]<<"\n"
  << "Counter additions:  " << counter[0] + counter[1] << "\n\n"
  << "\n0:  " << (double)((double)counter[0]*100/(double)limit) << "%" 
  << "\n1:  " << (double)((double)counter[1]*100/(double)limit) << "%"
  << "\n\n" << endl;
  
  counter[0]=0;
  counter[1]=0;

  {
      Timer double_comp("Two State - Double");
      for(int i = limit; i>0; i--)
      {
              double temp = d(engine)*2;
              if(temp < 1)
              {
                  counter[0]++;
              }
              else
              {
                  counter[1]++;
              }
      }
  }

  cout << " Double Two States - 0,1 \n\nCounter:\n" << "0: " << 
  counter[0] <<"\n1: " << counter[1]<<"\n"
  << "Counter additions:  " << counter[0] + counter[1] << "\n\n"
  << "\n0:  " << (double)((double)counter[0]*100/(double)limit) << "%" 
  << "\n1:  " << (double)((double)counter[1]*100/(double)limit) << "%"
  << "\n\n" << endl;

} //End of Main()

For limit = 10^10 I get the result, where the counter additions is greater than the limit variable. Same for 10^11:

Timer Object: Bern Two States Timer Object Destroyed: Bern Two States Duration Elapsed:  85.9409 s

 Bern Two States - 0,1

Counter: 0: 705044031 1: 705021377 Counter additions:  1410065408


0:  7.05044% 1:  7.05021%


Timer Object: Two State - Double Timer Object Destroyed: Two State - Double Duration Elapsed:  87.6082 s

 Double Two States - 0,1

Counter: 0: 705029886 1: 705035522 Counter additions:  1410065408


0:  7.0503% 1:  7.05036%

However, for limit = 10^9, the results are fine:

Timer Object: Bern Two States
Timer Object Destroyed: Bern Two States
Duration Elapsed:  62.5088 s

 Bern Two States - 0,1

Counter:
0: 500005067
1: 499994933
Counter additions: 1000000000


0:  50.0005%
1:  49.9995%


Timer Object: Two State - Double
Timer Object Destroyed: Two State - Double
Duration Elapsed:  62.6709 s

 Double Two States - 0,1

Counter:
0: 500015398
1: 499984602
Counter additions: 1000000000


0:  50.0015%
1:  49.9985%



After I catch an egg, everything stops

I tried to put move eggs after the last line of the function "check_catch", but it was going so fast and it only created two eggs I copied this code from a book, and it's an egg catcher, but after you catch your first egg, everything immediately stops. Does anyone know the problem? I think where the problem is. It is probably in the function "check_catch", but nothing i fix works

#importing modules
from itertools import cycle
from random import randrange 
from tkinter import Canvas, Tk, messagebox, font




canvas_width = 800
canvas_height = 400
#drawing the sky, sun, and grass and making the window
root = Tk ()
c = Canvas(root, width=canvas_width, height=canvas_height, background='deep sky blue')
c.create_rectangle(-5, canvas_height - 100,  canvas_width + 5, canvas_height + 5, \
               fill='sea green' , width=0)
c.create_oval(-80, -80, 120, 120, fill='orange' , width=0)
c.pack()
#assigning important variables
color_cycle = cycle(['light blue', 'light green' , 'light pink' , 'light yellow' , 'light cyan' ])
egg_width = 45 
egg_height = 55
egg_score = 10
egg_speed = 500
egg_interval = 4000
difficulty_factor = 100

catcher_color ='blue'
catcher_width = 100
catcher_height = 100
catcher_start_x = canvas_width / 2 - catcher_width / 2
catcher_start_y = canvas_height - catcher_height - 20
catcher_start_x2 = catcher_start_x + catcher_width 
catcher_start_y2 = catcher_start_y + catcher_height
#creating the arc for the catcher to catch the eggs
catcher = c.create_arc(catcher_start_x, catcher_start_y, \
                    catcher_start_x2, catcher_start_y2, start=200, extent=140, \
                    style='arc', outline=catcher_color, width=3)
#Writing the score and how much lives you have
game_font = font.nametofont('TkFixedFont')                      
game_font.config(size = 18)
score = 0
score_text = c.create_text(10, 10, anchor = 'nw', font = game_font, fill = 'DarkBlue', \
                           text = 'score: ' + str(score))

lives_remaining = 3
lives_text = c.create_text(canvas_width - 10, 10, anchor='ne', font=game_font, fill = ('darkblue'), \
                       text='Lives:  ' + str(lives_remaining))  
eggs = []
#creating the egg
def create_egg():
    x = randrange(10, 740)
    y = 40
    new_egg = c.create_oval(x, y, x + egg_width, y + egg_height, fill=next(color_cycle) , width=0)
    eggs.append(new_egg)
    root.after(egg_interval, create_egg)
#moving the eggs
def move_eggs():
    for egg in eggs:
        (egg_x, egg_y, egg_x2, egg_y2) = c.coords(egg) 
        c.move(egg, 0, 10)
        if egg_y2 > canvas_height:
            egg_dropped(egg)
    root.after(egg_speed, move_eggs)
#if the eggs reach the bottom of the window, minus one life and delete the egg
def egg_dropped(egg):
    eggs.remove(egg)
    c.delete(egg)
    lose_a_life()
    #if you have 0 lives, write Game Over!
    if lives_remaining == 0:
        messagebox.showinfo('Game Over!', 'Final score: ' \
                            + str(score))
        root.destroy() 
  #lose a life
def lose_a_life():
    global lives_remaining
    lives_remaining -= 1
    c.itemconfigure(lives_text, text = 'lives: ' + str(lives_remaining))
If the catcher(the arc) catches an egg, add 10 to the score and delete it
def check_catch():
    (catcher_x, catcher_y, catcher_x2, catcher_y2) = c.coords(catcher)
    for egg in eggs:
        (egg_x, egg_y, egg_x2, egg_y2) = c.coords(egg)
        if catcher_x < egg_x and egg_x2 < catcher_x2 and catcher_y2 - egg_y2 < 40:
            eggs.remove(egg)
            c.delete(egg)
            increase_score(egg_score)
    root.after(100, check_catch)
#increase the score
def increase_score(points):
    global score, egg_speed, egg_interval
    score += points
    egg_speed = int(egg_speed * difficulty_factor)
    egg_interval = int(egg_interval * difficulty_factor)
    c.itemconfigure(score_text, text='Score: ' + str(score))
#move left
def move_left(event):
    (x1, y1, x2, y2) = c.coords(catcher)
    if x1 > 0:
        c.move(catcher, -20, 0)
 #move right   
def move_right(event):
    (x1, y1, x2, y2) = c.coords(catcher)
    if x2 < canvas_width:
        c.move(catcher, 20, 0)
#If the left or right arrow key is hit, move that direction    
c.bind('<Left>', move_left)
c.bind('<Right>', move_right)
c.focus_set()
#Call the game functions
root.after(1000, create_egg)
root.after(1000, move_eggs)
root.after(1000, check_catch)
#Call the main Tkinter loop
root.mainloop()



Random number in Do While Loop C#

I have been trying to create a random string out of alphanumeric characters and to use Do-While Loop to check if the random string meet the requirement. Otherwise, it should continue the Do Loop. However, I found the code I have always generates the same string over and over again. To demonstrate, I set int message_length = 2 and ask While Loop to check if the generated string is "ab" like while (check != "ab").

I have tried to put Random seed = new Random() in the Do Loop, out of the Do Loop, and out of the Main() as you can see the code I commented out. None of them is working. I used Visual Studio 2017, Windows 10 Home. Anyone could help? Many thanks!

using System;
using System.Text;
using System.Collections.Generic;


public class Program
{
    //static Random seed = new Random();

    public static void Main(string[] arggs)
    {
        Random seed = new Random();
        const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Console.WriteLine(src.Length);
        int string_length = 2;
        List<string> all_message = new List<string>();
        string check = "";
        do
        {
            //Random seed = new Random();
            int i = 0;
            StringBuilder message = new StringBuilder();
            for (int j = 0; j < string_length; j++)
            {
                char c = src[seed.Next(0, src.Length)];
                message.Append(c);
            }
            all_message.Add(message.ToString());
            check = all_message.ToString();
            Console.WriteLine(i + " = " + all_message[i]);

            i++;
        }
        while (check != "ab");

    }
}



Why do STD implementations of mt19937 have double sizeof as boost version?

I have this simple C++ program with unexpected output:

#include<random>
#include<iostream>
#include "boost/random/mersenne_twister.hpp"
#include "boost/random/uniform_int_distribution.hpp"

int main(){
    std::cout << sizeof(std::mt19937) << std::endl;
    std::cout << sizeof(std::mt19937_64) << std::endl;
    std::cout << sizeof(boost::random::mt19937) << std::endl;
    std::cout << sizeof(boost::random::mt19937_64) << std::endl;
}

both clang and gcc output

5000

2504

2504

2504

What I find interesting is that sizeof standard implementation of mt19937(32bit one) is around 2x the the boost version, while 64bit ones match perfectly.

Since MT uses a lot of space it is not really a small difference.

Also it is weird that implementation of a strictly specified algorithm would have such different sizeof, we are not talking about std::string where implementers might pick different SSO buffer size...

My best guess would be that boost either has a bug or that it implements some slightly different version of mt19937, but wikipedia says this, suggesting boost might be right:

Relatively large state buffer, of 2.5 KiB,

edit: both boost and std version seem to satisfy requirement that 1000th generated value is 4123659995, so there seems to be no bug in boost.




ansible - read file, then randomly select entry

I'm using Ansible 2.9.10. I am trying to read a file in which consists of a list of items. I then want to choose 3 random items from this list. I've tried several things (noted below) but cannot seem to figure this out.

The file itemList is a list of items, one per line:

hammer
saw
wood
.....

In the playbook I have:

vars:
  file_contents: ""

# Printing file contents returns "widget\hammer\nsaw\nwood"..... etc. 
- name: Print file contents
  debug:
    msg: "File contents are "


# Now try to select one random item from file_contents
- name: Select one random item
  debug:
     msg: "item is "
  with_random_choice: ""

What am I missing? It seems as though I am making it harder than it seems. TIA




Random and replacement characters in c++ output

I am writing a program to reverse a string and insert random characters in between. Here is my code: main.cpp

#include <iostream>
#include <chrono>
#include <thread>
#include "encrypter.cpp"
using namespace std;
int main(int argc, char *argv[])
{
    char message[256];
 this_thread::sleep_for(chrono::milliseconds(1000));
 cout <<    "Make sure theres no one around you" << endl;
 this_thread::sleep_for(chrono::milliseconds(1000));
 cout <<    "Enter secret message ";
 cin.get(message, 256);
 cout <<    "message encrypted" <<  endl;
 enc(message);
 return 0;
}

encrypter.cpp

#include <iostream>
#include <string>
int getRandom(int a, int b) {
    return a + (rand() % static_cast<int>(b - a + 1));
}
using namespace std;
void enc(char message[256]) {
    int i = 0;
    int len =   strlen(message);
    int revlen =    len - 1;
    int wtpselector;
    int charselector;
    int encsim;
    char randchar[6] =  "@#$%&";
    char strreved[256];
    char strenc[1024];
    while (i <  len) {
        strreved[revlen]    =   message[i];
        i++;
        revlen--;
    }
    revlen =    strlen(strreved);
    len =   revlen - 1;
    i = 0;
    encsim =    0;
    while (i <  revlen) {
        wtpselector =   getRandom(0, 4);
        charselector =  getRandom(0, 4);
        if (wtpselector ==  0) {
            strenc[encsim]  =   strreved[i];
            i++;
            encsim++;
        } else {
            strenc[encsim]  =   randchar[charselector];
            encsim++;
        }
    }
    cout << strenc << endl;
}

But the output has many random characters that are not supposed to be there and are not in the program. Like:

Input: hello world
Output: $%@$#&&d&&@%$%1%row &#$$@%&ol@%#@%&1%&#$&#ehe$%%€@@8@&%@$#& #%@@%&¢&@%#&#$#@$#%%##&%#@&#&$8%#$#@#$@$@#%&&@&#@Q#$$#&¢%@% Q#\#&$@#{&&&&$@¢ \ $$$$@@@@@#&&&%%&&%{ $@¢v#&@&~u@@@@%&%¢

Please help!!!




JavaScript with Random Number

I must set up a payment widget on a website, I'm obviously new in this, tried following the help site from our gateway provider and was able to do as follow:

<html>
<head><meta charset="utf-8">
<title></title>
<script type="text/javascript" src="https://checkout.co/widget.js"></script>
</head>
<body>
<script>
var checkout = new WidgetCheckout({
   currency: 'COP',
   amountInCents: 20000000,
   reference: 'ReferenceID',
   publicKey: 'pub_test_aoqCB6UQtUGCGN9SUzT7LBwNFbQYw0aG',
   redirectUrl: '' // Opcional
});
</script>
<button onclick="checkout.open (function ( result ) {
var transaction = result.transaction
console.log('Transaction ID: ', transaction.id)
console.log('Transaction object: ', transaction)
})">Pagar</button>
</body>
</html>

Now the question is: is there any way I can setup a autogenerated 10 lenght random number on reference field: 'ReferenceID'? I tryed adding Math.round(Date.now() + Math.random()*9) but obviously not working. See the result of what happens when I add Math.round...

Screenshot

Thanks for your help




Frugal conversion of uniformly distributed random numbers from one range to another

Is there a way to convert uniformly distributed random numbers of one range to uniformly distributed random numbers of another range frugally?

Let me explain what I mean by "frugally".

The typical approach to generate random number within given range (e.g. $r \in [0..10)$ ) is to take some fixed random bits, let's say 31, which result non-negative random number less than 2147483648. Then make sure that the value is less than 2147483640 (because 2147483648 is not divisible by 10, and hence may lead to uneven distribution). If the value is greater or equal to 2147483640, throw it away and try again (get next 31 random bits and so on). If value if less than 2147483640, then just return the remainder of division by 10. This approach consumes at least 31 bit per decimal digit. Since theoretical limit is $\log_2{10} = 3.321928...$, it is quite wasteful.

We can improve this, if we use 4 bits instead if 31. In this case we will consume $4 \times 1.6 = 6.4$ bits per decimal digit. This is more frugal, but still far from the ideal.

    public int nextDit() {
        int result;
        do {
            result = next4Bits();
        } while (result >= 10);
        return result;
    }

We can try to generate 3 decimal digits at once. Since 1024 is quite close to 1000, the probability that raw source random number will be rejected is less than in previous case. Once we generated 3 decimal digits, we return 1 digit and reserve the rest 2 digits.

Something like below

    private int _decDigits = 0;
    private int _decCount = 0;

    public int nextDit() {
        if (_decCount > 0) {
            // take numbers from the reserve
            int result = _decDigits % 10;
            _decDigits /= 10;
            _decCount -= 1;
            return result;
        } else {
            int result;
            do {
                result = next10Bits();
            } while (result >= 1000);
            // reserve 2 decimal digits
            _decCount = 2;
            _decDigits = result % 100;
            result /= 100;
            return result;
        }
    }

This approach is much more frugal: it consumes $10 \times 1.024 \div 3 = 3.41(3)$ bits per decimal digit.

We can even go farther if we try to reuse the numbers, which we previously have been throwing away. The random number $r \in [0, 1024)$ falls into one of the 3 ranges: $[0, 1000)$, $[1000, 1020)$, $[1020, 1024)$.

If it falls into $[0, 1000)$, we do as we did before, reserve 2 decimal digits (in decimal digit reserve) and return 1 decimal digit.

If it falls into $[1000, 1020)$, we subtract 1000 converting to the range $[0, 20)$. Then we get 1 bit by dividing it by 10 and 1 decimal digit by getting remainder of division by 10. We put the bit to the binary digit reserve and return the decimal digit.

If it falls into $[1020, 1024)$, we subtract 1020 converting to the range $[0, 4)$. Here we get just 2 bits, which we put to the binary digits reserve.

    // decimal digit reserve
    private int _decDigits = 0;
    private int _decCount = 0;
    // binary digit reserve
    private int _binDigits = 0;
    private int _binCount = 0;

    private int nextBits(int bits, int n) {
        for (int i = 0; i < n; i += 1) {
            bits = (bits << 1) + _bitRandomDevice.nextBit();
        }
        return bits;
    }

    private int next10Bits() {
        // we bits from the binary reserve first, then from _bitRandomDevice
        int result;
        if (_binCount >= 10) {
            result = _binDigits >> (_binCount - 10);
            _binDigits = _binDigits & (1 << (_binCount - 10) - 1);
            _binCount -= 10;
        } else {
            result = nextBits(_binDigits, 10 - _binCount);
            _binCount = 0;
            _binDigits = 0;
        }
        return result;
    }

    public int nextDit() {
        if (_decCount > 0) {
            // take numbers from the decimal reserve
            int result = _decDigits % 10;
            _decDigits /= 10;
            _decCount -= 1;
            return result;
        } else {
            int result;
            while (true) {
                result = next10Bits();
                if (result < 1000) {
                    assert result >= 0 && result < 1000;
                    // reserve 2 decimal digits
                    _decCount = 2;
                    _decDigits = result % 100;
                    result /= 100;
                    // return 1 decimal digit
                    return result;
                } else if (result < 1020) {
                    result -= 1000;
                    assert result >= 0 && result < 20;
                    // reserve 1 binary digit
                    _binCount += 1;
                    _binDigits = (_binDigits << 1) + (result / 10);
                    // return 1 decimal digit
                    return result % 10;
                } else {
                    result -= 1020;
                    assert result >= 0 && result < 4;
                    // reserve 2 binary digits
                    _binCount += 2;
                    _binDigits = (_binDigits << 2) + result;
                }
            }
        }
    }

This approach consumes about 3.38... bits per decimal digit. This is the most frugal approach I can find, but it still wastes/loses some information from the source of randomness.

Thus, my question is: Is there any universal approach/algorithm that converts uniformly distributed random numbers of one arbitrary range $[0, s)$ (later called source numbers) to uniformly distributed random numbers of another arbitrary range $[0, t)$ (later called target numbers), consuming only $log_s{t} + C$ source numbers per target number? where C is some constant. If there is no such approach, why? What prevents from reaching the ideal limit?




Use random gradient from my own Custom list for the Bacckground ( SCSS )

I have my few own combinations of gradient that I want to use in my the website background in different areas.

I want them to Change every time the page refreshes.

I have already coded the gradient at different paces with different degree on gradient angle using 2 variables

$primary-color

$secondary-color

Now, In my variables.scss file, I want to get random pair of primary and secondary color to be taken as these variables value.

Gradient Combinations:

  1. #ffafbd → #ffc3a0

  2. #2193b0 → #6dd5ed

  3. #cc2b5e → #753a88

I want user to experience any one of the above gradient as the background of different <div> tags ( on which i have applied the gradient code ) every time they refresh or new user enters my website




mardi 25 août 2020

TypeError: Cannot mix BigInt and other types, use explicit conversions

I am trying to generate a 20 digit random number:

let code = Math.floor(10000000000000000000n + Math.random() * 90000000000000000000n)

I have tried putting the numbers in BigInt() as well as adding a n after but still this error comes.

Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions



Python Generate Non Uniform Randint

If I use python random's randint function, I seem to be getting a uniform distribution as below.

How do I make this a non-uniform randint?

I do not care about specifying a specific range like this: Generate random numbers with a given (numerical) distribution (numpy.random.choice/ random.choice), the answer can have any distribution over the range.

Thank you for your time.

Eg:

#Counter({2: 10760, 6: 190364, 4: 40092, 0: 160068, 7: 99936, 3: 99885, 8: 99845, 9: 99725, 5: 99675, 1: 99650})

Current Example Code:

from collections import Counter
from random import randint
list_size=1000000
random_list=list(sorted([randint(0,9) for x in range(list_size)]))
Counter(random_list)
#Counter({2: 100760, 6: 100364, 4: 100092, 0: 100068, 7: 99936, 3: 99885, 8: 99845, 9: 99725, 5: 99675, 1: 99650})

Things I have tried:

def really_random(start,stop):
    random_array_size=random.randint(3,10)
    random_array_choice=random.randint(0,random_array_size-1)
    random_value=[random.randint(start,stop) for x in range(random_array_size)][random_array_choice]
    return random_value

def really_random_test(start,stop):
    list_size = 100000
    random_list = list(sorted([really_random(start, stop) for x in range(list_size)]))
    print(Counter(random_list))

still pretty uniform

#Counter({7: 10094, 9: 10066, 3: 10044, 1: 10027, 5: 10012, 8: 10012, 0: 10009, 6: 9985, 2: 9878, 4: 9873})



How can I avoid generating the same number using a random number generator that I am assigning to two variables?

var randomDescriptor1 = descriptors[getRandomIndex(descriptors)];
  tagline1.innerText = randomDescriptor1;
  var randomDescriptor2 = descriptors[getRandomIndex(descriptors)];
  tagline2.innerText = randomDescriptor2;
function getRandomIndex(array) {
  return Math.floor(Math.random() * array.length);
}

I am altering an HTML file using dom and want to generate random descriptors in the same sentence. I pull from an array of stored strings, but sometimes they happen to return the same word twice in the sentence. How could I avoid this?




uniform_int_distribution with zero range goes to infinite loop

For unit tests I implemented a mock random number generator. I believe that this is a valid implementation of UniformBitGenerator (the mock actually uses google mock to set the return of operator(), but it behaves the same).

struct RNG
{
    using result_type = size_t;
    static result_type min() { return 0; }
    static result_type max() { return std::numeric_limits<result_type>::max(); }
    result_type operator()() { return max(); }
};

Now I use this mock to sample from std::uniform_int_distribution in the range [a, b], a == b. I believe this is allowed, the only restriction I have found here on the parameters of the distribution is b >= a. So I would expect the following program to print 5.

int main()
{
    auto rng = RNG();
    auto dist = std::uniform_int_distribution<>(5, 5);
    printf("%d\n", dist(rng));
    return 0;
}

Instead it goes into an infinite loop inside the STL, repeatedly drawing numbers from the generator but failing to find a number within the specified range. I tested different (current) compilers (including clang, gcc, icc) in different versions. RNG::max can return other values (e.g. 42) as well, doesn't change anything.

The real code I'm testing draws a random index into a container which may contain only one element. It would be easy to check this condition but it's a rare case and I would like to avoid it.

Am I missing something in the specification of RNGs in the STL? I'd be surprised to find a bug in ALL compilers ...




When I made code and then made from that code a function I changed print to return but nothing happens

contints = ["Europe", "North_America", "South_America", "Asia", "Australia", "Africa"]
Europe = "rich life"
North_America = "average life"
South_America = "poor life"
Asia = "average life"
Australia = "rich life"
Africa = "very poor life"
print(random.choice(contints))
if random.choice(contints) == "Europe":
    print("You will have a " + Europe)
elif random.choice(contints) == "North_America":
    print("You will have a " + North_America)
elif random.choice(contints) == "South_America":
    print("You will have a " + South_America)
elif random.choice(contints) == "Asia":
    print("You will have a " + Asia)
elif random.choice(contints) == "Australia":
    print("You will have a " + Australia)
else:
    print("You will have a " + Africa)

This works but when I make a function out of it and change to return statements nothings happens while I want to return the answer. I want that the continent is randomly chosen and then return the output.

import random def continent(contints): contints = ["Europe", "North_America", "South_America", "Asia", "Australia", "Africa"] Europe = "rich life" North_America = "average life" South_America = "poor life" Asia = "average life" Australia = "rich life" Africa = "very poor life" if random.choice(contints) == "Europe": return Europe elif random.choice(contints) == "North_America": return North_America elif random.choice(contints) == "South_America": return South_America elif random.choice(contints) == "Asia": return Asia elif random.choice(contints) == "Australia": return Australia else: return Africa




How to count each number that is generated randomly using array in C#

How to count each number that gets generated randomly using array in C#?

Output will be as below:

2 3 5 3 5

Number 1 : 0
Number 2 : 1
Number 3 : 2
Number 4 : 0
Number 5 : 2

I did come out with random numbers but then I'm stuck to figure out how to count each number.

int[] randNum;
randNum = new int[5];
Random randNum2 = new Random();

for (int i = 0; i < randNum.Length; i++)
{
    randNum[i] = randNum2.Next(0, 9);
    Console.Writeline(randNum[i]);
}

Console.WriteLine();



lundi 24 août 2020

Python Random - change random value from list each time I use print

I know this is probably one of the easiest things in the world to do, and I'll feel like an idiot once someone answers, but please, help.

import random

stuff_list = ['a1', 'a2', 'a3']
stuff_item = random.choice(stuff_list)

print(stuff_item)
print(stuff_item)
print(stuff_item)

This makes it choose a random value (Ax) from stuff_list, but each time I print stuff_item I always get the same value from the list. How do I make it so that each time I use print, it randomises it again?




SQL order by rand() fill result with duplicates if there's not enough rows

I have an exercising app for a language for running tests in 20,40,60 (LIMIT 20..40..60). How to fill result by duplicates if LIMIT exceeds rows in selected topic?

table: topic Cooking has only 18 rows

Lets say "select from table where topic=Cooking order by rand() LIMIT 40

How to populate result by duplicates so that result has 40 rows even there is not enough rows for it?




Get an uniform distributed sample but keep the order

How could i get a sample of a values of a vector but keep the order without compairing the values themself against each other?

for example:

V1 contains values (1,2,3,4,5,6,7,8,9,10,11,12,13,14)

I woule like to get a sample

sample <- (2,7,10,14)

As you can see the values are still on order but randomly selected.

But if i use a function sample or rdunif in R I get random orderd selection:

ie. (7,10,2,14)

Thank you!




Python LDAP3 TLS - Ramdom error - socket ssl wrapping error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate chain too long

I have a random error (Windows with Python 3.8) while query to DC (Active directory) via LDAP3.

I use a passwordless (Passwordless Python LDAP3 authentication from Windows client)

Running the program again and again works, but sometimes I get this error. Error: ("('socket ssl wrapping error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate chain too long (_ssl.c:1108)',)",)

Simple code below:

   from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, 
   AUTO_BIND_NO_TLS, SUBTREE, BASE, LEVEL, Tls
   from ldap3 import SASL, GSSAPI #for passwordless conection
   from ldap3.core.exceptions import LDAPCursorError, LDAPSocketOpenError
   import ssl
   tls_configuration = Tls(validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1)
   server = Server("DC-hostname-here", get_info=ALL, use_ssl=True, tls=tls_configuration)
   try: #the random error is triggered here
       conn = Connection(server, authentication=SASL, auto_bind=True, auto_referrals=False, sasl_mechanism=GSSAPI)
   except Exception as e:
       print(e)
   #If no fail, u can do some search, example:
   conn.search('DC=youdomin,DC=XXXX,DC=com', '(sAMAccountName=some_group_to_searche)', search_scope=SUBTREE,  attributes=['distinguishedName'])
   print(conn.entries[0].distinguishedName[0])
   conn.unbind()
  1. Why do I have this random error?
  2. How to solve it?
  3. Is this code secure? I mean, is the connection really encripted with certificates?

Thanks in advance




Partition array into N random chunks of different sizes with Numpy

With numpy.array_splits, you can split an array into equal size chunks. Is there a way to split it into chunks based on a list?

How do I split this array into 20 chunks, with each chunk determined by the size of the chunk given in chunk_size, and consisting of random values from the array?

>>> import numpy as np
>>> a = np.arange(0, 3286, 1)
>>> chunk_size = [975, 708, 515, 343, 269, 228, 77, 57, 42, 33, 11, 9, 7, 4, 3, 1, 1, 1, 1, 1]

I tried using something like this:

[np.random.choice(a,_) for _ chunk_size]

but I get multiple duplications, as expected.

With np.split, this is the answer I get:

>>> for _ in np.split(a, chunk_size): print (_.shape)
...
(975,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(0,)
(3285,)

With np.random.choice and replace=False, still gives duplicate elements

import numpy as np
np.random.seed(13)
a = np.arange(0, 3286, 1)
chunk_size = [975, 708, 515, 343, 269, 228, 77, 57, 42, 33, 11, 9, 7, 4, 3, 1, 1, 1, 1, 1]
dist = [np.random.choice(a,_, replace=False) for _ in chunk_size]

for _ in dist:
    if 2828 in list(_):
        print ("found")



How to get a random smallint

I am trying to get a random value based on its type.

Examples:

  1. tinyint - rand(0, 255);

  2. int - rand(PHP_INT_MIN, PHP_INT_MAX)

How do I do that with smallint or bigint?

My guess was something like this but it gives me syntax errors and looks terrible:

rand(-2^15*(-32,768) , 2^15-1*(32,767));




How to create droptown list with selection part and generate the random value?

So right now,there is 4 input text place.You can write everything what you want and when you click the "pick one" button, you gonna get back any text what you entered earlier. I would like change these kind of input text places to the dropdown lists where you can select some teams and when you click "pick one" you gonna get 1 team randomly. <?php

error_reporting(0);

if(isset($_POST['submit']))
    {
        $team1=$_POST['team1'];
        $team2=$_POST['team2'];
        $team3=$_POST['team3'];
        $team4=$_POST['team4'];

        $teams=array
        (
            "1" =>"$team1",
            "2" =>"$team2",
            "3" =>"$team3",
            "4" =>"$team4",
        );
    $random = rand(1, 4);
    }
?>


<html>
<form action="index.php" method="POST">
Enter the team name<input type="text" name="team1" value="<?php echo $team1 ?>"><br>
Enter the team name<input type="text" name="team2" value="<?php echo $team2 ?>"><br>
Enter the team name<input type="text" name="team3" value="<?php echo $team3 ?>"><br>
Enter the team name<input type="text" name="team4" value="<?php echo $team4 ?>"><p>

<input type="submit" name="submit" value="Pick One!"><br>
</form>

<?php

print $teams["$random"];

?>
</html>



Generating random synthetic payment data

I have seen people create fake data sets but usually there are no repeated people to bill matching.

For example, i want 100 people's name and in those 100 people, some have 2 or more telephone accounts while some have 1, and their bill are constant throughout the year for each account.

Basically, for a given name in a random list of names:

  • I need an ID number that match that specific name
  • 1 or more telco per name
  • bill amount that matches the name & telco
  • a date for every month of the bill

eg.

name, id_number, telco, bill amount, data of bill
john, X123, vodafone, 40, 1/1/2020
john, X123, telecomz, 25, 1/1/2020
john, X123, vodafone, 40, 1/2/2020
Gerald, T124, vodafone, 22, 1/1/2020
Gerald, T124, vodafone, 22, 1/2/2020
tim, A555, TPG, 100, 1/1/2020
tim, A555, TPG, 100, 1/2/2020

May i know how can i create such a synthetic dataset?




Why does python not shuffle properly when given a large amount of data?

I have a csv file named KDDTrain+.csv, which has 43 columns and 125973 lines.

Column 42 indicates the label of a certain row.

I built a simple code that reads the csv file into a dataframe, and shuffles it completely using pandas sample function, and then goes through each half of the dataframe and counts, how many rows are labeled "normal" and how many rows aren't:

import pandas as pd

csv= pd.read_csv("KDDTrain+.csv")
csv = csv.sample(frac=1).reset_index(drop=True)
results = csv['42'].tolist()
n = 0
a = 0
for res in results[:int(round(len(csv)/2))]:
    if res == "normal":
        n += 1
    else:
        a += 1
print(f"n:{n}, a:{a}|")
n = 0
a = 0
for res in results[int(round(len(csv)/2)):]:
    if res == "normal":
        n += 1
    else:
        a += 1
print(f"n:{n}, a:{a}|")

After running the code multiple times, it seems that the results are always very similar between the two halves, even though they are supposed to be shuffled. (Example: n:33627, a:29359| n:33716, a:29271|)

Note that I tried using other methods for shuffling the data such as SystemRandom, Numpy's Random, and multiple implementations of shuffle using the built in random method, and all gave similar results.

Why does python not really shuffle the data?




Python 3 Randomized Selection from Existing List

I have put together the following code in Python 3. The intention is to pull 5 random elements from the list and then to concatenate a string of the 5 elements together. The code works, but the means of randomly selecting the 5 elements is hugely clunky. I am sure that there is a more elegant way to do it, but can't find a better way. Any help on improving would be fantastic Thanks

import random

clean = ["We're the ship without a storm", 'The cold without the warm', 'Light inside the darkness', 
                'That it needs, yeah', "We're a laugh without tear", 'The hope without the fear', 'We are coming, home', 
                "We're off to the witch", 'We may never, never, never, come home', "But the magic that we'll feel", 
                'Is worth the lifetime', "We're all born upon the cross", "We're the throw before the toss", 
                'You can release yourself', 'But the only way is down', "We don't come alone", 'We are fire, we are stone', 
                "We're the hand that writes", 'Then quickly moves away', "We'll know for the first time", 
                "If we're divine"]

#Create a list of randomly selected sentences from the clean list
randomz = []
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])

#Concatenate the selected elements into single string
strg = ''
for x in randomz:
    strg += x + '.' + ' '
    
print(strg)



Train-Test Split & Random_state [duplicate]

I wonder what you need to use random_state in scikit-learn. what number to put for the random_state ? and how do we define the number to the random_state?




Applying staggered and randomised left / right placement for each wordpress post with javascript

So I'm trying to make each individual post (.card) on a WordPress site stagger, some more to the left, some to the right, and for this to be a random amount and to change on refreshing the page.

This is where I am at with the JavaScript code to try and do this:

//random position 

$(document).ready(function () {
    $('.card').each(function () {
        $('.card').css({
            'left': (Math.random() * 900) + 50
        })
    });
});

I don't think I am using the 'each' method correctly? It randomly places them left / right, but it applies the same distance to all posts, instead of each one being at a different distance.

Where am I going wrong here?




dimanche 23 août 2020

Random-effects ordered probit model - intraclass correlation

I am using mixor package in R (https://www.rdocumentation.org/packages/mixor/versions/1.0.4/topics/mixor) to explore influential factors on injury severity among crash-related, road-related and etc factors. it has assumed that shared variance among individuals involved in the same crash is high, so random-effects ordered probit model is utilized.

My question is how I can calculate intraclass correlation among individuals in the same crash to justify why i choose random-effects model




Something odd going on with my triplet optimization algorithm?

I've tried comp sci SE, data science SE, and science comp SE. Some people have suggested SO is the best place for this. Hopefully the geniuses of SO can help with this

I written an algorithm for data analysis using the CERN ROOT framework. It takes in three files of sorted UNIX timestamps from a single year, and pairs them up in the closest triplets, where each file contributes a triplet, and each triplet is unique. I know there are some more "well known" algorithms for accomplishing this, however this algorithm completes the task much faster, clocking in at about 20 minutes on my machine, as compared to many, many hours for some of the other algorithms I've tried. When complete, the algorithm plots the triplets (of the form {a,b,c]) on a 2-dimensional histogram, where the horizontal axis is a-b, and the vertical axis is a-c.

Problem is, it seems to be acting very weird. Namely, when I feed the algorithm one file of real data (these are timestamps generated by an experiment) and two files of completely random data, I get these weird diagonal lines: https://filebin.net/spbswnhkfy8xdkp8/random_plot.pdf?t=48f2yhjq. When I feed the algorithm three files of real data, a single diagonal line through the middle (and two more lines, running horizontally and vertically) appears if I use enough bins. Any idea what's going on with my algorithm?

EDIT: When I use three files of completely random data, I get this weird grid: https://filebin.net/k00htgl9v2wa5e7x/compRand.pdf?t=lrt6dpkr

        void unbiasedAnalysis(){

TNtupleD *D  = new TNtupleD("D","D","x:y");

ROOT::RDataFrame statn1("D", "./pathtodata");
ROOT::RDataFrame statn2("D", "./pathtodata");
ROOT::RDataFrame statn3("D", "./pathtodata");

vector<double> vec_1, vec_2, vec_3;
statn1.Foreach([&](double tstamp){ vec_1.push_back(tstamp); },{"UNIX"});
statn2.Foreach([&](double tstamp){ vec_2.push_back(tstamp); },{"UNIX"});
statn3.Foreach([&](double tstamp){ vec_3.push_back(tstamp); },{"UNIX"});

vector<vector<double>> pairs;
for(auto tstamp : vec_1){

    double first,second;

    //get iterator pointing to closest element greater than or equal to
    auto geq = std::lower_bound(vec_2.begin(), vec_2.end(), tstamp);
    //get iterator pointing to nearest element less than
    auto leq = geq - 1;

    double foo = tstamp - *geq;
    double bar = tstamp - *leq;

    //compare iterators, save the closest 
    if(dabs(foo) <  dabs(bar)){ first = *geq; }
    else { first = *leq; }




    //repeat
    geq = std::lower_bound(vec_3.begin(), vec_3.end(), tstamp);
    leq = geq - 1;

    foo = tstamp - *geq;
    bar = tstamp - *leq;

    if(dabs(foo) < dabs(bar)){ second = *geq; }
    else { second = *leq; }

    //add to pairs
    pairs.push_back({tstamp, first, second, (tstamp-first), (tstamp-second), std::min((tstamp-first), (tstamp-second))});

}

//sort vector of vectors by size of smallest difference
std::sort(pairs.begin(), pairs.end(),
    [](const vector<double>& A, const vector<double>& B){
        return A[5] < B[5];
});

std::set<double> cache;

ROOT::EnableImplicitMT();

for(auto pair : pairs){
    //if not in cache, add to TNtuple
    if(cache.find(pair[1]) == cache.end() && cache.find(pair[2]) == cache.end()){

            D->Fill(pair[3],pair[4]);

        //add to cache
        cache.insert(pair[1]); cache.insert(pair[2]);
    }
}

D->Draw("x:y>>htemp(100,-0.02,0.02,100,-0.02,0.02)","","colz");
}



User has x amount of probability to get the number he entered

Hi I'm stuck on a probability game.

how can i create a function where user has 20% chance to get the number he inputs? and also he has 15% chance to get previous number and next number?

user can pick a numbers from range 1-20.

Example: If user enters 8. He has 20% chance to get 8. 15% chance to get 7. 15% chance to get 9. etc




C Replacements for srand() and rand()

I'm trying to make a game in C fit under a 3KB limit, and to do so I want to remove all standard library references. The only header I want to have in my program is windows.h and so far I'm doing pretty good.

The only external references I have are one call each of rand(), srand(), time(), and getch(). This may seem like a lot for a game under 3KB, but the time, rand, and srand functions are only so that when the game starts it can have a random seed.

rand to get the numbers, srand to set the seed, and time to get random seeds. So if I could find a way to get rid of the excessive random generation procedure, I could get rid of 3/4 std library functions. I'm not so sure what to do about getch though, but ill focus on that later.

Some people have reccomended xorshifts, but it seems like that requires the type uint32_t, which belongs to stdint.h. I also tried using integers instead, and while the resulting number was random, it was random in the sense that the number given back was random, yet you could depend on it giving you that random number each time. I could give it time as a sort of seed, but then id still have to use the time function. Is there something I'm overlooking, or should I use a different method?




How to use the Random class to choose random elements from an array in java [closed]

I've been using the Math.random() method to generate random numbers in the past. However, I've been asked to generate a list of 100 numbers from the set (6,10,14,18,22) using the Random class, the question says the output has to be random but every time I run it I must get the same list. I tried looking for a method online for the Random class that chooses random elements from an array and chooses the same ones every time but couldn't find anything.

I don't need to know how to make the program, I just need to know the appropriate method to use




Starting python script from Java class

I have random number generetor in Python script and now I am writing a DES algorithm, which should use this python script. There will be 2 modes: DES and 3DES, so I need to specify how many keys it should generate (1, or 3). Keys will be generated to file and from this file I will load these keys to DES algorithm.

For know I am using Python script with this line:

python rng.py --sequence [size of sequence] [range of random numbers]

I have found kind of solution like this:

String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command + param );

But this one doesn't work for me and I do not know how to solve this. Program compiles succesfully, but I don't have any generated numbers in output.txt file inside Python script folder.

String command = "python /c start python C:\\Users\\danie\\PycharmProjects\\RNG\\rng.py --sequence 3 10000000";
Process p = Runtime.getRuntime().exec(command);



What is the std::uniform_random_bit_generator concept and how do I use it?

I want to do two things. First, I want to define a template function that takes an std::uniform_random_bit_generator type T as an argument and uses all of the std::uniform_random_bit_generator features of that type T within the function. Second, I want to define a class that satisfies the requirements of being an std::uniform_random_bit_generator.

It's not important that the function or the class have any semblance of being "random."




Choosing at random an integer between 0 and the length of a given list, inclusive

In Python 3.x, I need to choose at random an integer between 0 and the length of a given list, inclusive. In other words, given

mylist = [0, 5, 6, 8, -10]

I want to return a number between 0 and 5, inclusive. What's the most Pythonic way to do it? I tried

import numpy as np
my_list = [0, 5, 6, 8, -10]
def choose_at_random(a_list):
    choice = np.random.randint(0, len(a_list) + 1)
    return choice   

This works, but is this the Pythonic way to do it? The need to +1 the list length seems a bit error-prone (I mean, it's easy to forget to do it).




Coding a cryptography algorithm that accepts random bits from an unspecified source

I'm currently coding a cryptography algorithm that I want to share on GitHub. This algorithm accepts random bits as input. I know that there are many possible sources of pseudorandom bits, one of the weirdest being that you can buy them. Because the quality and sources of pseudorandom number generators can vary widely, I want the user to be able to generate their own pseudorandom bits as input to my algorithm. I'm not sure how to code my algorithm in a general way since I don't know what data structure pseudorandom numbers come from in professional crytographic or statistical projects and how I should write a template function to access those pseudorandom numbers in the most general way.

The pseudorandom number generator will be accessed by my function my_distribution. I assume the PRNG will return a double between 0 and 1 or return a data type that I can convert to a double between 0 and 1.

double my_distribution([pseudorandom number generator]) {
    double random_number_from_my_distribution;
    // compute random_number_from_my_distribution using the PRNG
    return random_number_from_my_distribution;
}

There are a few possible sources for the pseudorandom bits I can think of.

  1. The pseudorandom bits could be stored in a file that is opened at run-time
  2. The pseudorandom bits could be provided by a (non-io) stream.
  3. The pseudorandom bits could be the return value of a function.
  4. The pseudorandom bits could be stored in some other data structure.

How should I accept pseudorandom bits into my_distribution? Why?




That is the difference [closed]

I am using Python3

class Solution:

    def __init__(self, radius: float, x_center: float, y_center: float):
        self.cenx = x_center
        self.ceny = y_center
        self.r = radius
    def randPoint(self) -> List[float]:
        #switch to polar coordinates
        phi = (2*random.random() - 1) *pi
        r = (random.random() * (self.r)**2)**0.5
        res = [self.cenx + r*cos(phi), self.ceny + r*sin(phi)]
        return res

What is diff between random.random()*(self.r) and (random.random()*(self.r)**2)**0.5 if I use random.random()*(self.r) I am getting Wrong Answer in one test case

Problem link




Unix Shell - Why are the same $RANDOM numbers repeated?

I was experimenting with the $RANDOM variable in a Unix shell and noticed something peculiar. I ran the following command, which reads $RANDOM in a loop 10k times and then pipes the output to "uniq" to find the duplicates.

$ for i in {1..100000}; do echo $RANDOM; done | uniq -d

I ran the command above 7 times, and the same two numbers (4455 and 4117) were repeated all 7 times. The screenshot below shows the command line output.

$RANDOM entropy test

I also opened another terminal window and repeated the process. In the second terminal, the numbers were different, but repeated from in a similar fashion. This makes me wonder about when the entropy of the $RANDOM variable, and how it is seeded.

My guess is that it is re-seeded whenever bash is invoked, but I was wondering if anyone has any info about why the same values are repeated when I repeat the command in a single terminal window.




samedi 22 août 2020

Im wondering how I would be able to get a discord bot to randomly ping someone from the guild its in with discord.js

I have this

    }else if (message.content.toLowerCase() === `${prefix}command`) {
    message.delete()
    const randomuser = Array.from(message.member.guild.members)
    randomperson = (math.random() *0 + guild.membercount)
    message.channel.send([randomuser])
  .then(msg => {
    msg.delete({ timeout: 100 })
  })

but using it results with this

    message.channel.send([Array.from(message.member.guild.members())])
    TypeError: message.member.guild.members is not a function
    at Client.<anonymous> (C:\Users\mrcoo\Desktop\Discord Bots\WeeWeeBot\WeeWeeBot\index.js:59:59)
    at Client.emit (events.js:315:20)
    at MessageCreateAction.handle (C:\Users\mrcoo\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\mrcoo\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\mrcoo\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:\Users\mrcoo\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:\Users\mrcoo\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (C:\Users\mrcoo\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:315:20)
    at Receiver.receiverOnMessage (C:\Users\mrcoo\node_modules\ws\lib\websocket.js:797:20)

I want to make it get an array of users from the guild that the message was sent in and then randomly choose one using the amount of users in the guild and all the tutorials I've found are for v11.5.1




how to scale a number in a range of [min , max]

basically what I want is a way to scale any number no matter how big it is or whether it is signed or unsigned, to fit between a given range.

this is not specific to my code or to my coding language, but I'll provide a sample of what I'm trying to achieve:

this code is meant to generate a random number using " linear congruential generator "
either by taking a seed or by taking a seed and a range between min and max :

int seed = time(0);
unsigned int multiplier = 48271;
unsigned int increment = 0;
unsigned long long modulus = (2 * pow(10,31)) - 1;

...

int getRandom(int Givenseed)
{
    return (multiplier * Givenseed + increment) % modulus;
}

int getRandom(int min, int max,int Givenseed)
{
    int result = (multiplier * Givenseed + increment) % modulus;
    
non of the ways below seems to work :

    //return result % (max - min + 1);
    //return min + (result / (modulus - 1)) * (max - min);
    //return (result * (max - min)) + min;
    //return min + result * (max - min);
    //return (result % (max - min + 1)) + min;
}

...

as you can see everything is working just fine but when I get to working with the range things start to get messy, but as I said earlier this is just an example and what I really want is a way to scale a value to a range regardless of the context, the commented lines are basically what I found while searching but non of them seem to work

also I'm aware of the header in c++ and I've used it before, but this time I want to do all the work myself for the sake of experience

to simplify all of this my question in simply:

How do you scale a value into a range of two values using math ?