lundi 31 octobre 2022

why does it say Syntax,Error: invalid syntax at line 5 [closed]

from random import*
def saisie():
    ch1=""
    for i in range (1,9):
        ch1[i]=chr(randint(ord'A',ord'Z'))
        ch1=ch1+ch1[i]
    return ch1 

i wanted to get a word randomly selected with capital and 8 letters




How to get random element with doctrine/postgresql [symfony]

I have a symfony / doctrine project configured on postgresql and I would like to have a random result of an element of my table. How can I do that?




dimanche 30 octobre 2022

Why does the scatter plot of calculated determinants and traces using uniformly distributed inputs not look as expected?

I'm trying to find the probability for a linear system to be various types of stability, where the system is given by the following matrix:

[[a,b],
[c,d]]

And a,b,c,d are chosen from a random uniform distribution from a domain of [-1,1]. The primary graph of interest is trace vs. determinant, ie. (a+d) vs. (a*d-c*b)

Plot of stability classification

In my code I generate random matrices using numpy.random.uniform(-1,1,size(2,2)). The trace and determinant then have ranges of [-2,2]. Here is the code I used:

import numpy as np
import matplotlib.pyplot as plt

det = [] # determinant
tr = [] # trace
i=0

while i < 100000:
    linsys = np.random.uniform(-1, 1, size=(2,2))
    tr.append(linsys[0][0]+linsys[1][1])
    det.append(linsys[0][0]*linsys[1][1]-linsys[1][0]*linsys[0][1])
    i += 1
    
print(np.max(tr),np.max(det),np.min(tr),np.min(det))
    
plt.scatter(det,tr)
plt.title("Plot of Trace v Determinant")
plt.xlabel("a*d-c*b")
plt.ylabel("a+d")
#plt.scatter(np.abs(det),2*np.sqrt(np.abs(det)))
#plt.scatter(np.abs(det),-2*np.sqrt(np.abs(det)))

fig1, ax1 = plt.subplots(figsize =(6, 4))
ax1.hist(det, bins = [-3,-2,-1,0,1,2,3])
plt.title('Histogram of trace')
fig2, ax2 = plt.subplots(figsize =(6, 4))
ax2.hist(trace, bins = [-3,-2,-1,0,1,2,3])
plt.title('Histogram of determinant')

I'd expect the graph of trace vs. determinant to be completely uniform with no weird shapes but instead I find this very strange shape when plotting them:

Plot of trace v determinant

And these are the distributions of the trace and determinant:

