mardi 28 février 2023

How to take a string, create a list from string, and select randomly from that list (x) times

I want to create a Python function which will take names as input separated by commas; turn that string into a list, and finally choose (num - parameter) number of names from that list.

I am using random.choice(list), but instead of the function printing out (num) number of names from the list, the list itself is simply being printed (num) number of times instead. I can't figure out what I am doing wrong. This is my first ever question on Stack Overflow.

  • I am importing random module
  • I am using split to delineate names by commas
  • (num) parameter should help print randomly chosen names (num) times

Here is my code and also the output:

import random

def listgen(num):
    newlist=[oglist.split(',')]
    for x in range(num):
        print(random.choice(newlist))

print("Type in your list. Separate each name by a comma and press enter when finished")
oglist=input()

print("how many random names do you need?")
num=int(input())

listgen(num)

Output:

Type in your list. Separate each name by a comma and press enter when finished

Joe, Frank, Janet, Dion, Rachel, Lilly, Alyx

how many random names do you need?

3

['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']

['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']

['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']




Generate a Uniform Spherical Distribution using rejection methods in Python

I've been trying to generate a uniform spherical distribution in Python using uniform random sampling. For some reason my presumed spherical distribution looks more like an ovoid than like a sphere. I am using the fact that a sphere is defined: x^2 + y^2 + z^2 = R^2 and assuming R = 1 I get that the condition that the points should satisfy to be inside the sphere is: x^2 + y^2 + z^2 <= 1. For some reason this does not work. I have a perfect circular distribution from a top view (projection in the xy plane), but there is clearly a elliptical geometry in the planes xz and yz. ``` import numpy as np import numpy.random as rand import matplotlib.pyplot as plt

N = 10000

def sample_cube(number_of_trials):
    """
    This function receives an integer and returns a uniform sample of points in a square.
    The return object is a list of lists, which consists of three entries, each is a list
    of the copordinates of a point in the space.
    """

    cube = rand.uniform(low = -1, high = 1, size = (number_of_trials, 3))
    x_cube = cube[:,0]
    y_cube = cube[:,1]
    z_cube = cube[:,2]
    return [x_cube, y_cube, z_cube]

def sample_sphere(cube):
    """
    This function takes a list on the form [x_cube, y_cube, z_cube] and then sample
    an spherical distribution of points.
    """
    in_sphere = np.where(np.sqrt(cube[0]**2 + cube[1]**2 + cube[2]**2) <= 1)
    return in_sphere

"""
Main Code
"""
cube = sample_cube(N)
sphere = sample_sphere(cube)
print(sphere[0])
print(cube)

print(cube[0][sphere[0]])
x_in_sphere = cube[0][sphere[0]]
y_in_sphere = cube[1][sphere[0]]
z_in_sphere = cube[2][sphere[0]]
fig = plt.figure()
ax = plt.axes(projection = "3d")
ax.scatter(x_in_sphere, y_in_sphere, z_in_sphere, s = 1, color = "black")
plt.show()
plt.clf
![Distribution generated by the code above](https://i.stack.imgur.com/N83Ui.png)
![Side view of the distribution (plane xz)](https://i.stack.imgur.com/Di5kJ.png)
![Top view of distribution (plane xy)](https://i.stack.imgur.com/8uQvD.png)

I was simply trying to get a uniform sphere. There should be something wrong with the approach, but I can not spot the mistake.



Need .ASPX page that will return a random .png file

I have looked all over and all the solution I found were overly complicated (way above my head). I am hoping someone can help me. I would like to create an .ASPX/.ASP file that I can use as the image src= in a web page. Upon load, the "display_random_image.aspx" page would display a random image. The use case is for a random email footer image (think random email footer image)

website structure C:<random_email_footer_images> image_1.png image_2.png image_3.png image_4.png image_5.png

c:\display_random_image.aspx source would be something like this

<html>
  <body>
    <img src="generate_random_image.aspx" />
  </body>
</html>

c:\generate_random_image.aspx would randomly select a number (1-5) and return it. Very roughly I imagine with would be something like this:

<%@ Page Language="C#" %>
<script runat="server" language="c#">

1) select a number between 1 and 5
2) load that random image into an output stream
3) return the image

</script>

I googled lots of different versions and iterations of "Response.ContentType = "image/jpeg";" random image generator etc.




How to have a string thats constantly changing change into a set word one letter at a time

The label is printing a 5 letter word, consisting of random letters, every 10,000th of a second it changes creating a constanly changing random bunch of letters. I want to be able to make each index of the word(which is randomly changing), change into a letter from a word of my choice, with a delay between each letter updating so that while the index[0] has become the first letter of my selected word, the other index's are still 'scrambling', then index[1] becomes the second letter of the word, and so on.

letters = string.ascii_letters
text = "Dylan"
word= list(text)
index=0

def loop():
    loop1()
    loop2()
    loop3()
    loop4()
    loop5()
    window.after(1, loop)

count=0

def loop1():
    global word, letters, index, wordlist,count
    if count < 1:
        word[0] = random.choice(letters)
        label.config(text=word)


def loop2():
    global word, letters, index, wordlist,count
    if count < 2:
        word[1] = random.choice(letters)
        label.config(text=word)

    
def loop3():
    global word, letters, index, wordlist,count
    if count < 3:
        word[2] = random.choice(letters)
        label.config(text=word)


def loop4():
    global word, letters, index, wordlist,count
    if count < 4:
        word[3] = random.choice(letters)
        label.config(text=word)


def loop5():
    global word, letters, index, wordlist,count
    if count < 5:
        word[4] = random.choice(letters)
        label.config(text=word)


def dejumble(event):
    global stopvar, count
    for i in range(5):
        count+=1
        print(count)
        unscramble()

def update_label():
     label.config(text=wordlist)

    
index1=0

def unscramble():
    window.after(1000, update_label)
    global index1
    global wordlist, word
    print(text[index1])
    word[index1] = text[index1]
    window.after(1000, config)
    index1  += 1
    print(word)

def config():
    label.config(text=word)    
    
def looped(event):
    loop()
      

I tried the above code but instead of unscrambling one at a time, it pauses on the last list of random letters, then updates all at once. Based on the prints I think its the label not updating correctly and not the unscrambling bit.




lundi 27 février 2023

Is there any way to generate a uniform distribution out of two other distributions which are uniform?

X=rand(n,1) is a random variable which is uniformly distributed and the range of X is between 0 to 1. I want variable Y to be negatively correlated with X with corrcoef equal to -0.4 and its distribution be uniform and range of Y be between 0 to 1. I tackle this problem in this way that I introduced a noise to the problem "z" such that: Y=\alpha(1-X)+\beta(z) and z=rand(n,1)

\alpha here is 0.4 and \beta is 0.6. The corrcoef(X,Y) is around -0.4 and the range of Y is [0 1] which satisfy our condition but the distribution of Y is not uniform any more. IT IS NORMAL. How can I satisfy this condition as well?

I expexct the summation of two uniform distribution be uniform as well but it is normal.




How to do probabilities in C

I need to take different probabilities and choose one. For instance: if you choose 1 the probabilities are as follows: Common 60% Rare 25% Ultra Rare 14% Super Super Rare 1% And each different choice by the "player" would change the probabilities to match how good/expensive their choice is (Its not necessary to share those probabilities since I can implement those myself after I figure this out). I know I need to use an srand statement but I don't know how to properly implement or even use an srand statement in this way. I'm still very new to coding and struggling real hard with some more basic subjects such as this.

I haven't tried much since I don't really understand srand statements and I haven't found much online that made sense to me or explained how to fix my problem. Below is the code I'm using, I've set up a switch statement for whatever the user selects but i need to then run like three probability calculations in there. For now I just want to implement the probability and result and I'll figure out the rest later. But how do I even run those probability calculations and then print out the result to the user?? Doubt my code here means much but it may help to explain what I'm doing, thanks.

  #include <stdio.h>
  #include <math.h>
  #include <stdlib.h>
  #include <time.h>
  int DoPull();

  int main(void) {
    int userInput;
  
    printf("Welcome to the gacha simulator!\n");
    printf("What type of pull will you do?\n");
    printf("1 = Normal Pull\n");
    printf("2 = Good Pull\n");
    printf("3 = Great Pull\n");
    printf("-1 = Leave\n");
    scanf("%d", &userInput);
  
      switch(userInput) {
      case 1:
        srand // listen man idk how to do srands i just have this set up for later
      break;
      case 2:
        srand
      break;
      case 3:
        srand
      break;
      case -1:
        printf("You left!\n");
        return 0;
      break; 
      default:
        printf("Invalid Input\n");
      break;
    }
    return 0;
  }

  int DoPull() {
  }



dimanche 26 février 2023

Are these numbers random? [duplicate]

I have been thinking about random numbers a lot. I am looking for different ways of generating random numbers because the RNG in every computer isn't really random. I notice this mostly with music players. Whenever I play my music on random, it always repeats certain songs and skips others all together. Each time I reset my music player, different songs get repeated, but the pattern remains the same; certain songs get pick way more often then others.

So I thought about how to generate more "naturally" random numbers. Where does "true" randomness exist in a computer? The answer I came up with is in the cpu. The cpu clock will tick at different rates every picosecond because of a multitude of factors: Load, temperature, power fluctuation, etc. I concluded that taking snapshots of the clock at regular intervals would yield random numbers deep in the decimal ranges, from 100 microseconds - 1 picosecond (0.00000n - 0.00000000n)

I wrote the following script to test this..

#!/usr/bin/env python
import time
ct = 0

#Are these numbers random?

while ct < 10:

    print (str(time.monotonic())[-4:-1],str(time.monotonic())[-4:-1],str(time.monotonic())[-4:-1],end='\n')
    ct += 1

Output:

710 062 469

345 863 084

639 060 263

643 057 258

627 039 249

032 767 971

436 839 040

637 097 302

693 158 937

175 207 402

So now I ask those who know, are these numbers random?

Sorry for the lack of technical know-how.. I used to be a mechanic but I lost an arm in a motorcycle accident. Now I'm teaching myself what I can in computer science. Random numbers and prime numbers interest me, but I obviously don't know much about either.




Take random sample of rows from dataframe with grouping variables

I have a dataframe with the following structure:

dat <- tibble(
  item_type  = rep(1:36, each = 6), 
  condition1 = rep(c("a", "b", "c"), times = 72), 
  condition2 = rep(c("y", "z"), each = 3, times = 36), 
) %>% 
  unite(unique, item_type, condition1, condition2, sep = "-", remove = F)

which looks like this:

# A tibble: 216 × 4
   unique item_type condition1 condition2
   <chr>      <int> <chr>      <chr>     
 1 1-a-y          1 a          y         
 2 1-b-y          1 b          y         
 3 1-c-y          1 c          y         
 4 1-a-z          1 a          z         
 5 1-b-z          1 b          z         
 6 1-c-z          1 c          z         
 7 2-a-y          2 a          y         
 8 2-b-y          2 b          y         
 9 2-c-y          2 c          y         
10 2-a-z          2 a          z    

I would like to take a random sample of 36 rows. The sample should include 6 repetitions of the condition1 by condition2 combinations without repeating item_type.

Using slice_sample() it seems I can get the subset I want...

set.seed(1)
dat %>% 
  slice_sample(n = 6, by = c("condition1", "condition2")) %>% 
  count(condition1, condition2)
  condition1 condition2     n
  <chr>      <chr>      <int>
1 a          y              6
2 a          z              6
3 b          y              6
4 b          z              6
5 c          y              6
6 c          z              6

But on closer inspection I see that item_type is repeated.

set.seed(1)
dat %>% 
  slice_sample(n = 6, by = c("condition1", "condition2")) %>% 
  count(item_type) %>% 
  arrange(desc(n))
# A tibble: 22 × 2
   item_type     n
       <int> <int>
 1        10     3
 2        34     3
 3         1     2
 4         6     2
 5         7     2
 6        15     2
 7        20     2
 8        21     2
 9        23     2
10        25     2
# … with 12 more rows

In other words, I would like only unique pulls from item_type. Is it possible to get slice_sample() to do this?




Weighted random name selector from an external workbook

I'm new to VBA but have some coding background. The below must be done through Excel.

Objective: List of names that need to be selected at random, but the names will have weighting to them so that some names are more likely to be selected. The table of data will always be an external file, and the data cannot be printed to the main worksheet.

Example of the data that will be read:

ID Name Weighting
1 Person 1 3
2 Person 2 1
3 Person 3 2
4 Person 4 5
5 Person 5 1

So Person 4 will be 5 times more likely to be picked than Person 5, for example.

I've been going around in circles so far. I thought adding the data to an array and then looping through that array to find a weighting,array1(3,i) that is greater than 1, then grabbing the name to the left array1(2,i) and adding it again to the end of the array would work.

However, I have since found out you cannot increase the first dimension of an array dynamically in VBA.

I am initially declaring my array with array1 = wb.Worksheet(1).ListObjects("Table1").DataBodyRange.Value, where wb is the open workbook captured through GetOpenFilename().

Any idea what I can try? I would print my code, however my PC just reset and I lost the last save state, but can attempt a rewrite if it would be useful?

I have followed various examples/tutorials online but I think this exact scenario doesn't seem to be covered, and with my lack of VBA knowledge I'm at a loose end.




How could you encrypt random numbers and sell securely them via an API (randomness-as-a-service)

Since computers only have pseudo-random numbers, I could imagine setting up a company that offers random-numbers-as-a-service. The idea would be that you pay a small amount per month, and when you make an API call to the service, you get truly-random numbers. These numbers could be generated from natural sources of complexity. I found random.org which does this for free, and lavarand who did this for a price, based on lava lamps.

Assuming Alice is generating the random numbers, and wants to send them securely to Bob, how could Alice ensure that Eve (who has access to all traffic between Alice and Bob) can't steal the random numbers?

The issue with regular encryption, is that encrypting a random number would just result in another random number. In which case Eve could just take the encrypted random number and use that number for her random number needs. My assumption here is that any cryptographically secure encryption method, when applied on a uniform distribution, would result in another uniform distribution.

