mardi 31 août 2021

Create Dummy Population for Sampling

I have to create a function that generates a population of 5,000 individuals and returns the mean and standard deviation of how many times per day they pick-up their phone. Later in the assignment, I'll have to use this dummy data to extract a sample of 30 individuals, though I need help with the first part before I can move on to the sampling. Here is the given test code that gave me a hint on how to start:

pop_pickups, pop_mean, pop_std = get_population(45, 5000, 42)
assert np.abs(pop_mean - 45) < 0.5, "Get population problem, testing pop_mean, population mean returned does not match expected population mean"
assert np.abs(pop_std - np.sqrt(45)) < 0.5, "Get population problem, testing pop_std, population standard deviation returned does not match expected standard deviation"

I have the idea that the function will look something like:

def get_population(pickups, pop_size, std):

and that I may need to use the np.random.randint method to start, but I am really not sure where to go from there or if that's correct. I'm not clear on how to assign a random number to a fake sample (e.g. number of pickups per individual).




How to check if a specific input integer is in a random sample of a list [closed]

I'm sure that i'm doing something wrong, but i'm still learning. Basicly i want to check if my input is equal to random list of digits.

from random import sample

combo = int(input("Please enter a random combination of digits: (without 0)\n"))
tries = int(input("How many tries do you give me: ?\n"))
combo_lenght = len(str(combo))
print(combo_lenght)
print(type(combo_lenght))
print(f"I don't know the combination, but the lenght is {combo_lenght} digits.")
list_number = list(range(1, combo_lenght + 1))
list_input = int(combo)

for i in range(tries):
    var = (sample(list_number, len(list_number)))
    if list_input in var:
        print(f"Well, done! {var}")
        print(var)
    else:
        print(f'I keep trying to guess it... {var} ')
        print(combo)



How to make rand function display same number 1 time c++ [duplicate]

I'm trying to make it so that in my To-Do list, the tasks can only be called once and can't be called again. I put the tasks in a vector, and then randomly gets one of them with the rand() function. However, the rand() statement can use the same number twice. How do I make it so it can't, or is there a different way?




randomize question and answers from an api async/await

I am creating a random questions quiz using opentdb api. I'm using async/await in js to try and grab a question at random from the database, display it, and display the answers at random in each button I made. Here is my code, any help would be great!

const answerBtn = document.querySelector(".answers")
const questionsDisplay = document.querySelector("#questions")
let shuffleQuestions, currentQuestion
async function fetchData(results) {
   try {
      let res = await axios.get(url)
      let choices = res.data
      console.log(choices)
      choices.results.forEach((result) => {
         console.log(result)
         questionSelect(result.question)
         getAnswer(result.correct_answer, result.incorrect_answers)
      })   
   } catch(error) {
      console.log(error)
   }
}
fetchData()

function questionSelect(results, question) {
   shuffleQuestions = [results].slice(question).sort(() => Math.random() - .5)
   currentQuestion = 0
   nextQuestion()
}

function nextQuestion() {
   questions(shuffleQuestions[currentQuestion])
}

function questions(question) {
   questionsDisplay.innerText = question
}

function getAnswer(correct_answer, incorrect_answers) {
   // Shuffle through answers and place them randomly
  incorrect_answers.forEach((incorrect_answer) => {
     Math.floor(Math.random() * 3) + 1
     answerBtn.append(incorrect_answer)
     if(correct_answer) {
        answerBtn.dataset.correct = correct_answer
     }
  })
}
<div class="questions-container">
  <h2 id="questions" class="questions" data-id="4">What is your favorite color?</h2>
</div>
<div class="buttons">
  <button id="a" class="answers" data-id="6">A</button>
  <button id="b" class="answers" data-id="7">B</button>
  <button id="c" class="answers" data-id="8">C</button>
  <button id="d" class="answers" data-id="9">D</button>
</div>



How to integerList.add(randomNumber)

I'm not a expert in Android Kotlin and any idea will be appreciate. Why can't I add my randIndex in the integerList ? I'm looking for what I messed for hours now.

    private var integerList: MutableList<Int>? = null

private fun showSpinner() {
    var sv_mvmtChoosed = ""

    /* SCROLL VIEW */
    var linearLayout: LinearLayout? = null
    linearLayout = findViewById(R.id.linear1)
    val layoutInflater = LayoutInflater.from(this)

    var randIndex = 0
    for (i in sv_mvmtName) {
        val rand = Random()
        randIndex = rand.nextInt(40)


            while (integerList!!.contains(randIndex)) {
                randIndex = rand.nextInt(40)
            }
        
        integerList!!.add(randIndex)
        println("**** i = $i  *****  randIndex = $randIndex")
        ...


    }
}



VBA - How do I randomly select 10% of rows from a column, ensuring they are different and put a Y in column B?

I am looking to randomly select 10% of tasks worked by different users ('originator' Column P) and place a Y in column B to allow checkers to QC the work. If the 10% is not a whole number then I am required to round up i.e. 0.8 would require 1 row and 1.3 would require 2 rows.

I am new to coding I have been able to add code to filter the rows to show the required date and the 'Originator' in column P then name this range as "userNames". I am not sure how to code to select the random 10%. I have changed the part I am struggling with to bold below.

Sub randomSelection()

Dim dt As Date
dt = "20/08/2021"


Dim lRow As Long


'Format date
    Range("J:J").Select
    Selection.NumberFormat = "dd/mm/yyyy"
    
 'Select User Grogu

    ActiveSheet.Range("$A$1:$W$10000").AutoFilter 10, Criteria1:="=" & dt
    ActiveSheet.Range("$A$1:$W$10000").AutoFilter Field:=16, Criteria1:= _
        "SW\Grogu"
        
'Name range "userNames"
  With ActiveSheet
  
  lRow = .Cells(Rows.Count, 16).End(xlUp).Row
  If lRow < 3 Then Exit Sub
  
  .Cells(1, 16).Offset(1, 0).Resize(lRow - 1).SpecialCells(xlCellTypeVisible).Select
  End With

 Selection.Name = "userNames"
 
**'Randomly select 10% of rows from originator and put a Y in column B**
 
'remove all defined names

    On Error Resume Next
    ActiveWorkbook.Names("userNames").Delete

 'Select User Finn

    ActiveSheet.Range("$A$1:$W$10000").AutoFilter 10, Criteria1:="=" & dt
    ActiveSheet.Range("$A$1:$W$10000").AutoFilter Field:=16, Criteria1:= _
        "SW\Finn"
        
'Name range "userNames"
  With ActiveSheet
  
  lRow = .Cells(Rows.Count, 16).End(xlUp).Row
  If lRow < 3 Then Exit Sub
  
  .Cells(1, 16).Offset(1, 0).Resize(lRow - 1).SpecialCells(xlCellTypeVisible).Select
  End With

 Selection.Name = "userNames"
 
'remove all defined names

    On Error Resume Next
    ActiveWorkbook.Names("userNames").Delete
    
    'Formate Date back
    Range("J:J").Select
    Selection.NumberFormat = "yyyy-mm-dd"

End Sub



Pull random question from api and display answers at random [closed]

I am creating a random questions quiz using opentdb api. I'm using async/await in js to try and grab a question at random from the database, display it, and display the answers at random in each button I made. Here is my code, any help would be great!

const answerBtn = document.querySelector(".answers")
const questionsDisplay = document.querySelector("#questions")
let shuffleQuestions, currentQuestion
async function fetchData(results) {
   try {
      let res = await axios.get(url)
      let choices = res.data
      console.log(choices)
      choices.results.forEach((result) => {
         console.log(result)
         questionSelect(result.question)
         getAnswer(result.correct_answer, result.incorrect_answers)
      })   
   } catch(error) {
      console.log(error)
   }
}
fetchData()

function questionSelect(question) {
   shuffleQuestions = [].slice.call(question).sort(() => Math.random() - .5)
   currentQuestion = 0
}

function nextQuestion() {
   questions(shuffleQuestions[currentQuestion])
}

function questions(question) {
   questionsDisplay.innerText = question.question
}

function getAnswer(correct_answer, incorrect_answers) {
   // Shuffle through answers and place them randomly
  incorrect_answers.forEach((incorrect_answer) => {
     Math.floor(Math.random() * 3) + 1
     answerBtn.append(incorrect_answer)
  })
}
<div class="questions-container">
  <h2 id="questions" class="questions" data-id="4">What is your favorite color?</h2>
</div>
<div class="buttons">
  <button id="a" class="answers" data-id="6">A</button>
  <button id="b" class="answers" data-id="7">B</button>
  <button id="c" class="answers" data-id="8">C</button>
  <button id="d" class="answers" data-id="9">D</button>
</div>



Could I make my program choose randomly between variables (all integers) in a list, with it returning the variable, not the value?

So I have a list of variables (all being integers). I would want to randomly choose one of these variables, but make it so that it returns the actual variable, not the value.

for example:

list = [a, b, c, d]

(with all of them equal to 0)

print(random.choice(list)) 

would return 0, while I want it to return a, b, c or d;

So that if I write :

random.choice(list) += 2

It would update one of these variables.




stop audio from playing when another audio starts

this code works perfectly to play random audio files when a button is clicked, what I want. the only problem is that I want the current audio to stop when the button is clicked again so that it is not playing over the next file. any ideas on how to accomplish this would be appreciated!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<audio id="sound0" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound1" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound2" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound3" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>

<button id="button">Click To Play</button>
$( document ).ready(function() {
function playSound(){
  var pattern = [],
    tone;
  pattern.push(Math.floor(Math.random() * 4));
  tone = "#sound" + pattern[0];
  //$(tone).trigger('play');  //uncomment to play
  //$(tone).get(0).play();    //uncomment to play
  $(tone)[0].play();          //comment to turn off
}

$("#button").click(playSound);

});



How do I get a random variant of an enum in GDScript, Godot 3.3?

I have declared an enum like so in GDScript:

enum State = { STANDING, WALKING, RUNNING }

I want to get a random variant of this enum without mentioning all variants of it so that I can add more variants to the enum later without changing the code responsible for getting a random variant.

So far, I've tried this:

State.get(randi() % State.size())

And this:

State[randi() % State.size()]

Neither work. The former gives me Null, and the latter gives me the error "Invalid get index '2' (on base: 'Dictionary')."

How might I go about doing this in a way that actually works?




Is there an easy way to generate Captcha String in swift? [closed]

I have to implement captcha for verification in the login page of my application. The captcha must be a combo of lower, upper case letters and numbers.

eg: W3q5L0.

