samedi 30 avril 2022

Finding the x,y coordinates of a alphbeta that is in image

[Alphabet "a"] 1

Using Air-Canvas, I have drawn "a", as you can see in the image. Now I want the x and y coordinates of "a" from the image.




Trying to code a rock , paper, scissors game in Python

When the input is 'r' it works perfectly but when the input is 'p' or 'r' it just adds up these two letters to the word 'scissors´ from the input phrase

import random
def play():
   user = input("'r' for rock, 'p' for paper, 's' for scissors")
   computer = random.choice(['r','p','s'])

    if user == computer:
        return 'It`s a tie!'

    # r > s, s > p, p > r
    if is_win(user, computer):
        return 'You won!'

    return 'You lost'

def is_win(player, opponent):
    #return true if player wins
    #r>s, s>p, p>r
    if(player == 'r' and opponnent == 's') or (player == 's' and opponnent == 'p') or \
        (player == 'p' and opponnent == 'r'):
        return True



Generate a random number 10% of the time, otherwise generate 0

In Python I would like to create a distribution that picks a random number between 5 and 10, 10% of the time. The other 90% of the time, I would like it to pick zero.

I would like to sample 10,000 numbers.




Plotting frequency of random walk points (python)

First off; essentially identical question to this one, however the answer in the other thread just uses an imported library (numpy's histogram2d) to do the trick; this is a homework assignment where I have to do it without.

I'm creating 2d points using a random walk generator, and am to plot the frequency of points visited in a 1000-step random walk using matplotlib's imshow function. I.e. I generate a sequence of random walk points, for example

[(0, 0), (1, 0), (1, -1), (0, -1), (0, 0), (-1, 0), (-1, 1), (-1, 0), (0, 0), (1, 0)]

And then plot the frequency of each point on a "heat map" using imshow. In this case, for instance, the point (0,0) appears 3 times, so I should have value 3 tied to point (0,0), and so on (see sample picture; should be the end result)Random walk points frequency with imshow

My issue is that while I can get the frequency of each point, I have problems tying them to a grid. My idea was to create an M x N matrix of zeroes (with M being #different x-coordinates, and N being #different y-coordinates) and then filling it with frequencies. But since the points sometimes have negative values, I can't think of a 1:1 translation.

Some of the code I have thus far; now I need to fill out the mat matrix with frequencies of each x- and y-coordinate appearance. (Again; I know histogram functions from e.g. Numpy can do this, but I must implement my own method)

The random_walk() function I made. This works as intended;

from random import randint
def random_walk():
    x=y=0
    shift=[(-1,0),(1,0),(0,-1),(0,1)]
    while True:
        yield (x,y)
        randy=randint(0,3)
        x,y = x+shift[randy][0], y+shift[randy][1]

My work for plotting thus far - am stuck.

from itertools import islice
import matplotlib.pyplot as plt
from collections import Counter

points=[*islice(random_walk(),10)] #generate sequence with my random_walk() generator
count=Counter(points)
freq=list(count.values())          #This gives the occurences of each point (x,y)

xs,ys=zip(*points)                 #Lists of all the x- and y-coordinates
left,right = min(xs), max(xs)      #Total x-range
bottom,top = min(ys), max(ys)      #Total y-range
extent=(left,right,bottom,top)     #Extent of the final plot

#Matrix of zeroes; this should be changed to encode frequency of hitting each point [x,y]
mat=[[0]*(right-left+1)]*(top-bottom+1)

#### Do stuff here

#Final plotting
plt.imshow(mat,cmap='gray',extent=extent); plt.colorbar(); plt.show()



Random choice out of 1D array with 2-dimensional probability in python

I would like to choose randomly out of a list with 3 elements (HGA, CGA, SGA), but I have 3 lists with the probabilities in it.

My probabilities are given by (the lists have the same length):

Probs = { 'HGA':prob['HGA'], 'CGA':prob['CGA'], 'SGA':prob['SGA'] }

and now I want to create another list which should look something like this without using a loop:

particles = ['HGA', 'CGA', 'CGA', 'CGA', 'SGA' ...]

The length of 'particles' should obviously have the same length as the probabilities.




Randomly output an IF else command java

I used to enjoy programming with Java at school and am now trying to get back into programming with the help of a book. Now I am currently failing at a task to code a word guessing game. The user is asked questions in random order. If a question is answered incorrectly, it should be put back into the queue randomly. I started with if else, but quickly realised that I couldn't manage the random questioning. Can you give me a hint on how to code this?




vendredi 29 avril 2022

How to model random neurons in Jax?

Suppose I want to model random neurons in Jax, for instance, adding to each neuron's bias a small random value each time the neuron is used. How can I best do it?

The issue here is that random numbers in Jax are generated from a seed, in a stateless way. Therefore, I can think of two approaches, neither of which seems particularly appealing; my question is whether there is a better approach (and indeed, what is the recommended approach for such a thing).

The first approach would be to generate a matrix of random numbers as big as the neuron layer, and send to each neuron both their inputs, and these random numbers. This might work, but the problem I am imagining is that generating a big random matrix from a seed is a sequential, not parallel, operation (I assume?), and so by generating a big random matrix each time I do a forward step through the neurons, I forego much of the benefits of parallelization (because neuron computation can be done in parallel, but generating the random matrix each time might not be parallelizable).

The second approach would be to endow each neuron with their own seed, which would function as a random-state at the neuron level. Each time the neuron computes the output, it also splits the random seeds and output the split seed, which it will get as input the next time. That is, for a layer with N neurons, I would have an array of size N of random seeds, and I would vmap on the N (seeds, inputs) a function that computes as output the N outputs, and N new split seeds.

Is any of these two approaches the recommended one? Or is there a different approach that is better?




C#: state of a static member variable `Random` inside an instantiable object class

Consider the following code example. I have a class Randomiser that has a static member variable public static Random rand. I can instantiate the Randomiser object as many times as I want, while I can access the member variable public static Random rand at any scope. At each time I call rand.Next(), I expect that the variable rand changes its status. In particular, I can call rand.Next() in multiple threads as in the example code.

Because the Random rand is a static variable, any call of rand.Next() method will refer to the same memory stack, and it is supposed to use the same random states. This does not have any issue if rand.Next() is called in a single process as they will be executed in a sequential order and the random state is not mixed up. However, when multiple threads are invoking the rand.Next() method, and if they happen to call it exactly at the same time, if this is somehow possible, it is unclear how the random state should change; rand.Next() is not only a read-access but it also changes the random state.

It appears to be a very theoretical and even weird question, but is there anyone who can imagine what is going to happen to the Random rand's random state when multiple threads are invoking at identical CPU clock?

    class Randomiser
    {
        public static Random rand = new 
                      Random(DateTime.UtcNow.GetHashCode());
                  
        public Randomiser(in string _name_) { this.name = _name_; }

        public string name = "";
        public int    num = -1;
    }
    class Program
    {   
        static void Main()
        {
            Randomiser[] Guys = 
            { 
                new Randomiser("Charlie"), 
                new Randomiser("Fox")
            };

            double for_ = 0.1;
            bool run = true;
            var t0 = DateTime.UtcNow;   
            
            new Thread(()=>
            { 
                while(run) 
                { 
                    Guys[0].num = Randomiser.rand.Next(); 
                    Console.WriteLine($"{Guys[0].name}: {Guys[0].num}");
                } 

            }).Start();

            new Thread(()=>
            { 
                while(run) 
                { 
                    Guys[1].num = Randomiser.rand.Next(); 
                    Console.WriteLine($"{Guys[1].name}: {Guys[1].num}");
                } 

            }).Start();
            
            while (true)
            {
                if ((DateTime.UtcNow - t0).TotalSeconds > for_)
                {
                    run = false;
                    break;
                }
            }
        }

        Console.ReadLine();
        return;
    }



Randomly shuffling all files in a directory?

I am trying to find a solution with bash to shuffle a directory full of 2x3000 files of the type:

.mp4

.json (stores the metadata).

The .mp4 and .json are connected to each other so, the problem is:

I can shuffle both individually, but this loses the indirect connection in the process. So I would need a code, which stores the random value, into a variable and assign it to my .mp4+json package each.

The folder contains

  • 1.mp4
  • 2.mp4
  • 3.mp4
  • 3000.mp4

and also

  • 1.json
  • 2.json
  • 3.json
  • 3000.json

I´ve looked everywhere on the platform but didnt find a satisfying solution and its beyond my bash skills!

This was my base code:

for i in *; do mv "$i" $RANDOM-"$i"; done

paste <(printf "%s\n" *) <(printf "%s\n" * | shuf) |
  while IFS=$'\t' read -r from to; do mv -- "$from" "$to.mp4"; done

for f in *.mp4; do mv -- "$f" "${f%.mp4}"; done 

Thank you!

cheers Michael Schuller




How to make boundaries with numpy at mathplot lib

I am trying to generate random numbers from -0.005 to 0.005 and want to give position from 0 to box size

enter code here
import Numpy as np

 a= []
 velocities= np.random.random(a)
 [a=> -0.005]
 [a<  0.005]
 print(velocities)

 box_size=1 
 b=[0,box size]
 positions = np.random.random(b)



Keep k random strings from input file of unknown length in C

Problem

I want to get input from a file of unknown length, separating the input to strings at a defined delimiter and saving some of them. After reading the entire file, I want to have in an array of strings, k random strings from the input that was read. Each string must have the same probability of beeing kept in the final array.

Important Part

I don't want to read the file, save all the strings somewhere and then pick k of them at random. I want while reading each string, update the array with k strings (if needed depending on probabilities) and move on to the next string forgeting the previous string. In other words memory usage for how many strings are saved thought-out executing the program must be on the low side.


Code Structure

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

#define DELIMITER ':'

FILE* getInputSource(char* source);

char** pickStrings(char* source, int k);
void printStrings(char** strings, int k);
void freeStrings(char** strings, int k);

// your extra declerations (start)

// your extra declerations (end)

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

    int toKeep = 5;
    char** strings = pickStrings("input.txt",toKeep);
    printStrings(strings,toKeep);
    freeStrings(strings,toKeep);

    return 0;
}

char** pickStrings(char* source, int k) {
    FILE* input = getInputSource(source);

    char** strings = (char**) calloc(k,sizeof(char*));
    // your implementation here

    return strings;
}

// your extra implementations (start)

// your extra implementations (end)

FILE* getInputSource(char* source) {
    FILE* input = fopen(source,"r");
    if( !input ) {
        printf("Unable to open input file.\n");
        exit(0);
    }
    return input;
}

void printStrings(char** strings, int k) {
    for( int i = 0; i<k; i++ ) 
        printf("%d: %s\n", i, strings[i]);
}

void freeStrings(char** strings, int k) {
    for( int i = 0; i < k; i++)
        free(strings[i]);
    free(strings);
}

Contents of input.txt for testing:

ok:maybe:not:something:yes:off:blue:donut:A:B:C:D:E:F:G:

Expected Output

A random sequence of the strings in file separated by the delimiter. One sequence would look something like the following:

0: not
1: A
2: maybe
3: yes
4: blue

Assumptions

  • Each string length is unknown. You can either define a fixed length like 256 chars per string or dynamically allocate as many as needed for each string.
  • Strings can contain anything except the defined delimiter which is used to seperate them.
  • Delimiter is used at the last string as well.
  • If input.txt contains less than k strings, you can fill first slots of the array (at random order) and leave the rest of the array empty.

Preferences

  • Comments point out where to write your code. The rest of the code should stay as it is and should only change after discussion in comments.
  • Your answer should contain only the code you added. But if you believe posting it all is better then go ahead, no problem.

Note for this Question

This question was inspired from many other similar questions that exist here and there in stack overflow, but they do not meet my needs even if they partly give me an answer. This is an attempt to generalize this kind of question so that it can cover different possible variations of the question, and make it easier to search for. I tried to edit the existing questions (without changing the author's original question) so they can be more searchable and more meaningful, but many of the authors are inactive for a long period of time or their question was too specific and changing it would ruin it or there is not an accepted/completed answer.


Extras

Some of the other questions mentioned Reservoir Sampling either on comments or answers. It is something that can be considered on how to achieve equal probability of keeping for each string, but if there is anything else glad to hear it as well.





python random_sample to generate values

I am currently using random_sample to generate weightage allocation for 3 stocks where each row values add up to 1 and I rounded them to 2dp.

weightage=[]
n = 0
while n < 100000:
    weights = np.random.random_sample(3)
    weights  = weights/ np.sum(weights)
    weights = (np.around(weights,2))
    if any(i < 0.05 for i in weights):
        continue
    n += 1
    weightage.append(weights)
    
weightage

However there are some weightage allocations that exceed 1 as shown below. Possibily due to rounding up the values.

 array([0.74, 0.15, 0.12])

Is there any way to have my allocations in 2 decimal places without exceeding 1?




jeudi 28 avril 2022

Compare 2 random effects models

I have 2 random effects models which differs from each other based on one variable.

M1= plm(formula = Productiviteit ~ Kapitaalintensiteit + Bedrijfsgrootte + 
    Percentage_Hoogopgeleid + Gem_leeftijd_TMT + Aantal_leden_TMT + 
    J_2012 + J_2013 + J_2014 + J_2015 + J_2016 + J_2017 + J_2018 + 
    A + B + C + D + E + F + G + H + I + J + K + L + N + O + P + 
    Q + R + S, data = df, model = "random", index = c("Naam", 
    "Index_jaar"))

M2= plm(formula = Productiviteit ~ Kapitaalintensiteit + Bedrijfsgrootte + 
    Percentage_Hoogopgeleid + Std_leeftijd_TMT + Gem_leeftijd_TMT + 
    Aantal_leden_TMT + J_2012 + J_2013 + J_2014 + J_2015 + J_2016 + 
    J_2017 + J_2018 + A + B + C + D + E + F + G + H + I + J + 
    K + L + N + O + P + Q + R + S, data = df, model = "random", 
    index = c("Naam", "Index_jaar"))

in Model 2 I only added Std_leeftijd_TMT.

Now I want to compare these 2 models and see if model 2 has a significant better fit. I want to test this with lrtest(test1,test2), but i get following error: Error in UseMethod("logLik") : no applicable method for 'logLik' applied to an object of class "c('plm', 'panelmodel')"

Are there any other possibilities for comparing two random effects models?




mercredi 27 avril 2022

randomisation in python within a group for A/B test

I have a python list of size 67 with three unique values with following distribution

A - 20 occurrences randomly spread in the list
B - 36 occurrences randomly spread in the list
C - 11 occurrences randomly spread in the list

I want to perform random selection at 10% within each group to perform a special treatment on the values selected from randomisation.

Based on the occurrences in the list shown above, 2 treatments for group A, 3 treatments for B and 1 treatment for C should have been done.

Selection for treatment need not be done exactly on the 10th occurrence of a value but the ratio of treatment to values should be maintained at approximately 10%.

Right now, I have this code

import random 
if random.random() <= 0.1
   do something

Using this code, doesn't get me above requirement treatments at a group level. Instead it randomly picks treatments across all groups. I want to trim the selection of random samples at a group level. How do I do that?

Also, if this list were dynamic and keeps getting bigger and bigger and populated with more values of A,B,C at run time albeit with different distributions, how can I still maintain the randomisation at a group (unique value in the list) level.




ValueError: empty range for randrange() (100000, 10000, -90000)

The first number is bigger than the second...

x = random.randint(100000, 9999)
ValueError: empty range for randrange() (100000, 10000, -90000)



mardi 26 avril 2022

How to filter with a non non-model field?

I have a model with one of its fields is a random generated string as the following

from django.utils.crypto import get_random_string
class Competition(models.Model):
    name = models.CharField(verbose_name="challenge name", max_length=256)
    start_date = models.DateTimeField(verbose_name="start date")
    end_date = models.DateTimeField(verbose_name="end date")
    code = get_random_string(length=6)
    owner = models.ForeignKey(User, related_name="owner", on_delete=models.CASCADE)
    def __str__(self):
        return self.name

I am trying to have an endpoint like thathttp://192.168.1.2:8000/competitions/?code=${some_string} to access from react frontend. so in order to do so I have some filters

from django_filters import rest_framework as filters

class CompetitionFilter(filters.FilterSet):
    class Meta:
        model = competition
        fields = {
            "name": ["exact", "icontains"],
            "code": ["exact"],
            "start_date": ["exact", "lte", "gte"],
            "end_date": ["exact", "lte", "gte"],
            "owner": ["exact"],
        }

but I have an error saying TypeError: 'Meta.fields' must not contain non-model field names: code So how can I achieve it?




lundi 25 avril 2022

Unity Mathf.PerlinNoise built-in function how it works?

My question is very simple. Im using this function to create a texture and it work good but just for curiosity i want to know how it really works. Can anyone explain how this function works and return the float values that we pass in? I noticed that when we pass for example very close float values in it sometimes the number we get back is very different and when number are very different sometimes we have close values so looks like it elaborate and give back numbers in a random way but not really because everytime if we repeat the operation with the same previous numbers the result is always the same.. Thanks a lot!




I need to choose random function in C++ project

I am making a C++ game-project and in the game I need to choose random bonuses (functions).

(below is the example of the code)

void triple_balls(){
    /* CODE */
}

void longer_paddle(){
    /* CODE */
}

void shorter_paddle(){
    /* CODE */
}

void bonus_activator(){
    //Here I must choose one of the 3 functions above
    //FIXME
}



Optimizing sampling with varying sample sizes in jax

I'm looking for ideas on how to optimize the sampling of a varying number of guests for a varying number of hosts. Let me clarify what I'm trying to do.

Given a number of hosts "n_hosts", each one with a different number of possible guests, "n_possible_guests_per_host" I want to sample a number "n_guests" from the list of possible guests. "n_guests" is also different for each host. I'm finding it challenging due to jax's fixed input/output requirements. Here is a code sample of the brute-force approach, it took about 2 seconds on my laptop.

import numpy as np
import jax.numpy as jnp
from jax import random

n_possible_guests = 50_000
n_hosts = 1000
n_possible_guests_per_host = [np.random.randint(low=0, high=100) for i in range(n_hosts-1)]

n_possible_guests_per_host += [max(0,n_possible_guests - sum(n_possible_guests_per_host))]
guest_idx = np.arange(n_possible_guests) 
host_idx = np.arange(n_hosts)

n_to_sample = [np.random.randint(low=0, high=n) if n!= 0 else 0 for n in n_possible_guests_per_host]


def brute_force(guest_idx, host_idx, n_possible_guests_per_host, n_to_sample):
    first_guest_idx = np.cumsum(n_possible_guests_per_host) - n_possible_guests_per_host
    key = random.PRNGKey(0)
    chosen_guests = jnp.zeros(sum(n_to_sample))
    n_chosen = 0
    for (host_id, n_sample) in zip(host_idx, n_to_sample):
        possible_guests_in_host = guest_idx[
            first_guest_idx[host_id]:first_guest_idx[host_id] + n_possible_guests_per_host[host_id]
        ]
        chosen_idx = random.choice(
            key, possible_guests_in_host, shape=(n_sample,)
        )
        chosen_guests = chosen_guests.at[
            n_chosen:n_chosen+len(chosen_idx)
        ].set(chosen_idx)
        n_chosen += len(chosen_idx)    
    return chosen_guests

brute_force(guest_idx, host_idx, n_possible_guests_per_host, n_to_sample)



How to avoid generating too black colors at random in JavaScript?

Whenever I click a button on the browser it displays a random color along with its rgb(r,g,b) code. I made 3 variables r, g, and b which produce random numbers from 0 to 255 using the basic logic of Math.floor(Math.random()*256);

My problem is that sometimes the random colors generated are too dark and the rgb code displayed along with them is black in color.

I tried writing a logic that whenever r+g+b < 300, toggle the h1 element's class which has a property of color white.

const h1 = document.querySelector('h1');
const button = document.querySelector("button");
h1.classList.add('h1');
//if (r+g+b < 500)
button.addEventListener('click', () => {
    changeColor();
});

const changeColor = (() => {
    const newColor = randomColor();
    document.body.style.backgroundColor = newColor;
    h1.innerText = newColor;
    }
);

const randomColor = (() => {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r}, ${g}, ${b})`;
})



dimanche 24 avril 2022

Batch Rename Folders Randomly

I need some help to create a batch file that renames all folders in a specific directory to random names/numbers like "!random!" do. I know how to do with files but not with folders. Any suggestions?

Example of my idea




Defining a function that will interpret whether or not an answer has been input and give out a random string from a list

So here is the code in question. The error I get when I run the code is File "D:\obj\windows-release\37amd64_Release\msi_python\zip_amd64\random.py", line 259, in choice

TypeError: object of type 'type' has no len()

import random
import tkinter as tk
from tkinter import messagebox

root=tk.Tk()
root.title("Tragic 8 Ball")

def get_answer(entry, list):
    if (entry.get() != ""):
        messagebox.showwarning("Please ask question.")
    else: (entry.get() == "")
    messagebox.showwarning("Your answer", random.choice(list))
    
entry=tk.Entry(width=40)
entry.focus_set()
entry.grid()

get_answer(entry, list)

tk.Label(root, text="Ask a question:").grid(row=0)
tk.Button(root, text="Answer my question", command=get_answer(entry, list).grid(row=3), columd=0, sticky=tk.W, pady=4)

list=["It is certain.",
      "Outlook good.",
      "You may rely on it",
      "Ask again later.",
      "Concentrate and ask again.",
      "Reply hazy, try again.",
      "My reply is no.",
      "My sources say no."]

root.mainloop()
'''



samedi 23 avril 2022

How can I randomize a list with a certain degree of noise?

If I have a list, say, [1,2,3,4,5], how can I introduce a certain amount of noise to this list?

For example, a high degree of noise would be something completely random. An adversarial noise would be [5,4,3,2,1] A low degree of noise would be [2,1,3,4,5]

Thoughts?




Python Twitter - Tweepy to post unique content using data from txt or JSON files

I have developed a very basic Twitter bot using Python & Tweepy. It is successfully posting a tweet to twitter and I can modify the text in this line of code: response = client.create_tweet( text='Testing' ) to make different tweets

The full code I am using for this is:

import tweepy

client = tweepy.Client(consumer_key="XXXXX",
                    consumer_secret="XXXXX",
                    access_token="XXXXX",
                    access_token_secret="XXXXX")
# Create Tweet

response = client.create_tweet(
    text='Testing'
)
print(f"https://twitter.com/user/status/{response.data['id']}")

What I am trying to figure out is how I can code a Bot to randomly read data stored in file(s) and put it altogether to formulate a readable sentence or paragraph a little bit like how a mailmerge works. Here is an example, there are 3 files or 3 values:

Value1
Check out this, View this, See this
Value 2
product, item, piece
Value 3
on our online shop, on our store, on our website

If the bot was able to read and select data at random it could pick any of the data from the files or values in any order, put them together and it would make sense as a sentence or a paragraph

After researching I see that using text or JSON files might be a possibility. I followed a JSON tutorial and recreated an example that looks like this for text and images:

[
  {
    "text": "hi",
    "image": "/image1.jpg"
  },
  {
    "text": "hello",
    "image": "/image2.jpg"
  }
]

I think I have worked out how to read the JSON file with this code:

import json
with open(r"C:\Users\Administrator\Desktop\Python\test.json") as f:
    info = json.load(f)

randomChoice = random.randrange(len(info))
print (info[randomChoice])

The thing I am really struggling with is the best way to achieve this and how then to create the code that will post the tweet formulated with the random data it has selected

This is what I have so far as I attempt to combine Tweepy and the abilty to read in data from the JSON file but I can't get it to work as I don't know how to post the data it has read in to Twitter:

import tweepy
import random 
import json
with open(r"C:\Users\Administrator\Desktop\Python\test.json") as f:
    info = json.load(f)

client = tweepy.Client(consumer_key="XXXXX",
                    consumer_secret="XXXXX",
                    access_token="XXXXX",
                    access_token_secret="XXXXX")
# Create Tweet

randomChoice = random.randrange(len(info))
print (info[randomChoice])

response = client.create_tweet(
    text='NOT SURE HOW TO CODE THIS PART SO TWEEPY POSTS RANDOMLY SELECTED DATA'
print(f"https://twitter.com/user/status/{response.data['id']}")

I am brand new to Python and Tweepy so have only a very small understanding but would really appreciate any help on it




Pop into another list with list comprehension

I wrote this section of code to be used in a bigger code to simulate a zombie apocalypse. I have a class to represent healthy people and then zombies. The block of code here was written to make a list of healthy people and one zombie and assign them random positions, but I see now that I didn't include the combos list into the list comprehension loop to allow for random assignment. Is there a way I can include that in? I did not include my classes library only so this question wasn't obnoxiously long. Thanks!

combos = list(product(range(sysvals.A), range(sysvals.B)))
r.shuffle(combos)
temp = combos.pop()
row = temp[0]
col = temp[1]
populace = [zc.Human(i,row,col,'Alive') if i != 0 else zc.Zombie(i,row,col,'Alive') for i in 
range(sysvals.N)]



Print out a random string between certain characters from a text file

Hi I have a text file named "fortunes" with a lot of data containing many differens quotes. Each quote is separated with the character "%". What I am struggling to do is to make a code that will print out a random quote out the whole text file, meaning that the random print should contain a string that is between the separator(%). Does anyone have any suggestions of an easy fix to this? As you can see I have started on something, but I am not sure where to include to random. function in all of this. Thank you so much in advance

enter image description here




Having trouble creating a function that returns a vector of 5 random numbers from a pool of 20 numbers in R

Total noob here guys, I was asked to do this for a class I am taking and I'm having some trouble as my sample always pulls the same 5 numbers. I'd appreciate any tips that can steer me in the right direction. So far I have this inside the function brackets:

num <-c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)

rn = sample(num, 5, replace=T)

This will produce a vector of 5 integers, however, it is always the same 5. How can I fix this so it is always 5 different random numbers?

Thanks




vendredi 22 avril 2022

Why do some compression algorithms not change the size of the archive file, and some do?

This is a list of file sizes that were compressed. They are all originally from \dev\urandom, thus pretty pseudo random. The yellow file is the original size of any and all of them.

The pink files are the compressed sizes, and there are 30 in total. The blue files are the compressed sizes of the pink files once they have been randomly shuffled using Python's shuffle command. The compression algorithms were LZMA, BZ2 and ZLIB respectively from Python's inbuilt modules.

You can see that there are three general blocks of output sizes. Two blocks have a size difference of exactly zero, whilst the other block has randomnesque file size differences as I'd expect due to arbitrary runs and correlations that appear when files as randomly shuffled. BZ2 files have changed by up to 930 bytes. I find it mystifying that LZMA and ZLIB algorithms produced exactly the same filesizes. It's as if there is some code inside specifically looking for no effect.

Q: Why do the BZ2 files significantly change size, whilst shuffling LZMA and ZLIB files has no effect on their compressibility.

sheet




Genrate pseudo-random number python

I have the implementation of tls/ssl-prf (https://datatracker.ietf.org/doc/rfc5246/) (pseudo random function) and I want to create a pseudo random number from this implementation (https://github.com/python-tls/tls/blob/master/tls/_common/prf.py)




How to generate a list of lists using probabilities for each element in Python

I want to verify if i am doing things right, the question is : The function random, without arguments, assumed to be imported, returns a random real of the interval [0,1[. Write a function init(N) taking as input a strictly positive integer, and returning a grid (NxN) (in the form of a list of lists), each cell containing a cell with a value of True with a probability of 1/3. For example:

init(4) => [[True, False, False, False],[False, False, True, True],[False,False,False,False],[True,False, True, False]]

from random import random
def init(N):
    return [ [True if random()<1/3 else False  for j in range(N)] for i in range (N) ]
print(init(4))

I am confused is the probablity 1/3 means that the generated random value is less than 1/3 or it is referring to a weighted probability such the one used in random.choice




Math.random with percentage rate

I want to set a spawn rate for each var in the array. So far I can only make it random.Below are the codes for a scratch card game. Alternatively, I would make each result unique so a function can be execute when the array is empty. So far my splice function not working. Would need some help please.

var promoCode = '';
var bg1 = 'https://cdn.pixabay.com/photo/2020/06/01/22/23/eye-5248678__340.jpg';
var bg2 = 'http://farm5.static.flickr.com/4017/4717107886_dcc1270a65_b.jpg';
var bg3 = 'http://images6.fanpop.com/image/photos/41500000/adorable-puppies-cute-puppies-41538743-590-393.jpg';

var bgArray = [bg1, bg2, bg3];
selectBG = bgArray.splice(Math.floor(Math.random() * bgArray.length), 1)[0];
console.log(selectBG);

if (selectBG === bg1) {
  promoCode = 'SCRATCH400';
  
} else if (selectBG === bg2) {
  promoCode = 'SCRATCH500';
  
} else if (selectBG === bg3) {
  promoCode = 'SCRATCH600';
  
} else if (bgArray.length === 0) {
  alert("No more voucher");
}

$('#promo').wScratchPad({
  // the size of the eraser
  size: 70,
  // the randomized scratch image   
  bg: selectBG,
  // give real-time updates
  realtime: true,
  // The overlay image
  fg: 'https://cdn.glitch.com/2c225b7b-6134-4f2b-9842-1d5d060d9cd4%2Foverlay.png',
  // The cursor (coin) image
  'cursor': 'url("https://cdn.glitch.com/2c225b7b-6134-4f2b-9842-1d5d060d9cd4%2Fcoin1.png") 30 30, default',

  scratchMove: function(e, percent) {
    console.log(percent);
    console.log(promoCode);

    // Show the plain-text promo code and call-to-action when the scratch area is 50% scratched
    if ((percent > 50) && (promoCode != '')) {
      $('.promo-container').show();
      $('body').removeClass('not-selectable');
      $('.promo-code').html('Your code is: ' + promoCode);
      
    }
  }
});
html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

.scratchpad {
  width: 450px;
  height: 445px;
  border: solid 10px #FFFFFF;
  margin: 0 auto;
}

body {
  background: #efefef;
}

.scratch-container {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  width: 100%;
}

@media only screen and (max-width: 480px) {
  .scratchpad {
    width: 400px;
    height: 396px;
  }
  .scratch-container {
    width: 400px !important;
  }
}

/* Custom, iPhone Retina */

@media only screen and (max-width: 320px) {
  .scratchpad {
    width: 290px;
    height: 287px;
  }
  .scratch-container {
    width: 290px !important;
  }
}

.promo-container {
  background: #FFF;
  border-radius: 5px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  width: 450px;
  padding: 20px;
  margin: 0 auto;
  text-align: center;
  font-family: 'Open Sans', Arial, Sans-serif;
  color: #333;
  font-size: 16px;
  margin-top: 20px;
}

.btn {
  background: #56CFD2;
  color: #FFF;
  padding: 10px 25px;
  display: inline-block;
  margin-top: 15px;
  text-decoration: none;
  font-weight: 600;
  text-transform: uppercase;
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radiuss: 3px;
}
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700italic,700" rel="stylesheet" type="text/css">
    <title>Scratch Card</title>
  </head>

  <body>
    <div class="scratch-container">
      <div id="promo" class="scratchpad"></div>
    </div>
    <div class="promo-container" style="display:none;">
      <div class="promo-code"></div>
      <a href="www.we-know-fun.com" target="_blank" class="btn">Return</a>
    </div>

    <script type="text/javascript">
      (function(a) {
        'use strict';

        function b(c, d) {
          this.$el = a(c), this.options = d, this.init = !1, this.enabled = !0, this._generate()
        }
        b.prototype = {
          _generate: function() {
            return a.support.canvas ? void(this.canvas = document.createElement('canvas'), this.ctx = this.canvas.getContext('2d'), 'static' === this.$el.css('position') && this.$el.css('position', 'relative'), this.$img = a('<img src=""/>').attr('crossOrigin', '').css({
              position: 'absolute',
              width: '100%',
              height: '100%'
            }), this.$scratchpad = a(this.canvas).css({
              position: 'absolute',
              width: '100%',
              height: '100%'
            }), this.$scratchpad.bindMobileEvents(), this.$scratchpad.mousedown(a.proxy(function(c) {
              return !this.enabled || void(this.canvasOffset = a(this.canvas).offset(), this.scratch = !0, this._scratchFunc(c, 'Down'))
            }, this)).mousemove(a.proxy(function(c) {
              this.scratch && this._scratchFunc(c, 'Move')
            }, this)).mouseup(a.proxy(function(c) {
              this.scratch && (this.scratch = !1, this._scratchFunc(c, 'Up'))
            }, this)), this._setOptions(), this.$el.append(this.$img).append(this.$scratchpad), this.init = !0, this.reset()) : (this.$el.append('Canvas is not supported in this browser.'), !0)
          },
          reset: function() {
            var c = this,
              d = Math.ceil(this.$el.innerWidth()),
              f = Math.ceil(this.$el.innerHeight()),
              g = window.devicePixelRatio || 1;
            this.pixels = d * f, this.$scratchpad.attr('width', d).attr('height', f), this.canvas.setAttribute('width', d * g), this.canvas.setAttribute('height', f * g), this.ctx.scale(g, g), this.pixels = d * g * f * g, this.$img.hide(), this.options.bg && ('#' === this.options.bg.charAt(0) ? this.$el.css('backgroundColor', this.options.bg) : (this.$el.css('backgroundColor', ''), this.$img.attr('src', this.options.bg))), this.options.fg && ('#' === this.options.fg.charAt(0) ? (this.ctx.fillStyle = this.options.fg, this.ctx.beginPath(), this.ctx.rect(0, 0, d, f), this.ctx.fill(), this.$img.show()) : a(new Image).attr('crossOrigin', '').attr('src', this.options.fg).load(function() {
              c.ctx.drawImage(this, 0, 0, d, f), c.$img.show()
            }))
          },
          clear: function() {
            this.ctx.clearRect(0, 0, Math.ceil(this.$el.innerWidth()), Math.ceil(this.$el.innerHeight()))
          },
          enable: function(c) {
            this.enabled = !(!0 !== c)
          },
          destroy: function() {
            this.$el.children().remove(), a.removeData(this.$el, 'wScratchPad')
          },
          _setOptions: function() {
            var c, d;
            for (c in this.options) this.options[c] = this.$el.attr('data-' + c) || this.options[c], d = 'set' + c.charAt(0).toUpperCase() + c.substring(1), this[d] && this[d](this.options[c])
          },
          setBg: function() {
            this.init && this.reset()
          },
          setFg: function() {
            this.setBg()
          },
          setCursor: function(c) {
            this.$el.css('cursor', c)
          },
          _scratchFunc: function(c, d) {
            c.pageX = Math.floor(c.pageX - this.canvasOffset.left), c.pageY = Math.floor(c.pageY - this.canvasOffset.top), this['_scratch' + d](c), (this.options.realtime || 'Up' === d) && this.options['scratch' + d] && this.options['scratch' + d].apply(this, [c, this._scratchPercent()])
          },
          _scratchPercent: function() {
            for (var c = 0, d = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height), f = 0, g = d.data.length; f < g; f += 4) 0 === d.data[f] && 0 === d.data[f + 1] && 0 === d.data[f + 2] && 0 === d.data[f + 3] && c++;
            return 100 * (c / this.pixels)
          },
          _scratchDown: function(c) {
            this.ctx.globalCompositeOperation = 'destination-out', this.ctx.lineJoin = 'round', this.ctx.lineCap = 'round', this.ctx.strokeStyle = this.options.color, this.ctx.lineWidth = this.options.size, this.ctx.beginPath(), this.ctx.arc(c.pageX, c.pageY, this.options.size / 2, 0, 2 * Math.PI, !0), this.ctx.closePath(), this.ctx.fill(), this.ctx.beginPath(), this.ctx.moveTo(c.pageX, c.pageY)
          },
          _scratchMove: function(c) {
            this.ctx.lineTo(c.pageX, c.pageY), this.ctx.stroke()
          },
          _scratchUp: function() {
            this.ctx.closePath()
          }
        }, a.support.canvas = document.createElement('canvas').getContext, a.fn.wScratchPad = function(c, d) {
          if ('string' == typeof c) {
            var g, h = [],
              j = (void 0 === d ? 'get' : 'set') + c.charAt(0).toUpperCase() + c.substring(1),
              k = function() {
                g.options[c] && (g.options[c] = d), g[j] && g[j].apply(g, [d])
              },
              l = function() {
                return g[j] ? g[j].apply(g, [d]) : g.options[c] ? g.options[c] : void 0
              },
              m = function() {
                g = a.data(this, 'wScratchPad'), g && (g[c] ? g[c].apply(g, [d]) : void 0 === d ? h.push(l()) : k())
              };
            return this.each(m), h.length ? 1 === h.length ? h[0] : h : this
          }
          return c = a.extend({}, a.fn.wScratchPad.defaults, c), this.each(function() {
            var n = a.data(this, 'wScratchPad');
            return n || (n = new b(this, a.extend(!0, {}, c)), a.data(this, 'wScratchPad', n)), n
          })
        }, a.fn.wScratchPad.defaults = {
          size: 5,
          bg: '#cacaca',
          fg: '#6699ff',
          realtime: !0,
          scratchDown: null,
          scratchUp: null,
          scratchMove: null,
          cursor: 'crosshair'
        }, a.fn.bindMobileEvents = function() {
          a(this).on('touchstart touchmove touchend touchcancel', function(c) {
            var d = c.changedTouches || c.originalEvent.targetTouches,
              f = d[0],
              g = '';
            switch (c.type) {
              case 'touchstart':
                g = 'mousedown';
                break;
              case 'touchmove':
                g = 'mousemove', c.preventDefault();
                break;
              case 'touchend':
                g = 'mouseup';
                break;
              default:
                return;
            }
            var h = document.createEvent('MouseEvent');
            h.initMouseEvent(g, !0, !0, window, 1, f.screenX, f.screenY, f.clientX, f.clientY, !1, !1, !1, !1, 0, null), f.target.dispatchEvent(h)
          })
        }
      })(jQuery);

    </script>
  </body>

</html>



Counting how many times value meets 2 times in a row in list

I need to count how many times 'Eagle' appears 2 times in a row in random generated list. In case ['Eagle', 'Eagle', 'Eagle', 'Eagle'] it should count 2, not 3

import random
def HeadsOrTails(amo):
amo1 = []
Coin = ['Eagle', 'Tails']
for i in range(amo):
    amo1.append(random.choice(Coin))
return amo1

count = 0

for i in range(len(HeadsOrTails(30))):
    if HeadsOrTails(30)[i] == 'Eagle':
        if HeadsOrTails(30)[i] == HeadsOrTails(30)[i+1]:
            count += 1
    else:
        continue

print(HeadsOrTails(30))
print(f' Eagle repeats {count} times in the list')

For some reason it calculates amount of values wrongly




jeudi 21 avril 2022

How to generate generate four choices for users without two choices being the same?

I'm using an API to create an anime quiz. I'm also using Math.random() to create four choices for the user to click on. But I'm facing two problems. Firstly when the user is presented with the first set of 4 choices, there's a possibility that two are identical. I'd like all four choices to be distinct from each other. Secondly regardless of the user getting the right answer or not I'd like another set of four distinct questions to be generated. I tried to come up with something but it quickly turned into spaghetti code.

const animeApi = "https://anime-facts-rest-api.herokuapp.com/api/v1";
const intro = document.querySelector(".intro");
const anime_picture = document.querySelector(".anime_picture img");
const anime = document.querySelector(".anime");
const questions = Array.from(document.querySelector(".question").children)
const question1 = document.querySelector(".question1");
const question2 = document.querySelector(".question2");
const question3 = document.querySelector(".question3");
const question4 = document.querySelector(".question4");
const question5 = document.querySelector(".question5");
const randomNum1 = Math.floor((Math.random()* 13));
const randomNum2 = Math.floor((Math.random()* 13));
const randomNum3 = Math.floor((Math.random()* 13));
const randomNum4 = Math.floor((Math.random()* 13));
let [counter, score] = [0,0]
let data;

fetch(animeApi)
.then(res => res.json())
.then(response => {
  // response is an object but we need the array in property data
  console.log(response)
  data = response.data;
  console.log(data.length)
  for (let {anime_img} of data) {
    console.log(anime_img)
  }
  // alternative
  //data.forEach(item => console.log(item));
});

intro.addEventListener("click", () => {
  intro.classList.add("hide");
  anime.classList.remove("hide");
  anime.classList.add("show")
  quiz()
});

function quiz() {
  anime_picture.src = data[counter].anime_img;

  question1.innerHTML = data[randomNum1].anime_name;
  question2.innerHTML = data[randomNum2].anime_name;
  question3.innerHTML = data[randomNum3].anime_name;
  question4.innerHTML = data[randomNum4].anime_name;
}


for(var i = 0; i < questions.length; i++) {
  questions[i].addEventListener("click", userAnswer)
}

function userAnswer(e) {
  let target = e.target.innerHTML
  if(target === data[counter].anime_name) {
    console.log("correct");
    score++
  } else {
    console.log("incorrect");
  }
  update();
}

function update () {
  if(counter < data.length) {
    counter++;
    quiz();
  }
}
body {
  position: relative;
  display: flex;
  justify-content: center;
  align-content: center;
}

.intro {
  height: 300px;
  width: 300px;
  border: 1px blue solid;
  position: absolute;
  left: 25%;
  text-align: center;
}

.hide {
  visibility: hidden;
}

.show {
  visibility: visible;
}

.anime {
  height: 800px;
  width: 800px;
  border: 1px red solid;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.anime_picture {
  height: 400px;
  width: 400px;
  position: absolute;
}

.question {
  height: 100px;
  width: 100%;
  border: 1px blue solid;
  bottom: 0;
  position: absolute;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.question > div {
  height: 80px;
  width: auto;
  border: 1px black solid;
  background-color: #ddd;
}

img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

header {
  width: 100%;
  height: 100px;
  border: 1px black solid;
  position: absolute;
  top: 0;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="index.css">
    <title>anime page</title>

  </head>
  <body>
    <div class="intro">
      welcome to the anime website
    </div>
    <div class="anime hide">
      <div class="anime_picture">
        <img src="" alt="">

      </div>
      <div class="question">
        <div class="question1"></div>
        <div class="question2"></div>
        <div class="question3"></div>
        <div class="question4"></div>
      </div>
      <header>anime Quiz</header>

    </div>

  </body>
  <script src="index.js" type="text/javascript"></script>
</html>



Discord.js - If i have an array where a random option is chosen, is there a way to send a gif matching this option?

So, i have the following code:

var jobs = [
    'lawyer',
    'hitman',
    'gardener',
    'cashier'
]
var thumbnails = [
    "https://c.tenor.com/DP615vqUzeAAAAAC/ace-attorney-phoenix-wright.gif",
    "https://i.ytimg.com/vi/6nzyIHz5bb0/hqdefault.jpg",
    "https://c.tenor.com/vzSw7IoYMdYAAAAM/lifehack-hose.gif",
    "https://c.tenor.com/eYUWlNN0Fw4AAAAM/thisisalecx-cashier.gif"
]
let job = jobs[Math.floor(Math.random() * jobs.length)]

This chooses a random option out of the "jobs" array. And i have the list with the embed thumbnails i want to use. Now if it sends a random job from the array, is there a way to send one of the gifs that is matching this job? Any help is appreciated!




Rearrange all the characters from the input string randomly [duplicate]

import random

word = input("Type in a word: ")

What I want to do is to rearrange all the characters from the input randomly and then print out the result or store it in a string. How do I accomplish this?




Generate random binary variable conditionally in R

I would like to add an extra column, z based on the following conditions:

  • if x == "A", generate a binary variable assuming the prob of success (=1) is 0.5
  • if x == "C" & y == "N", generate a binary variable assuming the prob of success is 0.25.
# Sample data
df <- tibble(
x = ("A", "C", "C", "B", "C", "A", "A"),
y = ("Y", "N", "Y", "N", "N", "N", "Y")) 

Currently, my approach uses filter, then set.seed and rbinom, and finally rbind. But I am looking for a more elegant solution that doesn't involve subseting and re-joining the data.




mercredi 20 avril 2022

Python: simulate tossing a die until all values have appeared at least once

I want to sample from a list until all elements have appeared at least once. We can use tossing a die as an example. A die has six sides: 1 through 6. I keep tossing it until I see all six values at least once, then I stop. Here is my function.

import numpy as np

def sample_until_all(all_values):
    sampled_vals = np.empty(0)
    while True:
        cur_val = np.random.choice(all_values, 1)
        sampled_vals = np.append(sampled_vals, cur_val[0])        
        if set(all_values) == set(sampled_vals):
            return(len(sampled_vals))
        
sample_until_all(range(6))

cur_val is the value from the current toss. I keep all sampled values in sampled_vals using np.append, and I check if it contains all possible values after each toss using set(all_values) == set(sampled_vals). It works but not efficiently (I believe). Any ideas how to make it faster? Thanks.

I just use this as a toy example. The actual list I need is much larger than just 6 values.




Replace numbers in YAML/XML File with random numbers (Python)

I have a file with much numbers. I want that every number will be replaced with a random number. So that the Python script changes the XML file. How to code this in Python?

!h 1: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 2: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 3: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 4: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 5: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 6: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}



How do you display the number that has the lowest and highest amount of duplicates in a list w/o using built in functions?

I've created a program that displays 1000 (1k) random integers with duplicates its rng range is from 1 - 1000, with that I want to know how many times a specific number has been generated with the highest and lowest frequency and display it. Ex: 51 is the number that has been generated 50 times, which is the highest (Note: I cannot use any built in function for logic building purposes)

{
        List<int> numPool = new List<int>();
        Random rnd = new Random();

        string uinput = "";

        int storage = 0;

        while (true)
        {
            // generating number pool
            for (int i = 0; i < 1000; i++)
                numPool.Add(i + 1);

            // generating 100 numbers
            Console.WriteLine("Generating 100 numbers (1-1001) with duplicates...");
            int d = 1;
            while (numPool.Count > 0)
            {
                int temp = 0;

                temp = rnd.Next(0, numPool.Count); // this generates a random index between 0 and however long the list is
                Console.Write("{0}\t", temp);
                numPool.RemoveAt(temp); // removes the index
                if (d % 10 == 0)
                Console.WriteLine();

                d++;
            }

            Console.WriteLine("Highest amount of duplicate numbers: "); // this part should show the number with the highest amount of duplicates
            Console.WriteLine("Number of times it was duplicated: "); // this part will show how many times it was duplicated
            Console.WriteLine("\nLeast amount of Duplicate numbers: "); // this part should show the number with the least amount of duplicates
            Console.WriteLine("Number of times it was duplicated: "); // this part will show how many times it was duplicated

            Console.Write("\nWhat number would you like to show the frequency?: ");
            uinput = Console.ReadLine();
            storage = int.Parse(uinput);

            // from this part it should show the number of times the duplicate number has appeared according to the user input

            //Console.WriteLine("The number " + storage + " has appeared " + insert the amount of times it has appeared + " times.");


            Console.ReadKey();
            Console.Clear();
        }
    }



Visualize random numbers generate

how can I visualize the random number which is generated in python without the help of any internal or external library of python?

This is the code I am trying with

def random(x,y):
  from time import time
  r = time() - float(str(time()).split('.')[0])
  random = r*(x-y)+y
  return random
random(23,53)



mardi 19 avril 2022

Is there an efficient way to use random number deduplication?

I making a program that uses random numbers. I wrote the code as below, but the number of loops was higher than I expected Is there an efficient way to use random number deduplication?

#include <iostream>
#include <cstdlib>
#include <ctime>
#define MAX 1000
int main(void)
{
    int c[MAX] = {};
    int i, j = 0;
    srand((unsigned int)time(NULL));
    for (i = 0; i < MAX; i++)
    {
        c[i] = rand() % 10000;
        for (j = 0; j < i; j++)
        {
            if (c[i] == c[j])
            {
                i--;
                break;
            }
        }
    }
    for (i = 0; i < MAX; i++)
    {
        std::cout << c[i] << std::endl;
    }
    return 0;
}



How to give an array more chance based on its length?

I had these two data1 and data2 arrays which were going to get updated based on the different types of data they received (two different languages here).

After receiving enough data, I wanted my code to use the data inside one of the arrays randomly, but the chance of one getting selected had to change based on the amount of data they had stored. The more the data, the higher the probability.




Generate two random divisible numbers two between 1-10 using C language

How can I generate two divisible numbers using c? I know how to generate two random number between 1 to 10 but I don't know how to generate two DIVISIBLE NUMBERS (between 1 to 10)...




RNG that imports data

I am trying to code an RNG that imports data as (min:max,how many times a random number is generated) and then generates a random number based on the specifications. Could someone please help me?




lundi 18 avril 2022

Duplicate Records with RAND() function

I have a python program to extract data from Microsoft SQL Server and load them to another table in the same database. Using this extraction program, I am trying to do the following.

  1. Get the input arguments from an excel file
  2. Fetch one random record from the database for each row present in the excel
  3. Load the output to another table

Using the RAND() function, I'm seeing duplicate records being retrieved most of the time even though the combination has a sufficient number of entries in the database. I tried a couple of other approaches like NEWID() and calculating the total number of rows and then retrieving a random row using numpy. But these queries take hours to execute even for a single combination and does not seem feasible.

Note: The table is huge (~7 million records) and left joins are used to retrieve the required data.

Are there any other methods to fix this issue?




how to randomize a matrix keeping the rows fixed in python

I'm trying to randomize all the rows of my DataFrame but with no success. What I want to do is from this matrix

A= [ 1 2 3
     4 5 6 
     7 8 9 ]

to this

A_random=[ 4 5 6 
           7 8 9 
           1 2 3 ]

I've tried with np. random.shuffle but it doesn't work.

I'm working in Google Colaboratory environment.




Error: invalid BigNumber value (argument="value", value=undefined, code=INVALID_ARGUMENT, version=bignumber/5.6.0)

I was following Patrick Video "https://www.youtube.com/watch?v=9oERTH9Bkw0&t=5700s" where I encounter this error at 2:31:20 and the code in that video is almost same as mine, still is not working

//probably error is here below

        await transactionResponse.wait(1);
        log(`Now let's finish the mint...`);
        let finish_tx = await randomSVG.finishMInt(tokenId, { gasLimit: 2000000, gasPrice: 20000000000 });
        await finish_tx.wait(1);
        log(`You can view the tokenURI here ${await randomSVG.tokenURI(0)}`);

    }
};