![Distributions of trace and determinant

Again, since all the variables a,b,c,d have the same domain [-1,1] I'd expect the sum of them or products of them to still have a uniform distribution. I'm wondering then why there's this strange shape in the scatter plot of trace v determinant then? Maybe I am defining the uniformly random matrix incorrectly?




n*n array which has 2 times every random values

To randomly generate a n*n array of assorted characters such that there are exactly two of each character in PYTHON


import random import numpy as np from string import punctuation set(punctuation) S = 5 char = ['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',
'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'] Digits = [0,1,2,3,4,5,6,7,8,9] symbols = ['~', ':', '+', '[', '@', '^', '{', '%', '(', '-', '*', '|', '&', '<', '}',
'_', '=', ']', '!', '>', ';', '?', '#', '$', ')', '/']
def create_array(n): s =random.choices(char + Digits + symbols) print(s) x = np.empty((n, n), dtype=object) if(n<=100):

    for i in range(n): 
        for j in range(n): 
            k =random.choices(char + Digits + symbols)
            x[i][j] = k              
    for i in range(n): 
        for j in range(n): 
            print(*x[i][j],sep=" ",end = " ")  
        print() 

n = 5

create_array(n)

i don't know how to assign the same value a second time



Generate different number in each loop [duplicate]

i generate random number in a loop. sometimes i have some problems because the same number is generated. how can i make every generated number be different.by the way, I only produce 11 numbers.

for ($j = 0; $j <= 100; $j++){
    $randCount = rand(0, 99);
    if ($j == 11) {
       break;
    }
}



Shortest Rout Back to Depot

Hi I have a question that I already found my own solution which is to sort all randomly generated (tuples) in a list [(X,Y), (X,Y), (X,Y), (X,Y), (X,Y), etc..] coordinates from a list and find the shortest distance from point to point and then the shortest distance from the end point back to the beginning point. I am wondering if there is a way to find all possible routs through all the randomly generated (tuples) in a list and then find the shortest possible rout?

thank!! a picture of the problem is attached.enter image description here

I already found my own solution which is to sort all randomly generated (tuples) in a list [(X,Y), (X,Y), (X,Y), (X,Y), (X,Y), etc..] coordinates from a list and find the shortest distance from point to point and then the shortest distance from the end point back to the beginning point




samedi 29 octobre 2022

How to convert matlab function to python - finiterv

Here is the code I am trying to convert from matlab

function x=finiterv(s,p,m)
% returns m samples
% of finite (s,p) rv
%s=s(:);p=p(:);
r=rand(m,1);
cdf=cumsum(p);
x=s(1+count(cdf,r));`

and here is my python code:

def infinterv(s,p,m):
#return m samples
#of finite (s,p) rv
r=random.uniform((m,1))
cdf=p.cumsum(axis=0)
x=s(1+count(cdf,))`

I get an error saying - uniform() missing 1 required positional argument: 'b'

I think I am not converting the random uniform function correctly!




My code produce random number without using rand()

I expected as output positive divisors of 76 but when I run, the output is 2 and a random integer value. When I put 1 instead of 2 for i in the iz_num function it prints 1 and 2.

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

int sqrt1(int n)
{
    for(int i = 1; true; i++)
    {
        if ( i*i >n)
        {
            return i-1;
        }
    }
}

bool isPrime1(int a) {
    if (a !=2 && a%2==0)
        return false;

    int sq = sqrt1(a);
    for (int d = 3; d<= sq; d+=2)
    {
        if ( a%d==0)
            return false;
    }
    return true;
}

void iz_num(int arr[], int num){
    int k=0;
    if (isPrime1(num))
        return;
    for(int i = 2; i <= num / 2 ; ++i,++k){

        if (num % i == 0){
            arr[k]=i;

        }
    }
    int size = sizeof (arr) / sizeof (size);
    for (int j = 0; j < size;++j){
        printf("%d ", arr[j]);

    }
}

int main()
{
    int arr[] = {};
    iz_num(arr,76);
}

Next I would find just prime divisors of 76.




43. Multiply String

Its working for all random testcases and 153/300 testcases however it isnt working for some of the testcases , it will be really helpful if someone can find the mistake.

`

class Solution {
public:
    
    int stringtoint(string str){
       int size = str.size()-1;
       long long int num = 0;
        
        unordered_map<char,int>umap;
            umap.insert(pair<char,int>('0',0));
            umap.insert(pair<char,int>('1',1));
            umap.insert(pair<char,int>('2',2));
            umap.insert(pair<char,int>('3',3));
            umap.insert(pair<char,int>('4',4));
            umap.insert(pair<char,int>('5',5));
            umap.insert(pair<char,int>('6',6));
            umap.insert(pair<char,int>('7',7));
            umap.insert(pair<char,int>('8',8));
            umap.insert(pair<char,int>('9',9));
        
        for(int i = 0 ; i < str.size() ; i++){
            if(umap.find(str[i])!=umap.end())
                num = num + umap[str[i]]*pow(10,size);
            
            size--;
        }
        
        return num;
        
    }
    
    string multiply(string num1, string num2) {
        
        
        string sol = "0";
        
        long long int n1 = stringtoint(num1);
        long long int n2 = stringtoint(num2);
        long long int prod = n1*n2;
        
        
        if(prod==0)
            return sol;
        
        string ans = "";
        
        unordered_map<int,string>umap;
        umap[0] = '0';
        umap[1]= '1';
        umap[2]= '2';
        umap[3]= '3';
        umap[4]= '4';
        umap[5]= '5';
        umap[6]= '6';
        umap[7]= '7';
        umap[8]= '8';
        umap[9]= '9';
        
            
        
            while(prod!=0){
                int digit = prod%10;
                if(umap.find(digit)!=umap.end()){
                    ans = ans + umap[digit];
                }
                prod = prod/10;    
            }
        
        reverse(ans.begin() , ans.end());
        
        return ans;
        
    }
};

`

I tried to first convert string to numbers using a map and then simpy multiply those two numbers and thn simply map that product to a string again using a map.




vendredi 28 octobre 2022

Is it still considered a generative adversarial network if the random vector z is not used?

I am using a model very similar to the pix2pix model (https://arxiv.org/pdf/1611.07004.pdf). I don't feed a random noise vector to the "generator", as it works just fine without. But I condition on some input parameters. Is it wrong to call it a generative model and the first network a generator when I don't use this vector, as usually generative models are defined by this vector? Should it be instead called adversarial training? I use dropouts in the generator network, which could be considered a source of stochasticity. And also, in my mind, it is called a generator, as it is the network that generates fakes images, as opposed to the discriminator. I would be happy to hear what you think.

It is more of a theoretical question.




Requesting random number on Chainlink Testnet and getting zeroes

I have been working on something that encapsulates chainlink random number on nfts to provide them to users, using a chainlink subscription and adding my smart contract as a comsumer. When working on testnet I am finding some times it gives me zero numbers and not a random one. This behaviour is random. Subscription is funded and smart contract added as a comsumer.

May this happen on mainnet also?

is there any warranty the request random number operation finishes succesfully, or how can I take care of it on my code?

Thanks in advance!

Subscription is funded and smart contract added as a comsumer. geting some times zero numbers and not a random one




Julia: random multinomial numbers allocation

I have to generate a vector of random number drawn from a Multinomial distribution. Since I need to do it inside a loop I would like to reduce the number of allocations. This is my code:

pop = zeros(100)
p = rand(100)
p /= sum(p)

#imagine the next line inside a for loop
@time pop = rand(Multinomial(100, p)) #test1
@time pop .= rand(Multinomial(100, p)) #test2

Why test1 is 2 allocations and test2 is 4? Is there a way of doing it with 0 allocations?

Thanks in advance.




Python random - list index out of range

I am trying to make a program that reads words from a txt file and use them to create a word quiz where you choose the synonym of a given word from 5 options - the correct answer and 4 other random words.

The text file looks something like this:

alleviate,release,slacken
clique,sect,faction,clan
denigrate,minimize,belittle,derogate
...

Here is the code:

import random

b = input('Press enter to start, enter !END to end.')

with open('vocab.txt', 'r') as file:
    v = file.readlines()
    while b != '!END':
        group = random.choice(v)
        v.remove(group)
        group = group.split(',')
        
        word = random.choice(group)
        group.remove(word)
        correct = random.choice(group).replace('\n', '')

        choices = [correct]

        for i in range(4):
            group2 = random.choice(v)
            v.remove(group2)
            group2 = group2.split(',')
            ans = random.choice(group2).replace('\n', '')
            choices.append(ans)
            
        random.shuffle(choices)
        print(word.strip() + ':\n', choices)
        b = input('Which is the synonym?(1~5)')
        if b == '!END':
            continue
        a = int(b)
        
        while a-1 != choices.index(correct):
            b = input('incorrect, try again!')
            if b == '!END':
                continue
            a = int(b)
        print('correct!')

output:

Press enter to start, enter !END to end.
trifling:
 ['altercation', 'ravenous', 'neophyte', 'clique', 'paltry']
Which is the synonym?(1~5)5
correct!
escape:
 ['evade', 'churlish', 'expert', 'satisfied', 'worried']
Which is the synonym?(1~5)1
correct!
progeny:
 ['admit', 'alleviate', 'descendant', 'denigrate', 'dull']
Which is the synonym?(1~5)3
correct!
secondary:
 ['parallel', 'introduce', 'obeying', 'sympathize', 'regulate']
Which is the synonym?(1~5)1
correct!
poverty:
 ['impoverishment', 'impel', 'examine', 'pugilist', 'pilfer']
Which is the synonym?(1~5)1
correct!

But for some reason the process only repeats five times before it throws the error:

Traceback (most recent call last):
  File "FILE_LOCATION", line 19, in <module>
    group2 = random.choice(v)
  File "FILE_LOCATION", line 378, in choice
    return seq[self._randbelow(len(seq))]
IndexError: list index out of range

I think this might be because the list of words was becoming shorter and shorter, I didn't want any repetition so I removed a word from the list if it has been used before. But the number of remaining words were enough to chose 5 words randomly from after looping the process 5 times. Is there a way to solve this? Any help is greatly appreciated! :)




jeudi 27 octobre 2022

How to get the inicial state of a generator python

I have a function that creates a generator (I introduce a number and with xorshift it gives me another) how can I write another function that gives me the inicial state of create_generator(s) when I introduce on that function the number generated on create_generator? .




Generate a random number for each row dependent on another column Pandas DataFrame

Let it be the following Dataframe of pandas in Python.

Column_1 Column_2 Number
UDKA 1234 5
MAKU 1544 5
POKA 5434 2
UJFK 9104 3

I want to generate a random number column that generates for each row a random number between 1 and its value in the Number column df['Random'] = rand(1, x.Number). Example result:

Column_1 Column_2 Number Random
UDKA 1234 5 4
MAKU 1544 5 2
POKA 5434 2 1
UJFK 9104 3 2

Obviously Random cannot be strictly greater than Number.




mercredi 26 octobre 2022

What is the difference between using the '*' operator vs the '%' operator when using the rand() function in C++?

Below I am going to show two different versions of rand() implementations.

First, the modulo operator (%):

int r = rand() % 10;

Now, I know that this statement produces a random integer between 0-9.

Second, the multiplication operator(*):

double r = rand() * 101.0 / 100.0;

This is the one I am confused about. I have seen this implementation once before but I cannot find a good explanation of what the 'rules' are here. What are the bounds/restrictions? What is the purpose of the division instead of just typing:

double r = rand() * 1.0;



How do I replace NAs in a column with random participant codes created from a function?

I have hundreds of data points in a dataframe. Some, however, do not have a value for a certain column. I have successfully created a function to create the respective input, a random participant codes:

ParticipantCodeGenerator <- function(n=1, length=2)
{
  randomString <- c(1:n)                 
  for (i in 1:n)
  {
    randomString[i] <- paste(sample(c(0:9, LETTERS),
                                    length, replace=TRUE),
                             collapse="")
  }
  return(randomString)
}

# create 5 codes with 7 symbols each
ParticipantCodeGenerator(5,7)

I managed to replace the NAs in the column but not every row has a different code. When running the function by itself, every code is different.

df$var[is.na(df$var)] <- sample(ParticipantCodeGenerator(sum(is.na(df$var)),7), replace = TRUE)



Pick one string from an Array of 4 strings in C [duplicate]

I have this kind of array with these values declared in this way :

static char forecast[4][150] = {"Sunny","Cloudly","Heavy rain", "Ice"};

now, I want to pick up randomly one string among the other and to do this I did this:

        forecast = forecast[rand()%4];

but I'm receiving this error:

error: assignment to expression with array type

What's wrong with my code?

Thanks for the answer.




CMD to append random suffix to filename of files

I have a list of files and I need to append at the end of filename for each file a random numeric suffix with 5 digits, for example:

"test.txt" rename in "test_XXXXX.txt"

I found this script that it seems for linux, but I need Windows CMD script:

for file in *.txt; do
    mv -- "$file" "$(mktemp --dry-run xxxxx.txt)"
done



mardi 25 octobre 2022

How to make strings not repeat in a random word generator

I am making a random string generator, however I am having issues making the strings not repeat when generating

Here's the Code:

import random
import string

repeat = True

pp = input("What's your text? ").lower()
pl = len(pp)

while repeat == True:
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(pl))
    print(result_str)
    if result_str == pp:
        repeat = False

How can I make the strings always different from one another

I've tried searching it up on google, but got no result I was happy with.




how to add random numbers for each element in a list and then find average?

I'm writing a program that adds a random number for each element in a list of names and then divides the result by the length of the list to find the average. I wanted to know how to add a random number for each element in the list and then subsequently store those random numbers in a separate list. thank you!

def averageAssignment(names, assignment):

    print("Enter the student names you would like to find the average for")

    classlist = []

    while True:
        names = input("")
        if str.lower(names) == 'q':
            break
        classlist.append(names)

    for name in classlist:
        print(name)

    while 'q' or 'Q' in classlist:
        Assignemnt_Number = input(("Enter the Assignment you woudl like to average: "))
        if Assignemnt_Number == 0:
            for name in classlist:
                import random
                names = classlist.index(name)
                print("The average of assignment #" + Assignemnt_Number + "is: ")
                print (random.randint(1,101)*classlist[names])
        if Assignemnt_Number == 1:
            for name in classlist:
                import random
                names = classlist.index(name)
                print("The average of assignment #" + Assignemnt_Number + "is: ")
                print (random.randint(1,101)*classlist[names])
        if Assignemnt_Number == 2:
            for name in classlist:
                import random
                names = classlist.index(name)
                print("The average of assignment #" + Assignemnt_Number + "is: ")
                print (random.randint(1,101)*classlist[names])
        if Assignemnt_Number == 3:
            for name in classlist:
                import random
                names = classlist.index(name)
                print("The average of assignment #" + Assignemnt_Number + "is: ")
                print (random.randint(1,101)*classlist[names])
        else:
            return -999

averageAssignment(classist, Assignment_Number)



Python List of Functions without Executing

I'm working on a Python project, and part of it is where it chooses a function from random via list. Unfortunately, when it's declaring the list, its executing the function. Is there a way to have a list of functions without them executing?

Here's example code:

import random
def a():
  global var
  var = 1
def b():
  global var
  var = 2
list = [a(), b()]
print(var)

Outcome:

>>> 2



Is it allowed for srand(0) to have the same effect as srand(1)?

Is it allowed for srand(0) to have the same effect as srand(1)?

C11, 7.22.2.2 The srand function (empahasis added):

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand.

However, in glibc srand(0) has the same effect as srand(1):

  /* We must make sure the seed is not 0.  Take arbitrarily 1 in this case.  */
  if (seed == 0)
    seed = 1;

Hence, the same sequence of pseudo-random numbers is returned by subsequent calls to rand, which is confusing.

Extra: We see that in MSVC srand(0) does not have the same effect as srand(1).




How to limit and randomize the web output?

Is there a way where I can limit a website generaot output and make the output more randomize since it outputs the name alphabetically. I tried to use limit and randomize i, but it doesn't seem to work

import re
from selenium import webdriver
import os
import json
import requests
import validators
from urllib.request import Request, urlopen
import numpy as np
import random 
import whois
import pandas as pd
import itertools

Combined = open("dictionaries/Combined.txt", 'r', encoding="utf-8")
Example = open("dictionaries/examples.txt", 'w', encoding="utf-8")

with open("dictionaries/Combined.txt") as i:
    Test = [line.rstrip() for line in i]

This is what's inside the Combined.txt

Combined text file

delimeters = ['','-', '.']

output_count = 100
web = 'web'
suffix = 'co.id'
for x in range(output_count):
    output = []
    for combo in itertools.combinations(Test, 2):
        out = ''
        for i, d in enumerate(delimeters):
            out = d.join(combo)
            out = delimeters[i-1].join([out, web])
            addr = '.'.join([out, suffix])
            output.append(random.choice(out))
            Example.write(addr+'\n')

with open("dictionaries/examples.txt") as f:
websamples = [line.rstrip() for line in f]

This is the output that i get.

websamples

websamples

Websamples 2

As you see at the image, the web generator outputs too many web domain generator it doesn't even show the rest of the output in Jupyter Notebook. Is there a way where the web domain generator doesn't output the web alphabetically and mix it up and limits the number of outputs that I want? for example i want to limit it to just a 100 with randomize outputs instead of outputting possible combination domain name and outputs it alphabetically

Thanks




lundi 24 octobre 2022

How to randomly generate numbers each time the program is run and store those values in a list?

I am writing a program that asks the user to input a list of students. Once the list is made the user can input a student's name that was listed before to show 4 random integers from 1 to 100 that represent 4 different marks on assignments. When I run this program, however, the mark is the same number each time. How do I run the program so that each number for the mark is different, also how can I store these values in a separate list? Thank You!

def printMark(studentMark, studentName):
    print("Enter the names of your students")
    print("Press the enter key to store another name. print q or Q when you're done.")
    names = input("Enter student name: \n")
    classlist = []

    while True:
        names = input("")
        if str.lower(names) == 'q':
            break
        classlist.append(names)

    for name in classlist:
        print(name)

    student_choice = input("Enter a students in your classlist: ")
    if student_choice not in classlist:
        print("That students is not in your class")
    elif student_choice in classlist:
        mark = list(range(1, 101))
        print("A1:" + str(studentMark) + "\nA2:" + str(studentMark) + "\nA3:" + str(studentMark) + "\nA4:" + str(studentMark))

classlist = []
import random
mark = list(range(1, 101))
printMark(random.sample(mark, k=4), classlist)



how to check if the random number exists in array

i am tring to check my random number exists in my array this is m array

int [] img ={R.drawable.im1,R.drawable.im2}

My function to update data and show it random

private void updateQuestion() {
int ranom_number = random.nextInt(img.length);
image.setImageResource(img[ranom_number]);

ton= MediaPlayer.create(BallActivity.this,Questions.audinb[ranom_number]);

ton.start();

}

this is m class, in my view i have a button i want when the random number is displaying the user if he click right the others button gone. if he clic next the all button are showing. if the last number of array is displaying the activity finish

public void onClick(View v) {
switch (v.getId()) {

    case R.id.btn1:
        if (ranom_number == img.length) {
            bravo = MediaPlayer.create(getApplicationContext(), R.raw.bravo);
            bravo.start();
            bt2.setVisibility(v.GONE);
       
        }else{
            bt1.setVisibility(v.VISIBLE);
            bt2.setVisibility(v.VISIBLE);
           
        }

        break;
    case R.id.btn2:
        if(ranom_number <= img.length-1){
            
        }
        break;

    case R.id.suiv:
      if(ranom_number <= imgnb.length-1) {
          updateQuestion();
      }else{
          Intent i = new Intent(BallActivity.this, NewActivity.class);
          BallActivity.this.finish();
          startActivity(i);
      }

}

But doesn't work thank you for helping




Python def function calling and random errors

I want to write a code that will display a warning msg that the user's data has been encrypted (ransomware msg). In the msg, the name of the victim must be randomly selected from a list of names I have generated, and the amount to be paid also the same (100 to 1000). I have written the code but it is not running. How do you call a function after it has been made? And does my random code have errors that keeps it from running?

import random
def ransom_msg (name,ransom_amount):

    #Defining list of target names
    name = ["Daily Deal Retail","Healthline Medical","True Banking","HR solutions",
                 "Crypto Me", "Total Privacy", "Pineapple State University"]

    #Assigning payment range for random selection between 100 and 1000$
    ransom_amount = random.radint(100,1000)

    victim_name = random.choice(name)
    print(victim_name)
    victim_payment = random.choice(ransom_amount)
    print(victim_payment)
    print("please",victim_name,"pay us",victim_payment,"asap! Or else, all your data is forever lost.")

ransom_msg(victim_name,victim_payment)



dimanche 23 octobre 2022

Machine learning design for a simple problem

I'm a beginner in ML, have read some theory and tried some codes, but still a newbie and not yet confortable enough to have a clear mind on how to design a ML network to solve a specific problem.

Was hoping that some of you could give me some advices on this simple problem i would try to solve with ML.

I will try to simplify the problem and give you some reproducible code :

I have several matrices that i call "models" with some weights. Here is what a model could look like : enter image description here

9 letters, each letter has a weight.

I also have thousands of matrices that i call samples. they are based on a model. here is an example of 2 samples, based on the same model given earlier : enter image description hereenter image description here

Sample1 has 19 occurences, Sample2 has 26 occurences.

What i would my ML algorithm to do : I give a sample in input, and it will interpolate the original weights (weights of the model).

An important thing : on every model, weights are not independant. They are strongly inter-correlated. A and C could be strongly correlated in all the models, whereas A and I are weakly correlated. This is why i would try to solve this with a ML algorithm, the algorithm could learn to understand the correlations between letters, and use them to interpolate better the original weights.

To train the model, i would use hundreds of model matrices, for each model there would be hundreds of samples matrices. I give in inputs one sample (and eventually the number n of occurences that could be useful), and the outputs are the 9 weights.

Here is some code to generate one sample matrix, given a model matrix :

import random 

letters = ['A','B','C','D','E','F','G','H','I']

# 2 matrix models
all_model_weights = [[0.9, 0.7, 1, 0.6, 0.3, 0, 0, 0, 0.3],
                 [0, 0.2, 0.7, 1, 1, 1, 0.7, 1, 0.5]]

#Lets generate a sample based on the first model
model_weights = dict(zip(letters, all_model_weights[0]))

n = random.randrange(20,100)
random_letter = [random.randrange(0, 9) for i in range(n)]
probs = [random.uniform(0, 1) for i in range(n)]
occurences = [0] * 9

for i in range(0,n):
    if probs[i] < model_weights[letters[random_letter[i]]]:
        occurences[random_letter[i]]+=1

# This is the sample matrix generated
occurences    

I hope i made the problem clear and you guys can give me some advices on how to design an ML algorithm to try to do this task

Thanks !




How to generate random numbers in pre-defined range which sums up to a fixed number in R/Python

I have a simple data generation question. I would request for any kind of help with the code in R or Python. I am pasting the table first.

Total Num1_betw_1_to_4 Num2_betw_1_to_3 Num3_betw_1_to_3
9 3 3 3
7 1 3 3
9 4 3 2
9 3 3 3
5 2 2 1
7 3 2 2
9 3 3 3
7 2 3 2
5
6
2
4
9

In the above table, first column values are given. Now I want to generate 3 values in column 2, 3 and 4 which sum up to value in column 1 for each row. But each of the column 2, 3 and 4 have some predefined data ranges like: column 2 value must lie between 1 and 4, column 3 value must lie between 1 and 3, and, column 4 value must lie between 1 and 3.

I have printed first 8 rows for your understanding. In real case, only "Total" column values will be given and remaining 3 columns will be blank for which values have to be generated.

Any help would be appreciated with the code.




Get random gradient background color

I am trying to get a random gradient from colorArr. I have this code:

    const colorArr = [
  "#e5e2ff",
  "#ffd3e1",
  "#c7f7dc",
  "#fdfdbd",
  "#ff8787",
];

const getRandomColor = () => {
  return colorArr[Math.floor(Math.random() * colorArr.length)];
};

and it perfectly picks random plain color.

When I use something like this:

const colorArr = [
  "linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
  "linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
  "linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
  "linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
  "linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%)",
];

It gives me white backgrounds instead of the actual gradients.




samedi 22 octobre 2022

Swift random element with probability [duplicate]

It seems like randomElement() in Swift only allows for an equally weighted selection. What would be the best (and most efficient way, as I need to repeat this very often) to select from a collection with pre-specified probabilities/weights?




|Rust| What's the most performant way of initializing a BIG and RANDOMIZED array?

*Note i'm using the 'rand' crate.

I'm new to rust and through some research and testing I was able to find two solutions to this:

#1: This on initializes an array and then populates it with random values:

type RandomArray = [usize; 900]; 

pub fn make_array() -> RandomArray {

    let mut rng = thread_rng();
    
    let mut arr: RandomArray = [0; 900];
        
    for i in 0..900 {
        //I need a range of random values!
        arr[i] = rng.gen_range(0..900)
    }

    arr
}

#2: This one initializes an array, it populates it with values from 0 to 900 and then shuffles it:

type RandomArray = [usize; 900]; 

pub fn make_shuffled_array() -> RandomArray  {
    let mut rng = thread_rng();
    
    let mut arr: RandomArray = [0; 900];
        
    for i in 0..900 {
        arr[i] = i;
    }

    arr.shuffle(&mut rng);

    arr
}

Through my testing, it seems like '#1' is slower but more consistent. But none of these actually initializes the array with the random range of numbers.

Both of these seem to be pretty fast and simple, however, I'm sure that there is an even faster way of doing this.




Selecting correct Image source based on random integer generation

I have a list of images I want to use for a project. I would like to have it select a new image each time the page reloads out of that original list of images.

Is there a more scalable way to do this without explicitly assigning the source in each switch-case?

import greeting from "../images/memoji/image1.png";
import coding from "../images/memoji/image2.png";
import lightbulb from "../images/memoji/image3.png";

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min);
}