I am generating random letters & nums for each character of the string now. i.e for each letter in the captcha, I am generating a lowercase letter, a number for the next character and upper case letter for the 3rd character etc.

I am pretty sure that this is a long way of doing this. so I wanted to get opinion from you all for an easier method.




how to set boundary in multipart/form-data libcurl c++

I'm trying to send my data with content type multipart/form-data. Can Anyone help me how to set the boundary in multipart/form-data? . The desired output I'm looking for is " > Content-Type: multipart/form-data; boundary=------------------------f9e3897d86cb784a". My current output content type is "> Content-Type: multipart/form-data".

´´´

curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
std::string header = std::string(cmdData.begin(), cmdData.begin() + HeaderSize);
SYSLOG_INFO << "header = " << header << std::endl;
std::string headerAuth = "SCPv2: " + header;
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, headerAuth.c_str());
headers = curl_slist_append(headers, "Content-Type: multipart/form-data");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

´´´




Open random URL from a range in vba

I would need to open a random selected link from a cell to a website in my list. My internet links are put in column B, but I cannot get it to open the hyperlink after it has selected a cell from my list. Can someone help me with this? Many thanks!




lundi 30 août 2021

GLSL Pseudo Random in Range

I need to generate a pseudo random number, in specified range, using glsl

Something like this

float rand(vec2 co)
{
   return fract(sin(dot(co.xy,vec2(12.9898,78.233))) * 43758.5453);
}

or this

highp float rand(vec2 co)
{
    highp float a = 12.9898;
    highp float b = 78.233;
    highp float c = 43758.5453;
    highp float dt= dot(co.xy ,vec2(a,b));
    highp float sn= mod(dt,3.14);
    return fract(sin(sn) * c);
}

both from here and here respectively, would probably work, but I need to be able to specify a range (ie 1-10) for each pseudo random number.

In addition, I am using a glsl compute shader, not a vertex shader, so I do not have access to the typical vertex shader variables such as st




Efficient data.table method to generate additional rows given random numbers

I have a large data.table that I want to generate a random number (using two columns) and perform a calculation. Then I want to perform this step 1,000 times. I am looking for a way to do this efficiently with out a loop.

Example data:

> dt <- data.table(Group=c(rep("A",3),rep("B",3)), 
                   Year=rep(2020:2022,2), 
                   N=c(300,350,400,123,175,156),
                   Count=c(25,30,35,3,6,8), 
                   Pop=c(1234,1543,1754,2500,2600,2400))
> dt
   Group Year   N Count  Pop
1:     A 2020 300    25 1234
2:     A 2021 350    30 1543
3:     A 2022 400    35 1754
4:     B 2020 123     3 2500
5:     B 2021 175     6 2600
6:     B 2022 156     8 2400
> dt[, rate := rpois(.N, lambda=Count)/Pop*100000]
> dt[, value := N*(rate/100000)]
> dt
   Group Year   N Count  Pop      rate     value
1:     A 2020 300    25 1234 1944.8947 5.8346840
2:     A 2021 350    30 1543 2009.0732 7.0317563
3:     A 2022 400    35 1754 1938.4265 7.7537058
4:     B 2020 123     3 2500  120.0000 0.1476000
5:     B 2021 175     6 2600  115.3846 0.2019231
6:     B 2022 156     8 2400  416.6667 0.6500000

I want to be able to do this calculation for value 1,000 times, and keep all instances (with an indicator column for 1-1,000 indicating which run) without using a loop. Any suggestions?




How do I print two random string using the random module?

import random
user = "Jude"

file = ["do not lie", "do not cheat", "do not be bitter in anger", "do love all, is the greatest commandment"]
task = (input(f"There are four task in the task menu \nHow many task do wish to complete today {user}: "))
options1, options2, options3, options4 = file
for task in [random.randrange(*sorted([options1, options2, options3, options4])) for i in range(3)]:
    while True:
        if task == "1":
            print(options1)
            break
        elif task == "2":
            print(options1)
            print(options2)
            break
        elif task == "3":
            print(options1)
            print(options2)
            print(options3)
            break
        elif task == "4":
            print(options1)
            print(options2)
            print(options3)
            print(options4)
            break
        else:
            print("No task to be done today")
            break

The program I am trying to write is expected to print the number of task the user input. Example, if the user input 2 task, the program is expected to randomly select two task for the user and print it out. I am unable to make the program work properly, it keeps giving this error;

"C:\Users\Jude E\PycharmProjects\pythonProject3\venv\Scripts\python.exe" D:/python_tutorial/todolist.py
There are four task in the task menu  How many task do wish to complete today Jude: 2 Traceback (most recent call last):   File "D:\python_tutorial\todolist.py", line 7, in <module>
    for task in [random.randrange(*sorted([options1, options2, options3, options4])) for i in range(3)]:   File "D:\python_tutorial\todolist.py", line 7, in <listcomp>
    for task in [random.randrange(*sorted([options1, options2, options3, options4])) for i in range(3)]: TypeError: randrange() takes from 2 to 4 positional arguments but 5 were given

Please how do I fix it, or how do I get this program working?

Thanks.




Unable to replicate sample_n results using constant seed across R versions

I'm trying to replicate the sampling results from a script made in early January 2021. At the time, I forgot to record the R version and dplyr version I was using to create the sample. Now I have reinstalled R with the newest version of R (4.1.1) and dplyr (1.0.7) but I can't replicate my sampling results. I know that earlier R versions might use different RNGs, so I've tried to use RNGversion() to try out my seed with all versions of R but to no avail. This is not entirely surprising because I recall having used at least R 3.6.0, after which there shouldn't have been changes to the default RNG.

rm(list=ls())
library(dplyr)
RNGversion("3.5.0")
set.seed(182508)

Are there any other factors besides the R version that could affect my randomization results? For example, changes in the dplyr function sample_n? I know that sample_n has been superseded by slice_sample, but sample_n is still usable in the newest version of dplyr.




Double curly braces in PHP class - how ti use them to generate random string from 2 strings and return the value?

I stumbled on a script that generates random names from two different types of words in an array. Code is following:

    protected static $techTerms = array('AddOn', 'Algorithm', 'Architect', 'Array', 'Asynchronous', 'Avatar', 'Band', 'Base', 'Beta', 'Binary');

    protected static $culinaryTerms = array('Appetit', 'Bake', 'Beurre', 'Bistro', 'Blend', 'Boil', 'Bouchees', 'Brew', 'Buffet', 'Caffe', 'Caffeine', 'Cake');

    protected static $companyNameFormats = array(
        '',
        '',
        ''
    );

    public static function techTerm()
    {
        return static::randomElement(static::$techTerms);
    }

    public static function culinaryTerm()
    {
        return static::randomElement(static::$culinaryTerms);
    }

    public function companyName()
    {
        $format = static::randomElement(static::$companyNameFormats);

        return $this->generator->parse($format);
    }

Basically, the script should create and return a random combination of words as defined in $companyNameFormats. This script requires Faker\Factory, but I'd like to make it independent. At this point, there are 2 problems:

randomElement as an undefined method, and generator->parse as Call to a member function parse() on null

I've managed to modify the script and make it work, but I am interested in how can I use the as given in $companyNameFormats and return the result without using an external library?

The modified script is as follows:

    protected static function companyNameFormats()
    {
        $techArray = [];
        $techArray[] = self::techTerm();
        $culinaryArray = [];
        $culinaryArray[] = self::culinaryTerm();

        $result = array(
            array_merge($techArray, $culinaryArray),
            array_merge($techArray, $culinaryArray),
            array_merge($culinaryArray, $techArray),
            array_merge($techArray, $culinaryArray),
            array_merge($culinaryArray, $techArray)
        );

        return $result;
    }

    public static function techTerm()
    {
        $techTermKey = array_rand(static::$techTerms, 1);
        $techTermValue = static::$techTerms[$techTermKey];

        return $techTermValue;
    }

    public static function culinaryTerm()
    {
        $culinaryTermsKey = array_rand(static::$culinaryTerms, 1);
        $culinaryTermsValue = static::$culinaryTerms[$culinaryTermsKey];

        return $culinaryTermsValue;
    }

    public function companyName()
    {
        $companyNameKey = array_rand(static::companyNameFormats(), 1);
        $companyNameValue = static::companyNameFormats()[$companyNameKey];

        return $companyNameValue;
    }



how can I get n random names from the list given by user?

i did write , but it gets just the nam:

var namenListe = new List<string>();
while(true)
{
    Console.WriteLine("Geben Sie die Namen ein ; "); 
    string name = Console.ReadLine();
    Console.WriteLine("Die namen : ");
    namenListe.Add(name);

    for (int i = 0; i < namenListe.Count; i++)
    {
        Console.WriteLine(namenListe);
    }



dimanche 29 août 2021

Randomly pick rows from a data.frame based on a column value

I was wondering if there is away to make my expand.grid() output show unequal rows for each unique study value (currently, each unique study value has 4 rows)?

For example, can we randomly pick some or all rows of study == 1, some or all rows of study == 2, and some or all rows of study == 3?

The number of rows picked from each study is completely random.

This is toy study, a functional answer is appreciated.

library(dplyr)
(data <- expand.grid(study = 1:2, outcome = rep(1:2,2)))
arrange(data, study, outcome)
#   study outcome
#1      1       1
#2      1       1
#3      1       2
#4      1       2 #--- Up to here study == 1
#5      2       1
#6      2       1
#7      2       2
#8      2       2 #--- Up to here study == 2
#9      3       1
#10     3       1
#11     3       2
#12     3       2 #--- Up to here study == 3                      



Random Numbers in a Domain with unknown function in MATLAB

I want to create an array of random floating-point numbers in MATLAB that are inside D where the boundary D is between

  1. ( (0.6+0.1*cos(3t))*cos(t) , (0.6+0.1*cos(3t))*sin(t) ) t \in [0, pi]
  2. (x,y) where y=0

How can I create this array in MATLAB?

something like this picture; red points are on the boundary D




Should I choose higher AUC over higher accuracy

I have imbalanced classification problem. I did some method such as oversampling using random oversampling and SMOTE-TOMEK. In random oversampling, it has higher AUC but lower accuracy compared to SMOTE-TOMEK. The accuracy after random oversampling is below 0.7 while the accuracy after using SMOTE-TOMEK is above 0.7. Both AUC are above 0.5. Should I prefer random oversampling over SMOTE-TOMEK although the accuracy in random oversampling is lower than SMOTE-TOMEK?




Flutter ontap works in simulator but not consistent in mobile

I have flutter ontap guesture that works well in simulator but does not work consistently on mobile when installed.

On simulator it works always but on mobile randomly works dont know how to debug.




samedi 28 août 2021

Get random number of colors from a list instead of 8

I am experimenting on particles and I have set a list of 8 colors that create random shape. Now I have always the 8 colors showing up in the particles but I would like to have a random number of colors (1 to 8) everytime I run the script.

this is the relevant part of the code:

let colors = [
   "dodgerBlue",
  "red",
  "#fff200",
  "limeGreen",
  "slateGrey",
  "orange",
  "hotPink", 
  " #080808"
];
const dpi = 100;

let Particle = function(x, y) {
  this.x =  getRandomInt(cw);
  this.y =  getRandomInt(ch);
  this.coord = {x:x, y:y};
  this.r =  Math.min(getRandomInt(cw / dpi), 10 );
  this.vx = (Math.random() - 0.5) * 100;
  this.vy = (Math.random() - 0.5) * 100;
  this.accX = 0;
  this.accY = 0;
  this.friction = Math.random() * 0.07 + 0.90;
  this.color = colors[Math.floor(Math.random() * 8)];
}

how can I get a random number output instead of the "8" of the last line?




Python generate strings [closed]

Code

It always prints the same generated string(generated_name) but I want it to print different ones

Who knows how to fix that?




Small glitch in finding number game

So I am making this small project where it picks a random number from 1 to 100 and it keeps printing it till it sees 20 in it and stops it. Though I am getting the random numbers it does not do anything when it prints out 20. Maybe this is me being dumb but it would be appreciated if someone could help me. Thanks!

The script:

import random

while True:
    n = random.randrange(1,101)
    print(n)


if n == 20:
    print("That is the number we are looking for")
    break



How can a create a random order list and including same numbers?

I want to create five random list but have same and not repeat number from 1-100. I only know I can remove the number from a list which have all number I want and chose randomly put in to new list:

All_list is a list I save all the list I want to save random number from 1-100

number_list is the list including all number I want but it isn't random

number_list = list(range(1, 101))

for i in range(5):
    All_list.append(list)

    for a in range(1,101):
        random_num = random.choice(number_list)
        All_list[i-1].append(random_num)
        number_list.remove(random_num)

But in:

All_list[i-1].append(random_num)

It have a typeError:descriptor 'append' for 'list' objects doesn't apply to a 'int' object. and I don,t know why.

Can anyone help me rewrite this code? I will be appreciate about it.




C - Trying to generate random value between 0-6 but getting errors

I am trying to generate a random value between 0-6 for my game however using this function I get given two errors. This is the code:

int get_random_gesture() {
    return (rand()/((double)RAND_MAX + 1)) * 6;
}

The errors I am receiving in my IDE are as follows:

error: implicit declaration of function 'rand' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
    return (rand() /((double)RAND_MAX + 1)) * 6;
            ^
error: use of undeclared identifier 'RAND_MAX'
    return (rand() /((double)RAND_MAX + 1)) * 6; 
                             ^

Does anyone have an idea how to fix these errors?

Cheers.




How to generate the level after pressing the pygame menu button

I have been coding a maths game with Pygame. The menu is in one file named Menu121.

# Import the required libraries
import pygame
import pygame_menu


# Initialize pygame
pygame.init()
surface = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Projecte MatZanfe")


font = pygame_menu.font.FONT_8BIT
font1 = pygame_menu.font.FONT_NEVIS
font2 = pygame_menu.font.FONT_BEBAS

#Make menu Sumes
menu3 = pygame_menu.Menu('Sums', 600, 400,
                       theme=pygame_menu.themes.THEME_BLUE)

menu3.add.button('Infinite sums', font_name = font1, font_color = 'green')
menu3.add.button('Sums with images', font_name = font1, font_color = 'blue')
menu3.add.button('Sums with audio', font_name = font1,font_color = 'red')

#Make menu Restes
menu4 = pygame_menu.Menu('Subtraction', 600, 400,
                       theme=pygame_menu.themes.THEME_DEFAULT)

menu4.add.button('Infinite subtractions', font_name = font1, font_color = 'green')
menu4.add.button('Subtractions with images', font_name = font1, font_color = 'blue')
menu4.add.button('Subtratcions with audio', font_name = font1,font_color = 'red')

#Make menu Multiplicacions
menu5 = pygame_menu.Menu('Multiplications', 600, 400,
                       theme=pygame_menu.themes.THEME_ORANGE)

menu5.add.button('Infinite multis', font_name = font1, font_color = 'green')
menu5.add.button('Multis with images', font_name = font1, font_color = 'blue')
menu5.add.button('Multis with audio', font_name = font1,font_color = 'red')

#Make menu Divisions
menu6 = pygame_menu.Menu('Divisions', 600, 400,
                       theme=pygame_menu.themes.THEME_GREEN)

menu6.add.button('Infinite divisions', font_name = font1, font_color = 'green')
menu6.add.button('Divisions with images', font_name = font1, font_color = 'blue')
menu6.add.button('Divisions with audio', font_name = font1,font_color = 'red')

# Make menu 2
menu2 = pygame_menu.Menu('Module selection', 600, 400,
                       theme=pygame_menu.themes.THEME_SOLARIZED)


menu2.add.button('Sums',menu3, font_name = font2, font_color = 'green')
menu2.add.button('Subtractions',menu4, font_name = font2, font_color = 'blue')
menu2.add.button('Multiplications',menu5, font_name = font2,font_color = 'red')
menu2.add.button('Divisions',menu6, font_name = font2, font_color = 'purple' )

# Make main menu
menu = pygame_menu.Menu('Projecte MatZanfe', 600, 400,
                       theme=pygame_menu.themes.THEME_SOLARIZED)

user_input = menu.add.text_input('User: ', font_name = font1, font_color = 'blue')
age_input = menu.add.text_input('Age: ', font_name = font1,font_color = 'Black')
menu.add.button('Start', menu2, font_name = font, font_color = 'green')
menu.add.button('Exit', pygame_menu.events.EXIT, font_name = font,font_color = 'red')

# Run the menu
menu.mainloop(surface)

As you can see, you will eventually arrive at the "level selector", which consists in three different exercices related to the mathematical operations. I need to link the buttons to the code that generates the level, but don't really know how to do it. This is an example of the infinite levels, specifically the Subtractions level. The file name is Infinitesubtractions

import pygame
import random
from InputBox import InputBox
from pygame import mixer

pygame.init()

pygame.time.set_timer(pygame.USEREVENT, 1000)
clock = pygame.time.Clock()
surface = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Projecte MatZanfe")
font = pygame.font.SysFont('comicsans', 50)
base_font = pygame.font.Font(None, 32)
user_text = ''
color_active = pygame.Color('lightskyblue3')
running = True
points = 0
t = 60

def start_the_game():
    x = random.randint(5, 10)
    y = random.randint(0, 5)
    is_correct = False
    return x, y

def display_the_game(x, y):
    # Variables
    z = x + y
    surface.fill((70, 90, 255))
    text = font.render(str(x) + " - " + str(y), True, (255, 255, 255))

    text_surface = base_font.render(user_text, True, (255, 255, 255))
    surface.blit(text, (260, 120))
    input_box.draw(surface)
    punts = font.render("Puntuació: " +  str(points),True, (255,255,255))
    surface.blit(punts, (350,30))
    titolresta = font.render("Resta (1)", True, (0, 0, 0))
    surface.blit(titolresta, (10, 20))
    temps = font.render("Temps: " + str(t), True, (255, 255, 51))
    surface.blit(temps, (0, 360))

x, y = start_the_game()
input_box = InputBox(190, 250, 200, 32)

while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.USEREVENT:
            t -= 1
            temps = font.render("Temps:" + str(t), True, (255, 255, 51))
            surface.blit(temps, (0, 360))
            pygame.display.flip()
            if t == 0:
                pygame.QUIT
        else:
            result = input_box.handle_event(event)
            if result != None:
                if int(result) == int(x) - int(y):
                    points = points + 5
                    t = t + 5
                    mixer.music.load('StarPost.wav')
                    mixer.music.play(1)

                # create new random numbers
                x, y = start_the_game()

                # reset input box (just create a new box)
                input_box = InputBox(190, 250, 200, 32)

    display_the_game(x, y)
    pygame.display.update()

pygame.quit()

And finally the imported InputBox:

import pygame


pygame.init()
surface = pygame.display.set_mode((600, 400))
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('black')
FONT = pygame.font.SysFont('comicsans', 32)
base_font = pygame.font.Font(None, 32)
color_active = pygame.Color('lightskyblue3')
user_text = ''


class InputBox:

    def __init__(self, x, y, w, h, text=''):
        self.rect = pygame.Rect(x, y, w, h)
        self.color = COLOR_INACTIVE
        self.text = text
        self.txt_surface = FONT.render(text, True, self.color)
        self.active = False

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            # If the user clicked on the input_box rect.
            if self.rect.collidepoint(event.pos):
                # Toggle the active variable.
                self.active = not self.active
            else:
                self.active = False
            # Change the current color of the input box.
            self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    user_input = self.text
                    self.text = ''
                    self.txt_surface = FONT.render(self.text, True, self.color)
                    return user_input
                elif event.key == pygame.K_BACKSPACE:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode
                # Re-render the text.
                self.txt_surface = FONT.render(self.text, True, self.color)

    def update(self):
        # Resize the box if the text is too long.
        width = max(200, self.txt_surface.get_width()+10)
        self.rect.w = width

    def draw(self, screen):
        # Blit the text.
        screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
        # Blit the rect.
        pygame.draw.rect(screen, self.color, self.rect, 2)



def main():
    clock = pygame.time.Clock()
    input_box2 = InputBox(190, 250, 200, 32)
    input_boxes = [input_box2]
    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            for box in input_boxes:
                box.handle_event(event)

        for box in input_boxes:
            box.update()

        surface.fill((255, 70, 90))
        for box in input_boxes:
            box.draw(surface)

        pygame.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pygame.quit()



Distribution of java.util.Random.nextX upon shared usage

As written in the javadoc of java.util.Random methods Random.nextX returns the uniformly distributed pseudorandom values.

If the instance of the Random class is shared between different users, and users call the same nextX method with different frequency (assume the frequency is distributed normally).

My question is: Would each user get a uniformly or normally distributed sequence of numbers?




generate random size sphere which are randomly distributed inside a cylinder and not intersecting with each other in python

I want to generate the random size spheres which are randomly generated inside a cylinder in python. The condition should be that spheres would not overlap with each other.




Python input and random system

I'm making an input system that asks for the user if the user selects low or high and then prints out if it's low or high with:

print(random.randint(1, 2))

But it gives this error:

  File "main.py", line 13
    print(random.randint(1, 2))
                              ^

IndentationError: unindent does not match any outer indentation level

pls debug me here's the code

import random
print("Hello Welcome to the up down game!")

while True:

  first = input("[1]Low or [2]High. Which one?\n")


 print(random.randint(1, 2))
break



vendredi 27 août 2021

Iterate through an array randomly but fast

I have a 2d array that I need to iterate through randomly. This is part of an update loop in a little simulation, so it runs about 200 times a second. Currently I am achieving this by creating a array of the appropriate size, filling it with a range, and shuffling it to use to subscript my other arrays.

std::array<int, 250> nums;
std::iota(nums.begin(), nums.end(), 0);

timer += fElapsedTime;
if (timer >= 0.005f)
{
    std::shuffle(nums.begin(), nums.end(), engine);

    for (int xi : nums)
    {
        std::shuffle(nums.begin(), nums.end(), engine);

        for (int yi : nums)
        {
            // use xi and yi as array subscript and do stuff
        }
    }

    timer = 0.0f;
}

The issue with this solution is that is is really slow. Just removing the std::shuffles increases the fps by almost 2.5x, so the entire program logic is almost insignificant compared to just these shuffles.

Is there some type of code that would allow me to generate a fixed range (0 - 249) of non-repeating randomly generated ints that I could either use directly or write to an array and then iterate over?




Shuffle vector elements such that two similar elements coming together at most twice

For the sake of an example:

I have a vector named vec containing ten 1s and ten 2s. I am trying to randomly arrange it but with one condition that two same values must not come together more than twice.

What I have done till now is generating random indexes of vec using the randperm function and shuffling vec accordingly. This is what I have:

vec = [1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2];
atmost = 2;
indexes = randperm(length(vec));
vec = vec(indexes);

>> vec =
      2  1  1  1  2  1  2  1  2  1  1  1  2  2  1  2  1  2  2  2

My code randomly arranges elements of vec but does not fulfill the condition of two similar values coming at most two times. How can I do this? Any ideas?




Exclude points from circle in javascript

to get a random point ona circle i use this code :

const position = randomCirclePoint(...)

const x = position.x;
const y = position.y;

function randomCirclePoint(circleRadius, circleX, circleY) {
    let ang = Math.random() * 2 * Math.PI,
        hyp = Math.sqrt(Math.random()) * circleRadius,
        adj = Math.cos(ang) * hyp,
        opp = Math.sin(ang) * hyp

        const x = circleX + adj;
        const y = circleY + opp;
        
    return {x, y}
}

But how can i exclude some points from it ?




How to generate unique letters and append them to a string in python?

I am currently writing a code where the user needs to enter an input string minimum of 4 to 12 letters, must not contain any numbers and must be unique. Once all three conditions are passed, the program will generate a set of letters that will include the input string and other unique letters to form double the length of the input string. I have cleared all three conditions but am unsure how to generate unique letters and append them to the input string.

def main2():
    player_input = input("Enter target letters: ").upper() 
    if  4 <= len(player_input) < 12 \
        and len(set(player_input)) == len(player_input) \
             and player_input.isalpha():
                  print(player_input)
    
    elif not 4 <= len(player_input) < 12:
         print(f"Must be unique characters from and of length 4 to 12")
    elif len(set(player_input)) != len(player_input):
         print(f"Must be unique characters from and of length 4 to 12")
    elif not player_input.isalpha():
         print(f"Must be unique characters from and of length 4 to 12")
    else:
         print(player_input)        
main2()



Uniform Distribution: Bug or Paradox

Imagine 10 cars randomly, uniformly distributed on a round track of length 1. If the positions are represented by a C double in the range [0,1> then they can be sorted and the gaps between the cars should be the position of the car in front minus the position of the car behind. The last gap needs 1 added to account for the discontinuity.

In the program output, the last column has very different statistics and distribution from the others. The rows correctly add to 1. What's going on?

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int compare (const void * a, const void * b)
{
  if (*(double*)a > *(double*)b) return 1;
  else if (*(double*)a < *(double*)b) return -1;
  else return 0;
}

double grand_f_0_1(){
  static FILE * fp = NULL;
  uint64_t bits;

  if(fp == NULL) fp = fopen("/dev/urandom", "r");
  fread(&bits, sizeof(bits), 1, fp);
  return (double)bits * 5.421010862427522170037264004349e-020; // https://stackoverflow.com/a/26867455
}

int main()
{
  static int n = 10;
  double values[n];
  double diffs[n];
  int i, j;
  
  for(j=0; j<10000; j++) {
  
    for(i=0; i<n; i++) values[i] = grand_f_0_1();

    qsort(values, n, sizeof(double), compare);
    
    for(i=0; i<(n-1); i++) diffs[i] = values[i+1] - values[i];
    diffs[n-1] = 1. + values[0] - values[n-1];

    for(i=0; i<n; i++) printf("%.5f%s", diffs[i], i<(n-1)?"\t":"\n");

  }
  
  return(0);
}



Divert background color choosing in p5js

I'm a noobie, so please be kind to me :)

I'm putting together a p5js script. Background color is random, choosing from an array with values for black or white background. Drawing color is also random.

It works fine most of the times, but from now and then I get a color that can't really be appreciated from the background, so the question is, is there a way in which I can vary the background resulting color depending on the color of the draw? How would I go about discerning what combination is "perceivable" and which one isn't?




How to random between multiple strings in Kotlin?

I would like to write a code in Kotlin to random between "Rock", "Paper" and "Scissors". How to do it ?

I have tried something similar, that is random between H and T:

fun main() {
    val coin = "HT"
    println("My first coin flip is ${coin.random()}")
}



jeudi 26 août 2021

Equivalent way of srand() and rand() using post-c++11 std library

I have old code that uses predates c++11 and it uses rand() for generating random ints.

However, there is shortcoming in rand(): you can't save and then restore the state of the random device; since there is not an object I can save, nor can I extract the state.

Therefore, I want to refactor to use c++11's solution <random>.

However, I do not want a behaviour change - I hope to get exactly the sequence rand() gives me but with <random>.

Do you guys know whether this is achievable?




Discord.js - Post image from folder ERROR

I want my bot to respond with an image if someone uses the command !image. This image needs to be a random image from a specific folder named gta.

My code:

client.on("message",message=>{
  if(message.content==('!imagetest')){
    var files = fs.readdirSync('./gta/')
    var chosenFile = files[Math.floor(Math.random() * files.length)] 
    console.log(chosenFile)
    message.channel.send(
      {
        files : [
          chosenFile
        ]
      }
    )
  }
})

The error: UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat '/home/container/d864050.jpg'

It think should be /home/container/gta/... (a random image), but i don't know how to do that.

Any help would be appreciated!




To create random first and last name. multiple pieces

I would like to ask for your help.

I want to create a script. The script will automatically list random firstname and lastname. There are two database tables. First: fake_name_id, fake_firstname Second: fake_name_id,fake_lastname

Unfortunately, I'm not very good at this.

So far I have made this:

controller file

$data['lastname'] = array();

$results = $this->getRandomLastNames();
    foreach ($results as $result) {
        $data['lastname'][] = array(
            'lastname'        => $result['lastname'],
        );
    }

$data['fullnames'] = array();
$results = $this->getRandomNames();

    foreach ($results as $result) {
        $data['fullnames'][] = array(
            'firstname'        => $result['firstname'],

        );
    }

model file >>>>> sql query firstname and lastname

public function getRandomName($fake_name_id) {
                
        $query = $this->db->query("SELECT DISTINCT *, fake_firstname FROM " . DB_PREFIX . " fakereviews_name WHERE fake_name_id = '" . (int)$fake_name_id . "'");
        
        if ($query->num_rows) {
            return array(
                'fake_name_id'             => $query->row['fake_name_id'],
                'firstname'             => $query->row['fake_firstname'],
            );
        } else {
            return false;
        }
    }
    
    public function getRandomNames($data = array()) {

            $sql = "SELECT * FROM " . DB_PREFIX . "fakereviews_name ORDER BY Rand() ASC LIMIT 0, 20";
            $fake_firstname_data = array(); 
            $query = $this->db->query($sql);
                       
            foreach ($query->rows as $result) {
                
                $fake_firstname_data[$result['fake_name_id']] = $this->getRandomName($result['fake_name_id']);
            }       
        return $fake_firstname_data;
    }   
    
    
    
    
 public function getRandomLastName($fake_name_id) {
                
        $query = $this->db->query("SELECT DISTINCT *, fake_lastname FROM " . DB_PREFIX . " fakereviews_lastname WHERE fake_name_id = '" . (int)$fake_name_id . "'");

        if ($query->num_rows) {
            return array(
                'fake_name_id'             => $query->row['fake_name_id'],
                'lastname'             => $query->row['fake_lastname'],
            );
        } else {
            return false;
        }
    }
        
    public function getRandomLastNames($data = array()) {

            $sql = "SELECT * FROM " . DB_PREFIX . "fakereviews_lastname ORDER BY Rand() ASC LIMIT 0, 20";
            
            $fake_lastname_data = array();  
            
            $query = $this->db->query($sql);
                       
            foreach ($query->rows as $result) {
                
                $fake_lastname_data[$result['fake_name_id']] = $this->getRandomLastName($result['fake_name_id']);
            }       
        return $fake_lastname_data;
    }   

twig file


When the page loads. well creates 20 pieces of firstname.

But I can't get it to display lastname correctly.

Please help me to create foreach random fullname (first and last name) with predefined quantity.




How to solving complex integral in Python?

I've been trying to write this function, shown in the link below, in python but I haven't been able to find how to write the equation even after looking through the libraries my goal is to solve for y when x = (random.random()). If someone could help an inexperienced coder out I'd be much appreciative.

Link to Function




Java - How to get a random video by hashtag using youtube api

I need a way of get a random youtube video by hashtag. as example #meme

How can I do with with the YouTube API? (Java)

as requested here is what i tried so far:

  1. went through the api and examples at youtube dev site. http://www.youtube.com/dev/ no luck finding the correct api or a way of doing it there.

  2. google search. got http://randomyoutubevideo.net/ but they only offer an api from THEM to use in between me and youtube. < this gives me hope that it IS actually possible to do this.

Thank




Randomized QuickSort IndexOutOfBounds exception

this is the QuickSort Randomized that I've come up with, but it constantly throws out IndexOutOfBounds exception. Could I have some help with it? Thanks!

import java.util.Random;

public class QuickSort {

    void quickSort(int[] A, int start, int end) { // Initially: start = 0, end = n-1
        while (start < end) {
            int iOfPartition = randomisedPartition(A, start, end);
            if (iOfPartition - start < end - iOfPartition) {
                quickSort(A, start, iOfPartition - 1);
                start = iOfPartition + 1;
            } else {
                quickSort(A, iOfPartition + 1, end);
                end = iOfPartition - 1;
            }
        }
    }

    int randomisedPartition(int[] A, int start, int end) {
        Random rng = new Random();
        int randomNum = rng.nextInt(end + 1 - start) + start;
        swap(A, A[randomNum], A[start]);
        return hoarePartition(A, start, end);
    }

    int hoarePartition(int[] A, int start, int end) {
        int pivot = A[start];
        int i = start;
        int j = end;
        while (i < j) {
            while (A[i] <= pivot && i < end) i++;
            while (A[j] > pivot && j > start) j--;
            if (i < j) swap(A, A[i], A[j]); 
        }
        swap(A, A[start], A[j]);
        return j; 
    }

    void swap(int[] A, int i, int j) {
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
}

I keep getting an arrayindexoutofbounds error.




Gaussian draws in C++ using bind gives different result than drawing from distribution explicitly

I am studying the issue of generating Gaussian draws in C++. As the title says, I seem to get a different result from using bind instead of just drawing from the distribution. That is to say the following code

default_random_engine ran{1};
auto normal_draw = bind(normal_distribution<double>{0, 1}, ran);

for (int i = 0; i < 9; ++i)
    cout << normal_draw() << endl;

    cout << "new sequence" << endl;

for (int i = 0; i < 9; ++i)
    cout << normal_distribution<double>{0, 1}(ran) << endl;

generates the output

-1.40287 -0.549746 -1.04515 1.58275 -1.95939 0.257594 -0.315292 -1.50781 0.071343

new sequence

-1.40287 -1.04515 -1.95939 -0.315292 0.071343 -1.41555 0.631902 -0.903123 0.194431

I find this perplexing as I believed that both sequences would be the same. Note also that if one generates 18 draws using normal_draw() then the sequence comprising the last 9 draws is not equal to the second sequence above. So it seems like drawing directly from the distribution is using a different method than that implicit in bind(), which clearly cannot be the case.

Can someone please explain what I am missing?

thanks in advance!




Can someone explain me why this "random number" is allways the same (1)? [duplicate]

I have one class for showing my GUI called GUI and I have another class called Dice which should do some things for me.

First I only want to add the method createDice() which should create a random number and I want to show it in the console. It shows allways 1 in the console. Please help me. I am new here and I am exited about beeing a part of the community now :)

My Code:

    //returns new dice (number between 1 and 6)
    public int createDice () {
        int dice = (int) Math.random()*6+1;
        return dice;
    }



mercredi 25 août 2021

How to get the number e (2.718) using a random number sensor?

Is it possible to calculate the number e (2.718) using random numbers?




ERROR when trying to upload a video on Instagram

Hey first sorry for my bad english!! I am trying to run a code that upload randomly a video that there are in my folder automatically on my instagram profile, but it occurs an error.

This error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\imageio\plugins\ffmpeg.py", line 81, in get_exe exe = get_remote_file('ffmpeg/' + FNAME_PER_PLATFORM[plat], File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\imageio\core\fetching.py", line 102, in get_remote_file raise NeedDownloadError() imageio.core.fetching.NeedDownloadError

import random
from instabot import Bot
import os, glob
from pathlib import Path
import shutil


cookie_del = glob.glob("config/*cookie.json")
os.remove(cookie_del[0])


bot = Bot()

sent_videos = []


def upload(path):
     bot.login(username= '', password='')
     bot.upload_video(path, caption='😍 ')
     sent_videos.append(path)


while True:
    group_of_items = os.listdir("C:/Users/user/Desktop/teste/PICS")
    num_selet = 1
    list_of_random = random.sample(group_of_items, num_selet)
    first_random = random.choice(group_of_items)
    path = "C:/Users/user/Desktop/teste/PICS/" + str(first_random)
    if path in sent_videos:
        continue
   else:
      path.endswith('.mp4')
      upload(path)



How to use use numpy random choice to get progressively longer sequences with the same numbers?

What I tried was this:

import numpy as np
def test_random(nr_selections, n, prob):
    selected = np.random.choice(n, size=nr_selections, replace= False, p = prob)
    print(str(nr_selections) + ': ' + str(selected))

n = 100
prob = np.random.choice(100, n)
prob = prob / np.sum(prob) #only for demonstration purpose
for i in np.arange(10, 100, 10):
    np.random.seed(123)        
    test_random(i, n, prob)

The result was:

10: [68 32 25 54 72 45 96 67 49 40]
20: [68 32 25 54 72 45 96 67 49 40 36 74 46  7 21 20 53 65 89 77]
30: [68 32 25 54 72 45 96 67 49 40 36 74 46  7 21 20 53 62 86 60 35 37  8 48
     52 47 31 92 95 56] 
40: ...

Contrary to my expectation and hope, the 30 numbers selected do not contain all of the 20 numbers. I also tried using numpy.random.default_rng, but only strayed further away from my desired output. I also simplified the original problem somewhat in the above example. Any help would be greatly appreciated. Thank you!

Edit for clarification: I do not want to generate all the sequences in one loop (like in the example above) but rather use the related sequences in different runs of the same program. (Ideally, without storing them somewhere)




Reusing Jmeter Random Variable in the same request

I'm currently using Jmeter 5.1 and "bzm - Random CSV Data Set config" to read random MemberID from a file, And I'm using this variable inside a post, as you can see below. So, My question is.. Do we have a way to use the same variable and have different MemberID in the same request?

Post Body data

[
 {
        "memberExternalId": "${MemberId}",
    }

    {
        "memberExternalId": "${MemberId}",
    } 
 }
]

Thanks




How to insert multiple files into a single ext program in BASH

I have a simple problem and I need your help.

I want the files in a specific folder, conditionally '1.txt', '2.txt', 'and three.txt' whose sizes are also conditional 1kb, 3mb, 55kb. There are thousands of files that I can do this manually. I want to insert all the above mentioned files in dd command, to be produced with the same name and size.

find . -name "*.txt" -print | while IFS= read -r fn
do
        echo "$fn"
done
size=$(ls -nl *.txt | awk '{print $5}')
for size in $size
do
        echo "$size"
done

exec dd if=/dev/random of=$fn bs=$size count=1"

I want something like that, thanks in advance.




Random select buttons which has same value and attribute

I am trying to randomly vote. I have two buttons. <button type="button" class="btn-primary aria-label="Vote>

How can I select these buttons randomly?




int object is not callable, with random liblary, python [closed]

I was coding 0 - player game with random library, the error often accrues after thousands of iterations for no apparent reason, I am using only random.randint so there is no need for rounding, I have seen similar question like this but with no answer because user didn't send enough error traceback, here is link:

'int' object is not callable only appears randomly

my code looks like that:


inventory = 0
sprint = 0
dirt = 0
stone = 0
wood = 0
plank = 0
stick = 0
craftingTable = 0
woodPick = 0
stonePick = 0

def randomMove():
    global inventory
    global sprint
    if inventory == 0:
        if sprint == 0:
            randomed = random.randint(0, 10)
            listOfActions = [rightH, rightC, leftH, leftC, W, A, S, D, angleRandomize, openInventory, startSprint]
            listOfActions[randomed]()
        else:
            randomed = random.randint(0, 10)
            listOfActions = [rightH, rightC, leftH, leftC, W, A, S, D, angleRandomize, openInventory, stopSprint]
            listOfActions[randomed]()
    else:
        randomed = random.randint(0, 1)
        listOfActions = [closeInventory, craft]
        listOfActions[randomed]()

def rightH():
    global dirt, stone, wood, woodPick
    rand = random.randint(0, 1)
    if rand == 0:
        rand = random.randint(0, 99)
        if rand < 74:
            if woodPick == 0:
                print("Broke stone, not dropped")
            else:
                print("Broke stone")
                stone += 1
        if 74 < rand < 99:
            print("Broke dirt")
            dirt += 1
        if 98 < rand:
            print("Broke wood")
            wood += 1
    else:
        print("Holding Right Click")

def rightC():
    print("Clicking Right Click")

def leftH():
    print("Holding Left Click")

def leftC():
    print("Clicking Left Click")

def W():
    print("Going forward")

def A():
    print("Going left")

def S():
    print("Going backwards")

def D():
    print("Going right")

def angleRandomize():
    x = random.randint(-180, 180)
    y = random.randint(-90, 90)
    print("Randomized angle, looking " + str(x) + " " + str(y))

def openInventory():
    global inventory, sprint
    print("Opening inventory")
    inventory = 1
    sprint = 0

def closeInventory():
    global inventory
    print("Closing inventory")
    inventory = 0

def startSprint():
    global sprint
    print("Sprinting")
    sprint = 1

def stopSprint():
    global sprint
    print("Stopping Sprint")
    sprint = 0

def craftPlanks():
    global plank, wood
    plank += 4
    wood -= 1

def craftSticks():
    global stick, plank
    stick += 4
    plank -= 2

def craftCraftingTable():
    global craftingTable, plank
    craftingTable += 1
    plank -= 4

def craftWoodPick():
    global woodPick, plank, stick
    woodPick += 1
    plank -= 3
    stick -= 2

def craftStonePick():
    global stonePick, stick, stone
    stonePick += 1
    stone -= 3
    stick -= 2

def craft():
    options = []
    if wood >= 1:
        options.append(craftPlanks)
    if plank >= 2:
        options.append(craftSticks)
    if plank >= 4:
        options.append(craftingTable)
    if plank >= 3 and stick >= 2 and craftingTable >= 1:
        options.append(craftWoodPick)
    if stone >= 3 and stick >= 2 and craftingTable >= 1:
        options.append(craftStonePick)
    if len(options) == 0:
        print("Can't craft")
    else:
        randomCraft = random.randint(0, len(options) - 1)
        options[randomCraft]()

for i in range(100000):
    inventoryStored = [dirt, stone, wood, plank, stick, craftingTable]
    print("Inventory: " + str(inventoryStored))
    randomMove()
    if craftingTable == 1:
        break

and error traceback is:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.3.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.3.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/***/PycharmProjects/randomMinecraftAgent/RandomAgnetWithSimulatedMinecraft.py", line 147, in <module>
    randomMove()
  File "C:/Users/***/PycharmProjects/randomMinecraftAgent/RandomAgnetWithSimulatedMinecraft.py", line 29, in randomMove
    listOfActions[randomed]()
  File "C:/Users/***/PycharmProjects/randomMinecraftAgent/RandomAgnetWithSimulatedMinecraft.py", line 141, in craft
    options[randomCraft]()
TypeError: 'int' object is not callable

this "simulation" is working for thousands of iterations and then it just breaks, how to fix that?




Generate random numbers with equal probabilities in c++

For example, array of pairs of ranges p={[23, 28], [11, 14], [31, 39]}

You have to return random number such that this number should be:

  1. In any one of these pairs
  2. Each number in these ranges should have equal probability of being chosen.

I can easily generate a random number that lies between any of these intervals like

int x=(rand()%(p[i].second-p[i].first) )+ p[i].first;

How can I generate a random number that can lie in any interval in the array and that too with equal probability.




Generating discrete random numbers under constraints

I have a problem that I'm not sure how to solve properly.

Suppose we have to generate 1 <= n <= 40 numbers: X[1], X[2], ..., X[n].

For each number, we have some discrete space we can draw a number from. This space is not always a range and can be quite large (thousands/millions of numbers).

Another constraint is that the resulting array of numbers should be sorted in ascending order: X[1] <= X[2] <= ... <= X[n].

As an example for three numbers:

X[1] in {8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}

X[2] in {10, 20, 30, 50}

X[3] in {1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003}

Examples of valid outputs for this test: [9, 20, 2001], [18, 30, 1995]

Example of invalid outputs for this test: [25, 10, 1998] (not increasing order)

I already tried different methods but what I'm not satisfied with is that they all yield not uniformly distributed results, i.e. there is a strong bias in all my solutions and some samples are underrepresented.

One of the methods is to try to randomly generate numbers one by one and at each iteration reduce the space for the upcoming numbers to satisfy the increasing order condition. This is bad because this solution always biases the last numbers towards the higher end of their possible range.

I already gave up on looking for an exact solution that could yield samples uniformly. I would really appreciate any reasonable solution (preferably, on Python, but anything will do, really).




Efficiently sampling a random 0-1 sequence of length l with at least k ones

Is there a way to efficiently sample a random 0-1 sequence of length l with at least k ones?




mardi 24 août 2021

Implementing a payment method in flutter

I'm developing a mobile application for both Andriod and IOS using flutter. You can buy in the application an E-Ticket for an event. Are google pay and apple pay the best payment method in this scenario? How much will google and apple take on each transaction?




Change values in array based on distance to other elements in the same array

I have a one-dimensional Boolean Array. Later this array is used for indexing over coordinates indicating a certain area in a 3-dimensional Point array. I want to make the edges of this area a little bit more rough/noisy. (True= area_of_interest) Therefore I want to change the False values in the array based on their distance to the next true value i.e. Values next to a True value are likely to be true while far away ones (further than the cutoff) are unlikely to change.

Input:

bool_array = [False, False, False, False, True, True, False, False]

sample Output:

func(bool_array) = [False, False, False, True, True, True, True, False]

I came up with a solution however this is incredibly slow for huge data (which for me is the case).

decay_prob = lambda x: random() < e ** (-x / 10)

boolean_array = np.asarray([False, False, False, False, True, True, False, False, False, False])
cutoff = 3
true_indeces = np.asarray(np.where(boolean_array == True))

for i in range(boolean_array.size):
    distances = np.abs(true_indeces - i)
    # only modify the ones in within a certain area
    if np.any(distances < cutoff):
        # calculate the distances from the current index to the closest True value
        # change the value dependent on the distance (smaller values are more likely to change to true)
        boolean_array[i] = decay_prob(np.min(distances))

I'm probably missing something obvious but I also couldn't find anything more pythonic or numpy based.




code outputting same variable no matter number generated [duplicate]

Every time I try to run the code i get "you lost" when i guessed the right number. tried moving stuff around but no solution.

this is my code

import random

numgened = random.randint(1,2)

print('Enter your bet amount:')
amtbet = input()
print('You have bet ' + amtbet)

print('Number to bet on:')
numbet = input()
print('You bet on ' + numbet)

print(numgened)
if numgened == numbet:
    print('you won '+ amtbet)
else:
    print('you lost '+ amtbet)



How do I change the Java source for random data?

I'm trying to run code on a machine where /dev/random does not fill up quickly, and a java program I'm trying to use is hanging for lack of random numbers.

/dev/urandom produces "not as good" random numbers, but isn't blocking, and for this case I'd rather have less randomness and completing, than better randomness but never completing.

I tried passing this to java

-Djava.security.egd=file:/dev/./urandom

But it didn't fix anything("/dewv/urandom" has problems in places, whereas "/dev/./urandom" works everywhere, which is why I used that path). Is there a way to do this?




ffmpeg random mp3 audio play

I stream images from an IP camera to an external player and play back mp3 files as background music in a loop. In order to keep the playback continuity, I combined several mp3 songs together. Each time the external player is started, the background music starts from the same track (which was saved first as a result of joining mp3 files). When I start the player, I would like to run a random mp3 file as background music and play the whole list in random order and additionally in a loop. Here is my current camera streaming code + logo position + mp3 playback

 ffmpeg -stimeout 5000000 -rtsp_transport tcp \
 -i "rtsp://IP:PORT/Streaming/Channels/101/" \
 -i /root/logo_streaming.png -filter_complex "overlay=x=main_w-overlay_w-30:y=30" -stream_loop -1 \
 -i /root/mix_57m37s.mp3 \
 -vcodec libx264 -preset veryfast -vprofile baseline -x264opts keyint=40 -b:v 4096k -bufsize 1024k \
 -f mpegts udp://IP:PORT?pkt_size=1316



How can I generate two Weibull Random Vectors with a given correlation coefficient in Matlab?

I need to create two vectors X and Y containing both N samples. They are both weibull distributed with the same λ,k parameters and they are correlated with a correlation coefficient ρ that is neither -1 nor 1 nor 0, but a generic value that indicates a partial correlation.

How can I create them?




lundi 23 août 2021

Can anyone help me with the following code? I want to understand what the code do?

I am a beginner in programming and I am trying to understand a code that sorts random numbers and how binary search work.

import random
def bub_sort(a):
    for i in range(len(a)-1):
        for j in range(len(a)-1-i):
            if a[j]>a[j+1]:
                a[j],a[j+1]=a[j+1],a[j]
    return a
    


def ins_sort(a):
    for i in range(1,len(a)):
        for j in range(0,i):
            if a[j]>a[i]:
                a[j],a[i]=a[i],a[j]
    return a



def bin_search(L,s):
    low=0
    high=len(L)-1
    while low<=high:
        m=(low+high)//2
        if L[m]==s:
            return 1,m
        elif L[m]>s:
            h=m-1
        else:
            L=m+1
    return 0,None
            
  

L=[]
for i in range(10):
    n=random.randint(1,100)
    L.append(n)
s=int(input("Enter search element"))
l1=bub_sort(L)
ans=bin_search(l1,s)
if ans[0]==1:
    print("found at index ",ans[1])
else:
    print("not found")

Can anyone help me understand the whole code? I am very sorry for posting such a simple question.




Getting error while using the random choices function

I'm trying to open random links using

webbrowser.open(random.choices("link1","link2","link3")

but it's showing error Check it out and help me resolve this issue.

My code:

webbrowser.open(random.choices("https://www.youtube.com/watch?v=YGf8JJZM_Yg", "https://www.youtube.com/watch?v=upsF9NULamA"))

Error I am facing:

    total = cum_weights[-1] + 0.0   # convert to float
TypeError: can only concatenate str (not "float") to str



How to start the functions from another file on this code [duplicate]

Recently I have been working on a videogame with Pygame, and I have already created the menu on one file, the game functions (sums) on another one, and the entry box (where the user writes the answer) on another one. I would like to start the game function (the sums) when I press the "Start" button of the menu. The names of each file are those: Menu - Suma - InputBox

Here is the code of the menu.

import pygame
import pygame_menu

pygame.init()
#Size and name of the window
surface = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Projecte MatZanfe")

font = pygame_menu.font.FONT_8BIT
font1 = pygame_menu.font.FONT_NEVIS

menu = pygame_menu.Menu('Projecte MatZanfe', 600, 400,
                       theme=pygame_menu.themes.THEME_SOLARIZED)

user_input = menu.add.text_input('User: ', font_name = font1, font_color = 'blue')

age_input = menu.add.text_input('Age: ', font_name = font1,font_color = 'Black')
menu.add.button('Start', font_name = font, font_color = 'green')
menu.add.button('Exit', pygame_menu.events.EXIT, font_name = font,font_color = 'red')
menu.mainloop(surface)

Here is the code that contains the game itself (the sums).

import pygame
import random
from InputBox import InputBox
from pygame import mixer
pygame.init()

clock = pygame.time.Clock()
surface = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Projecte MatZanfe")
font = pygame.font.SysFont('comicsans', 50)
base_font = pygame.font.Font(None, 32)
user_text = ''
color_active = pygame.Color('lightskyblue3')
running = True
points = 0

def start_the_game():
    x = random.randint(0, 10)
    y = random.randint(0, 10)
    is_correct = False
    return x, y

def display_the_game(x, y):
    # Variables
    z = x + y
    surface.fill((255, 70, 90))
    text = font.render(str(x) + "+" + str(y), True, (255, 255, 255))

    text_surface = base_font.render(user_text, True, (255, 255, 255))
    surface.blit(text, (260, 120))
    input_box.draw(surface)
    punts = font.render("Puntuació: " +  str(points),True, (255,255,255))
    surface.blit(punts, (350,30))
    titolsuma = font.render("SUMA (1)", True, (0,0,0))
    surface.blit(titolsuma,(10,20))

x, y = start_the_game()
input_box = InputBox(190, 250, 200, 32)

while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        else:
            result = input_box.handle_event(event)
            if result != None:
                if int(result) == int(x) + int(y):
                    points = points + 5
                    mixer.music.load('StarPost.wav')
                    mixer.music.play(1)

                # create new random numbers
                x, y = start_the_game()

                # reset input box (just create a new box)
                input_box = InputBox(190, 250, 200, 32)


    display_the_game(x, y)
    pygame.display.update()

pygame.quit()

And finally here is the code from the imported InputBox (don't know if I actually need to use it).

import pygame


pygame.init()
surface = pygame.display.set_mode((600, 400))
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('black')
FONT = pygame.font.SysFont('comicsans', 32)
base_font = pygame.font.Font(None, 32)
color_active = pygame.Color('lightskyblue3')
user_text = ''


class InputBox:

    def __init__(self, x, y, w, h, text=''):
        self.rect = pygame.Rect(x, y, w, h)
        self.color = COLOR_INACTIVE
        self.text = text
        self.txt_surface = FONT.render(text, True, self.color)
        self.active = False

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            # If the user clicked on the input_box rect.
            if self.rect.collidepoint(event.pos):
                # Toggle the active variable.
                self.active = not self.active
            else:
                self.active = False
            # Change the current color of the input box.
            self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
        if event.type == pygame.KEYDOWN:
            if self.active:
                if event.key == pygame.K_RETURN:
                    user_input = self.text
                    self.text = ''
                    self.txt_surface = FONT.render(self.text, True, self.color)
                    return user_input
                elif event.key == pygame.K_BACKSPACE:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode
                # Re-render the text.
                self.txt_surface = FONT.render(self.text, True, self.color)

    def update(self):
        # Resize the box if the text is too long.
        width = max(200, self.txt_surface.get_width()+10)
        self.rect.w = width

    def draw(self, screen):
        # Blit the text.
        screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
        # Blit the rect.
        pygame.draw.rect(screen, self.color, self.rect, 2)



def main():
    clock = pygame.time.Clock()
    input_box2 = InputBox(190, 250, 200, 32)
    input_boxes = [input_box2]
    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            for box in input_boxes:
                box.handle_event(event)

        for box in input_boxes:
            box.update()

        surface.fill((255, 70, 90))
        for box in input_boxes:
            box.draw(surface)

        pygame.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pygame.quit()



Prevent randomly placed images from appearing in a certain spot (javascript)

I'm quite new to javascript, but I have been trying to use it. I've written a (too lengthy) code that places images randomly on the page. Now I want to make sure the images don't appear behind two menus on the page, but I'm unable to find a functional way of doing this.

The blue highlighted areas are the areas I don't want the images to appear behind: I want the images to avoid the blue highlighted areas

The code I have so far:

(function() {
  var w = window.innerWidth;
  var h = window.innerHeight;

  var urls = ['0', '1', '2', '3', '4'];
  var imageUrl1 = urls[Math.round(Math.random() * urls.length)];
  while (typeof imageUrl1 === 'undefined') {
    var imageUrl1 = urls[Math.round(Math.random() * urls.length)];
  }
  var imageUrl2 = urls[Math.round(Math.random() * urls.length)];
  while (typeof imageUrl2 === 'undefined' | imageUrl2 == imageUrl1) {
    var imageUrl2 = urls[Math.round(Math.random() * urls.length)];
  }
  var imageUrl3 = urls[Math.round(Math.random() * urls.length)];
  while (typeof imageUrl3 === 'undefined' | imageUrl3 == imageUrl1 | imageUrl3 == imageUrl2) {
    var imageUrl3 = urls[Math.round(Math.random() * urls.length)];
  }

  function swap() {
    /* IMAGE 1 */
    var image1 = document.getElementById('image1');

    image1.setAttribute('src', 'images/' + imageUrl1 + '.jpg');
    imageWidth = window.innerWidth / 2.5 + Math.round(Math.random() * 100);
    image1.setAttribute('width', imageWidth);

    var availW = w - image1.clientWidth;
    image1.onload = function() {
      let availH = h - this.height;
      let image1Y = Math.round(Math.random() * availH) + 'px';
      image1.style.top = image1Y;
    }
    var image1X = Math.round(Math.random() * availW) + 'px';

    image1.style.left = image1X;

    /* IMAGE 2 */
    var image2 = document.getElementById('image2');

    image2.setAttribute('src', 'images/' + imageUrl2 + '.jpg');
    imageWidth = window.innerWidth / 3 - Math.round(Math.random() * 250);
    while (imageWidth < 200) {
      imageWidth = window.innerWidth / 3 + Math.round(Math.random() * 150);
    }
    image2.setAttribute('width', imageWidth);

    var availW = w - image1.clientWidth;
    image2.onload = function() {
      let availH = h - this.height;
      var image2Y = Math.round(Math.random() * availH) + 'px';
      image2.style.top = image2Y;
    }
    var image2X = Math.round(Math.random() * availW) + 'px';

    image2.style.left = image2X;

    /* IMAGE 3 */
    var image3 = document.getElementById('image3');

    image3.setAttribute('src', 'images/' + imageUrl3 + '.jpg');
    imageWidth = window.innerWidth / 2.5 - Math.round(Math.random() * 350);
    while (imageWidth < 80) {
      imageWidth = window.innerWidth / 2.5 - Math.round(Math.random() * 150);
    }
    image3.setAttribute('width', imageWidth);

    var availW = w - image1.clientWidth;
    image3.onload = function() {
      let availH = h - this.height;
      var image3Y = Math.round(Math.random() * availH) + 'px';
      image3.style.top = image3Y;
    }
    var image3X = Math.round(Math.random() * availW) + 'px';

    image3.style.left = image3X;
  }


  // Mozilla, Opera and webkit nightlies currently support this event
  if (document.addEventListener) {
    window.addEventListener('load', swap, false);
    // If IE event model is used
  } else if (document.attachEvent) {
    window.attachEvent('onload', swap);
  }

})();
<img id="image1" />

<img id="image2" />

<img id="image3" />

How do I make sure the images don't appear behind these text blocks?




generate 9 sets of normal distribution values and obtain a matrix output

I need to fit 9 different normal distributions, and i have to randomly sample 400 values from each distribution 10000 times. As an output I need to have a matrix of 400x9 (samples x normal distribution column). Basically, I need to combine all the 9 columns into one data frame. Currently, I can only see the first column but i need the 9 columns and 400 rows as an output. I would appreciate help on this. Thanks!

set.seed(400) 
num.reps<- 10000
sample.pc<- list(mode="vector", length = num.reps)

for(i in 1:num.reps){
  sample.pc[[i]] <- rnorm(400, mean =5.537264e-17, sd = 2.49595553)
  sample.pc2 <- rnorm(400, mean = -2.429305e-16, sd = 1.35352493)
  sample.pc3 <- rnorm(400, mean=    -7.333272e-18, sd = 0.90022111)
  sample.pc4 <- rnorm(400, mean = -1.983712e-16, sd = 0.28241488)
  sample.pc5 <- rnorm(400, mean = 3.032541e-17, sd = 0.15098984)
  sample.pc6 <- rnorm(400, mean = 2.077501e-18, sd = 0.11122803)
  sample.pc7 <- rnorm(400, mean = 8.101434e-18, sd = 0.08348879)
  sample.pc8 <- rnorm(400, mean = -2.521973e-17, sd = 0.06165478)
  sample.pc9 <- rnorm(400, mean = 1.780955e-17, sd= 0.04559334)
**strong text**}



How to efficiently use numpy random choice for varying weight list

I am trying to use choice() function to randomly choose numbers from a list whose weights are in a list of lists. That is for every row I want to generate one number. It is possible to do it with for loop like following,

from numpy.random import choice
W_list=np.array([0.9,0.1],
                [0.95,0.05],
                [0.85,0.15])
number_list=[]
for i in range(len(W_list)):
   number_list.extend(choice([0,1],size=1, p=W_list[i]).tolist())

the p parameter needs to 1D hence not possible to use p=W_list I was wondering if there's any way to do this more efficiently without using the for loop.




Python: Values Not Assigned Correctly to Key in Loop

I am trying to create a calibration scheduler in Python. To test the program, I just want to be able generate random dates to assign to a "property" of each instrument. For a reason I can't explain, the output clearly indicates that randdays is correctly randomized yet when assigned to the last_calibrated "property", it indicates identical values for all instruments! Why is this and how can I avoid it?

instrument_props = {"last_calibrated": None,
                 "calibration_due": None,
                 "calibration_expired": None,
                 "installed": None,
                 "replaced_by": None}

instruments = {}

start_date = datetime.date(2020, 1, 1)
end_date = datetime.date(2020, 2, 1)
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days

for instrument in [4167,4958,4959,4960,4961,4962,4963,4964,4965,4966,4967,4968,4969,4970,4971,4972]:
    instruments[instrument] = instrument_props
    randdays = random.randrange(days_between_dates)
    print(randdays)
    instruments[instrument]['last_calibrated'] = start_date + datetime.timedelta(days=randdays)

pp.pprint(instruments)

Here is the output for the above code:

24
25
30
25
0
24
23
9
23
20
16
30
3
20
21
29

{   4167: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4958: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4959: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4960: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4961: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4962: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4963: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4964: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4965: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4966: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4967: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4968: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4969: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4970: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4971: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None},
    4972: {   'calibration_due': None,
              'calibration_expired': None,
              'installed': None,
              'last_calibrated': datetime.date(2020, 1, 30),
              'replaced_by': None}}



Javascript random object inside a random object

Hello i ve been searching for how to get to an object randomly but i need to get another random object that is inside the first random.

This is a card game i want to try.

To be clear my objects are 4 in wich each one they have 10 other objects. I need to get first a random one and with that object get the randoms inside. It needs to be the ones on the selected one because each of them have different values.

i have this

var palos= {
    espada: {
        uno:70, dos:45, tres:50, cuatro:5, cinco:10, seis:15, siete:60, diez:25, once:30, doce:35
    },
    basto: {
        uno:65, dos:45, tres:50, cuatro:5, cinco:10, seis:15, siete:20, diez:25, once:30, doce:35
    },
    Oro: {
        uno:40, dos:45, tres:50, cuatro:5, cinco:10, seis:15, siete:55, diez:25, once:30, doce:35
    },
    copa: {
        uno:40, dos:45, tres:50, cuatro:5, cinco:10, seis:15, siete:20, diez:25, once:30, doce:35
    },
    
}

var palosdados = Object.keys(palos)[Math.floor(Math.random()*Object.keys(palos).length)];
console.log(palosdados);

Thank you in advance.




Has anyone encounter this this stripping artifact during "RayTracing in one Weekend"?

I am trying to port the "RayTracing in One Weekend" into metal compute shader. I encounter this strip artifacts in my project: enter image description here

Is it because my random generator does not work well?

Does anyone have a clue?

// 参照 https://www.pcg-random.org/ 实现
typedef struct { uint64_t state;  uint64_t inc; } pcg32_random_t;

uint32_t pcg32_random_r(thread pcg32_random_t* rng)
{
    uint64_t oldstate = rng->state;
    rng->state = oldstate * 6364136223846793005ULL + rng->inc;
    uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
    uint32_t rot = oldstate >> 59u;
    return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}

void pcg32_srandom_r(thread pcg32_random_t* rng, uint64_t initstate, uint64_t initseq)
{
    rng->state = 0U;
    rng->inc = (initseq << 1u) | 1u;
    pcg32_random_r(rng);
    rng->state += initstate;
    pcg32_random_r(rng);
}

// 生成0~1之间的浮点数
float randomF(thread pcg32_random_t* rng)
{
    //return pcg32_random_r(rng)/float(UINT_MAX);
    return ldexp(float(pcg32_random_r(rng)), -32);
}

// 生成x_min ~ x_max之间的浮点数
float randomRange(thread pcg32_random_t* rng, float x_min, float x_max){
    return randomF(rng) * (x_max - x_min) + x_min;
}



dimanche 22 août 2021

Having YouTube play a random video from an array

How would I be able to have this work in the code?

or for this to be able to work in the code, would it be written differently?

var videos = [
    '0dgNc5S8cLI',
    'mnfmQe8Mv1g',
    'CHahce95B1g'
];

var index=Math.floor(Math.random() * videos.length);

How the code is set up is that, you click on the cover which opens a video.

https://jsfiddle.net/e4bg537p/

How would I be able to set it up so that it plays 1 random video from an array of YouTube ids?

That is what I am trying to figure out how to do.

Can someone show me how this would be done?

<div class="video video-frame" data-id="-SiGnAi845o"></div>

    (function manageCover() {

    function show(el) {
        el.classList.remove("hide");
    }

    function hide(el) {
        el.classList.add("hide");
    }

    function coverClickHandler(evt) {
        const cover = evt.currentTarget;
        hide(cover);
        const video = cover.parentElement.querySelector(".wrap");
        show(video);
    }

    const cover = document.querySelector(".jacket");
    cover.addEventListener("click", coverClickHandler);
}());

const videoPlayer = (function makeVideoPlayer() {

    let player = null;

    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    const firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    function onPlayerReady(event) {
        player = event.target;
        player.setVolume(100); // percent
    }

    function addPlayer(video) {

        const config = {
            height: 360,
            host: "https://www.youtube-nocookie.com",
            videoId: video.dataset.id,
            width: 640
        };
        config.playerVars = {
            autoplay: 0,
            cc_load_policy: 0,
            controls: 1,
            disablekb: 1,
            fs: 0,
            iv_load_policy: 3,
            rel: 0
        };
        config.events = {
            "onReady": onPlayerReady
        };
        player = new YT.Player(video, config);

    }

    function play() {
        player.playVideo();
    }
    return {
        addPlayer,
        play
    };
}());

function onYouTubeIframeAPIReady() {
    const cover = document.querySelector(".jacket");
    const wrapper = cover.parentElement;
    const frameContainer = wrapper.querySelector(".video");
    videoPlayer.addPlayer(frameContainer);
}

(function initCover() {

    function coverClickHandler() {
        videoPlayer.play();
    }

    const cover = document.querySelector(".jacket");
    cover.addEventListener("click", coverClickHandler);
}());



How do I generate a 4-digit number with no duplicates

I wanna generate a 4-digit number with no duplicates, here are the functions that generate a random number with 4-digits. I'm curious if there is a JS method that can do that for me, or do I have to loop through the elements, or even do a while loop until it generates a number with no duplicates (since it's only 4 digits, it is small anyway)..

function genRandomNumber(range = 10) {
  return Math.floor(Math.random() * range);
}

function HiddenNumber(digit = 4) {
    const number = Array.from(
  {
    length: digit
  }, () => genRandomNumber()).join("");
  console.log(number);
  return Number(number);
}



Overlap labels in a heatmap legend-How to move legend labels in ggplot in R?

I want to not overlap the labels with the color legend as in the attachment: legend example Here is the code.

p + guides(fill = guide_colorbar(title = "value(ha.)", label.position = "bottom", title.position = "left", title.vjust = 1, frame.colour = "black", barwidth = 18, barheight = 1))




Using a custom attribute to drive a seed value in Blender Geometry nodes

I am attempting to use a custom attribute ('rand') to drive the seed value of a Random Float node.

Screenshot of sample node set up

I am using the Attribute Randomize node to create a random integer called 'rand' for every point created by the Point Distribute node. I am hoping to use this 'rand' value to introduce randomization to the scale/rotation of the individual points.

I know that I can use the Attribute Randomize node to achieve this; I'm attempting to drive the Seed value using a custom attribute as part of a larger issue.

I haven't been able to figure out a way to get access to the rand attribute as an integer than I can connect to an input (for example, the Seed input of the Random Float node). To be clear, this is what I am attempting to solve.

I also know the nodes I've shared are incorrect, I'm just using them to try to demonstrate the problem :)