module.exports.tags = ["all", "rsvg"];



Unbalanced random binary sequence generator

I’m trying to write a function to generate binary sequence which is unbalanced. Unbalanced means P(0) = 1/2 + bias, P(1) = 1/2 - bias, P(0) + P(1) = 1. bias can be negative

auto genenator(int length, int bias) {
       std::vector<int> result;
       ......
       return result;
}

For example, res = generator(20, 0.1).

res may = {0,0,1,0,1,0,0,1,0,1,1,0,1,1,0,0,0,1,0,0}, there are twelve 0 and eight 1, so P(0) = 12 / 20 = 0.6, P(1) = 0.4.

I only found this https://www.geeksforgeeks.org/generate-a-random-binary-string-of-length-n/




dimanche 17 avril 2022

Microprocessor Generation of Summed Sine Waves with Random LF Modulation

I would like to program a micro to do the following:

  1. Generate five audio frequency sine waves at different frequencies and amplitudes
  2. Sum the above sine waves into one signal
  3. Generate a pseudo-random low frequency waveform at a set amplitude
  4. Multiply the two signals above so that the summation of the five signals randomly changes in amplitude and frequency.

What would be the recommended approach to this in terms of chosen micro (prefer PIC if possible) and design of the code? I am asking for general advice on how to get started with this project.