const randomInt = getRandomIntInclusive(1, 3);
let source;

switch (randomInt) {
  case 1:
    source = greeting;
    break;
  case 2:
    source = coding;
    break;
  case 3:
    source = lightbulb;
    break;
  default:
    source = greeting;
}

 <img src={source} />

Any help would be greatly appreciated!




vendredi 21 octobre 2022

Python random.choice() fails to work in a function

I'm having trouble getting Pythons random.choice to work

Here's the working code:

import random
letters = ['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', '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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Password Generator")
user_amount_letters = int(input("How many letters would you like in your password?\n")) 
user_amount_symbols = int(input("How many symbols?\n"))
user_amount_numbers = int(input("How many numbers\n"))

characters = []

for i in range(user_amount_letters):
  characters.append(random.choice(letters))
for i in range(user_amount_numbers):
  characters.append(random.choice(numbers))
for i in range(user_amount_symbols):
  characters.append(random.choice(symbols))

random.shuffle(characters)
password = "".join(characters)
print(password)

Here's the same code within a function:

.
.
.
def randomise_user_password(letters, symbols, numbers):
  user_letters = letters
  user_symbols = symbols
  user_numbers = numbers
  characters = []
  
  for i in range(user_letters):
    characters.append(random.choice(letters))
  for i in range(user_numbers):
    characters.append(random.choice(numbers))
  for i in range(user_symbols):
    characters.append(random.choice(symbols))

  random.shuffle(characters)
  password = "".join(characters)
  return password


print(randomise_user_password(user_amount_letters, user_amount_symbols, user_amount_numbers))

The problem seems to be with random.choice, heres the error for reference:

3.8.12/lib/python3.8/password_generator.py", line 288, in choice
    i = self._randbelow(len(seq))
TypeError: object of type 'int' has no len()

I understand what the error is telling me, but have no clue how to resolve it.




Drawing samples of a dataset with specific mean and artificially increased standard deviation

I want to create a list of 10 artificial dataframes with the same mean of my original dataframe, and an artificially increased standard deviation. In each of the 10 artificial dataframes, the columns should have the same name and size of the original dataset. Each column should also have the same expected mean as the corresponding column in the original dataframe, but the expected standard deviation of each column is increased by 10%, 20% etc in each artificial dataframe relative to the standard deviation of the column in the original dataframe. So each artificial dataframe in the list will be corresponding to an x increase in the expected standard deviation of each column, where x in x = seq(10,100,10). One artificial dataframe will have the same exact columns of the original dataframe with same expected mean and size, but an expected standard deviation increased by 10%, the second sample will have an expected standard deviation of each column increased by 20% and so on.

Based on this other post Generate random numbers with fixed mean and sd this is my attempt so far:

#First define the function to draw random numbers given specific values of n, mean, sd

    rnorm2 <- function(n,mean,sd) {mean+sd*scale(rnorm(n))} 

#Create random df for replicability
df = data.frame(replicate(9,sample(0:1,100,rep=TRUE)))

names(df) = c("a", "b", "b" , "d", 
            "e" , "f", "g" ,
            "h" , "i")

#Compute and store mean, standard deviation and size of each column in my dataset:

# First, initialize  vectors

columns = c("a", "b", "b" , "d", 
            "e" , "f", "g" ,
            "h" , "i")

ncols = length(df)

column_means <- vector(mode = "numeric", length = ncols)
column_sd <- vector(mode = "numeric", length = ncols)

#Now loop through each column to obtain mean, standard deviation and increased standard deviation by x

xs = seq(10, 100, 10)

for(x in seq_along(xs)){
    for (i in seq_along(columns)){
     column_means[i] <- mean(df[[i]], na.rm = TRUE)
     column_sd[i] <- sd(df[[i]], na.rm = TRUE)
     column_sd_new[[i]][x] <- column_sd[i] + ((x/100)*column_sd[i])
 } 
}

However this gives me the following error:

Error in `*tmp*`[[i]] : subscript out of bounds

Also, I cannot find a way to apply the rnorm2 function to obtain a list of 10 artificial dataframes.

Any help would be greatly appreciated!




Trying to make a program that randomises teams acording to user input (amount of teams and names of all participants) these will then be equal in size

I need to make a program where the user inputs all students names (this is then converted into a list each name becomes an item) and y amount of teams, the program will then randomize the teams with the names of the students. Ex. The user chooses 2 teams and has 4 different students the program then spits out 2 randomized teams with 2 students in each (these cannot be the same students).

import random
import os

#clears the screen
os.system('cls')

#creates the list that later is filled with user input
list_name = []

temp_name = ""

#team_total is the user choosen amount of teams, this is then converted into integer
team_total = input("How many teams do you want?\n")
team_total = int(team_total)

#makes it so that all names written by the user are converted to individual list items
name = input("What are your students names?:\n")
for x in name:
    if x == " ":
        list_name.append(temp_name)
        temp_name = ""
        continue
    else:
        temp_name = temp_name + x
list_name.append(temp_name)

#using len to create varible that is equivilant to the amount of items in list_name
y = len(list_name)

#team_size is the amount of people in each team (amount of teams divided by amount of students)
team_size = (y / team_total)

print(f"There will be {team_size} per team!")




#r1 is the student in team_1 
r1=random.randint(0,int(y))
team_a = (list_name[r1])

#r2 is the student in team_b (this also makes it so that r2 cant be the same as r1)
r2=random.randint(0,int(y))
while r2 == r1:
    r2 = random.randint(0,(y))
    r2=random.randint(0,int(y))
team_b = (list_name[r2])

This is how far I've gotten, I am completely stuck so help would be appriciated!




How to refer to a randomised choice [duplicate]

How do I refer to a randomised choice? I want the program to print and speak the same choice it made from the list. Code so far:

speaklist = ["wassup", "hello", "how do I help?"] speak(random.choice(speaklist))

I want to add a:

print(same thing it had chosen from the list)




jeudi 20 octobre 2022

Rnadom sampling one row within each id using R

I made a data like this:

data<-data.frame(id=c(1,1,1,1,2,2,2,3,3,3,4,4,4),
                 yearmonthweek=c(2012052,2012053,2012061,2012062,2013031,2013052,2013053,2012052,
                                 2012053,2012054,2012071,2012073,2012074),
                 event=c(0,1,1,0,0,1,0,0,0,0,0,0,0),
                 a=c(11,12,13,10,11,12,15,14,13,15,19,10,20))

id stands for personal id. yearmonthweek means year, month and week. I want to clean data by the following rules. First, find id that have at least one event. In this case id=1 and 2 have events and id=3 and 4 have no events. Secondly, pick a random row from an id that has events and pick a random row from an id that has no events. So, the number of rows should be same as the number of id. My expected output looks like this:

data<-data.frame(id=c(1,2,3,4),
                 yearmonthweek=c(2012053,2013052,2012052,2012073),
                 event=c(1,1,0,0),
                 a=c(12,12,14,10))

Since I use random sampling, the values can be different as above, but there should be 4 rows like this.




MySQL: in designing a loot drop table, is it possible to specify a number of times the query repeats itself and outputs each result on the same table

as part of teaching myself SQL, I'm coding a loot drop table that I hope to use in D&D campaigns.

the simplest form of the query is:

SELECT rarity,
     CASE
        WHEN item=common THEN (SELECT item FROM common.table)
        WHEN item=uncommon THEN (SELECT item FROM unommon.table)
        ...etc
     END AS loot
 FROM rarity.table
ORDER BY RAND()*(1/weight)
LIMIT 1

the idea is that the query randomly chooses a rarity from the rarity.table based on a weighted probability. There are 10 types of rarity, each represented on the rarity.table as a single row and having a column for probabilistic weight.

If I want to randomly output 1 item (limit 1), this works great.

However, attempting to output more than 1 item at a time isn't probabilistic in that the query can only put out 1 row of each rarity. If say I want to roll 10 items (limit 10) for my players, it will just output all 10 rows, producing 1 item from each rarity, and never multiple of the higher weighted rarities.

I have tried something similar, creating a different rarity.table that was 1000 rows long, and instead of having a 'weight' column representing probabilistic weight in rows, ex. common is rows 1-20, uncommon rows 21-35...etc. Then writing the query as

ORDER BY RAND()
LIMIT x

-- (where x is the number of items I want to output)

and while this is better in some ways, it results are still limited by the number of rows for each rarity. I.E. if I set limit to 100, it again just gives me the whole table without taking probability into consideration. This is fine in that I probably won't be rolling 100 items at once, but feels incorrect that the output will always be limited to 20 common items, 15 uncommon, etc. This is also MUCH slower, as my actual code has a lot of case and sub-case statements.

So, my thought moved on to if is possible to run the query with a limit 1, but to set the query to run x number of times, and then include each result on the same table, preserving probability and not being limited by the number of rows in the table. However, I haven't figured out how to do so.

Any thoughts on how to achieve these results? Or maybe a better approach? Please let me know if I can clarify anything.

Thank you!




Choose from multinomial distribution

I have a series of values and a probability I want each those values sampled. Is there a PySpark method to sample from that distribution for each row? I know how to hard-code with a random number generator, but I want this method to be flexible for any number of assignment values and probabilities:

assignment_values = ["foo", "buzz", "boo"]
value_probabilities = [0.3, 0.3, 0.4]

Hard-coded method with random number generator:

from pyspark.sql import Row

data = [
    {"person": 1, "company": "5g"},
    {"person": 2, "company": "9s"},
    {"person": 3, "company": "1m"},
    {"person": 4, "company": "3l"},
    {"person": 5, "company": "2k"},
    {"person": 6, "company": "7c"},
    {"person": 7, "company": "3m"},
    {"person": 8, "company": "2p"},
    {"person": 9, "company": "4s"},
    {"person": 10, "company": "8y"},
]
df = spark.createDataFrame(Row(**x) for x in data)

(
    df
    .withColumn("rand", F.rand())
    .withColumn(
        "assignment", 
        F.when(F.col("rand") < F.lit(0.3), "foo")
        .when(F.col("rand") < F.lit(0.6), "buzz")
        .otherwise("boo")
    )
    .show()
)
+-------+------+-------------------+----------+
|company|person|               rand|assignment|
+-------+------+-------------------+----------+
|     5g|     1| 0.8020603266148111|       boo|
|     9s|     2| 0.1297179045352752|       foo|
|     1m|     3|0.05170251723736685|       foo|
|     3l|     4|0.07978240998283603|       foo|
|     2k|     5| 0.5931269297050258|      buzz|
|     7c|     6|0.44673560271164037|      buzz|
|     3m|     7| 0.1398027427612647|       foo|
|     2p|     8| 0.8281404801171598|       boo|
|     4s|     9|0.15568513681001817|       foo|
|     8y|    10| 0.6173220502731542|       boo|
+-------+------+-------------------+----------+



Generate Uniform Distribution of Floats in Javascript

I'm trying to generate random numbers in javascript that are evenly distributed between 2 floats. I've tried using the method from the mozilla docs to get a random number between 2 values but it appears to cluster on the upper end of the distribution. This script:

function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

function median(values) {
    if (values.length === 0) throw new Error("No inputs");

    values.sort(function (a, b) {
        return a - b;
    });

    var half = Math.floor(values.length / 2);

    if (values.length % 2)
        return values[half];

    return (values[half - 1] + values[half]) / 2.0;
}

const total = 10_000_000
let acc = []
for (i = 0; i < total; i++) {
    acc.push(getRandomArbitrary(1e-10, 1e-1))
}
console.log(median(acc))

consistently outputs a number close to .05 instead of a number in the middle of the range (5e-5). Is there any way to have the number be distributed evenly?

Thank you!

EDIT: changed script to output median instead of mean.




Reflecting a picturebox name and a resource picture using a random number

I have 4 picturebox. The names: pb1, pb2, pb3, pb4 And I have 4 resource file: cards_club, cards_diamon, cards_heart, cards_spades

The resource files contains some french card picture. One of the names is: Cards-6-Club.svg

So my problem is: how to reflect them using a random number.

I mean - here is the main part of the code:

    Random rnd = new Random();
            int color = rnd.Next(1,4+1);
            int value = rnd.Next(1,13+1);
            int pb_num = rnd.Next(1,4+1);
            textBox1.Text=color.ToString()+" "+value.ToString(); //this is just a helper data. It will never show to the user when the program is done
            switch (color) {
                case 1:             
                    if(value>=2 && value<=10){
                        pb??.Image = Projectname.cards_club.(Cards_+VALUE+_Club_svg).ToString();
    
                    }

My problem is: how can I use the previously generated number (stored as pb_num) here pb??.Image = , where the question mark is. And here Projectname.cards_club.(Cards_+value+_Club_svg).ToString(); how can I combine a previously generated random number (stored as value) with the name of the picture? So with this I can get a picture in the picturebox, where a random number (for example 5) shows the exact card. If I get 5 (value = 5) I want to show in the picturebox the Cards-5-Club.svg.

Thank you so much your answers, and please feel free to ask if anything is not exactly clear.




calculating the distance between cells in excel (randomize moving cells)

Suppose I want to compute the distance between a 3by4 cells in a square grid in excel. The distance between two cells is 1m.

Each grid cell is a number between 1 and 12 but randomized so every number can be anywhere.

Sample Table

For instance: (example in the bottom-left side of the grid):

1___2___3___4

5___6___7___8

9__10__11__12

distance between cells 1 and 5 is 1

distance between cells 1 and 6 is 2

distance between cells 1 and 12 is 5

Is it possible to have the formula to be able to calculate all of the distance between 2 cells????

Thanks for any help in advance! :)




mercredi 19 octobre 2022

how to crack a random substitution text cypher?

i was reading about caesar cipher where the characters are simply shifted by a number life this:

l=['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']

def shift(l,n):
    res = l[n:] +l[:n]
    return res

we can then switch the function to 2 steps for the rights for example to get:

l_c2= ['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b']

for encrypting the message one just has to substitute each chatacter in the original text with the shifted one. This method is very easy to break, because once you know the mirror of one characted, you know all others, even if we do not, we can try 26 shiftings to find the correct shift, its a small number of tests.

so i was thinking if i randomly reorder the elements of the list with:

import random

def randomReorder(l):
    return random.sample(l,len(l))

then i will get a list that looks like this;

l_r = ['f', 'e', 'l', 'r', 'p', 't', 'k', 'v', 'u', 'c', 'd', 'o', 'a', 'x', 'm', 'g', 'b', 'z', 'q', 's', 'h', 'j', 'i', 'n', 'w', 'y']

so if i subsitute the letters in the original text with these ones, if one know the key to one character, its hard to predict the others, because they are simpley randomly reordered, so for "hello" for example it become "vpoom". Can this method of crypting data be powerful?, or there are complicated ways that crackers use to break these cypher texts?




How to know if a customized random string function returns a string that matches a particular regex on Python 3?

Context:

One of the great features that the Binance API has is to allow its users to set a custom order id (a.k.a. newClientOrderId) for every trade they place on the Binance Futures market, this feature becomes useful if someone wants to keep a track of the trades that were placed following a particular trading strategy.

According to its Offical Docs, the parameter to be sent in the POST request to place the new order must be newClientOrderId and its value has to match this regex criteria: ^[\.A-Z\:/a-z0-9_-]{1,36}$

Problem:

I wrote a simple random string function on Python3 that returns a random string based on 2 parameters which are a string and the length of the desired string to combine, here it is:

import random, string
def randstr(s, length):

    all_chars = string.ascii_lowercase
    result = s
    for i in range(length):
        result += random.choice(all_chars)
    return(result)

Tests

randstr('test1',5)
Out[14]: 'test1uljgp'

randstr('test1',2)
Out[15]: 'test1mo'

randstr('test1',5)
Out[16]: 'test1pbgjw'

How can I know if the output of my custom randstr function matches this regex criteria: ^[\.A-Z\:/a-z0-9_-]{1,36}$? By knowing this, I will ensure that future developments related to this API will keep working nonstop.




More "random" alternative to shuf for selecting files in a directory

I put together the following Bash function (in my .bashrc) to open a "random" image from a given folder, one at a time until the user types N, after which it exits. The script works fine aside from the actual randomness of the images generated - in a quick test of 10 runs, only 4 images are unique.

Is this simply unavoidable due to the limited number of images in the directory (20), or is there an alternative to the shuf command that will yield more random results?

If it is unavoidable, what's the best way to adapt the function to avoid repeats (i.e. discard images that have already been selected)?

function generate_image() {
    while true; do
        command cd "D:\Users\Hashim\Pictures\Data" && 
        image="$(find . -type f -exec file --mime-type {} \+ | awk -F: '{if ($2 ~/image\//) print $1}' | shuf -n1)" &&
        echo "Opening $image" &&
        cygstart "$image"
        read -p "Open another random image? [Y/n]"$'\n' -n 1 -r
        echo
        if [[ $REPLY =~ ^[Nn]$ ]] 
        then exit
        fi 
    done
}



defining regions in excel sheet with python and select random cells

I have an excel sheet full of 0 and 1. I want to define three circular regions and select some random cells from each region. I showed what I mean in the attached picture. I tried different methods but still no success. I really appreciate any ideas or suggestions Thanks :-) 1