My core question is: How can Alice securely send a random number to Bob, but still ensure that the transferred data is less random than the original random number (such that the encrypted random number is useless as a random number in it's own right). I'm using 'less random' to mean that the encrypted number is further from a uniform distribution than the original number.




Just started learning javasript from "Bro code" and he was creating random number generator, and i did the same thing he did but my code's not working [closed]

So when went to console there is an error(Uncaught TypeError: Cannot set properties of null (setting 'onclick'). So i check if I wrote all ID names correctly but no there is no mistake.

After pressing the button "submit" three random numbers have to appear but it doesn't happen.

Here's the code:


let x;
let y;
let z;

document.getElementById("rollButton").onclick = function(){    
 
    x = Math.floor(Math.random() * 7);
    y = Math.floor(Math.random() * 7);
    z = Math.floor(Math.random() * 7);

    document.getElementById("xlabel").innerHTML = x;
    document.getElementById("ylabel").innerHTML = y;
    document.getElementById("zlabel").innerHTML = z;
}
HTML:
    <label class="xlabel"></label><br>
    <label class="ylabel"></label><br>
    <label class="zlabel"></label><br>
    <button class="rollButton">roll</button>




Sampling from uniform distribution row wise

Consider the following data:

df <- data.frame(id=1:5,
                 x_min = c(0.1,0.2,0.3,0.4,0.5),
                 x_max = c(0.15,0.23,0.38,0.44,0.57))

I intend to draw a random sample from a uniform distribution for each row. Why I'm getting the same values for column y? Here is what I did:

set.seed(12)
df$y <- runif(1, min=df$x_min, max=df$x_max)

Output:

> df
  id x_min x_max        y
1  1   0.1  0.15 0.103468
2  2   0.2  0.23 0.103468
3  3   0.3  0.38 0.103468
4  4   0.4  0.44 0.103468
5  5   0.5  0.57 0.103468



samedi 25 février 2023

Error with recursion from call "random.shuffle()"

Im trying to create a very simple blackjack game, and I think I'm almost done, but when I try to play the game I get an error:

Traceback (most recent call last):
  File "c:\Users\nils.edstrom\github-classroom\NTI-Gymnasiet-Nacka\februariprojektet-Nilleni2\Main.py", line 176, in <module>
    dealer = Dealer(player1)
  File "c:\Users\nils.edstrom\github-classroom\NTI-Gymnasiet-Nacka\februariprojektet-Nilleni2\Main.py", line 107, in __init__
    self._dealer = Dealer('Dealer')
  File "c:\Users\nils.edstrom\github-classroom\NTI-Gymnasiet-Nacka\februariprojektet-Nilleni2\Main.py", line 107, in __init__
    self._dealer = Dealer('Dealer')
  File "c:\Users\nils.edstrom\github-classroom\NTI-Gymnasiet-Nacka\februariprojektet-Nilleni2\Main.py", line 107, in __init__
    self._dealer = Dealer('Dealer')
  [Previous line repeated 493 more times]
  File "c:\Users\nils.edstrom\github-classroom\NTI-Gymnasiet-Nacka\februariprojektet-Nilleni2\Main.py", line 105, in __init__
    self._deck = Deck()
  File "c:\Users\nils.edstrom\github-classroom\NTI-Gymnasiet-Nacka\februariprojektet-Nilleni2\Main.py", line 43, in __init__
    self.populate()
  File "c:\Users\nils.edstrom\github-classroom\NTI-Gymnasiet-Nacka\februariprojektet-Nilleni2\Main.py", line 60, in populate
    random.shuffle(self._cards)
  File "C:\Users\nils.edstrom\AppData\Local\Programs\Python\Python39\lib\random.py", line 360, in shuffle
    for i in reversed(range(1, len(x))):
RecursionError: maximum recursion depth exceeded while calling a Python object

This is my code:

import random

class Card:
    def __init__(self, suit, number):
        self._suit = suit
        self._number = number

    def __repr__(self):
        return self._number + ' of ' + self._suit

    #Allows the user to write my_card.suit
    @property
    def suit(self):
        return self._suit
    
    #Prevents the user from changing the suit of a card to unvalid values
    @suit.setter
    def suit(self, suit):
        if suit in ['Hearts', 'Clubs', 'Diamonds', 'Spade']:
            self._suit = suit
        
        else: 
            print("That's not a valid suit")

    #Allows the user to write my_card.number
    @property
    def number(self):
        return self._number
    
    #Prevents the user from chaninging the number of a card to something non-existent
    @number.setter
    def number(self, number):
        if number in ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']:
            self._number = number
        
        else:
            print("That's not a valid number")
        

class Deck:
    def __init__(self):
        self._cards = []
        self.populate()
    
    def __repr__(self) -> str:
        return f'{self._cards}'

    def populate(self):
        suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades']
        numbers = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']

        cards = []
        for suit in suits:
            for number in numbers:
                cards.append(Card(suit, number))    
        
        self._cards = cards

        #Shuffles the deck so it's random what card is drawn each time
        random.shuffle(self._cards)

#Test
my_deck = Deck()
print(my_deck)

#Player class
class Player:
    def __init__(self, name, hand=None, score=0):
        self._name = name
        self._hand = [] if hand is None else hand
        self._score = score
    
    #Adds a card to the player hand
    def add_card(self, card):
        self._hand.append(card)
    
    def get_score(self):
        score = 0
        aces = 0
        for card in self._hand:
            if card.number == 'A':
                aces += 1
                score += 11
            
            elif card.number in ['J', 'Q', 'K']:
                score += 10
            
            else:
                score += int(card.number)
        
        #Calculates weather or not to count Aces as 1 or eleven depending on your score
        while aces > 0 and score > 21:
            value -= 10
            aces -= 1
        
        return score
            



# Dealer class
class Dealer:
    def __init__(self, player_name):
        self._hand = []
        self._deck = Deck()
        self._player = Player(player_name)
        self._dealer = Dealer('Dealer')

    
    def first_cards(self):
        self._player.add_card(self._deck._cards.pop())
        self._dealer.add_card(self._deck._cards.pop())
        self._player.add_card(self._deck._cards.pop())
        self._dealer.add_card(self._deck._cards.pop())

    def player_turn(self):
        while self._player.get_score() < 21:
            if str(input('Do you want to hit? (Y/N)')).lower() == 'y':
                self._player.add_card(self._deck._cards.pop())
                print(f'Your current hand is : {self._player.get_score()}')
            
            else:
                break

    def dealer_turn(self):
        while self._dealer.get_score() < 17:
            self._dealer.add_card(self._deck._cards.pop())
        print(f'The dealer\'s hand is: {self._dealer.get_score()}')


    def add_card(self, card):
        self._hand.append(card)

    def get_score(self):
        score = 0
        aces = 0
        for card in self._hand:
            if card.number == 'A':
                aces += 1
                score += 11
            
            elif card.number in ['J', 'Q', 'K']:
                score += 10
            
            else:
                score += int(card.number)
        
        #Calculates weather or not to count Aces as 1 or eleven depending on your score
        while aces > 0 and score > 21:
            score -= 10
            aces -= 1
        
        return score

    def start(self):
        print('Welcome to blackjack! By Nils Edstrom')
        self.first_cards()
        print(f'Your current hand is: {self._player.get_score()}')
        print(f'The dealer\'s current hand is: {self._dealer.get_score()}')

        self.player_turn()
        if self._player.get_score() > 21:
            print(f'You lose your current score is: {self._player.get_score()}')

        if self._player.get_score() > self._dealer.get_score():
            print('You won')

        elif self._player.get_score() < self._dealer.get_score():
            print('The dealer won')

        else:
            print('It\'s a tie')


player1 = str(input('What is your name? '))
dealer = Dealer(player1)
dealer.start()

I'm very frustarated with this, it seems to be coming from the populate method in the deck class specifically the random.shuffle() call. But I cannot figure out why it's creating a recursion error.

I'm very frustarated with this, it seems to be coming from the populate method in the deck class specifically the random.shuffle() call. But I cannot figure out why it's creating a recursion error.




Generating a random number (more than once) and using it inside two class functions

I am building a GUI with tkinter where two buttons modify two text fields. One button chooses a random key from the example_dict and displays it in text1 , and the other reveals the corresponding value in text2 . I have chosen a OOP approach to organize my code, because it seems the easiest to read.

To give a more compact overview, I have boiled the script down to my problem. In the actual script I use a pandas dataframe instead of the example_dict , but for the purpose of this question, I wanted to maintain the possibility of copying and pasting .

import tkinter as tk
from random import randint

example_dict = {'a': "one", 'b': "two", 'c': "three"}

class MainApp:
    def __init__(self, master):
        self.master = master

        self.reveal_button = tk.Button(master, text="reveal", command=self.reveal)
        self.reveal_button.pack()
        self.reveal_button.place(relx=0.5, rely=0.25, anchor=tk.CENTER)
        
        self.random_button = tk.Button(master, text="randomize", command=self.random_word)
        self.random_button.pack()
        self.random_button.place(relx=0.5, rely=0.6, anchor=tk.CENTER)
        
        # create two text fields that will display the key:value pair from the dictionary
        self.text1 = tk.Text(master, height=2, width=20)
        self.text1.pack()
        self.text1.place(relx=0.3, rely=0.25, anchor=tk.CENTER)
        
        self.text2 = tk.Text(master, height=2, width=20)
        self.text2.pack()
        self.text2.place(relx=0.7, rely=0.25, anchor=tk.CENTER)

    def random_word(self):
        rand_num = randint(0,2)
        self.text1.delete(1.0, tk.END)
        self.text2.delete(1.0, tk.END)
        self.text1.insert(tk.END, list(example_dict.keys())[rand_num])

    def reveal(self):
        self.text2.delete(1.0, tk.END)
        self.text2.insert(tk.END, list(example_dict.values())[rand_num])

root = tk.Tk()
MainApp(root)
root.mainloop()

The problem is of course that rand_num is only defined within random_word , resulting in a NameError when I click the reveal_button. I am not sure where to generate the random number to be able to use the same number in both class functions.

I have tried a few things. First, I created a separate function that only generates a random integer, which I then called from both other functions. I did not expect this to work, because it generates different integers each time it is called, leading to mismatched key:value pairs. The attempt looked like this:

def random_number(self):
    return randint(0,2)

def random_word(self):
    rand_num = self.random_number()
    self.text1.delete(1.0, tk.END)
    self.text2.delete(1.0, tk.END)
    self.text1.insert(tk.END, list(example_dict.keys())[rand_num])

def reveal(self):
    rand_num = self.random_number()
    self.text2.delete(1.0, tk.END)
    self.text2.insert(tk.END, list(example_dict.values())[rand_num])

Second, I declared rand_num as global, which works, but everytime I've seen global variables being mentioned, people say they should be avoided, leading me to believe I should avoid them too.

def random_word(self):
    global rand_num
    rand_num = randint(0,2)
    self.text1.delete(1.0, tk.END)
    self.text2.delete(1.0, tk.END)
    self.text1.insert(tk.END, list(example_dict.keys())[rand_num])

Another idea I had and quickly discarded was generating the random number as an instance attribute, but that should just generate a number once, and I need it to generate a new number every time the random_button is clicked.

How do I generate a random number every time the random_button is clicked, that I can then use with both my functions?




How to randomize key objects in model form and successfully submit in Django

I am trying to save user response (choice) in my Django application out of a set of values in the source model. The user is expected to select one of the many choices presented on the form (as radio buttons). The source model looks like this:

class Emotion(models.Model):
    emote_id = models.AutoField(primary_key=True, ...)
    emote_state_grp = models.ForeignKey(EmotGroup, ...)     # Grouping of Emotion State
    emote_state = models.CharField(max_length=55, ...)

The response/s will be saved in the following model:

class EmoteStateResponse(models.Model):
    emote_state_test = models.AutoField(primary_key=True, ...)
    emote_state_selected = models.ForeignKey(Emotion, ...)

Using a model form I am able to successfully save user choice (i.e. the "emote_state" value) in table "EmoteStateResponse".

However, as the choices might run into a number of instances of field "emote_state" (individual emotions) of table "Emotion", I am trying to select "at random" only a minimal number to display.

To do that, I am trying to randomize the choices in my form that goes like the following:

import random

class EmoteTestForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EmoteTestForm, self).__init__(*args, **kwargs)
        self.auto_id = True

    class Meta:
        model = EmoteStateResponse
        # ...
        fields = ('emote_state_selected', ...)

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

        qs_emot_state = Emotion.objects.all().values_list('emot_state_grp__emotion_grp_id', 'emote_id') # "emotion_grp_id": Key Field model "EmotGroup"
        list_qs_emot_state = list(qs_emot_state)
        rand_emot_state_list = list(dict(random.sample(list_qs_emot_state, len(list_qs_emot_state))).values()) # Random values

    # And finally...
    self.fields['emote_state_selected'].queryset = Emotion.objects.filter(emote_id__in=rand_emot_state_list)

However, on submit I come across the following error:

Select a valid choice. That choice is not one of the available choices.

May somebody please point out what I am doing wrong? How may I display the choice field "emote_state_selected" with random values from table "Emotion" and save it?




vendredi 24 février 2023

mrand48_r GNU extension

I'm trying to use mrand48_r for a programming assignment, right now, I have something like:

#include <errno.h>
#include <stdlib.h>
#include <assert.h>

// buffer to use                                                                                                                                                            
static struct drand48_data buffer;

static_assert(sizeof(long) == sizeof(unsigned long long));

// initialize mrand48_r                                                                                                                                                     
void
mrand48_init (void)
{
  // zero-filled by default, no init necessary                                                                                                                              
  // memset(&buffer, 0, sizeof(buffer)); same behavior                                                                                                                      

}

// generate values                                                                                                                                                          
unsigned long long
mrand48_wrapper (void)
{
  long result;
  errno = 0;
  if (-1 == mrand48_r(&buffer,&result)){
    perror("mrand48_r");
    abort();
  }
  return (unsigned long long) result;
}

void
mrand48_fini (void)
{
}

on a machine that's compatible with them (portability is not an issue for the assignment).

However, I'm noticing the values generated aren't too random. When generating 20 bytes, about 15 of them don't show up on the screen, and when pointing it to file.txt, I see they are the control character ^@.

What is the proper way to seed this function?




How to fix this problem when generating a pseudorandom number in Python?

import hashlib
import time
def random():
    hashtime = str(int(time.time() * (10 ** 6)))
    encoded = hashlib.new("sha3_512", hashtime.encode())
    decoded = int(encoded.hexdigest(), 16)
    
    dcsmall = decoded / (10 ** (len(str(decoded))))
    return (dcsmall)

I tried this code to simulate the function random.random() without the module random. I wanted to generate a random number between 0 and 1 but this code doesn't output numbers between 0 and 0.1 because of the length of "decoded" and I have no idea how to fix it. Please don't make huge changes to my code but instead give me an idea how to solve the problem. Thank you




How to randomly sample balanced pairs of rows from a Pandas DataFrame

Suppose I have a dataset which contains labels, filenames, and potentially other columns of metadata. The dataset may have as many as 200,000 examples. I've provided a snippet below that simulates this setup.

import pandas as pd
import numpy as np
import IPython.display as ipd

size = 20000
df = []
rng = np.random.default_rng(0)
for i in range(size):
    l = rng.choice(('cat', 'dog', 'mouse', 'bird', 'horse', 'lion', 'rabbit'))
    fp = str(rng.integers(1e5)).zfill(6) + '.jpg'
    df.append((l, fp))
df = pd.DataFrame(df, columns=['label', 'filenames'])
ipd.display(df)

I would like to efficiently produce N randomly generated pairs of data, with the condition that the dataset is balanced between positive and negative pairs, e.g.,

# df_out would be of size "N"
df_out = pd.DataFrame([], columns=['label_1', 'label_2', 'filepath_1', 'filepath_2'])

Here I am defining a positive pair as one where label_1 equals label_2, and a negative pair as one where the two labels are not equal. So the goal is for df_out to contain roughly 50%-positive and 50%-negative pairs.

The first approach I tried works by sampling 2N rows from the DataFrame, then collapses them into pairs.

N = 20
ii = rng.permutation(np.arange(N*2)%len(df))
func = lambda x: x.dropna().astype(str).str.cat(sep=',')
df_out = df.iloc[ii].reset_index(drop=True)  # subsample 
df_out = df_out.groupby(df_out.index//2)  # collapse every two rows into one row
df_out = df_out.agg(func).reset_index(drop=True)  # use `func` to combine rows
for k in df.columns:
    df_out[[f'{k}_1',f'{k}_2']] = df_out[k].str.split(',', expand=True)
    del df_out[k]

So this works to make pairs of rows, but it doesn't take any consideration to positive or negative pairs.

# as one would expect, this percentage is not equal to 50%
print(sum(df_out.eval('label_1==label_2')) / N)



jeudi 23 février 2023

I want to unjumble a constantly jumbling string one letter at a time [closed]

I'm unsure how to make this unscramble to reveal a word, unscrambling one letter at a time from left to right

def jumble():
    letters = string.ascii_letters
    random_letters = ""
    for i in range(5):
        letter = random.choice(letters)
        random_letters += letter
    label.config(text=random_letters)
    window.after(25, jumble)

What I'm trying to do will be usefull in a seperate ciphering program I have, after a certain time (window.after(x, y), this will start unscrambling itself.




Generating random size of an array c++ [duplicate]

I made a class called Room and i need to generate an array with random size, but compiler says it needs a constant value. My code:

int randN(int from, int to) {
    return from + rand() % (to - from + 1);
}

void main() {
    srand(time(nullptr));
    
    int roomSize = randN(5, 13);
    const int rs = roomSize;
    Room raray[rs];

}

I tried to write:

const int roomSize(randN(5,13));

but it doesn't work.




How to generate the same random number sequence within each thread

I have a code that converts an image with 32 output layers, from an AI segmentation model output, into a single layer where each pixel in each layer has a probability proportional to its score to make to this single layer. In order to do that, I need to generate a random float number to figure out each of the 32 layers is going to be the winner.

When I run this code in a single thread, it generates the same output every single time. However, when I use it with OMP (to make it faster), it generates a different output every time, even when I make the random number generator private to each thread and initialize it with the same seed (for each row). I also tried to hardcode the seed to 0 and it did not solve the problem. It is like one thread is interfering with the sequence of the numbers in the other one.

I need this code to generate consistently the same result every time in order to make it easier to test the output. Any idea?

    cv::Mat prediction_map(aiPanoHeight, aiPanoWidth, CV_8UC1);
#pragma omp parallel for schedule(dynamic, aiPanoHeight/32)
    for (int y=0;y<aiPanoHeight;++y){
        static std::minstd_rand0 rng(y);
        std::uniform_real_distribution<float> dist(0, 1);
        for (int x=0;x< aiPanoWidth;++x){
            float values[NUM_CLASSES];
            // populate values with the normalized score for each class, so that the total is 1
            float r = dist(rng);
            for (int c = 0; c < NUM_CLASSES; ++c)
            {
                r -= values[c];
                if(r<=0) {
                    prediction_map.at<uchar>(y, correctedX) = int(aiClassesLUT[c]); // paint prediction map with the corresponding color of the winning layer
                    break;
                }
            }
        }
    }




How do I manipulate random.randint( ) in Python to give a particular number in the range I defined in the parentheses?

I am creating a dice game for fun, where you roll two dice. To win, you have to get 6 on both die. Now, I have been rolling my game for the past 10 minutes and I am yet to get a win. That's when I realize there is so much possible combinations between two die when rolled at random. This will be incredibly boring to players.

So suppose I want to rig each die to randomly show 6 a little more often, how do I do it?

Please note that I am writing in Python, using the random module.




mercredi 22 février 2023

Processing adding random colors to SVG files in a random grid layout

I'm inserting a few SVG files in a grid layout and want the colors to be random. But they're only applying random color to the square SVG object itself, not the shapes within the SVG. Is this something that I needed to embed in the SVG file? I'm very new to this and feel like I'm trying to learn Latin.

Grid layout code:

HDrawablePool pool;
HColorPool colors;

void setup(){
size(400,1300);
H.init(this).background(#000000);
smooth();

colors = new HColorPool(#9EA2A2, #C7C9C7, #101820, #FCE300, #78BE20, #FE5000, #E03E52);

pool = new HDrawablePool(12);
pool.autoAddToStage()
  .add(new HShape("BlockQ.svg"))
  .add(new HShape("BlockX.svg"))
  .add(new HShape("BlockY.svg"))
  .add(new HShape("BlockZ.svg"))
 

  .layout(
    new HGridLayout()
    .startX(50)
    .startY(50)
    .spacing(100,100)
    .cols(3)
  )

  .onCreate(
    new HCallback() {
      public void run(Object obj) {
        HShape d = (HShape) obj;
        d
          .enableStyle(false)
          .strokeJoin(ROUND)
          .strokeCap(ROUND)
          .strokeWeight(1)
          .stroke(#000000)
          .anchorAt(H.CENTER)
          .rotate( (int)random(4) * 90 );
        ;
        d.randomColors(colors.fillOnly());
     }
   }
 )
 .requestAll()
;

H.drawStage();
}

Code for one of the SVG files:

import processing.svg.*;

void setup() {
   size(100, 100, SVG, "BlockO.svg");
}

void draw() {
  //size (100,100);
   background (255);
   line (0,0,0,100);
   line (0,0,100,0);
   line (100,0,100,100);
   line (0,100,100,100);

  // Exit the program
  println("Finished.");
  exit();
}

I was hoping the random color would appear within the SVG files, like the little triangles and such.




Generate unique file names in Laravel

In Laravel when using the storage Facade to save file uploads it uses Str::random(40) under the hood to auto generate unique filenames. Source https://github.com/laravel/ideas/issues/161

I have a requirement for a file upload site to ensue uploaded files have unique filenames.

So my question is Str::random(40) adequate in terms of collision proof or should I be using Str::uuid instead to generate unique filenames?




How to make that there aren't identical values ​next to each other while randomizing and disable entry in text field?

So I have this Python code that generates pseudorandom numbers with tkinter GUI:

def ButClick():
    try:
        MinNum = int (txt1.get())
        MaxNum = int (txt2.get())
        Num = int (txt3.get())
    except ValueError:
        messagebox.showerror("ValueError", "Check if you typed in correct! You can't type in text! Numbers only!")
    else:
        Nums = ''
        if MinNum <= MaxNum:
            i = 0
            while i < Num:
                numOne = randint(MinNum,MaxNum)
                Nums = Nums + " " + str(numOne)
                i += 1
            scr.insert(INSERT, str(Nums) + "\n")
        else:
            messagebox.showerror("NumError!", "Your Min Number can't be higher than your Max Number or vice versa!") 
    pass

def remove_text():
    scr.delete(1.0,END)

def confirm():
    answer = askyesno(title='Exit',
                    message='Tired of randomness?') 
    if answer:
        root.destroy() 

root = Tk()
root.title("Hey")
message = Label(root, text= "Welcome to random numbers generator! Developed by Yaroslav Poremsky")
message.pack()

root = Tk()
root.title("Random is so random :)")

lb1 = Label(root, bg = "green", text = "Min number") 
lb1.grid(
    row = 0, 
    column = 0, 
    pady = 10, 
    padx = 10) 

txt1 = Entry(root, width = 30) 
txt1.grid(
    row = 0,
    column = 1,
    pady = 10,
    padx = 10)

lb2 = Label(root, bg = "orange", text = "Max number")
lb2.grid(
    row = 1,
    column = 0,
    pady = 10,
    padx = 10)

txt2 = Entry(root, width = 30)
txt2.grid(
    row = 1,
    column = 1,
    pady = 10,
    padx = 10)

lb3 = Label(root,  bg = "pink", text = "Number")
lb3.grid(
    row = 2,
    column = 0,
    pady = 10,
    padx = 10)

txt3 = Entry(root, width = 30)
txt3.grid(
    row = 2,
    column = 1,
    pady = 10,
    padx = 10)

but = Button(root, width = 15, height = 2,  bg = "magenta", text = "Generate", command = ButClick) 
but.grid(
    row = 3,
    column = 0,
    columnspan = 2, 
    pady = 10,
    padx = 10)

but_remove = Button(root, width = 15, height = 2, bg = "crimson", text = "Remove", command = remove_text) 
but_remove.grid(
    row = 3,
    column = 1,
    columnspan = 2,
    pady = 15,
    padx = 20)

but_quit = Button(root, width = 15, height = 2, bg = "violet", text = "Quit", command = confirm) 
but_quit.grid(
    row = 3,
    column = 3,
    columnspan = 2,
    pady = 15,
    padx = 20)
scr = scrolledtext.ScrolledText(root, bg = "grey", height = 10) 
scr.grid(
    row = 4,
    column = 0,
    columnspan = 2,
    pady = 10,
    padx = 10)

root.mainloop()

  1. The problem is, when I enter the Min number of 0, Max number of 1 and Number of 12, sometimes identical values stand next to each other(Picture 1) Picture 1 How can I make that there aren't identical values ​​next to each other while randomizing?
  2. The second thing is, I can type in this box(Picture 2) Picture 2 How can I disable entry in this field?

I've seen that it is possible to disable entry via creating a button, but can I make it without creating it somehow?




mardi 21 février 2023

What is the time complexity of my shuffled number array generator?

I have the following function, written in JavaScript:

function genNumArray(n) {

    let answer = []

    while (answer.length < n) {
        let randNum = Math.floor(Math.random() * n + 1)

        if (!answer.includes(randNum)) {
            answer.push(randNum)
        }
    }

    return answer
}

I want to know the time complexity of this code expressed in Big O notation, assuming that my function's n is the growing term that tends to infinity. When you answer this question, please include an explanation for your answer, which I hope would include some statistics-based models or reasoning.

Supplementary Thoughts:

This function takes a positive integer, n, and returns an array of length n with the values 1 through n as its contents, ordered at random.

I am aware that the given function code is not the most efficient way of implementing the function description I just gave.

For those of you less familiar with JavaScript, Math.random creates a pseudo-random, floating point number greater than or equal to 0, but less than 1. See the docs for more info.

In regards to your answer to this question, I would prefer you pretend that JavaScript's Math.random creates "true randomness" rather than considering JavaScript or computer architecture shortcomings that make the randomness less pure (although, any thoughts on how the difference effects time complexity are welcome). However, I'm unsure of whether this would change the answer either way.

For any sticklers out there who say "well, Math.random has a finite amount of decimal places, so your function fails to create a random, equal distribution of numbers when n is very large", let's also pretend that any given result of Math.random somehow doesn't have a finite amount of decimal places.




Why is this error(list index out of range) generated and how to fix it?

I run this program several times, sometimes it doesn't give an error, sometimes it gives this error.I wonder why this is happening? and how to fix it?

I run this program in Pycharm,and I use archlinux.

Below is my entire code:

#!/usr/bin/env ipython3

import random


class Animal:
    """a baseclass for special animal."""

    def __init__(self, species, priority):
        self._species = species
        self._priority = priority

    def get_species(self):
        return self._species

    def get_priority(self):
        return self._priority

    def animal_compete(self, other):
        if self.get_priority == other.get_priority:
            return False
        elif self.get_priority > other.get_priority:
            return True


class Bear(Animal):
    """Bear class."""

    def __init__(self):
        super().__init__("bear", 1)


class Fish(Animal):
    """Fish class."""

    def __init__(self):
        super().__init__("fish", 0)


class Ecosystem:
    """Ecosystem class."""

    def __init__(self, scale=100):
        self._animals_index = []
        self._None_index = [j for j in range(scale)]
        self._river = [None] * scale

    def get_animals_index(self):
        return self._animals_index

    def get_river(self):
        return self._river

    def get_None_index(self):
        return self._None_index

    def add_animal(self, animal_instance, index=None):
        """if index = None,add a new animal randomly into the river, otherwise put the animal into the index."""
        if index is None:
            new_animal_index = random.choice(self.get_None_index())
            if animal_instance.get_priority() == 0:
                new_fish = Fish()
                self._river[new_animal_index] = new_fish
            if animal_instance.get_priority() == 1:
                new_bear = Bear()
                self._river[new_animal_index] = new_bear
            self._None_index.remove(new_animal_index)
            self._animals_index.append(new_animal_index)
        else:
            self._river[index] = animal_instance
            self._None_index.remove(index)
            self._animals_index.append(index)

    def delete_animal(self, index):
        """delete the animal."""
        self._animals_index.remove(index)
        self._river[index] = None
        self._None_index.append(index)

    def replace_animal(self, animal1_index, animal2_index):
        """replace animal2 with animal1"""
        self._river[animal2_index] = self._river[animal1_index]
        self._animals_index.remove(animal1_index)

        self._river[animal1_index] = None
        self._None_index.append(animal1_index)


if __name__ == "__main__":
    test_ecosystem = Ecosystem()
    for i in range(20):
        test_ecosystem.add_animal(Fish())
        test_ecosystem.add_animal(Bear())
    loop_count = 0
    animals = sorted(test_ecosystem.get_animals_index())
    none_index = sorted(test_ecosystem.get_None_index())
    while len(animals) < 90:
        for animal in animals:
            river = test_ecosystem.get_river()
            step = random.randint(-1, 1)
            if step != 0:
                if 0 < animal + step < len(test_ecosystem.get_river()):
                    if river[animal + step] is None:
                        test_ecosystem.add_animal(river[animal], animal + step)
                    if isinstance(river[animal + step], Animal):
                        if (
                            river[animal].get_priority()
                            > river[animal + step].get_priority()
                        ):
                            test_ecosystem.replace_animal(animal, animal + step)
                        elif (
                            river[animal].get_priority()
                            == river[animal + step].get_priority()
                        ):
                            test_ecosystem.add_animal(river[animal])
        animals = sorted(test_ecosystem.get_animals_index())
        none_index = sorted(test_ecosystem.get_None_index())
        loop_count += 1


I tried googling when list out of range error happens, and learned that this error is produced when the index is not in the list, but I am more confused why random.choice() produces an value that is not in the list?




lundi 20 février 2023

how to generate sample data ( 1 < x1^2 + x2^2 < 2 ) in python [closed]

Hi I want to generate 100 random sample data for x1 and x2 with numpy library,that satisfy below conditions. ( 1 < x1^2 + x2^2 < 2 )




how to fix openssl random generator error?

we have a problem with openssl 1.1.1n (that compiled by nginx --with-openssl flag), sometimes we see some errors in nginx logs, but we can not regenerate to debug, errors content is : random number generator:rand_pool_add:internal error anyone have an idea?

rand_pool_add() returns 0 in the following cases: 1.If there's an error, i.e. too much data is added for the given pool. 2.If there isn't enough entropy.




How does the seed function operate

Let’s say we have a year record and I want to sample round a year and I choose a seed value of 22; does this mean it takes the first value and goes to the 22nd value and picks and continue just that way?




How would I generate random numbers that satisfy a specific ratio in C++?

Consider this piece of contrived code in the context of generating trees for a game:


// Pretend there's some code somewhere that associates the 0-100 number to its corresponding size.
enum class TreeSize : uint32_t
{
    Small, // 0-9
    Medium, // 10-60
    Large,// 61-90
    ExtraLarge, // 91-100

};

// returns tree size
int GenerateTree()
{
    std::random_device rd;
    std::mt19937_64 mt(rd());
    std::uniform_int_distribution<int32_t> dist(0, 100);

   return dist(s_mt);
}

Let's say I want to generate 1000 trees, but bound to a specific ratio of tree sizes. For example:

  • Small trees: 15%
  • Medium trees: 30%
  • Large trees: 40%
  • Extra large trees: 15%

How would I do that? Is there something off the shelf that accomplishes this? Surely this is a problem many people have had to contend with before, yeah?




dimanche 19 février 2023

nnet() different results in different operating systems (Windows vs Linux)

I am working with R scripts specifically for ANN models using the nnet() package. I run my scripts on my local computer (Windows) and my colleague runs the same R scripts on his computer (Docker -> Linux). We get similar but different results for the ANN models. There are large differences in the neuron weights, and slight differences in fitted values and predictions.

We are setting the same seed just before the nnet() function so we are on the same randomization set. Additionally, I have set the initialization weights ("Wts") to be the same value (1) for all coefficients, biases etc for the model. I have also tested the randomization of both systems by setting the seed and doing a random sample(), which returns the same results.

I have also tested our model inputs (spectra) and everything is 1:1 unity.

We build a number of models including PLS, GPR and SVR (with grid search parameters) and we always get the same result. These models do not utilize randomization so the assumption is that the randomization within the ANN models is the cause for the difference.

We have also updated R to the most recent version (4.2.2) and updated all of our packages including nnet() and dependencies from the same repository.

I am at a loss on what the difference could be from, my last thought is the difference between operating systems (me = Windows, he = Linux). Could there be another difference that could affect the nnet() function such as rounding (as the model input variables are in low magnitude decimals) or ordering differences between the operating systems?

The expectation is to have complete unity across ANN models (weights, fitted values and predictions).

Sorry for no reproducible code, the models work on high dimensional data (spectra > 1000 variables, n > 1000). I can share our nnet() function code:

  cv_wts <- rep(1,cv_wts_n)
  
  set.seed(seed)
  cal <- nnet(TV ~ NIR, data = training_dat, size = n, decay = d, Wts = cv_wts,
              linout=TRUE, maxit = 1000000, MaxNWts = 1000000, trace = FALSE)



Variable undeclared with random in c

I don't why it gives me l and col as undeclared inside this function.

I had written srand(time(null)) in main and I have already used rand in other variable in main and in this function, it's the second time using it.

void joueur_ordinateur(char jeton, int *a) {
  srand(time(NULL));
  do {
    int l = rand() % 9;
    int col = rand() % 9;
  } while (matrice[l][col] == '.');

  matrice[l][col] = jeton;
  for (int i = 0; i < DIMENSION; i++) {
    for (int j = 0; j < DIMENSION; j++)
      copie[i][j] = matrice[i][j];
  }

  for (int i = 0; i < DIMENSION; i++) {
    for (int j = 0; j < DIMENSION; j++) {
      capture_chaine(i, j, jeton, a);
    }
  }

  printf("\n");
}



c++ getline fails to operate with spaces and 2-digit long input [duplicate]


#include <iostream>
#include <random>
#include <fstream>
#include <string>

        using namespace std;

        void converter(string klucz)
        {
            string failename;
            string buffer;
            string tekst;
            string dummy;
            int mode = 0;
            cout << "\nNazwa pliku z rozszerzeniem: ";
            getline(cin, failename);
            cout << "\n\nTYP OPERACJI:\n--------------------------------\n1. Jednoliniowa konwersja\n2. Wieloliniowa konwersja (plik)\n--------------------------------\n\n";
            cin >> mode;
            cin.ignore();
            if (mode == 2)
            {
                fstream peik;
                peik.open(failename);
                if (peik)
                {
                    std::cout << "Converting...\n";
                }
                else
                {
                    peik.close();
                    fstream plik;
                    std::cout << "File created. Input any text and press enter when ready." << endl;
                    bool ended = false;
                    int i = 1;
                    plik.open(failename, std::ios_base::app);
                    while (ended != true)
                    {
                        string appendtext;
                        cout << i << "> ";
                        getline(cin, appendtext);
                        if (appendtext == "[end]")
                        {
                            ended = true;
                        }
                        else
                        {
                            plik << appendtext + "\n";
                        }
                        i++;
                    }
                    plik.close();
                }
            }
            if (mode == 1)
            {
                string ciagwyrazow;
                cout << "\nKONWERTUJ: ";
                getline(cin, ciagwyrazow);
                if (ciagwyrazow.length() - 1 > 1)
                {
                    for (int i = 0; i <= ciagwyrazow.length() - 1; i++)
                    {
                        cout << ciagwyrazow[i] << " ";
                    }
                    for (int i = 0; i <= ciagwyrazow.length() - 1; i++)
                    {
                        for (int j = 0; j <= 94 - 1; j++)
                        {
                            if (j == (int)ciagwyrazow[i] - 32)
                            {
                                cout << klucz[j];
                            }
                        }
                    }
                    getline(cin, buffer);
                }
                else
                {
                    for (int j = 0; j <= 94 - 1; j++)
                    {
                        if (j == (int)ciagwyrazow[0] - 32)
                        {
                            cout << klucz[j];
                        }
                    }
                    getline(cin, buffer);
                }
            }
            else if (mode != 1 && mode != 2)
            {
                cout << "\nZłe dane.\n";
            }
        }
        int main()
        {
            std::cout << "KLUCZ: ";
            //key digits
            char characterenc[94]{};
            //initalize the table
            for (int i = 0; i <= 94 - 1; i++)
            {
                characterenc[i] = 0;
            }
            //IsCharGen = has given char generated?
            bool IsCharGen = false;
            //seed the generator
            random_device rd;
            mt19937 gen(rd());
            //generator range
            //32 = the smallest possible number
            //126 = highest possible number
            uniform_int_distribution<> distr(32, 126);
            for (int i = 0; i <= 94 - 1; i++)
            {
                //generate the number
                int liczbagenerowana = distr(gen);
                //check if the value has been generated already
                for (int j = 0; j <= 94 - 1; j++)
                {
                    //scenario = char has been generated before
                    if (liczbagenerowana == (int)characterenc[j])
                    {
                        IsCharGen = true;
                    }
                }
                if (IsCharGen == true)
                {
                    i--; //rerun the cycle for this digit
                }
                else
                {
                    characterenc[i] = liczbagenerowana; //value hasn't been generated
                }
                IsCharGen = false;
                //std::cout the key digit by digit
            }
            string klucz;
            for (int i = 0; i <= 94 - 1; i++)
            {
                klucz = klucz + characterenc[i];
            }
            std::cout << klucz <<endl;

            // converter
            converter(klucz);
        }

This code is a greater piece of a cipher changing characters to values found in klucz variable, randomized every launch. Ex.

Klucz: 'sN lou*n(/CYcw$;8PZ)y17a?M>x,~0Li2U%9k}XgAK=G^3H[@p".z-h:_]etQSqW#&RFdV<|m6b5rDBvT!4O`+JEfj{

"!" after conversion: s "!!!" after conversion: sss "! !" after conversion: s~s

\n found in sentences should also be treated as text

Value of given symbol is present in ciagwyrazow[x], where x = (int)char - 32.

Now let's focus on mode 1 (single-line conversion). Everything works just fine as long as user input's length isn't 2 (where only one character is output at the end) or when the sencence has spaces (only the piece before the first one gets converted, rest is discarded).

Error consequences differ from code studios. When started on onlinegdb.com, it makes a loud noise (see ascii elements 0-9) and displays some partially readable gibberish, with some root directory of its at the end, not featuring even a bit of expected output. (all tries)

Visual Studio Code outputs user input before conversion and then outputs converted sentence, everything seems to work normally except spaces, which are never modified.

Visual Studio outputs only the first converted piece if spaces are present, its IntelliSense doesn't detect errors in the code (Studio Code has the same problem too), and outputs only the first char if length of the sentence is 2.

I believe the problem resides in getlines, yet i wasn't able to properly debug my faulty concotion, as gdb debugger skipped user input no matter what I've tried and then proceeded to fail as described above, microsoft products' debuggers didn't work for me, making me unable to trace the problem.

So far I've tried adding namespaces (std) before cins and getlines themselves, using cin.ignore() in prolly every possible way and done other experiments on these i don't remember because of me being overloaded with information back then and read multiple articles about possible causes, including one that says it's dangerous to use cins and getlines in correlation (that's why cin.ignore() are pressent in the code). But to no avail, the program's behavior didn't change, no matter what I've tried. I'm out of ways how to fix this.




r generate random poisson values

How do I randomly generate 50% 1s, 30% 2s, 15% 3s and remaining 4s ?

Finally when I do a table , table(x, useNA = "ifany"), it should be

                         1      2      3    4
                         50     30     15   5

I am not sure how to use rpois to generate this.




samedi 18 février 2023

Python flipping x coins x times using loops but receiving odd output

I'm new to python and coding in general. I have an assignment for class to write a program that uses a loop to flip multiple coins multiple times. The code must:

  1. ask for the number of coins and how many times to flip those coins.
  2. Must ask again if the input is less then 0.
  3. Print the result of flipping each coin the specified number of times and must be random.
  4. Then print the total number of heads and tails. I do have to use random so suggestions of other modules or better ways to achieve randomization aren't something I'm looking for, thank you.

The output should look something like:

How many coins do you want to flip? 2
How many times do you want to flip each coin? 2

Coin 1
Flip: 1; Result: Heads
Flip: 2; Result: Tails

Coin 2
Flip: 1; Result: Tails
Flip: 2; Result: Heads

There were 2 Tails in total
There were 2 Heads in total

Here's what I tried: (I'm having to use my phone due to some irl problems to ask this so if the format is off I'm sorry!)

import random

heads = 0
tails = 0

coins = int(input("How many coins: "))

while coins !="":
    if coins \<= 0:
        print ("Invalid input")
        coins = int(input("How many coins: "))
    else:
        flips = int(input("How many times to flip: "))
        if flips \<= 0:
            print ("Invalid input")
            flips = int(input("How many times to flip: "))
        else:
            for n in range (0, coins):
                for i in range (0, flips):
                    print (" ")
                    print ("Coin %0d" %n)
                    print (" ")
                    n = coins + 1
                    for flips in range (0, flips):
                        flip = random.randint(0,1)
                        if flip == 0:
                            heads += 1
                            print ("Flips: %0d;" %i, "Result: heads")
                        else:
                            tails += 1
                            print ("Flip: %0d;" %i, "Result: tails")
                        i = flips + 1
print ("total heads:", heads)
print ("total tails:", tails)
break

What I get varies wildly by the numbers I input. I might flip 4 coins 3 times and it flips 6 coins. Or 1 coin 3 times and it flips 6 coins. But 1 coin 2 times flips 1 coin 2 times. The numbers counting the coins and flips also don't work right. I get results like:

Coin 0
Flip: 0; Result: Tails
Flip: 3; Result: Heads

Coin 2
Flip: 1; Result: Tails
Flip: 3; Result: Tails.

I'm stumped and at this point all the code looks like abc soup. Any help is appreciated.




How to take a random sample from mutliple groups with unequal sample sizes (in R)

I have a dataset that I want to randomly sample up to 6 rows for each animal ID per day. Not every animal ID was sampled each day, and some animals were sampled less than 6 times per day. For example - if an animal was only sampled 2 times in a given day, then I want to retain both those samples. I want to retain all the info in the sampled row.

in the image:

  • New_ID is the animal Id
  • New_Date_Hour is the hour of the day (this is the variable that I want to randomly sample 6 times per day)

There are 13 different animal IDs

[Image of Example data]

I have tried a few different approaches but without success.




how to correctly replace bytes with memset?

I need to patch first 23 bytes of 32 bytes randomly generated by the rand256 function but it seems memset isn't correctly patching.

0000000000000000000000C90F4094919B9FAE4616149C0FDC61E7C1F318E234

as you can see, memset added only 23 zeroes of which i am expecting 46 zeroes. Now i am wondering if there is something like zfill that can correctly fill 23 bytes with zeros.

 static uint256_t rand256(struct seed *seed)
{
    seed->counter++;
    return sha256(seed, sizeof(struct seed));
}

static uint256_t rand256_and_mask(struct seed *seed)
{
    uint256_t r = rand256(seed);
    memset(&r, 0x000, 23);
    return r;
}

struct seed
{
    uint256_t seed;
    uint128_t counter;
};

static inline uint256_t sha256(const void *data, size_t len)
{
    secp256k1_sha256_t cxt;
    secp256k1_sha256_initialize(&cxt);
    secp256k1_sha256_write(&cxt, (uint8_t *)data, (int)len);
    uint256_t res;
    secp256k1_sha256_finalize(&cxt, (uint8_t *)&res);
    return res;
}

how can i correctly patch first 23 bytes?




How would I stop receiving a new RandomNumber within this code? [closed]

I am trying to encode a string of words the user gives using ASCII. Doing it by each character. But the random number keeps changing insetead of using the same number to encode.

I want all the Uppercase letters to be the same number/character.

    const rand = generateRandom(65, 90);
    const randomNum = rand;
    function generateRandom(min, max)
    {
         let rand = Math.floor(Math.random() * (max - min) + 1) + min;
         return rand;
    }
      function encodeIt()
      {
           document.getElementById("message").innerHTML = ("<h2>&nbsp;</h2>");
           var msg = prompt("Enter your message." , " ");
           let newmsg = " ";
           var upCaseCode = 155;
           var newCode = 0;
           var lowCaseCode = 219;
           var specialCode = 3;
     
       
           //the loop encodes each letter in the message string
              for (var j = 0; j < msg.length; j++)
              {
  
           //check for lowercase letters and encode them
         if ((msg.charCodeAt(j)>=97) && (msg.charCodeAt(j)<=122)) 
                 {
                     newcode = (lowCaseCode - msg.charCodeAt(j));
                 }
                else
   //check for numbers and special characters and encode them33.                 
   if (((msg.charCodeAt(j)>90) && (msg.charCodeAt(j)<97)) || (msg.charCodeAt(j)<65))
                 {
                      newcode = (msg.charCodeAt(j) + specialCode);
                 }
  //add each encoded character to the new message
       newmsg = newmsg + " " + String.fromCharCode(newcode);
       }
  //display the encoded message on the web page
       document.getElementById("secret").innerHTML = ("<h2>" + newmsg + "</h2>");
  //decide if original message should be shown
       var choice = prompt("Do you want the special key? Yes or No?", " ");
       if ((choice.charAt(0) == 'y') || (choice.charAt(0) == 'Y'))
       {
            document.getElementById("message").innerHTML  = ("<h2>" + randomNum + "</h2>");
        
        }
  }

  //check for upppercase letters and encode them
            if ((msg.charCodeAt(j)>=65) && (msg.charCodeAt(j)<=90))
            {
                 newcode = (**randomNum **- msg.charCodeAt(j));      
            }
            else



vendredi 17 février 2023

Python 3.10.10 can't run old python repository

I can't run this old python repository with Python 3.10.10 When i run it displays this error

Traceback (most recent call last):
  File "C:\Users\user\OneDrive\Desktop\file\testsimp.py", line 7, in <module>
    print (namegen.get_random_name("any"));
  File "C:\Users\user\OneDrive\Desktop\file\German_Name_Generator_master\german_name_generator.py", line 68, in get_random_name
    name=get_random_from_list(names_w)
  File "C:\Users\user\OneDrive\Desktop\file\German_Name_Generator_master\german_name_generator.py", line 50, in get_random_from_list
    assert(l!=[] and l is not None)
AssertionError

My python code is (python version 3.10.10):

import string;
import json;
import randompassgen;
import random
import German_Name_Generator_master.german_name_generator as namegen

print (namegen.get_random_name("any"));

Expected: Name Surname




Check if my array has consecutive similar letters randomly generated

I have to generate 200 random numbers (function has to do it) separated by commas. It doesn't matter if they are repeated but it must not be consecutively. If they are consecutive, I have to replace it with a new letter generated randomly by my function. I am new to programming. I also cannot modify my function as a constraint.

For the sake of the output, I am generating 10 numbers instead of 200.

This is my working code. I just can't manage to add a new random letter where I deleted a duplicate.

const characters = 'abcdefghijklmnopqrstuvwxyz';

function getRandomLetter() { return characters.charAt(Math.floor(Math.random() * characters.length)).toUpperCase(); }

var randomLetters = [];

for (let j = 0; j < 10; j++) { randomLetters [j] = getRandomLetter(); }

document.write("10 random letters: ", randomLetters );


let uniqueArr = [];

for(let i of randomLetters) {
    if(uniqueArr.indexOf(i) === -1) {
        uniqueArr.push(i);
    }
}
document.write("10 random letters without duplicates: ", uniqueArr);



DEVC++ is showing a duplicate code in the output window, while other C++ give me the right ouput. What am I doing wrong? (Random Number Generator)

As default, I use DevC++ to write programs for my computer science class. I am really new to all of this. For this program, we are told to use a random number generator to display values using loops. We used for, while, and do..while loops. I was able to do the for loop (Set1) and while loop (Set2) with no struggle. Once I got to do.. while loop (Set3), and finished it, the output window shows a repeat of Set 2, which is the while loop. I ran it through onlinegdb and it gave me the right output. Is it something with DevC++ or is there something wrong in my code that I haven't been able to see?

The coding for my program:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>

using namespace std;

//declare constant doubles for the program

#define NUM_ONE 30
#define MAX_NUM_TWO 75
#define MAX_NUM_THREE 155
#define MIN_RAND_DOUBLE_VAL 0.0
#define MAX_RAND_DOUBLE_VAL 100.0
#define VAL_DISPLAY 7

int main()
{
    //input the seed value of 12 into the random number generator

    srand(12);

    //declare integer values

    int random_num;
    int cnt;
    int per_line;

    per_line = 0;

    //start the random number generator for the first set

    cout << "Set 1 -- " << NUM_ONE << " values" << endl;

    for (cnt = 1; cnt <= NUM_ONE; cnt++) {
        random_num = rand();

        cout << setw(13) << random_num;
        per_line++;

        if (per_line % VAL_DISPLAY == 0) {
            cout << endl;
        }
    }

    cout << endl
         << endl;

    //form the formula to start the random number generator for the second set (1-75)

    int random_num2;

    random_num2 = rand() % MAX_NUM_TWO + 1;

    //start the random number generator for the second set

    cout << "Set 2 -- " << random_num2 << " values" << endl;

    int cnt2;
    int per_line2;
    cnt2 = 1;
    per_line2 = 0;

    while (cnt2 <= random_num2) {
        random_num = rand();
        cnt2++;

        cout << setw(13) << random_num;
        per_line2++;

        if (per_line2 % VAL_DISPLAY == 0) {
            cout << endl;
        }
    }

    cout << endl
         << endl;

    //start the random number generator for the third set

    int random_num3 = rand() % MAX_NUM_THREE + 1;

    cout << "Set 3 -- " << random_num3 << " values" << endl;

    double double_random_num;
    int cnt3;
    int per_line3;
    cnt3 = 1;
    per_line3 = 0;

    do {
        double_random_num = MIN_RAND_DOUBLE_VAL + (rand() / (RAND_MAX / (MAX_RAND_DOUBLE_VAL MIN_RAND_DOUBLE_VAL)));

        cout << fixed << setprecision(5) << setw(13) << double_random_num;
        cnt3++;
        per_line3++;

        if (per_line3 % VAL_DISPLAY == 0) {
            cout << endl;
        }
    }

    while (cnt3 <= random_num3);

    cout << endl;

    return 0;
}

On DevC++ the output is supposed to look like this:

Set 1 -- 30 values
 77     5628     6232   29052   1558   26150   12947
 29926  11981   22371   4078   28629   4665     2229
 24699  27370    3081   18012   24965   2064    8285
 21054  5225    11777   29853   2956   22439   3341
 31337  14755
Set 2 -- 65 values
 24855   4173   32304    292   5344   15512   12952
 1868   10888   19581   13463  32652   3409   28353
 26151  14598   12455   26295  25763   26040   8285
 27502  15148   4945   26170   1833    5196    9794
 26804  2831    11993   2839   9979   27428    6684
 4616   30265   5752   32051   10443   9240    8095
 28084  26285   8838   18784   6547    7905    8373
 19377  18502   27928  13669   25828   30502  28754
 32357   2843   5401   10227   22871  20993    8558
 10009 6581
Set 3 -- 87 values
 39.08811   14.20026   75.05417   65.71551   28.70876   20.87466   92.68166
 7.11081    0.00916    85.52507   67.95251   58.98312   55.28123   55.23850
 47.74316   66.31062   52.77261   25.62334   84.13038   6.10981    11.68859
 38.34346   4.33363    90.12421   66.59139   30.37812   25.38835   33.32011
 24.34767   75.70421   91.63793   53.89264   26.74642   9.94293    63.23130
 20.26124   71.88940   78.69503   33.71685   10.81576   97.50053    0.06714
 4.85549    1.96539    79.29014   82.14972   96.79250   50.13276   47.45933
 85.93097   21.68950   83.30638   74.52010   74.41633   98.99594   67.82434
 37.49199   38.45637   40.39125   65.93829   7.67846    39.96399   82.64412
 49.83978   71.09287   63.16111   96.37745   87.76513   32.64565   14.43525
 48.99747   67.77551   7.29698    61.47343   49.82147   74.88327   51.20396
 52.24464   55.53758   87.09067   36.05152    4.54726   64.19263   6.03656

But it is giving me:

Set 1 -- 30 values
           77         5628         6232        29052         1558        26150        12947
        29926        11981        22371         4078        28629         4665         2229
        24699        27370         3081        18012        24965         2064        26890
        21054         5225        11777        29853         2956        22439         3341
        31337        14755

Set 2 -- 65 values
        24855         4173        32304          292         5344        15512        12952
         1868        10888        19581        13463        32652         3409        28353
        26151        14598        12455        26295        25763        26040         8285
        27502        15148         4945        26170         1833         5196         9794
        26804         2831        11993         2839         9979        27428         6684
         4616        30265         5752        32051        10443         9240         8095                             Set 2 -- 65 values
        24855         4173        32304          292         5344        15512        12952
         1868        10888        19581        13463        32652         3409        28353
        26151        14598        12455        26295        25763        26040         8285
        27502        15148         4945        26170         1833         5196         9794
        26804         2831        11993         2839         9979        27428         6684
         4616        30265         5752        32051        10443         9240         8095
        28084        26285         8838        18784         6547         7905         8373
        19377        18502        27928        13669        25828        30502        28754
        32357         2843         5401        10227        22871        20993         8558
        10009         6581

Set 3 -- 87 values
     39.08811     14.20026     75.05417     65.71551     28.70876     20.87466     92.68166
      7.11081      0.00916     85.52507     67.95251     58.98312     55.28123     55.23850
     47.74316     66.31062     52.77261     25.62334     84.13038      6.10981     11.68859
     38.34346      4.33363     90.12421     66.59139     30.37812     25.38835     33.32011
     24.34767     75.70421     91.63793     53.89264     26.74642      9.94293     63.23130
     20.26124     71.88940     78.69503     33.71685     10.81576     97.50053      0.06714
      4.85549      1.96539     79.29014     82.14972     96.79250     50.13276     47.45933
     85.93097     21.68950     83.30638     74.52010     74.41633     98.99594     67.82434
     37.49199     38.45637     40.39125     65.93829      7.67846     39.96399     82.64412
     49.83978     71.09287     63.16111     96.37745     87.76513     32.64565     14.43525



Better random shuffler in Rust?

I just made a program that creates a deck with 26 cards, splits it into 5 hands of 5 cards (discarding 1) and checks the poker combinations that are in those hands, if any.

Now, I also made another program that loops over this until a Royal Flush is found (which is very rare and should happen, on average, once every 600k or so decks).

And the strange thing is, once I added a counter to show how many decks it went through, it only said 150 - 4000 ! And I think it's the random shuffler's fault. I had made a similar program in Python, and that was checking approximately the correct amount of decks.

I used this, which should shuffle the deck in place:

fn shuffle_deck(deck: &mut Vec<Card>) -> () {
    deck.shuffle(&mut rand::thread_rng())
}

Apparently, it's not doing a very good job at being random. Can anybody help me in finding a better solution? Thanks in advance.

Edit: also, for anyone wondering, this is the Card struct:

pub struct Card {
    value: i32,
    suit: String
}



Bitwise convert a random to FP64 with vlues between 0 and 1

I am writing a laboratory data processing script in Excel VBA. The idea is acquiring improved random numbers using RtlGenRandom. The difficulty is that RtlGenRandom seeds the byte array in a byte-wise manner. So for reducing the time and keeping the "randomish" distribution, I want to apply a bitwise mask for reducing the number to [0 to 1] values. Below is a mnemonic explanation what I want to do regardless of exact implementation:

longlong buffer
longlong mask
double rand_val
RtlGenRandom(buffer,8)
buffer=not(buffer or mask)
rand_val=typeless_copy(rand_val, buffer)

So I got a little lost what should be the value of that mask for the said truncation of valuses. Bitwise, or in 0xHex.

I thought, it should be 0xC000 0000 0000 0000, but something is wrong.




jeudi 16 février 2023

How to create rows of non-duplicating strings from a list?

I want to create a 16X4 data frame with these coordinates as strings: (.1,.1),(-.1,-.1),(-.1,.1),(.1,-.1). But, I do want not there to be duplicates.

To put it another way, the script would output a 16X4 matrix/dataframe like this:

(.1,.1),(-.1,-.1),(-.1,.1),(.1,-.1)
(-.1,.1),(-.1,-.1),(.1,.1),(.1,-.1)
(-.1,-.1),(.1,.1),(-.1,.1),(.1,-.1) ...

In this way, I would get all the possible combinations of these four coordinates with no column duplicates.

I have been trying to brainstorm solutions. I know I can put them in an array and use random.choice() to randomly sample. But, I am not sure how to form this code in such a way where there will be no column duplicates and that patterns wont repeat.




Where is it better to store random_device/mt19937?

I have a function which makes use of randomness

void fun() {
    random_device rd;
    mt19937 gen(rd());
    uniform_real_distribution<double> dis(0.0, 1.0);
    // ...
}

And, as I suspect, I'll get poor random if it's call repeatedly and both rd and gen are created each time. Is it better to make these variables global/private fields of a class so they are not redeclared multiple times?




mercredi 15 février 2023

Is there a significant difference between using a in built random number generator vs using cryptographic random number generator?

I was going through the Crypto++ library RNG page and I was wondering is there any issues with using something like

 std::srand(std::time(nullptr)); //using the current time as seed 

compared to the one of the rng in crypto library?

I'm beginner in cryptography, but one possible argument could be that the crypto rng functions are collision resistant ? However, I'm not sure how much better/stronger they are quantitively




How to get the top 5 numbers from a 2D array of random numbers

I am pretty new to java and am just learning 2D arrays. I am trying to get the top 5 numbers to display from a random list. I think this could work but am not sure why I am getting an error. One other thing is that I cannot use the sort function.

Code here:

public static void main(String[] args) {
 //Random Number stuff
        Random rand = new Random();
        
        int[] large = new int [5];
        
        int max = 0, index;

        int[][] arrSize = new int [4][5];
        
        
        for (int i = 0; i < arrSize.length; i++) {
            for (int j=0; j< arrSize[i].length; j++) {
                arrSize[i][j] = rand.nextInt(89) + 10;
                
                System.out.print(arrSize[i][j] + " ");
            }
                
            System.out.println();
            
        }
        // Top 5
        for (int p = 0; p < 5; p++) {
        max = arrSize [0][0];
        index = 0;
        
        for (int i = 0; i < arrSize.length; i++) {
            for (int j = 0; j < arrSize[i].length; j++) {
                
                if (max < arrSize[i][j]) {
                    
                    max = arrSize[i][j];
                    index = i;
                    
                }
        }
        }
        
        
        large[p] = max;
        arrSize[index] = Integer.MIN_VALUE;  //Error here
        
            System.out.println("Highest Number: " + large[p]);
    }
 
}
}

Error text:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from int to int[]

    at secondAssignment.BiggestNumbersRectangular.main(BiggestNumbersRectangular.java:47)

I am not sure why I am getting an error, any help would appreciated. If anyone else has any answers for how I could get the top 5 in a different way that would also be appreciated.




prng,python, tkinter,need to change picture

I ran into this problem and don't know how to solve it. When I press the "generate" button(self.gen), my picture 11 changes to picture 22. BUT I need the image 11 to NOT change when the button is clicked and an error occurs(messagebox.showerror pops up) OR so that after closing the messagebox.showerror, picture 22 changes to 11

import tkinter
from tkinter import *  
from tkinter import messagebox, scrolledtext
from PIL import Image, ImageTk
from random import randint

class App:
    def __init__(self):
        self.window = tkinter.Tk()
        self.window.title("Генератор") 
        self.window['bg'] = '#FFF5EE'
        self.window.geometry('660x550') 
        self.window.resizable(False,False)

        self.lb1 = Label(self.window, text="Enter:", background='#FFF5EE', font = ("Comic Sans MS", 14))  
        self.lb1.grid(column=0, row=2) 

        self.lb2 = Label(self.window, text="min(1-999)",background='#FFF5EE', font = ("Comic Sans MS", 12))  
        self.lb2.grid(column=1, row=3) 

        self.lb3 = Label(self.window, text="max(1-999)", background='#FFF5EE', font = ("Comic Sans MS", 12))  
        self.lb3.grid(column=1, row=4) 

        self.lb4 = Label(self.window, text="amount of numbers", background='#FFF5EE', font = ("Comic Sans MS", 12))  
        self.lb4.grid(column=4, row=3)  

        self.txt2 = Entry(self.window,width=10, borderwidth=3)  
        self.txt2.grid(column=2, row=3)  

        self.txt3 = Entry(self.window,width=10, borderwidth=3)  
        self.txt3.grid(column=2, row=4) 

        self.txt4 = Entry(self.window,width=10, borderwidth=3)  
        self.txt4.grid(column=5, row=3)  

        self.scrolltxt = scrolledtext.ScrolledText(self.window, width=30, height=3, borderwidth=7, state='disabled')
        self.scrolltxt.grid(row=1, column=2, columnspan=3, padx=10, pady=10)

        self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
        self.photo = ImageTk.PhotoImage(self.image)

        self.gen = Button(self.window, width = 15, text="Generate", command = lambda:[self.clicked1(), self.gen1()])
        self.gen.grid(row=4, column=6)

        self.canvas = tkinter.Canvas(self.window, height=230, width=230)
        self.canvas.grid(row=0,column=4)
        self.image = self.canvas.create_image(0, 0, anchor='nw', image = self.photo)


        self.btn = Button(self.window, width = 15, text="Delete", command=lambda:[self.delete(),self.clicked2()])  
        self.btn.grid(column=6, row=5)

        self.exit = Button(self.window, width = 15, text="Exit", command=lambda: [self.clicked3(), quit()])
        self.exit.grid(column=6, row=6)

        self.i = Button(self.window, width = 8,text = "i", font = ("Eras Bold ITC", 10) , command = self.inf)
        self.i.grid(row = 0,column = 6)
 
        self.window.mainloop()


    def clicked1(self):
        print("clicked1")
        self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\22.png")  
        self.photo = ImageTk.PhotoImage(self.image)
        self.canvas.grid(row=0,column=4)
        self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)

    def gen1(self):
        try:
                MinNum = int(self.txt2.get())
                MaxNum = int(self.txt3.get())
                Num = int(self.txt4.get())
        except ValueError:
                messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
        else:
                Nums = " "
                if MinNum <= MaxNum:
                        i = 0
                        while i < Num:
                                numOne = randint(MinNum, MaxNum)
                                Nums = Nums + ' ' + str(numOne)
                                i += 1
                        self.scrolltxt.config(state="normal") # enable the text box 
                        self.scrolltxt.delete(1.0, END)
                        self.scrolltxt.insert(INSERT, str(Nums) + "\n") 
                        self.scrolltxt.config(state="disabled") # disable the text box
                else:
                        messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
        

    def delete(self):
        self.txt4.delete(0, END)
        self.txt3.delete(0, END)
        self.txt2.delete(0, END)
        self.scrolltxt.config(state="normal") # enable the text box 
        self.scrolltxt.delete(1.0, END)
        self.scrolltxt.config(state="disabled") # disable the text box

    def clicked2(self):
        print("clicked2")
        self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")  
        self.photo = ImageTk.PhotoImage(self.image)
        self.canvas.grid(row=0,column=4)
        self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)

    def clicked3(self):
        messagebox.showinfo("Це Звірополіс. Будь-хто може бути будь-ким.", "Хто сказав, що неможливе недосяжне?! Пошкодуйте цього дивака.")

    def inf(self):
        messagebox.showinfo("Info", "Лисичка замахалась")
    
app = App()

is it possible to implement this through tkinter?




My random number generator creates the same numbers

i = 0
x = 0
ranNum=[]
 
while x <= 5:
    while i <= 5: 
        ranNum.append(random.randint(1,5))
        i+=1
    print(ranNum)
    print(sum(ranNum)/len(ranNum),'\n')
    random.seed(10)
    x+=1

Hi I am currently playing around with while loops and ranNumber generator in python

But the 6 arrays I get all have the same numbers.

Ideally I would want a batch of 6 numbers each per array.




I need to find the top 5 numbers in a 2D array of random numbers

I am pretty new to java and am just learning 2D arrays. I need to get the top 5 numbers and have tried everything I could think of. I was able to get the highest number using an If statement but am not able to get past that. I figured that I would try and get the second number and then move on to the rest. My friend said he got it done using for loops but I also could not get that to work. Any help would be appreciated. Thanks!

This is the code that I used:

package secondAssignment;

import java.util.Random;

public class BiggestNumbersRectangular {

    public static void main(String[] args) {

        Random rand = new Random();

        int[][] arrSize = new int [4][5];
        
        
        for (int i = 0; i < arrSize.length; i++) {
            for (int j=0; j< arrSize.length; j++) {
                arrSize[i][j] = rand.nextInt(89) + 10;
                
                System.out.print(arrSize[i][j] + " ");
            }
                
            System.out.println();
            
        }
        
        int max = arrSize [0][0];
        int largeNumTwo = arrSize [0][0];
        
        for (int i = 0; i < arrSize.length; i++) {
            for (int j = 0; j < arrSize.length; j++) {
        if (max < arrSize[i][j]) {
            max = arrSize [i][j];

        if (largeNumTwo < max) {
            arrSize [i][j] = largeNumTwo;
            
        }
        }
        }
        }
        
        System.out.println("Highest Number: " + max);
        System.out.println("Second Highest Number:" + largeNumTwo);
  
 }
}

The output that I get is this:

45 10 44 70 
36 87 35 38 
68 14 30 79 
34 69 50 92 
Highest Number: 92
Second Highest Number:45

The code that I used for the second number is outputting only the first randomly generated number. I am not sure how to fix this.




mardi 14 février 2023

Sampling from truncated multivariate normal distribution in R given a frequency table of values (of one variable) needed

Let's assume we are interested in getting a set of individuals with following ages from a multivariate normal:

age n
25 20
30 43
35 66

The multivariate normal has following parameters:

mu = c(32, 170) #The first element is mean age and the second on is mean is height, but it plays no role here.
sigma = matrix(c(9, 10,
                10, 100), nrow = 2)

The samples (2 in this example) can be drawn using e.g. mvrnorm function from MASS package, i.e.:

MASS::mvrnorm(n = 2, mu = mu, Sigma = sigma)
         [,1]     [,2]
[1,] 32.50403 168.4208
[2,] 31.45465 153.8083

As I mentioned above and can be seen from the table, I would like to get 20 25-year-olds etc.

What would be the best way of doing this?

What initially came into my mind was to loop through the rows of the frequency table, and generate sample after sample, until I have as many individuals with the correct age, e.g.

frqtable = data.frame(age = c(25, 30, 35), n = c(20, 43, 66))

tempmatrix <- matrix(nrow = 0, ncol = length(mu))
for(row in 1:nrow(frqtable)) {
    rowtempmatrix <- matrix(nrow = 0, ncol = length(mu))
    while(nrow(rowtempmatrix) < frqtable[row, 'n']) {
        sample <- MASS::mvrnorm(n = frqtable[row, 'n'] - nrow(rowtempmatrix), mu = mu, Sigma = sigma) #I think, it is best to sample at least as many as still needed...
        rowtempmatrix <- rbind(rowtempmatrix, sample[sample[,1] >= frqtable[row, 'n'] & sample[,1] < frqtable[row, 'n'] + 1,]) #I define being 25 years old as >= 25, but < 26.
    }
    tempmatrix <- rbind(tempmatrix, rowtempmatrix)
}

However, this does not work (infinite while loop), and this solution is quite complex and ugly in general.

Any suggestions, how to get this done effectively and efficiently? I know, I could draw like one million samples, and reject the ones I do not need, but if I happen to have a mu vector and covariance matrix with more elements, this may sometimes need a bit too much memory.

(I do not know, if dplyr package could be utilized here, since as far as I know, it has no functions to filter matrices.)




I want to use the uuid generator but I have an error

I import this on my JS file :

import {v4 as uuidv4} from './uuid';

**and here is the error : **

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

need help pls




How could I pick a random item from a slice with bias towards one end of the slice using Go?

I understand one way to pick a random value from a slice in Go:

rand.Seed(time.Now().UTC().UnixNano())     
                                                
var db [500]string                         
log.Println(db[rand.Intn(len(db))])        

But how would I pick a random item from the slice, with a bias towards one end of the slice? For my use case I'll have a slice that grows over time using append(). My understanding is that the newest items will be added to the right-hand side of the slice. I'd like to create a function that picks a random item from the slice, with bias towards the newest members of the slice. My first guess is to use a normal distribution via rand.NormFloat64(), but I'm not sure how or if I can use it to achieve this.

The function should be capable of picking any item from the slice, but should pick new items added to the slice at a much higher frequency.




lundi 13 février 2023

r - draw random samples from a uniform distribution with a gap in the interval

I am interested into drawing random samples from a uniform distribution which is spread across 2 intervals: from -2 to -1 and from 1 to 2. Any value which belongs to these intervals should have equal probability of being sampled and the other values (e.g. from -1 to 1) should have 0 probability from being sampled.

The runif function only accepts single numbers as arguments for the upper and lower limit. Thus, it is impossible to make that function sample from two intervals.

Another option would be running two runif functions, one on the interval from -2 to -1, and one on the interval from 1 to 2. However, in this case I explicitly make it so that in each draw there will be an equal number of numbers drawn from each interval.

I want to allow this to vary and, while on the average there will be roughly the same amount of positive and negative numbers, I still need to see some random variation, e.g. draws where more numbers were drawn from the positive interval or vice versa.