samedi 16 avril 2022

Im trying to get an if statement to reply to a random number in python and display and print a message

I'm trying to get an if statement to recognize a randomly generated number but I don't know what is going wrong, it just ends the program as soon as i hit start and does not print anything, so far I have this.

import random

random.randint(1,3)

if random.randint == ('1'):
    print('message')

I have tried changing the random.randint(1,3) into a variable by making it "a == ('random.randint(1,3)" but that did not work either. Does anyone know whats going wrong with it?

P.S: Sorry if the question is asked badly, I don't use this site much.




Weird behaviour of random with double click on batch script

Alright, hello everyone

I feel very confused right now, I would like to have some insight on what is going on. I am trying to write a batch script that would launch a random web browser when I double-click the icon. Easy enough.

Here's my first attempt:

set /a var=%random% %%7 + 1

if %var%==1 (start "brave" "C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe")
if %var%==2 (start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
if %var%==3 (start "edge" "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
if %var%==4 (start "firefox" "C:\Program Files\Mozilla Firefox\firefox.exe")
if %var%==5 (start "libreWolf" "C:\Program Files\LibreWolf\librewolf.exe")
if %var%==6 (start "opera" "C:\Program Files\Opera\opera.exe")
if %var%==7 (start "vivaldi" "C:\Program Files\Vivaldi\Application\vivaldi.exe")

This works perfectly, nothing to complain about.

Now, I wanted to make my random picking a little bit cleaner, so I did this:

set /a minval=1
set /a maxval=7
set /a var=%RANDOM% * (%maxval% - %minval% + 1) / 32768 + %minval%

And here is where the strange stuff is happening.

When I double-click the icon, it keeps opening the same browser on and on (meaning, and I verified it, that var always has the same value). But when I start the script from the cmd, it works perfectly, as before.

What is going on?! How is the first attempt okay but not the second one? And why does it work from the command line and not from mouse input?

P.S.: Sorry for my english, please be nice :)




Random coordinate generator for VERILOG

I have been trying to implement a random number generator for one variable between 10 and 1390 and for another variable between 110 and 890. I have been unable to get anywahere with my current ideas and would appreciate any help or input to correct me. My current code can be seen below however I am not confident in it at all, the values are not exact to those described above as I have modified it to experiment.

reg [10:0] randx;
reg [10:0] randy;


reg [9:0] i = 600;
reg [9:0] j = 400;

always @ (posedge clk)
begin
if (i<820)
i <= i + 40;
else 
i<= 600;
end

always @ (posedge clk)
begin
if (j>200)
j <= j - 40;
else 
j <= 400;
end

always @ (i,j)
begin
randx <= i;
randy <= j;
end



Assigns the value of each td in the table with a random unique number with Javascript

I have a function that can generate a unique random number, the result is stored in an array. my question. How can each number be entered in rows td when there is a click event.

function random(max, min) {
        arr = [];
        for (i = 0; i < max; i++) {
            x = Math.floor(Math.random() * max) + min;
            if (arr.includes(x) == true) {
                i = i - 1;
            } else {
                if (x > max == false) {
                    arr.push(x);
                }
            }
        }
        return arr;

    }

For example, I have a table that has 3 rows

<button class="btn btn-md btn-danger" id="shuffle">Loop</button>
    <table class="table">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">First</th>
                <th scope="col">Last</th>
                <th scope="col">Number</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th scope="row">1</th>
                <td>Mark</td>
                <td>Otto</td>
                <td name="random"></td>
            </tr>
            <tr>
                <th scope="row">2</th>
                <td>Jacob</td>
                <td>Thornton</td>
                <td name="random"></td>
            </tr>
            <tr>
                <th scope="row">3</th>
                <td>Larry</td>
                <td>the Bird</td>
                <td name="random"></td>
            </tr>
        </tbody>
    </table>

And trigger code

$('#shuffle').on('click', function(e) {
        var td = $('td[name="random"]');
        td.each((key, value) => {
            value.value = random(3, 1); // this's just example
        });

    });



python random_sample minimum value

I am currently using random_sample to generate weightage allocation for 3 stocks where each row values add up to 1.

for portfolio in range (10):
    weights = np.random.random_sample(3)
    weights  = weights/ np.sum(weights)
    print (weights)

[0.39055438 0.44055996 0.16888567]
[0.22401792 0.26961926 0.50636282]
[0.67856154 0.21523207 0.10620639]
[0.33449127 0.36491387 0.30059486]
[0.55274192 0.23291811 0.21433997]
[0.20980909 0.38639029 0.40380063]
[0.24600751 0.199761   0.5542315 ]
[0.50743661 0.26633377 0.22622962]
[0.1154567  0.36803903 0.51650427]
[0.29092731 0.34675988 0.36231281]

I am able to do it but is there any way to ensure that the minimum weightage allocation is greater than 0.05? Meaning that the minimum weight allocation could only be something like [0.05 0.9 0.05]




vendredi 15 avril 2022

How to stop function from going back in without calling quit()

so I've been trying to make a little number-guessing game where the user guesses a number and the computer basically says whether that's higher/lower than the correct number or if it's correct.Basically, everything works correctly up until the user enters an invalid input(anything that isn't an integer). Then it still works correctly but when you eventually guess the right number it tells you that you won and the number of tries that you took būt it also returns a Typerror which says that strings and ints cannot be compared. This is weird because it doesn't do it as soon as you enter the invalid input but rather at the end when you get it correct. Additionally, it shouldn't even be doing that as there is no part in the else statement that tells it to go back into the function.