Random Number in Python from a Specific Set [duplicate]

I want to generate random ints from 4 specific numbers (1,2,5,10). I only want the output to be one of these. How?




How can i test "how English" a sentience is in python? [closed]

I was using the random module in python to create a random sentience out of the following list:

l = ['a','b','c','d','e','f','g','h','i','j','l','m',' ']

I resample this list and output a sentence using join method using the following function:

import random

def generate(l):
    res = random.sample(l,len(l))
    return ''.join(res).title()

Using this function i could print out a random sentence made up from two words, however the two words are not English at all. With increasing length of the given list and with increasing the number of the space (' ') element i can make a bigger sentence with more words.

I want pass the output of this function into another function which tests how English the given input is and will give me 100% if the input is absolutely English. I'm doing this for scientific purposes only. Can anyone help me please




Select random dictionary

Let's say I have 2 dictionaries:

pal1 = {1:"bli", 2:"bla", 3:"blub"}
pal2 = {1:"blib", 2:"blab", 3:"bleb"}

Now I want to randomly select one of the two for further usage. My thought was creating another dictionary and assign a number to each dictionary name like so:

palettes = {1:"pal1", 2:"pal2"}

now the random part:

r1 = random.randint(1,2)
used_palette = palettes[r1]

so now used_palette has the dict name I will choose for further usage as a string in it. But how do I actually access that dictionary? var = used_palette[1] won't work obviously.