Many thanks in advance for any advice!




How to add random state in numpy array

I am creating a random noise using np.random.normal(). I wanted to add random state in it. I tried this:

R = np.random.RandomState(1989)

mu, sigma = 0, 0.1 
noise = R.normal(mu, sigma, [2, 2])

I also tried setting random state using random package:

import random

random.seed(32)
noise = np.random.normal(mu, sigma, [2, 2])

Then I also tried setting random seed with:

np.random.seed(34)

But nothing is working. Can anyone tell me how do I add random state in this noise, so that np.random.normal will give me the same result every time I run it.

NOTE: mu and sigma are mean and standard deviation resp.




Random sample of points on a region of the surface of a unit sphere

I need to generate a random sample of points distributed on a region of the surface of a sphere. This answer gives an elegant recipe to sample the entire surface of the sphere:

def sample_spherical(npoints, ndim=3):
    vec = np.random.randn(ndim, npoints)
    vec /= np.linalg.norm(vec, axis=0)
    return vec

(vec returns the (x, y, z) coordinates) which results in:

enter image description here

I need to restrict the sampling to a rectangular region. This region is defined by center values and lengths, for example:

  • center coordinates, eg: (ra_0, dec_0) = (34, 67)
  • side lengths, eg: (ra_l, dec_l) = (2, 1)