from random import randint
def game(rand_num = randint(1,10),trys=1): #generates random number and sets trys to 1
    user_guess = input('enter your guess 1-10:') #user guess
    try: # try except to check for validity of input,restarts functions with preserved random number and # of tries
        user_guess = int(user_guess)
    except:
        print('please try again and enter a valid input')
        game(rand_num=rand_num,trys=trys)
    
        # if and elif to check if the number was higher or lower,if it was then it will restart the game function with preserved random number
        # and trys increased by 1
    if user_guess < rand_num: 
        print('your guess was lower than the magic number so try again')
        game(rand_num=rand_num,trys=trys+1)
    elif user_guess > rand_num:
        print('your guess was higher than the magic number so try again')
        game(rand_num=rand_num,trys=trys+1)
    else: #if both don't work then you must have won and it tells you that as well as how many trys you took``
        print('hurray you won!!!!!')
        print(f'you took {trys} trys')
    
game()

example of user interactions in the console

Also when I tried to use a breakpoint to determine the issue, again everything seemed fine until after it told the that they won,it mysteriously just went back into the function and started doing stuff with the previously invalid input set as the user_guess variable which is presumably why the Type error happened.

the first place where the function "goes" to after telling the user they won

the first place where the function "goes" to after telling the user they won

the 2nd place where it "goes"