Any suggestions or other ways of doing this? Thanks!




mardi 18 octobre 2022

Taking 4 random objects from an array of objects and adding some extra properties to it

I want to implement a functionality where I want to take some selected objects totally in a random manner out of an array of objects. And then, add some extra properties to those selected objects by using a spread operator { extra properties, ...selected object}

Algorithm as follows

  1. Taking data as an array of objects (say an array consisting of 150 objects)
  2. Taking 4 random objects out of it based on their Id properties, but no two ids should match (say, it should not be 1, 2, 3, 1 , or 15, 67, 43, 67, they all should be unique , like 45, 67, 89, 12, and so on).
  3. pushing these 4 random objects into the new array, so that I could add the different properites to these 4 objects as per their index positions, inside this array.
  4. finally mapping the modified 4 objects to somewhere else, keeping the rest of (150) objects as it is.

so this is my logic...

const Data = [{
id : 1,
property : 'string1'
},
id : 2,
property : 'string2'
},
id : 3,
property : 'string3'
},
id : 4,
property : 'string4'
},
id : 1,
property : 'string5'
} ... and so on , till data.length;

//

for (let i = 0; i <= 3; i++){
var rand = Data[Math.floor(Math.random() * Data.length)];
console.log(rand); //but this is also giving me 2 duplicate objects, which I need to avoid, so how should I reframe this function?

}

    let newArr : any[] = [];
    newArr.push(rand); // i want all 4 objects to get stored into this array seperated by a comma, so that I could access them as per their index values

switch(newArr) {
case 0 : {(row : 4, col : 5, ...rand)};
break;
case 1 :  {(row : 3, col : 2, ...rand)};
break;
case 2 :  {(row : 1, col : 4, ...rand)};
break;
case 3 :  {(row : 3, col : 2, ...rand)};\
break;
default : 
}



//finally I would like to map these objects into my styled component...
<MyComponent>
Data.map(...)
</MyComponent>

I feel like < I am able to make you understand the solution I want to achieve.

In shortest possible words, 
"Out of an array of objects containing 500 objects or even more, I want to select only 4 random objects, 
then add few styling properties to those 4 objects using spread operator ..., and then map these 4 objects into <MyComponent />.

All suggestions are welcome and hereby appreciated in advance: )




What is the PRNG behind C++'s rand() function? [duplicate]

I don't know if this question makes sense, but for example, python's random module has the Mersenne Twister 19937 as the PRNG behind it.

What would be the equivalent for C++'s random function?

edit: I know not to use the rand() function, I'm just running some test and was wondering if there was such a thing, or if it just is a LCG.




lundi 17 octobre 2022

How do I make this random package pyrhon project run? [closed]

I cant make my code run on VSC it just dosent want to open or run the program and on PyCharm it says 'Process finished with exit code 0'.

Here's the code:

import random

def code():

  try:
    winning_number = random.randint(0, 50)
    player_input = int(input('''
    Pick Your Number:
     '''))
  
    Win = False
    NoError = True

    if player_input < 0:
      print('Invalid Input')
      NoError = False
    
    if player_input > 50:
      print('Invalid Input')
      NoError = False

    if  player_input == winning_number:
      Win = True

    if NoError == False:
      code()
    
    if Win == True:
      print('Congratulations, You Won!')
    else:
      print('''Sorry, you have lost.
      The winning number is:''')
      print(winning_number)

  except ValueError:
    print('Invalid Input')

def input():
  def help():
    print('''Type HELP for help
    Type QUIT to quit
    Type PLAY to play''')

  def start():
    start_input = (input('Type PLAY to play or HELP for help.'))

    if start_input == 'PLAY':
      code()

    if start_input == 'HELP':
      help()

    if start_input == 'QUIT':
      quit()

input



Member variable are assigned seemingly randomly [duplicate]

In the SortingAlgorythems class i have two variables called xWin and yWin to save the Windows size of the renderer. The Constructur is supposed to set those values. In the visualize function these are used to draw a rectangle. (It looks a bit yanky cause im using it to check said values) What i expect is that a rectangle is drawn with size 1000x1000. What happens is that each time you run the code, the rectangle has the correct height but a different width each time. So something weird is happening with the xWin and yWin variables.

#include <ctime>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <vector>

#define WINDOW_WIDTH 1000
#define WINDOW_HEIGHT 1000

class SortingAlgorythems {
    public:
    int x;
    int array[50];
    
    int xWin;
    int yWin;
    
    SortingAlgorythems(int yV, int xV) {
        xWin = xV;
        yWin = yV;
    }
    
    void randomize (int numbers[]){
        int randomIndex;
        int temp;
            for(int i =0;  i < 51; i++){
            randomIndex = rand() % 50;
                temp = numbers[i];
                numbers[i] = numbers[randomIndex];
                numbers[randomIndex] = temp;
        }
    }

    void visualize(int visualizedArray[50], SDL_Renderer* renderer) {
        int width = 10;
        int arrLen = 50;
    
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 0, 255, 0, 0);

        for (int i = 0; i <= arrLen; i++){
            SDL_Rect rect;
            rect.x = 0;//2000 / arrLen * i;
            rect.y = 0;
            rect.w = xWin;//xWin / arrLen;
            rect.h = yWin;//arrLen * visualizedArray[i];
            SDL_RenderFillRect(renderer, &rect);
            SDL_RenderDrawRect(renderer, &rect);
        }
        SDL_RenderPresent(renderer);
    }
    
    void setArray (int arr[50]){
        for (int i = 0; i < 51; i++){
        array[i] = arr[i];
        }
    }
    
    void bubbleSort (int l, int virtualArray[l],SDL_Renderer *renderer){
            for (int i = 0; i < 50; i++){
                for (int j = 0; j < 50 - i; j++){
                    if (virtualArray[j] > virtualArray[j+1]){
                        int temp = virtualArray[j];
                virtualArray[j] = virtualArray[j+1];
                visualize (virtualArray, renderer);
                }
            }
        }
    }
    
    void quickSort(int *array, int low, int high, SDL_Renderer *renderer)
{
    int i = low;
    int j = high;
    int pivot = array[(i + j) / 2];
    int temp;

    while (i <= j)
    {
        while (array[i] < pivot){
            i++;}
        while (array[j] > pivot){
            j--;}
        if (i <= j)
        {
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
            i++;
            j--;
            visualize(array, renderer);
            SDL_Delay(60);
        }
    }
    
    if (j > low){
        quickSort(array, low, j, renderer);}
    if (i < high){
        quickSort(array, i, high, renderer);}
    }
};