where (ra_0, dec_0) are coordinates in the equatorial system, and the lengths are in degrees.

I could use the above function in the following way: call it using a large npoints, transform the returned (x, y, z) values into the equatorial system, reject those outside the defined region, and repeat until the desired number of samples is reached. I feel that there must be a more elegant way of achieving this though.




F# System.Random duplicate values

I'm trying to use System.Random in F# but keep getting duplicate values. I'm aware that if I create a new instance of System.Random each time I do .Next i might get duplicate values. What I'm trying to achive is setting a random id on each record when creating them. Here is an example of the problem in code:

[<AutoOpen>]
module Domain = 
    type Test = {id: int; ....} 

module Test =

    let r = System.Random() 

    let t create =
        {id = r.Next(); ....}


let a = Test.create
let b = Test.create

In the code above bot a and b gets the same id.

What I'm guessing is happening is that let r = System.Random() doesn't get treated as a variable but as a function which returns a new instance of Random. Is this correct? And how can I Solve this problem?

Thanks!




samedi 21 août 2021

Pandas Fast Alternative to SLOW FOR LOOP

I have a data column with 3 unique items: '1-2 Year', '< 1 Year', '> 2 Years'.

My goal is to transform all the rows to random numbers in months. For example, < 1 year can be any number between 1 and 12 meaning 1 to 12 months. I used a FOR loop but it is running very slow and I am wondering if there is an efficient way to get the task done.