the 2nd place where it "goes"

It does that for a few more times but yeah it just basically cycles through if elif and try except for some reason

however, I found out that you can use a quit() at the end of the else statement that tells the user they won to solve this but as far as I know that just suppresses the function from doing anything and exits it so it isn't really a solution.




Python: Word Guessing Game - trouble with WHILE Loop

import random
import time

word_list = ['snack','snore','place']

guess = ''
word = ''

while True:
    guess = input("Guess a word: ")
    word = random.choice(word_list)

    if guess == word: 
        time.sleep(.9)
        print (f"Congrats, you won! the word was {word}")
        time.sleep(.5)
        print() 

        play = (input("If you want to play again, hit ENTER otherwise type n: ")) 
        if play != '':
            break
        else:
            print("Let's play again")

I am working on a 'word' guessing game. User has to guess one of the three words to win. I want the loop to continue for as long as the user wants to play. But it seems that once they play once, the random word choice isn't working. Here is an example of my output:

Guess a word: snack
Guess a word: snore
Guess a word: place
Guess a word: snack
Guess a word: place
Congrats, you won! the word was place

You can see that the word was place, but I had already guessed that word, it wasn't until I guessed it again that it worked.

Any help on this is greatly appreciated. I am brand new at Python and just trying to figure out the foundation of this software to the best of my ability.