int main() {
    SortingAlgorythems sort(WINDOW_WIDTH, WINDOW_HEIGHT);
    
    int array[50];
    for (int i = 0; i < 51; i++){
        array[i] = i;
    }
    
    SDL_Event event;
    SDL_Renderer *renderer;
    SDL_Window *window;
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_HEIGHT, 0, &window, &renderer);    
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
    SDL_RenderClear(renderer);
    
    srand((int) time(0));
    sort.randomize (array);
    sort.setArray (array);
    sort.visualize(array, renderer);
    sort.quickSort(array,0,50,renderer);
    
    
    while (1) {
        if (SDL_PollEvent(&event) && event.type == SDL_QUIT) {
            break;
        }
    }
    
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return EXIT_SUCCESS;
} ```




Edit file pairs and assign a random number [closed]

I need ideas for a personal non-profit project, I need to edit pairs of files (ex: a JPEG file and a TXT file) by assigning them the same random number.

The user can upload multiple pairs of files composed as follows:

1.jpeg - 1.txt

2.jpeg - 2.txt

The program must be able to randomize the pairs of files and assign them a random number.

Thanks so much for the answers!




dimanche 16 octobre 2022

Why does the vaule of Bird1.HP() jump to a random number after compiling my code once? (JAVA)

The goal of this code is a simple project where I want to run a while-loop to see how long it takes for my static Bird Object to either die (reach 0) or Pass a set amount (goal = 20) but each time I run the project It does it's job once; Than it wants to pick a random number for my Bird1.HP and then breaks the code forever. If you could aid me I'd greatly appreciate it.

public static int loop() {
    Random rand = new Random();
    int pcChoice;
    int shock = 1;
    int health = 2;
    int goal = 20;
    pcChoice = rand.nextInt(2) + 1 ;
    
    while (Bird1.HP < goal) {
        if (pcChoice == shock) {
            Bird1.HP = Bird1.HP - 5;
            System.out.println("Chip was Shocked");
            System.out.println("Chips Health is: " + Bird1.HP);
            
        }
        else if (pcChoice == health) {
            Bird1.HP = Bird1.HP + 2;
            System.out.println("Chip Ate some food");
            System.out.println("Chips Health is: " + Bird1.HP);
            
        }
        else {
            System.out.println("nothing is done");
        }
    }
    return Bird1.HP;



Create orderer names from a certain base

I am stuck with this problem. I have to create a list of names like A0001, A0002... A0100 with all the alphabet letters. But I tried with the method random, and with some for loops, but I can not create the list with the names ["A0001"..."A0100"] it is done in python.

import numpy as np
import datetime
import re
import os
import random as rd
import string

letters = []
num = []
crias = []
numeros = []


# Crear lista del abecedario

def alphabet():
    x = list(string.ascii_uppercase)
    letters.append(x)
    return "Se han agregado las letras"


def numbers(n):
    for i in range(n + 1):
        num.append(i)
        numeros.append([str(x) for x in num])


for l in letters:
    try:
        counter = 0
        crias.append(l[counter] + numeros)
    except:
        pass

numbers(int(input("Ingrese el numero de variables de nombre (1-n)")))
alphabet()

print(crias)



A random seed that makes tests fail the same way every time?

I've never worked with the random library and I'm a bit confused about what this fixme statement is asking me to do. Is there a seed number that specifically does this?

The code is making an ordered list ADT and this file is testing the functions within that file. We use the random library to create random numbers that will be added into, or removed from the ordered list ADT.

Please let me know if there's any other information I should give!

enter image description here

enter image description here




Is there a way to pass a random variable defined in one function to another in Python?

I want to use a variable that chooses between 2 numbers at random, that I get from one function, and use it in another function

def rayuela_extremo1():
    n2 = random.choice([0,1])
    n2 = n2
    print (n2)
    return n2

def rayuela_cuerpo3():
    n2 = rayuela_extremo1()
    if n2 == 0:
        n3 = random.choice([1,3])
        return n3
    elif n2 == 1:
        n3 = random.choice([0,2])
        return n3

The problem is that when I take the variable n2 from my first function and I try to use it in the second one, the value of n2 its choseen at random again so the value of n2 could be 1 in the function rayuela_extremo1 and 0 in rayuela_cuerpo3




How do I test random number generators? [closed]

Hi I'm a twelve grader and I'm doing a project for school in which I'm testing the random modules in different programming languages, python's random module for example.

However, I've got no idea where to even start. I've heard of TestU01 and Dieharder but I've been having a lot of trouble installing them, they just seem very complex and there is little help online. Are there any more straight forward/simple ways to so this? I'm on windows btw.

Sorry if the question is too general I'll be happy to answer to any comments to clarify the task.




How to generate random 0 and 1 with 80-20 probability in sql server

I have a Table with 10 records, I have a column (name:RandomNumber) ,that its data type is bit . now I want to insert data in to this column randomly in such a way that 80 percent of record (8 record) get 0 randomly and 20 percent (2 record) get 1.

For Example Like this:

Id RandomNumber
1 0
2 0
3 0
4 1
5 0
6 0
7 0
8 1
9 0
10 0



samedi 15 octobre 2022

Odd behaviour of sample when subsetting Seurat objects

I am seeing a peculiar behaviour from the R Seurat package, when trying to subset objects to specific sets of cells.

So, say that I generate three sets of random cell names from a Seurat object using sample

library(Seurat)

set.seed(12345)

ten_cells_id <- sample(Cells(pbmc_small), 10)
other_ten_ids <- sample(Cells(pbmc_small), 10)
and_other_ten <- sample(Cells(pbmc_small), 10)

I can now subset the object using [] and print the cell tags

Cells(pbmc_small[, ten_cells_id], pt.size=3)
Cells(pbmc_small[, other_ten_ids], pt.size=3)
Cells(pbmc_small[, and_other_ten], pt.size=3)

No surprises here; it yields three different things as expected.

> Cells(pbmc_small[, ten_cells_id], pt.size=3)
 [1] "CATGAGACACGGGA" "CGTAGCCTGTATGC" "ACTCGCACGAAAGT" "CTAGGTGATGGTTG" "TTACGTACGTTCAG" "CATGGCCTGTGCAT"
 [7] "ACAGGTACTGGTGT" "AATGTTGACAGTCA" "GATAGAGAAGGGTG" "CATTACACCAACTG"
> Cells(pbmc_small[, other_ten_ids], pt.size=3)
 [1] "GGCATATGCTTATC" "ACAGGTACTGGTGT" "CATCAGGATGCACA" "ATGCCAGAACGACT" "GAGTTGTGGTAGCT" "GGCATATGGGGAGT"
 [7] "AGAGATGATCTCGC" "GAACCTGATGAACC" "GATATAACACGCAT" "CATGAGACACGGGA"
> Cells(pbmc_small[, and_other_ten], pt.size=3)
 [1] "GGGTAACTCTAGTG" "TTTAGCTGTACTCT" "TACATCACGCTAAC" "CTAAACCTGTGCAT" "ATACCACTCTAAGC" "CATGCGCTAGTCAC"
 [7] "GATAGAGAAGGGTG" "ATTACCTGCCTTAT" "GCGCATCTTGCTCC" "ACAGGTACTGGTGT"

However, if I do

cells1 <- pbmc_small[, sample(Cells(pbmc_small), 10)]
cells2 <- pbmc_small[, sample(Cells(pbmc_small), 10)]
cells3 <- pbmc_small[, sample(Cells(pbmc_small), 10)]

Cells(cells1)
Cells(cells2)
Cells(cells3)

I get three times the same thing

> Cells(cells1)
 [1] "GATAGAGATCACGA" "GGCATATGCTTATC" "ATGCCAGAACGACT" "AGATATACCCGTAA" "TACAATGATGCTAG" "CATGAGACACGGGA"
 [7] "GCACTAGACCTTTA" "CGTAGCCTGTATGC" "TTACCATGAATCGC" "ATAAGTTGGTACGT"
> Cells(cells2)
 [1] "GATAGAGATCACGA" "GGCATATGCTTATC" "ATGCCAGAACGACT" "AGATATACCCGTAA" "TACAATGATGCTAG" "CATGAGACACGGGA"
 [7] "GCACTAGACCTTTA" "CGTAGCCTGTATGC" "TTACCATGAATCGC" "ATAAGTTGGTACGT"
> Cells(cells3)
 [1] "GATAGAGATCACGA" "GGCATATGCTTATC" "ATGCCAGAACGACT" "AGATATACCCGTAA" "TACAATGATGCTAG" "CATGAGACACGGGA"
 [7] "GCACTAGACCTTTA" "CGTAGCCTGTATGC" "TTACCATGAATCGC" "ATAAGTTGGTACGT"

The values are always the same, independently of the seed I use! I guess that R is somehow resetting the seed each time. This is not an issue with [] as:

a <- 1:100
a[sample(1:100, 10)]
a[sample(1:100, 10)]
a[sample(1:100, 10)]

Returns three different values.

The only thing I can think of is that something strange is happening because Seurat overloads []. Any ideas?




micro:bit python - random library only generates one number

I am making a hangman game on my microbit and am having trouble with the random library. I need to choose a random number between 1 and 7, and every single time I run the program it always yields the number '5'.The strangest part is when I copy the exact same code into a IDE like visual code studio and run in via the terminal instead of through the micro:bit emulator it creates, like I would expect, random numbers between 1 and 7

What I have tried

Attempt 1

from microbit import * #omitted when ran in terminal
import random

num = random.randint(1, 7)
display.show(str(num)) #changed to print(num) when ran in terminal

Attempt 2

from microbit import * #omitted when ran in terminal
import random

numbers = [1, 2, 3, 4, 5, 6, 7]
num = random.choice(numbers)
display.show(str(num)) #changed to print(num) when ran in terminal

I have been following the documentation on the random library on micropython's offical docs. Is there something I am doing wrong?




Python random gives really bad numbers

Here I have a function to choose "sun of the day" in a chat. But I observed that it works really bad. For example, in a chat of 8 members, one man hadn't been "sun of the day" for 56 days! Can this problem be solved using only python features, not connecting any external services such as random.org API?

def send_sun(id):
    try:
        members = (vk_session.method('messages.getConversationMembers', {'peer_id': 2000000000 + id})['profiles'])
        num_of_members = len(members)
        if num_of_members == 1:
            send(id, "Хотела я выбрать из этой беседы солнышко, а выбирать-то не из кого, вы здесь один...")
        else:
            sun = random.choince(members)['id']
            sun_profile = vk_session.method('users.get', {'user_ids' : sun})[0]
            if(setting_interface.check(id, "send_sun")):
                send(id, "Солнышко сегодняшнего дня - [id" + str(sun_profile['id']) + "|" + sun_profile['first_name'] + " "+ sun_profile ['last_name'] + "]")
            return
    except:
        send(id, "Что-то не то с солнышком. Пожалуйста, проверьте, что у меня есть права администратора, попробуйте выключить эту функцию и включить снова (команды могу напомнить по команде: Ира, что ты умеешь?). Если проблема не исчезнет, сообщите моему создателю, пожалуйста")

I should add that the bot is restarted each day about 1 a.m., and the suns are chosen each day about 12 pm. May be, it influences random.seed()?




vendredi 14 octobre 2022

Is there a way to check a radius around a random point in order for random points to be separate from each other

I'm currently creating a drawing project, where I use random to create random star points in the sky. I currently have the ability for two points to not be the same, but I would like to find a way to make it so they wouldn't land in a x radius circle. Is there any way in python to complete this

import turtle as t, random as r
screen=t.Screen()
screen.bgcolor("#3A3B3C")
t.speed(1)


def randomStars(y, num):
  t.penup()
  t.pensize(2)
  t.color("white")
  locations = []
  
  for x in range(num):
    repeat = True
    t.penup()
    t.seth(90)
    y_pos = starLocationY(y)
    x = starLocationX()
    while repeat == True:
      if [x,y_pos] in locations:
          y_pos = starLocationY(y)
          x = starLocationX()
      else:
        locations.append([x,y_pos])
        repeat = False
    t.goto(x,y_pos)
    t.pendown()
    t.seth(60)
    t.fd(2)
    t.fd(-2)
    t.seth(-60)
    t.fd(2)
    t.fd(-2)
    t.seth(240)
    t.fd(2)
    t.fd(-2)
    t.seth(120)
    t.fd(2)
    t.fd(-2)

randomStars(85,30)

p.s: I'm using trinket for the project, as required by the class, so the modules are limited

link to trinket:https://trinket.io/python/9776ba1b8a




Python: Random numbers from multiple lists without repetition

I've been trying to create randoms lists of 15 numbers picking only a single one from each list available (15 lists) and without repeat any number.

The code as follows did that, but it is limited to only two different lists. I'd like to get rid of this limitation.


import random
n1 = list(range(1, 5))
n2 = list(range(2, 5))
n3 =  list(range(3,6))
n4 =  list(range(5,8))
n5 =  list(range(6,10))
n6 =  list(range(8,12))
n7 =  list(range(10,13))
n8 =  list(range(11,15))
n9 =  list(range(13,17))
n10 =  list(range(14,18))
n11 =  list(range(16,20))
n12 =  list(range(18,21))
n13 =  list(range(20,23))
n14 =  list(range(22,24))
n15 =  list(range(23,25))
for  i in range(10):
  lista = random.sample(list(zip(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14,n15)),1)
  print(lista)



Random numbers generator which are not equal and Stackable in a 2Dimension Array

I want to get 6 not equal numbers into the first arrray [0][0-5] and then get 1 up and do the same with 6 not equal numbers [1][0-5] but the numbers from 0 and 1 can be equal. The code works with normal array but i tryd to make it 2d but is doesnt work. This is what i got so far. but doesnt work

for ( int a = 0; a < anzahlDerSpiele; a++){
    
    for ( int b = 0; b < 6; b++){
      zahlenRandom[a][b] = (double) (Math.random());
      zahlenRandom[a][b] = zahlenRandom[a][b] * 48+1;
      zahlenRandom[a][b] = Math.round(zahlenRandom[a][b]);
      boolean schonDrinne = false;            
      for (int j = 0; j < a; j++) {
        if (zahlenRandom[j][b] == zahlenRandom[a][b]) {
            schonDrinne = true;
            break;
        }
      }
      if (schonDrinne) {
        a--;     
      }
   }
}



generating bi-polar random sequence

Generate a bi-polar random sequence with length 300 for 2 bits/symbol transmission. in matlab

the idea is create bi polar for 2 bit symbol with legnth 300




Generate dataframe using Gauss law

I would like to generate a dataframe. In this dataframe, the column "Date" using the timestamp has to be randomly generated. I would like to generate it using the gauss-law. I know the function random.gauss() and I have this code :

from faker import Faker
import pandas as pd
import numpy as np
from datetime import timedelta

fake_parking = [
    {'Licence Plate':fake.license_plate(), 
     'Start_date':fake.date_time_between_dates(datetime_start='-2y', datetime_end='-1d'),
     'Duration':fake.time_delta(end_datetime='+30d')
    } for x in range(10000)]
df = pd.DataFrame(fake_parking)

Here, I generate random date and I would like that these dates are generated featuring the gauss-law




How to generate derivative list with frequencies

I have some C++ code that picks a random item from a list. I need it to weight that randomness so that an item at place "n" has a chance equal to x/n where "x" is the chance that item one in the list will be selected. My current code is like this:

srand(time(NULL));
string a[≈9000] = {"String#1", "String#2", . . ., "String #≈9000"};
int value = rand() % ≈9000;
cout << a[value]

Note that the number notated as "≈9000" is a precise integer obscured for confidentiality. Variable names may be changed.

How can I weight it? I've come up with an equivalent formula

List B[≈9000] = "Item 'n' of 'a' times ≈9000 ÷ n"

Though you might notice that that isn't accurate CPP notation. Do y'all have any ideas how I can implement this?




Implementing a bias in coin toss simulation

I want to simulate a biased coin being flipped 2048 times and record the results from each attempt, along with the total count of each coin. My current code is fully functional and is able to simulate a fair coin, but I'm unsure about how to implement a bias of 0.25 within my current code. What can I do to add this particular bias?

    def heads_tails(number_of_flips):
        tails_count = 0
        heads_count = 0
    for i in range(number_of_flips):
        rand = random.randint(1,2)
        if rand == 1:
            tails_count += 1
            print(tails_count, 'tails')
    else:
        heads_count += 1
        print(heads_count, 'heads')
    print('Total Heads: ', heads_count)
    print('Total Tails: ', tails_count)
heads_tails(2048)



Tensorflow distribute on GPU : how to generate independent random variable on different GPU

I try to generate independent random variable with tensorflow distributed code on different GPU. I use the split method on the random generator to generate n subgenerators for my n GPU. Then i'd like to run some code distributed with each GPU using its own subgenerator.

The code below is an example of what i'd like to do. I fails on GPU.

import numpy as np
import tensorflow as tf
import time
import sys, os
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--n_gpus', type=int, default=1)
args = parser.parse_args()
n_gpus = args.n_gpus

device_type = "GPU"
devices = tf.config.experimental.list_physical_devices(
          device_type)
devices_names = [d.name.split('e:')[1] for d in devices]

strategy = tf.distribute.MirroredStrategy( devices=devices_names[:n_gpus])


with strategy.scope():   
    optimizerControl= tf.keras.optimizers.Adam(learning_rate = 1e-3)
    modelControl = tf.keras.Sequential([tf.keras.layers.Dense(8, activation = tf.nn.relu),
                                        tf.keras.layers.Dense(1 )])
    
@tf.function
def cal( locGen, nbSimul, modelControl):
    x= locGen.normal( [nbSimul])
    return tf.reduce_sum(tf.square(modelControl(tf.expand_dims(x, axis=-1))[:,0]-tf.square(x)))

def train_step(newGen,  nbSimul, modelControl, optimizerControl):
    i = tf.distribute.get_replica_context().replica_id_in_sync_group
    print("Devic run", i)
    with tf.GradientTape() as tape:
         loss = cal( newGen[i], nbSimul, modelControl)
    gradients = tape.gradient(loss, modelControl.trainable_variables)
    optimizerControl.apply_gradients(zip(gradients, modelControl.trainable_variables))
    return loss
    

def distributed_train_step(newGen,nbSimul, modelControl, optimizerControl):
  per_replica_losses = strategy.run(train_step, args=(newGen,int(nbSimul/n_gpus), modelControl, optimizerControl,))
  return strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses,
                         axis=None)/nbSimul
                         
gen = tf.random.Generator.from_seed(1)
newGen = gen.split(n_gpus)
batchSize=10
for epoch in range(10):
    valTest = distributed_train_step(newGen,batchSize,modelControl,optimizerControl) 

If someone has any idea.. Thank you




jeudi 13 octobre 2022

How to select a random array?

I was thinking of making a bruteforce wifi app so I stumbled upon the idea of why not pick a random array which varies every pick




How to shuffle column values while keeping same dataset

I would like to to shuffle some columns from a table in Postgres database. I have 2 millions rows. I need to update all not null values by another.

I need to keep the same dataset. It's not possible to have the same value two times. It's not possible to swap data with next values because, if I do the same process with another column I will keep the same link. It's to anonymise my database. Just need to shuffle data and keep the dataset.

exemple (change firstname and lastname):

id firstname lastname
1 albert einsten
2 isaac newton
3 curie
4 alexandre Graham Bell
5 thomas Edison

shuffle firstname column:

id firstname lastname
1 isaac Graham Bell
2 albert Edison
3 einsten
4 thomas newton
5 alexandre curie

How to do this with a speedy process?




random.uniform(low, high) How to choose the low and high values?

I have generated 10 random exponential functions with some restrictions. I chose the lower and higher values of the a, b and c (see below) randomly.

a = random.uniform(0, 5) 
b = random.uniform(1, 6) 
c = random.uniform(-5, 5)

Actually I used the random uniform ranges from another example. Now I need to explain why I used this ranges, does somebody know how these ranges are dependent on the exponential functions? I only figured out that the computational cost is higher when these values are very high, but otherwise I can use any number that I want and the outputs are exactly the same..

# Restrictions
max_value = 2
min_length = 10
n_functions = 10

# Noise
mu = 0
sigma = 0.01

#%% Create exponentials
curve_list = []
curve_count = 0
id_count = 0
df = pd.DataFrame(columns=['x', 'y', 'id'])
while(1):
    df_ = pd.DataFrame(columns=['x', 'y', 'id'])
    
    a = random.uniform(0, 5) 
    b = random.uniform(1, 6) 
    c = random.uniform(-5, 5)
    
    if (max_value-c) > 0:
        len_func = np.log((max_value-c)/a)/np.log(b)
    else:
        len_func = 0

    if len_func > min_length:
        x = np.arange(0, len_func, 0.1)
        func = a*(b**x)+c
    
    
        if func[0] > 0: 
            noise = np.random.normal(mu, sigma, [len(func)])
 
            df_.x = func+noise
            df_.y = np.arange(len(func)-1, -1, -1)
            df_.id = id_count
            
            df = pd.concat([df, df_])
            
            id_count = id_count + 1
            curve_count = curve_count + 1
            if curve_count == n_functions+1:
                break



Random values are going weird in conditional statement with seed

from random import seed,random
for i in range(21):
     if i%3==0:
         seed(10)
     if i%2==0:
         random()
     else:
         random()

with above code, result is

0.5714025946899135
0.4288890546751146
0.5780913011344704
0.5714025946899135
0.4288890546751146
0.5780913011344704
0.5714025946899135
0.4288890546751146
0.5780913011344704
0.5714025946899135
0.4288890546751146
0.5780913011344704
0.5714025946899135
0.4288890546751146
0.5780913011344704
0.5714025946899135
0.4288890546751146
0.5780913011344704
0.5714025946899135
0.4288890546751146
0.5780913011344704

which,

a=0.5714025946899135
b=0.4288890546751146
c=0.5780913011344704   

is continuously repeating.

But according to seed(10), i should get only a=0.5714025946899135 with a seed applyed,

and the others should be random.

but why other value (0.4288890546751146 and 0.5780913011344704) is constant too?




Math.random create random sentences with 3 different arrays [duplicate]

  1. Make sentences from the three arrays. Firt index with first index form each array so on.. 10 sentences. (This I have figured out and managed)
  2. Use Math.random to mix the words from the arrays randomly to make new sentences, doesnt matter if a word get used two times.

Question: where do i best put the Math.random in my code?

let substantiv = ['Daddy', 'Jag', 'Hästen', 'Mamma', 'Glaset', 'Gameboy', 'Pelle','Blondie', 'Sängen', 'Bilen']
let verb = ['cyklar', 'rider', 'bakar', 'springer', 'hoppar', 'äter', 'dricker', 'går', 'läser', 'sover']
let adj = ['bra', 'dåligt', 'roligt', 'inte', 'alltid', 'på Söndag', 'aldrig', 'imorgon', 'idag', 'snabbt']

let cont = document.createElement('div')
document.body.append(cont)


for(let i=0; i<10; i++){
    const el1 = document.createElement('div')
    el1.textContent = `${substantiv[i]} `+`${verb[i]} `+`${adj[i]}`
    cont.append(el1)    
}



Linear mixed model estimator output incorrect

I want to perform a linear mixed model with a fixed effect for time plus a random intercept & slope for time per subject. I do this with the following code:

lme.rik<-lmer(formula = AI ~ Time + (1+Time|ID), data=df6, control = lmerControl(check.nobs.vs.nRE = "ignore"))

I use the control = lmerControl(check.nobs.vs.nRE = "ignore" because there is probably something wrong with my Time variable. Nonetheless, the mode gives some output where it shows as fixed effects some sort of dummy variable for the number of weeks (i.e., time variable). So first the intercept, then Time[2], Time[..], Time[7]. Only excluding Time[1]. Same applies for the random effects. Is there a way to change the Time variable so that it will only include 1 fixed and 1 random estimate for estimate for Time?

The following output is my dataset:

structure(list(ID = c("ID1", "ID1", "ID1", "ID1", "ID1", "ID1", 
"ID1", "ID10", "ID10", "ID10", "ID10", "ID10", "ID10", "ID10", 
"ID11", "ID11", "ID11", "ID11", "ID11", "ID11", "ID11", "ID12", 
"ID12", "ID12", "ID12", "ID12", "ID12", "ID12", "ID13", "ID13", 
"ID13", "ID13", "ID13", "ID13", "ID13", "ID14", "ID14", "ID14", 
"ID14", "ID14"), Time = c("1", "2", "3", "4", "5", "6", "7", 
"1", "2", "3", "4", "5", "6", "7", "1", "2", "3", "4", "5", "6", 
"7", "1", "2", "3", "4", "5", "6", "7", "1", "2", "3", "4", "5", 
"6", "7", "1", "2", "3", "4", "5"), AI = c(0.393672183448241, 
0.4876954603533, 0.411717908455957, 0.309769862660288, 0.149826889496538, 
0.2448558592586, 0.123606753324621, 0.296109333767922, 0.309960002123076, 
0.445886231347992, 0.370013553008003, 0.393414429902431, 0.318940511323733, 
0.131112361225666, 0.31961673567578, 0.227268892979164, 0.433471105477564, 
0.207184572401005, 0.144257239122978, NA, NA, 0.520204263001733, 
0.194175420670027, 0.507417309543222, 0.1934679395598, 0.0831932654836405, 
0.115391861884329, 0.141420940969022, 0.361215896677733, 0.256393554215028, 
0.429431082438377, NA, NA, NA, NA, 0.239250372076152, 0.219099984707727, 
NA, 0.289692898163938, 0.287732972580083), AI_VAR = c(0.154977788020905, 
0.237846862049217, 0.169511636143347, 0.0959573678125739, 0.0224480968162077, 
0.0599543918132674, 0.0152786294674538, 0.0876807375444826, 0.0960752029161373, 
0.198814531305715, 0.136910029409606, 0.154774913655455, 0.101723049763444, 
0.0171904512661696, 0.102154857724042, 0.0516511497159746, 0.187897199283942, 
0.0429254470409874, 0.020810151039384, NA, NA, 0.270612475245176, 
0.0377040939923819, 0.257472326024082, 0.0374298436375145, 0.00692111942183149, 
0.0133152817891321, 0.0199998825445637, 0.130476924012699, 0.0657376546430145, 
0.184411054564196, NA, NA, NA, NA, 0.0572407405385771, 0.0480048032989263, 
NA, 0.0839219752466215, 0.0827902635097706), activity = c(0, 
0.303472222222222, 0.232638888888889, 0.228472222222222, 0.348611111111111, 
0.215972222222222, 0.123611111111111, 0.357638888888889, 0.235416666666667, 
0.233333333333333, 0.2875, 0.353472222222222, 0.356944444444444, 
0.149305555555556, 0.448611111111111, 0.213888888888889, 0.248611111111111, 
0.288888888888889, 0.25625, NA, NA, 0.238888888888889, 0.263888888888889, 
0.247916666666667, 0.315277777777778, 0.298611111111111, 0.173611111111111, 
0.185416666666667, 0.45625, 0.239583333333333, 0.335416666666667, 
NA, NA, NA, NA, 0.36875, 0.251388888888889, NA, 0.266666666666667, 
0.309722222222222)), row.names = c(NA, -40L), class = c("tbl_df", 
"tbl", "data.frame"))



mercredi 12 octobre 2022

Generate Randomized Color Board

generate a random (height x width) grid such that for every coordinate (i, j), there can be no three consecutive same colors in a row or in a column.

generate(int: width, int: height, list: colors)

Example:

getvalidMatrix(3, 3, [0, 1, 2])

output:

[

[1, 2, 1],

[1, 0, 2],

[0, 1, 2],

]
import random
def getvalidMatrix(length,width,colors):
    map = dict()
    
    for i in range(len(colors)):
        map[colors[i]]=i
        
    res = [[0] * length] * width
    for i in range(length):
        for j in range(width):
            end = len(colors)
            if i - 1 >= 0 and i - 2 >= 0 and res[i-1][j] == res[i-2][j]:
                index = map[res[i-1][j]]
                colors[index] = colors[end]
                colors[end] = map[res[i-1]][j]
                end -= 1
            if j - 1 >= 0 and j - 2 >= 0 and res[i][j-1] == res[i][j-2]:
                index = map[res[i][j-1]]
                colors[index] = colors[end]
                colors[end] = map[res[i][j-1]]
                end -= 1
            next=random.randint(0,end)
            res[i][j] = colors[next]
            
    return res

if __name__ == '__main__':
    length = 3
    width = 3
    colors = [0,1,2]
    print(getvalidMatrix(length, width, colors))

I got IndexError: list index out of range with the code above. Which part of the code should I fix in order to avoid the IndexError?




Generating 10 random numbers in a range in an awk script

So I'm trying to write an awk script that generates passwords given random names inputted from a .csv file. I'm aiming to do first 3 letters of last name, number of characters in the fourth field, then a random number between 1-200 after a space. So far I've got the letters and num of characters fine, but am having a hard time getting the syntax in my for loop to work for the random numbers. Here is an example of the input:

Danette,Suche,Female,"Kingfisher, malachite"
Corny,Chitty,Male,"Seal, southern elephant"

And desired output:

 Suc21 80
 Chi23 101

For 10 rows total. My code looks like this:

BEGIN{
FS=",";OFS=","
 }
{print substr($2,0,3)length($4)

 for(i=0;i<10;i++){
 echo $(( $RANDOM % 200 ))
}}

Then I've been running it like

awk -F"," -f script.awk file.csv

But it only shows the 3 characters and length of fourth field, no random numbers. If anyone's able to point out where I'm screwing up it would be much appreciated , thanks guys




How to assign a random value to a constant so that it does not change its value

I wanted to generate a random number using Random() and make it unchanged with-in a given execution irrespective of number of calls to that method.

How can I do it?

The following explanation would make my question more clear.

I am generating a randomNumber within a range by the following method.

        private int generateARandomNumber(int min, int max) {
//        min = 101;
//        max = 10001;
        Random random = new Random();
        myRandomNum = random.nextInt(max - min) + min ;
        return myRandomNum;
    }

How can I assign the value returned to a constant like

MYID = generateARandomNumber(101,10001),

which will remain unchanged for this execution?




Weighted sampling without replacement with multiple weight vectors

This is a slightly more complicated problem than just the weighted sampling without replacement. I'd like to simulate a weighted sampling w/o replacement when there are multiple weight distributions to consider. Here's an example scenario:

Consider a simple game between two people, say 4 objects to choose from. Each person has an associated weight vector for each of the items (say corresponding to the value that they place on each object). Example of these weights, in ascending object order:

W1 = [30, 40, 20, 10] --> Probs = [30/100, 40/100, 20/100, 10/100]

W2 = [85, 10, 3, 2] --> Probs = [85/100, 10/100, 3/100, 2/100]

Assume we can normalize the weights at any point in the game so that the weight associated with the corresponding object acts as a probability. Here is a sample realization of the game to describe what I'm trying to do:

Stage 1: Player 1 selects Object 2 (randomly by his/her weight set)

Stage 2: Player 2 now selects from the following object and weight set:

Objects_avail = [1,3,4]
W2 = [85, 3, 2] --> Probs = [85/90, 3/90, 2/90]

--> Player 2 selects Object 1.

Stage 3: Player 1 now selects from the following object and weight set:

Objects_avail = [3,4]
W2 = [3, 2] --> Probs = [3/5, 2/5]

And so on until all objects have been selected. Then repeat this experiment N number of times. The final result of one iteration is just an ordering of the objects selected, e.g.

[2,1,4,3]

is the output from one run of this experiment (structure type not important, so just something that gives me the order in which objects were selected).