for i in all_data['Age']:
    if i == '1-2 Year':
        all_data['months'] = np.random.randint(12, 24, all_data.shape[0])
    elif i == '< 1 Year':
        all_data['months'] = np.random.randint(1, 12, all_data.shape[0])
    else:
        all_data['months'] = np.random.randint(25, 60, all_data.shape[0])

Above is my code. Please assist with a more efficient way. Thank you.




Random Number in Fortran

I am learning Fortran and I would like to make a little game to practice the input. The objective is to find the good number, who is a random one. I made a code to generate the number but my problem is that, the result is a random number, but it's always the same. For example, when I execute the code 3 times, it print 21 the three times.

Here is my code :

program find_good_number
    integer :: random_number
    integer :: seed
    seed = 123456789
    call srand(seed)
    random_number = int(rand(0)*100)
    print*, random_number
end program find_good_number

Can you help me please ? Thanks




How to find a certain string/name in a txt file?

So im making a name generator/finder, So for the find command i want to find that name in the txt file with the line number! So how do i find the name with the line number?

line = 0

names = open(r"names.txt", "r")
name1 = names.readlines()

uname = input("Please enter the name you want to find: ")
for name in name1:
  try:
    print(name)
    print(line)
    if name == uname:
      print(f"Found name: {name} \nLine No. {line + 1}")
    else:
      line = line + 1
  except:
    print("Unable to process")