Create a two-dimensional symmetric matrix from Python [duplicate]

I coded a two-dimensional symmetric matrix with Python. However, the result value does not keep coming out of the situation I want. I think my code can make a symmetric matrix perfectly, but I don't know why there are other results. Below is the Python code.

import random

inputN = random.randrange(1, 10)
inputArr= [[0]*inputN]*inputN

for i in range(0, inputN):
    for j in range(i, inputN):
        if i != j:
            Rvalue = random.randrange(0, 11)
            inputArr[i][j] = Rvalue 
            inputArr[j][i] = Rvalue 

print(inputN)
for i in range(0, inputN):
    for j in range(0, inputN):
        print(inputArr[i][j], end=" ")
    print("")

Below is the output value.

6
8 3 6 2 8 8 
8 3 6 2 8 8
8 3 6 2 8 8
8 3 6 2 8 8
8 3 6 2 8 8
8 3 6 2 8 8



jeudi 14 avril 2022

How can I build a page that generates random images from a gallery each time the page is refreshed?

Pardon my complete n00bness as I try to figure this out:

I run a daily cartoon/drawing website. I'm not a developer so I'm using the site builder called Pixpa which has worked well for my straightforward needs: daily update on homepage + archival galleries.

There is one thing I would like to implement that the site builder is not equipped for. I would like to have a page called "random cartoon" that, when visited, populates with a random cartoon from the archive.

I can create a basic page using the site builder and it has the option to add HTML to customize. Theoretically, I figure this means I could create this "random cartoon" page from scratch, but I don't know where to start.

One other note that may be an issue - the image files for the cartoon are not located in any one central folder/volume in the backend of the website. Pixpa does not have that function. So right now each cartoon exists on the site in a corresponding gallery and has been assigned a url such as "https://ift.tt/8pJ5d0c"

There are almost 700 cartoons so far, with more being added each and every day, so this is a major aspect of my issue...

In summation my question is - how and where should I organize my images so that I can implement this "random cartoon" page most efficiently, and once I have completed that organization, what CSS should I use to create the functional page?

Appreciate any insights you may have. Thank you in advance!




Conditional sampling a dataframe

I am a newbie in R and want to perform a specific task but I am lost on the specificities of it and I would really appreciate if someone could help me through it.

What I would like to do is: I want to sample, say, 2 random couple on year 2000 including every unique male on that year (e.g. on year 2000, the first random couple sampled is M1-F2, and therefore the second couple must be M2 (the other unique male) - any female other then F2). Then, sample another 2 from 2001, but on 2002 I want to sample 3. When the loop finishes to sample across all years I want to store the mean of "Diff_ages" and "Diff_weights". Then repeat this loop 100 times to get a distribution and compare to my real data.

So the conditions are that on each year I want to sample different number of random couples (those numbers are stored in another df, and the male and female should be unique within each year but can vary across years).

I started the code like this: (I know that this only samples twice from year 2000 and can have the same male which I don't want).

couples <- data.frame (Male = c("M1","M1","M1","M2","M2","M2","M1","M1","M1","M1","M3","M3","M3","M3","M3","M3","M3","M4","M4","M4","M5","M5","M5"), Female = c("F1","F2","F3","F1","F2","F3","F2","F3","F4","F5","F2","F3","F4","F5","F3","F6","F7","F3","F6","F7","F3","F6","F7"), Year = c(2000,2000,2000,2000,2000,2000,2001,2001,2001,2001,2001,2001,2001,2001,2002,2002,2002,2002,2002,2002,2002,2002,2002), Diff_ages = c(0,2,1,3,2,1,1,0,1,1,0,5,4,3,0,1,2,2,3,2,1,0,2), Diff_weights = c(0.20,0.25,0.24,0.34 ,0.21 ,0.24,0.21,0.25,0.26,0.24,0.26,0.23,0.22,0.21,0.18,0.21,0.23,0.24,0.25,0.23,0.28,0.25,0.24))

Nb_true_couples <- data.frame(Year = c(2000,2001,2002), Nb_true_couples = c(2,3,2))

# Seed for reproducibility
set.seed(2022)

# Number iterations to build null distribution
  n_rep = 100 

# Number of samples to draw for each year
  sample_size = Nb_true_couples

# Vector to store means
  mean_diff_ages = rep(NA,n_rep)
  mean_diff_weights = rep(NA,n_rep)
  
for (i in 1:n_rep){
  random_couples_sample=couples[sample(which(couples$Year == "2000"),size=2,replace=F),]
  
  # Calculate and store the means
  mean_diff_ages[i] = mean(random_couples_sample$Diff_ages)
  mean_diff_weights[i] = mean(random_couples_sample$Diff_weights)
}

This is my first question on SO so please be patient with me if I am not doing this in clearer way. If someone can guide me through this I would really appreciate. Thanks in advance




How to generate different password each time i clicked the button python

I have 2 python files: 1, the password generator, and 2, the password manger.

In the password manger I am using tkinter. I want to retrieve a generated password each time I click on the the generate button that imports from password generator file. however each time each I clicked on the generate button the same password shows.

Is there a way to generate a different password each time I click on the generate button?

File 1: password generator:

#Password Generator Project
from random import  shuffle,choice,randint
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 = ['!', '#', '$', '%', '&', '(', ')', '*', '+']



password_list = []

password_list = [choice(letters) for char in range(randint(8,10))]

password_list += [choice(symbols) for char in range(randint(2,4))]



password_list += [choice(numbers) for char in range(randint(2,4))]


shuffle(password_list)

password = "".join(password_list)


file 2: password manger(PASSWORD GENERATOR Function):

from tkinter import  *
from tkinter import messagebox
import pyperclip
YELLOW = "#f7f5dd"

# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def GENERATOR_PASSWORD():
    password_input.delete(0,END)
    import password_gen
    generated_password = password_gen.password
    password_input.insert(0,generated_password)
    pyperclip.copy(generated_password)




mercredi 13 avril 2022

How can i get an random value out of an array in OCaml

so i have this

function let init_color() : t_color t_array = 
  {len = 7 ; value = [|blue ; red ; green ; yellow ; cyan ; magenta ; grey|]} ;;

In OCaml and I'm trying to get a random value(color) of of it with another function. And im kinda struggling to do it, new to coding so il be glad to get some help.




Randomly selecting a subset of rows from a pandas dataframe based on existing column values

I have a dataframe that contains multiple columns and would like to randomly select an equal number of rows based on the values of specific column. I thought of using a df.groupby['...'] but it did not work. Here is an example:

dataframe

Assume that I would like to randomly select one row per GroupID, how can I accomplish this? For example, let's say I select one random row per GroupID, the result would yield the following:

dataframe random selection

such that it outputs a single row based on the values in GroupID. Assume, for example, that rows are sorted by GroupID (from asc to desc), then select an "n" number of rows from ones that pertain to GroupID 1, 2, 3, and so on. Any information would definitely be helpful.




can't generate a Random value?

I´ve made a code on visual basic for a wind calc. but can't run a random value, as the results are not random. I´ve run it twice just to check if values are random but not at all. Lot of time working on this code and need some help pls

Please see my code below (if you spot others mistakes, please let me know, much appreciate)

For j = 1 To n_p
    ti = 0
    For i = 0 To n_t
        ti = delta_t * i
        Sum2 = 0
    
        For m = 1 To j
            Sum1 = 0
            For l = 1 To n_f
                w_lm = (l - 1 + m / n_p) * delta_w
                C = Exp(-lbd * w_lm * delta_L / (2 * Pi * U_m))
                
                If j < m Then
                    G = 0
                ElseIf m = 1 Then
                    G = C ^ Abs(j - m)
                ElseIf m <= j And m >= 2 Then
                    G = C ^ Abs(j - m) * Sqr(1 - C ^ 2)
                End If
                
                fu = L_u * w_lm / (2 * Pi * U_m)
                S = 4 * fu * S_v ^ 2 / (w_lm * (1 + 70.8 * fu ^ 2) ^ (5 / 6))
                                
                fi = Rnd() * 2 * Pi
                
                Sum1 = Sum1 + Sqr(S) * G * Cos(w_lm * ti + fi)
            Next l
            
            Sum2 = Sum2 + Sum1
        Next m
        
        Vi = Sqr(2 * delta_w) * Sum2



mardi 12 avril 2022

How to send the same word to each number using Twilio. I am importing random word from a text file to send to recipients

I am wanting to send the same random word from my text file to each recipient. Right now it sends a different random word to each phone number and I need it to be the same to all. I am using Twilio to send texts to numbers. Here is what I have tried below:

import os
from twilio.rest import Client
import random

# Open the file in read mode
with open("5words.txt", "r") as file:
    allText = file.read()
    word = list(map(str, allText.split()))

account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
family = {'+123456789', '+123456789','123456789','123456789','123456987','123456789'}
for number in family:
    client.messages.create(
         body=('Your word of the day is ' + random.choice(word)),
         from_='+12345678',
         to=(number)
     )



How do I have it so that sprites in a group all spawn in random locations only once in the draw function?

I want to have it in my code such that all of the sprites in a group variable spawn in different locations once in the draw function. The problem I am currently having is that since the draw function constantly repeats, all of the sprites are constantly changing positions due to this; and as you can imagine, they are rapidly moving all across the screen.

  drawSprites(toppingsGroup);
  for (var i = 0; i < toppingsGroup.length; i++) {
     toppingsGroup[i].position.x = 600;
     toppingsGroup[i].position.y = random(height);

}



rng('default') for rand() function in MATLAB vs Octave

I have a matlab piece of code that generates same random numbers (rand(n,1)) when I initialize with rng('default');

Example:

>> rng('default');
>> rand(3,1)

ans =

    0.8147
    0.9058
    0.1270

Now I need to generate the same output in Octave. Is there an equivalent function for rng('default') in Octave? Please advise on how to get the same set of random numbers as MATLAB in Octave.




python random int append to list and count "x" top numbers that occurred and number of times int occurred

New to python so all help is appreciated! I did check and found several count post but couldn't find any that print the top occurrences from the list. (ie 3 occurred 6x, 4 occurred 4x and 2 occurred 3x)

Goal: I'd like to have the code print 1000 numbers 0,1000 randomly and then be able to choose how many to show.

so for example num = [0,5,12,5, 22,12,0 ,32,22,0,0,5] I want to be able to see say the top 3 repeated numbers and how many times that number occurred. 0-4times, 5-3times, 12-2times.

code Progression #valid attempts are made

Prints 1000 times randomly

import random

for x in range(1001):
    print(random.randint(0,1001))

Append the randint directly to num

import random

num = []
for x in range(1001):
    num.append(random.randint(0,1001))

print(num)

Includes prompt to get how many integers you want to see.

import random

num = []
for x in range(1001):
    num.append(random.randint(0,1001))

highscore = input("Please enter howmany numbers you'd like to see: ")
print("The top", highscore, "repeated numbers are: ", num)

Issues left: how to print highscore's count for num (this part 0-4times, 5-3times, 12-2times.)

Attempt at count issue (prints 0 every time. added num to print to confirm if "y" was in the list)

import random

#creates list
num = []
for x in range(0,10):
    num.append(random.randint(0,10))

highscore = input("input number of reoccurrence's you want to see: ")
y = num.count(highscore)
print(num, y)



How do I take a specific dictionary item along with it's key randomly? [duplicate]

Take a look at this example:

dictionary = {"hello":"world", "yes":"sir", "very":"funny", "good":"bye"}

Now if I want to pick a random item (along with it's key) from this dictionay, how would I do that? I tried:

random.choice(dictionary)

But it does not work and returns this traceback error:

  File "C:\Users\dado\AppData\Local\Programs\Python\Python310-32\lib\random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]
KeyError: 3

I want to take a random item with it's key and store each of those in variables like this:

random_item = # Code to grab a random item
random_items_key = # Code to grab that random item's key

So if we ranodmly selected:

("hello":"world")

The value of the variables would be:

random_item = # This would be "hello"
random_items_key = # And this should be "world"

So how do we grab a random pair from a dictionary in python? And how do we store each in different variables? Would appreciate some help, thanks -




Scramble/Obfuscate email values in SQL Server

I would like to improve the following function to randomize the letters in an email column. So far I have the following function but the output is not what I expected:

CREATE VIEW dbo.vwRandom
AS
SELECT RAND() as RandomValue;
GO
     
CREATE  FUNCTION dbo.Character_Scramble 
    (
        @OrigVal varchar(MAX)
    )
    RETURNS varchar(MAX)
    WITH ENCRYPTION
    AS
    BEGIN
     
    -- Variables used
    DECLARE @NewVal VARCHAR(MAX);
    DECLARE @OrigLen INT;
    DECLARE @CurrLen INT;
    DECLARE @LoopCt INT;
    DECLARE @Rand INT;
     
    -- Set variable default values
    SET @NewVal = '';
    SET @OrigLen = DATALENGTH(@OrigVal);
    SET @CurrLen = @OrigLen;
    SET @LoopCt = 1;
     
    -- Loop through the characters passed
    WHILE @LoopCt <= @OrigLen
        BEGIN
            -- Current length of possible characters
            SET @CurrLen = DATALENGTH(CHARINDEX('@', @OrigVal));
     
            -- Random position of character to use
            SELECT
                @Rand = Convert(int,(((1) - @CurrLen) *
                                   RandomValue + @CurrLen))
            FROM
                dbo.vwRandom;
     
            -- Assembles the value to be returned
            SET @NewVal = 
                                 SUBSTRING(@OrigVal,@Rand,1) + @NewVal;
     
            -- Removes the character from available options
            SET @OrigVal =
                     Replace(@OrigVal,SUBSTRING(@Origval,@Rand,1),'');
     
            -- Advance the loop="color:black">
            SET @LoopCt = @LoopCt + 1;
        END
        -- Returns new value
        Return LOWER(@NewVal);
    END
    GO

The output returned by the function is:

SELECT dbo.Character_Scramble('waltero.lukase@gmail.com')
-- output: vmgoli.@cuares

The output I want would be to respect the length of the word and the position of the symbols (., @, _, etc.).

SELECT dbo.Character_Scramble('waltero.lukase@gmail.com')
-- pkderso.modefk@poajf.lpd

Any help would help me enormously. Thank you!




lundi 11 avril 2022

Pls help me with this while loop nested in if condition nested in for loop 0_0

I'm trying to extract a certain amount of numbers from a range of 17 numbers. However if a number is not valid (decided by the user) I need to extract another unique nuber that is different from the number not valid and the numbers that has been extracted. This is my code:

import random
import rich
from rich.console import Console

console = Console()
num = int(console.input('[yellow]How many number you want to extract[/yellow]: '))
non = int(console.input('[yellow]Number you want to exclude[/yellow]: '))
x = random.sample(range(1,18),num)
console.print("[yellow]Numbers extracted: [/yellow]",str(x))

for i in x:
    if i == 1:
        if non != 1:
            console.print('[green]:heavy_check_mark:[/green] Baiesi')
        else:
            console.print('❌ Baiesi')
            riserva = random.sample(range(1,18),1)
            notvalid = True
            while notvalid:
                if i not in riserva or x[i] not in riserva:
                    sosti = random.sample(range(1,18),1)
                    print(sosti)
                    notvalid = False
                else:
                    notvalid = True
                    print('unique nuber not valid')

#copy the code written before for every number until 17

The problem with this code is that the unique number that is supposed to be extracted is not unique: sometimes it gives numbers already extracted. Does someone have any idea on how to do this?




dimanche 10 avril 2022

Randomly select strings based on multiple criteria in R

I'm trying to select strings based on multiple criteria but so far no success. My vector contains the following strings (a total of 48 strings): (1_A, 1_B, 1_C, 1_D, 2_A, 2_B, 2_C, 2_D... 12_A, 12_B, 12_C, 12_D)

I need to randomly select 12 strings. The criteria are:

  • I need one string containing each number
  • I need exactly three strings that contains each letter.

I need the final output to be something like: 1_A, 2_A, 3_A, 4_B, 5_B, 6_B, 7_C, 8_C, 9_C, 10_D, 11_D, 12_D.

Any help will appreciated.

All the best, Angelica




R: Randomly Replacing Elements of a Data Frame with 0

I am working with the R programming language.

Suppose I have the following data frame:

var_1 = var_2 = var_3 = var_4 = var_5 =  c("1,2,3,4,5,6,7,8,9,10")

my_data = data.frame(var_1,var_2,var_3,var_4,var_5)

my_data = rbind(my_data, my_data[rep(1, 100), ])

rownames(my_data) = 1:nrow(my_data)

The data looks like this:

    head(my_data)

                 var_1                var_2                var_3                var_4                var_5
1 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10
2 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10
3 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10
4 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10
5 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10
6 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10

My Question: I would like to randomly replace elements in this data frame with 0 - for instance, the final result should look something like this (for brevity, I am only showing the first row):

# desired result

                 var_1                var_2                var_3                var_4                var_5
1 1,0,3,0,5,6,0,0,9,10 1,2,0,4,5,0,0,8,9,0 1,0,3,0,0,0,0,8,9,0 1,2,3,4,0,6,7,0,0,10 1,2,0,4,5,0,7,8,0,10

I tried to do this with the following line of code (Replace random values in a column in a dataframe) :

my_data$var_1[sample(nrow(my_data),as.integer(0.5*nrow(my_data)) , replace = TRUE)] <- 0
my_data$var_2[sample(nrow(my_data),as.integer(0.5*nrow(my_data)), replace = TRUE)] <- 0
my_data$var_3[sample(nrow(my_data),as.integer(0.5*nrow(my_data)), replace = TRUE)] <- 0
my_data$var_4[sample(nrow(my_data),as.integer(0.5*nrow(my_data)), replace = TRUE)] <- 0
my_data$var_5[sample(nrow(my_data),as.integer(0.5*nrow(my_data)), replace = TRUE)] <- 0

But this is replacing ALL the elements of a row with 0 (instead of just replacing some of the elements within a row):

head(my_data)
                 var_1                var_2                var_3                var_4                var_5
1 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10                    0                    0                    0
2                    0                    0 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10                    0
3                    0 1,2,3,4,5,6,7,8,9,10                    0 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10
4                    0 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10                    0 1,2,3,4,5,6,7,8,9,10
5 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10
6 1,2,3,4,5,6,7,8,9,10                    0 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10                    0

Can someone please show me what I am doing wrong and how to get the desired result?

Thanks!




samedi 9 avril 2022

Can I predict the value of Pi(3.14) using a random number function generated from scratch?

I have tried to predict the value of Pi using a random function generated from scratch. But it is giving an output of 4 instead of 3.14.My code for predicting Pi works perfectly when I'm using "np.random.uniform" instead of my random function.How can I improve my random function so that I can get an output of 3.14?

import numpy as np
import matplotlib.pyplot as plt
#random function using linear congruent generator
def generate_rand(mult=16807,mod=(2**31)-1, seed=123456789, size=1):
    U = np.zeros(size)
    X = (seed*mult+1)%mod 
    U[0] = X/mod 
    for i in range(1, size):
        X = (X*mult+1)%mod
        U[i] = X/mod 
    return U
def generate_random(low=0,high=1, seed=123456789, size=1):
#Generates uniformly random number between 'low' and 'high' limits
    return low+(high-low) *generate_rand(seed=seed, size=size)
def pi_estimator(samples):
    points_inside_circle= 0
    total_num_points = 0

    for _ in range(samples):
        x = generate_random()
        y = generate_random()
        distance = x**2 + y**2
        if distance <= 1:
            points_inside_circle +=1
        total_num_points += 1
    return 4* points_inside_circle/total_num_points
pi_estimator(10000)



How to make sure items in list do not repeat in JavaScript [duplicate]

for (var i = 0; i < 3; i++) { var newTeam = randomNumber(0,30);

In this code, how do I make sure the randomly chosen numbers do not repeat? (for example: after 1 is being chosen, it will not be picked again)




How to store a rand() variable?

I am trying to store the value of a rand() variable. I don't know if the questions is going to make much sense. I send tcph_seqnum to the Server, the Server reads receives: 1732610923. Then, I try to use the same variable again, let's say with a printf statement, and I get: 193094224.

This is my code below:

u_int16_t tcph_seqnum = rand();
write(clientSocket, &tcph_seqnum, sizeof(tcph_seqnum)); /* server receives 1732610923 */
printf("%d\n", tcph_seqnum); /* prints to the console 193094224*/

How can I reuse the same value sent to the Server? Store in a variable without the value changing?




Simulate loaded dado for the number you choose

how to simulate loaded dado for the number you choose (1, 2,3,4, 5 or 6)? For example, when you insert 1 and of the 10 releases, 1 is the one with the highest appearance or probability.




Random Name Generator - output is alphabetical, but I don't want it to be

I've put together a random name generator (using a few other helpful threads on here) and this is the code I've come up with. It keeps outputting the list in alphabetic order, but I don't want it to. Is it being caused by aSort? I'm stumped.... Thank you!

Sub createPickList() Dim N As Long, i As Long

N = Range("E2").Value
ReDim arr(1 To N)
For i = 1 To N
    arr(i) = Cells(i, "F").Value
Next i

Call aSort(arr)

For i = 1 To N
    Cells(i, "G").Value = arr(i)
Next i

End Sub Public Sub aSort(ByRef InOut)

Dim i As Long, J As Long, Low As Long
Dim Hi As Long, Temp As Variant

Low = LBound(InOut)
Hi = UBound(InOut)

J = (Hi - Low + 1) \ 2
Do While J > 0
    For i = Low To Hi - J
      If InOut(i) > InOut(i + J) Then
        Temp = InOut(i)
        InOut(i) = InOut(i + J)
        InOut(i + J) = Temp
      End If
    Next i
    For i = Hi - J To Low Step -1
      If InOut(i) > InOut(i + J) Then
        Temp = InOut(i)
        InOut(i) = InOut(i + J)
        InOut(i + J) = Temp
      End If
    Next i
    J = J \ 2
Loop

End Sub




Why does n-of show a discontinuity when the size of the reported agentset goes from 2 to 3?

The n-of reporter is one of those reporters making random choices, so we know that if we use the same random-seed we will always get the same agentset out of n-of.

n-of takes two arguments: size and agentset (it can also take lists, but a note on this later). I would expect that it works by throwing a pseudo-random number, using this number to choose an agent from agentset, and repeating this process size times.

If this is true we would expect that, if we test n-of on the same agentset and using the same random-seed, but each time increasing size by 1, every resulting agentset will be the same as in the previous extraction plus a further agent. After all, the sequence of pseudo-random numbers used to pick the first (size - 1) agents was the same as before.

This seems to be confirmed generally. The code below highlights the same patches plus a further one everytime size is increased, as shown by the pictures:

to highlight-patches [n]
  clear-all
  random-seed 123
  
  resize-world -6 6 -6 6

  ask n-of n patches [
    set pcolor yellow
  ]
  
  ask patch 0 0 [
    set plabel word "n = " n
  ]
end

enter image description here enter image description here enter image description here enter image description here

enter image description here enter image description here enter image description here enter image description here

But there is an exception: the same does not happen when size goes from 2 to 3. As shown by the pictures below, n-of seems to follow the usual behaviour when starting from a size of 1, but the agentset suddenly changes when size reaches 3 (becoming the agentset of the figures above - which, as far as I can tell, does not change anymore):

enter image description here enter image description here enter image description here

What is going on there behind the scenes of n-of, that causes this change at this seemingly-unexplicable threshold?

In particular, this seems to be the case only for n-of. In fact, using a combination of repeat and one-of doesn't show this discontinuity (or at least as far as I've seen):

to highlight-patches-with-repeat [n]
  clear-all
  random-seed 123

  resize-world -6 6 -6 6
  
  repeat n [
    ask one-of patches [
      set pcolor yellow
    ]
  ]
  
  ask patch 0 0 [
    set plabel word "n = " n
  ]
end

enter image description here enter image description here enter image description here enter image description here

enter image description here enter image description here enter image description here enter image description here

Note that this comparison is not influenced by the fact that n-of guarantees the absence of repetitions while repeat + one-of may have repetitions (in my example above the first repetition happens when size reaches 13). The relevant aspect simply is that the reported agentset of size x is consistent with the reported agentset of size x + 1.


On using n-of on lists instead of agentsets

Doing the same on a list results in always different numbers being extracted, i.e. the additional extraction does not equal the previous extraction with the addition of a further number. While this looks to me as a counter-intuitive behaviour from the point of view of expecting always the same items to be extracted from a list if the extraction is based on always the same sequence of pseudo-random numbers, at least it looks to happen consistently and therefore it does not look to me as ambiguous behaviour as in the case of agentsets.