But it seems to not work except if you write the last name in file it works. So could give any help?




Generate random number that fluctuates by F within range R

I want to generate a random number within this range: [0.79, 2.7]

Every time I generate a number I want to store its value so that next time I generate a new number its absolute difference (compared to the previous one) is never greater than 0.01.

What I'm trying to simulate is the fluctuation of the value of a cryptocoin in 0.01 steps

I have come up with this method:

const MIN = 0.79
const MAX = 2.7
const DIFF = 0.01
const INTERVAL = 1000

let previous = undefined 

function getRandom() {
  let current = Math.random() * (MAX - MIN) + MIN;
    
  if (Math.abs(current - (previous || current)) > DIFF){
    return getRandom()
  } else {
    previous = current
    return current
  }
}

setInterval(() => {
  console.log(getRandom())
}, INTERVAL)

It works, as in, the MIN, MAX and DIFF restrictions are applied. However, the values I get seem to always fluctuate around the very first random number that will be generated. So if the first random number I get is e.g. 2.34 I will then start getting:

2.338268500646769
2.3415300555082035
2.3438416874302623
2.3475220779731107
2.3552742162452693
2.353575076772505
2.3502457929806693
2.3561300642858143
2.353045875361622
2.3592926605489004
2.360013424409005
2.3520769942926023

Whereas, what I want is for them to fluctuate all the way from 0.79 to 2.7 with 0.01 steps but randomly nevertheless. So the value of a cryptocoin might start going up for a X seconds, then down for Y seconds, then further down for another Z seconds then all of a sudden up for T seconds etc..

Can you think of an algorithm to mimic that ?

Thank you in advance for your help.