jeudi 30 septembre 2021

Can I temporarily disable random / srand in c++?

I have a very large codebase that uses srand and rand that I need to debug. The random executions make debugging difficult, since bugs occur randomly too. Is there any way to temporary make the library execute deterministically so I can debug the code?




How to randomize material for multiple objects in blender in python?

I'm trying to randomize the material of multiple objects in blender, but all I found is this code

import bpy

prefix = '_'

materials = []
for mat in bpy.data.materials:
     if mat.name.startswith(prefix):
         materials.append(mat)

for obj in bpy.context.selected_objects:
     obj.active_material = random.choice(materials)

but this changes it for only the selected object. what I want is to type the name of the objects I want to change material to it instead of only the selected ones so for example:

change the "cube" in the scene material to Only materials that start with the prefix "x" at the same time change the materials of the "circle" with Only the materials that start with the prefix "Y" so now I have multiple objects change material at the same time but each object has its own materials to change from. Is there any way I can do it?




How can I generate a random with time interval in PHP

I have the code :

$length = 16;
$characters = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
   $randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$key = $randomString;

How to solve this if the string will be shuffled after 10 minutes, and the string is always the same every 10 minutes?




What is the best way of generating a random value within a closed interval in C?

In general, when I need to generate a random value within a closed interval (considering B as the beginning and E as the end of the interval) in C, I use one of the following approaches:

Approach 1:

n = round(B + ( (float)rand() / RAND_MAX ) * (E - B));

Approach 2:

n = B + rand()%(E - B+1);

Both of them consider the initialization of the random seed with the function time():

srand(time(NULL));

In Linux systems, both approaches seem good enough for generating interesting random values. However, in Windows systems, sometimes the numbers do not appear to be random enough.

Investigating these systems, I've found that the value of RAND_MAX is different. In the Linux systems that I have tested RAND_MAX is 2147483647. In these windows systems with a not-so-good behavior, RAND_MAX is 32767.

I think that with a larger RAND_MAX value we can generate better random numbers. But I'm not sure.

With this in mind, my question is: Is there some good way of generating interesting random numbers (within a closed interval) that work well on all systems?

Besides that, my approaches 1 and 2 are good approaches for generating random numbers within a closed interval?




Java: I am trying to generate a word with random characters and then checking it against a hashmap of words to see if it is real

So, I am trying to generate a word and then check if it is a real word using word index. Can someone help me figure out how to solve this, it is constantly giving me a never-ending loop. I just simply wanted to create random characters, and after each character see if it exists in the hashmap. First by checking to find the key which is the first letter of the word, and then by checking the substring of each word in that key selection.

  public ArrayList<String> randomSize(int length) {
            ArrayList<String> randomWords = new ArrayList<>(length);
            String letters = "abcdefghijklmnopqrstuvwxyz";
            // for loop add a new slot into randomWords
            for (int eachSlot = 0; eachSlot < length; eachSlot++) {
                // for each slot generate a random length for the word
                int randWordLength = (int) (Math.random() * (10 - 0) + 0);
                // every slot generate a random firstLetter
                int slotFound = 0;
                String firstConfirmedLetter = "";
                // while the first letter is not found in WordIndex
                while (slotFound == 0) {
                    int randNumer = (int) (Math.random() * (24 - 0) + 0);
                    String firstLetter = letters.substring(randNumer, randNumer + 1);
                    if (wordIndex.containsKey(firstLetter) == true)
                    {
                        firstConfirmedLetter = firstLetter;
                        randomWords.add(firstConfirmedLetter);
                        System.out.println(firstLetter);// working
                        randWordLength--;
                        slotFound = 1;
                        // if it is found end the while loop
                    }
    
                }
    
                // we found the first letter, now we need to find the rest of the letters
                for (int eachLetter = 0; eachLetter < randWordLength; eachLetter++){
                    int isFound = 0;
                    // while letter is not found loop through until it is found with combimation to the previous letter
                    while (isFound == 0){
                        // gerate a random letter
                        int randLetter = (int) (Math.random() * (24 - 0) + 0);
                        String nextLetter = letters.substring(randLetter, randLetter + 1);
                        //create curr word
                        String currWord = randomWords.get(eachSlot) + nextLetter;// works until here
                        // loop through each word in wordIdex to find match
                        System.out.println(wordIndex.get(firstConfirmedLetter).size());
                        for(int i = 0; i< wordIndex.get(firstConfirmedLetter).size(); i++){
                            String test = wordIndex.get(firstConfirmedLetter).get(i);
                            if(test.length() > eachLetter+2){
                              System.out.println(test.substring(0,eachLetter+2));
                              if(test.substring(0,eachLetter+2).equals(currWord)){
                                  String currState = randomWords.get(eachSlot);
                                  randomWords.set(eachSlot,currWord);
                                  isFound =1;
                              }
                            }
                        }
    
                    }
                }
    
    
    
            }
            return randomWords;
        }



I would like to generate random points in an image with delauney triangulation with mean distance between neighbours of 4.1 pixels

I am using this function to generate uniformly distributed points on a an image.

def generate_uniform_random_points(image, n_points=100):
    """
    Generates a set of uniformly distributed points over the area of image
    :param image: image as an array
    :param n_points: int number of points to generate
    :return: array of points
    """
    ymax, xmax = image.shape[:2]
    points = np.random.uniform(size=(n_points, 2))
    points *= np.array([xmax, ymax])
    points = np.concatenate([points, edge_points(image)])
    return points 

However, I would like to get randomly distributed points with with mean distance between neighbours of 4.1 pixels.

Any help will help.




Generate a random number which change every 24 hours

Hi I make a app and want to know can we use random module to generate a random number which will change every 24 hours? Thanks for help.




What is the most efficient way to generate random numbers from a union of disjoint ranges in Kotlin?

I would like to generate random numbers from a union of ranges in Kotlin. I know I can do something like

((1..10) + (50..100)).random()

but unfortunately this creates an intermediate list, which can be rather expensive when the ranges are large.

I know I could write a custom function to randomly select a range with a weight based on its width, followed by randomly choosing an element from that range, but I am wondering if there is a cleaner way to achieve this with Kotlin built-ins.




mercredi 29 septembre 2021

I have list items containing images on both side of the card, my goal is to select list item randomly and flip the card automatically to infinite

this is the card styling I need to change randomly on every card, properties I need to change on flip is transform, position and z-index.

    <style>
.card-front {
    backface-visibility: hidden;
    left: 0px;
    position: relative;
    top: 0px;
    transform: rotateX(0deg);
    transform-style: preserve-3d;
    width: 100%;
    height: 100%;
    z-index: 2;
    transition: all 1.3s ease 0s;
}
.card-back {
    backface-visibility: hidden;
    left: 0px;
    position: absolute;
    top: 0px;
    transform: rotateX(-180deg);
    transform-style: preserve-3d;
    width: 100%;
    height: 100%;
    transition: all 1.3s ease 0s; 
}
</style>

this is one of the list items containing front and back cards which is going to flip.

    <body>
              <li>
                    <div class="react-card-flip" style="perspective: 1000px; z-index: auto">
                      <div id="card" class=" " style="position: relative; height: 100%; width: 100%">
                        <div class="react-card-front card-front front">
                          <span>
                            <img src="#" alt="Dummy Image" />
                          </span>
                        </div>
                        <div class="react-card-back card-back back">
                          <span>
                            <img src="#" alt="Dummy Image" />
                          </span>
                        </div>
                      </div>
                    </div>
                  </li>
</body>

I'm having a problem with an event in jquery which is going to invoke automatically and randomly on a list items with infinite time intervals, please help me out.

    <script>
$('.react-card-flip').ready(function() {
    $("li").trigger(function(){
        var $li = $("li");
        $li.eq(Math.floor(Math.random()*$li.length))
    });
    $("li .react-card-flipper > .card-front").css({
        "backface-visibility": "hidden",
        "position": "relative",
        "transform": "rotateX(0deg)",
        "z-index": "2",
        "left": "0px",
        "top": "0px",
        "transform-style": "preserve-3d",
        "width": "100%",
        "height": "100%",
        "transition": "all 1.3s ease 0s"
    });
    $(".react-card-flipper > .card-back").css({
        "position": "absolute",
        "transform": "rotateX(-180deg)",
        "z-index": "1"
    });
});
$("li .react-card-flipper > .card-front").css({"position": "absolute", "transform": "rotateX(-180deg)","z-index": "1"});
$(".react-card-flipper > .card-back").css({"position": "relative", "transform": "rotateX(0deg)", "z-index": "2"});
</script>



How to keep a fixed size of unique values in random positions in an array while replacing others with a mask?

This can be a very simple question as I am still exploring Python. And for this issue I use numpy. Let's say I have a 2D array like this:

test_array = np.array([[0,0,0,0,0],
                      [1,1,1,1,1],
                      [0,0,0,0,0],
                      [2,2,2,4,4],
                      [4,4,4,2,2],
                      [0,0,0,0,0]])
print("existing classes:", np.unique(test_array))
# "existing classes: [0 1 2 4]"

Now I want to keep a fixed size (e.g. 2 values) in each class that != 0 (in this case two 1s, two 2s, and two 4s) and replace the rest with 0. Where the value being replaced is random with each run (or from a seed).

For example, with run 1 I will have

([[0,0,0,0,0],
[1,0,0,1,0],
[0,0,0,0,0],
[2,0,0,0,4],
[4,0,0,2,0],
[0,0,0,0,0]])

with another run it might be

([[0,0,0,0,0],
[1,1,0,0,0],
[0,0,0,0,0],
[2,0,2,0,4],
[4,0,0,0,0],
[0,0,0,0,0]])

etc. Could anyone help me with this?




randomly sampling of dataset to decrease the values in the dataset

I am currently trying to decrease the values in a column randomly according to a given sum. For example, if the main data is like this;

ID Value

1 4
2 10
3 16

after running the code the sum of Value should be 10 and this need to be done randomly(the decrease for each member should be chosen randomly)

ID Value

1 1
2 8
3 1

Tried several command and library but could not manage it. Still a novice and Any help would be appreciated!

Thanks




Linux cron job (at least) every hour with random delay

I want to run a script approximately every hour but I want it with a random delay while keeping the time between the runs at least one hour.

That means:

  • 00:00 01:00 + RANDOM minutes (5) => 01:05 (execution)
  • 01:05 + 1 = 02:05 + RANDOM minutes (7) => 02:12 (execution)
  • 02:12 + 1 = 03:12 + RANDOM minutes (2) => 03:14 (execution) ...

Is this possible using cron?




C++ std::random and enum class

I've got a fussy question regarding more modern C++ "preferred" styles.

Say I want to use the contents of std::random in order to select a value from an enum class. How can I finagle that? We're talking some pretty basic stuff here, where the first selection works just fine, but Visual Studio scolds me (rightly) for using bare enums:

enum Direction:uint8_t {
    Left, Right
};

std::uniform_int_distribution<uint8_t> direction(Direction::Left, Direction::Right);

// and so on...

I was surprised enum-base works for a classic enum. But, simply adding the word class into the mix causes the whole shebang to fail to compile.

enum class Direction:uint8_t {
    Left, Right
};

std::uniform_int_distribution<uint8_t> direction(Direction::Left, Direction::Right);

// Severity Code    Description Project File    Line    Suppression State
// Error    C2338   invalid template argument for uniform_int_distribution:
//    N4659 29.6.1.1 [rand.req.genl]/1e requires one of short, int, long, long long, unsigned short, 
//    unsigned int, unsigned long, or unsigned long long 
//    C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30133\
//    include\random    1863    

And so on. =)

I can certainly swallow my pride and principle for the sake of this homework, but goshdernit I wanted to abide by modern standards.

I'd be tickled pink if someone had some clever workaround or other best-practice-style-thing when one wants to shuffle an enum like this.

Thanks in advance!




Creating windows that spawn in random locations on a building in Python Turtle

I have a function called draw_object that I want to draw skyscrapers and within that function I want there to be windows that will be created within the bounds of that skyscraper.

Since I want the skyscraper in many locations I thought the best idea for the windows would be to have them spawn in random locations based upon where the skyscraper is.

Here is the code I have no far:

def draw_object(x,y):
    draw_rectangle(t1,x,y,1,"black","gray",60,40)
    draw_rectangle(t1,randint(x,y),randint(y,),1,"yellow","yellow",5,5)



quel est le probleme avec ce code qui génére un texte bien parenthésé aleatoirement? [closed]

Bonjour, j'ai écrit ce cette fonction pour générer un texte bine parenthésé mais j'ai que des parenthèses ouvrantes dans le résultat.

void genereTextBienParenthese(FILE * output){
    int n = random() % TAILLE_MAX_TEXTE;
    char c;
    PileChar p;
    int cond;
    for (int i = 0; i < n; i++)
    {
        cond=1;
        printf("i = %d\n",i);
        c = genereChar();
        if(c=='('){ empiler(&p,c);}
        if(c==')'){
        if(est_vide(&p)||(sommet(&p)!='(')){cond= 0;}
        else{depiler(&p);}
        }
        
        if(c=='{'){empiler(&p,c);}
        if(c=='}'){
        if(est_vide(&p)||(sommet(&p)!='{')){cond=0;}
        else{depiler(&p);}
        }

        if(c=='['){empiler(&p,c);}
        if(c==']'){
        if(est_vide(&p)||(sommet(&p)!='[')){cond=0;}
        else{depiler(&p);}
        }
        if (cond){fprintf(output, "%c", c);}
    }
}``



replacing the positive and negative number of a column with certain condition

i have a text file that contain four columns of data,I want to modify only 4th column with some conditions.

condition : The 4th column of the input file contains negative and positive values. First of all I want to keep the negative values of 4th column if it falls within the range -1.249582196275393240e-02 and -2.100552742679913983e-02 and similarly i want to keep the positive values of the 4th column if it falls within the range 1.381056887718538353e-04 and 2.346095085764924595e-04.

However remaining negative values of the 4th column should be replaced randomly and that random number should fall in the range -1.145493471994996071e-03 and -1.8445493471994996071e-03 and in the similar way the remaining positive values should fall randomly within the range 1.531056887718538353e-06 and 1.956056887718538353e-06.

My input file is

    2.60000038 2.99699998 -0.00000000 -1.249582196275393240e-02
    2.70000076 2.99699998 -0.00000000 -2.296202816069126129e-02
    2.80000114 2.99699998 -0.00000000 -2.527230263998111234e-02
    2.89999962 2.99699998 -0.00000000 -2.100552742679913983e-02
    2.89999962 2.99699998 -0.00000000 -2.150552742679913983e-01
    2.89999962 2.99699998 -5.00000000 -2.190552742679913983e-01
    2.89999962 2.99699998 -900000000  -2.190552742679913983e-03
    0.500000000 2.99699998 -1.14950405E-09 1.381056887718538353e-04
    0.600000381 2.99699998 -1.66670497E-10 2.346095085764924595e-04
    0.700000763 2.99699998 -9.37441375E-11 2.136244050537546566e-04
    0.800000763 2.99699998 -9.37441375E-11 1.126244050537546566e-04
    0.700000763 2.99699998 -9.37441375E-11 1.136244050537546566e-04
    0.700000763 2.99699998 -9.37441375E-11 2.136244050537546566e-03

the below mentioned three lines of the input file  
    2.89999962 2.99699998 -0.00000000 -2.150552742679913983e-01
    2.89999962 2.99699998 -5.00000000 -2.190552742679913983e-01
    2.89999962 2.99699998 -900000000  -2.190552742679913983e-03
 should be replaced by
    2.89999962 2.99699998 -0.00000000 -1.149552522674912181e-03
    2.89999962 2.99699998 -5.00000000 -1.141552612675913281e-03
    2.89999962 2.99699998 -900000000  -1.346552142676911382e-03

Additionally, these three lines of the input file

    0.800000763 2.99699998 -9.37441375E-11 1.126244050537546566e-04
    0.700000763 2.99699998 -9.37441375E-11 1.136244050537546566e-04
    0.700000763 2.99699998 -9.37441375E-11 2.136244050537546566e-03

should be replaced by

   0.800000763 2.99699998 -9.37441375E-11 1.561056887718538353e-06
   0.700000763 2.99699998 -9.37441375E-11 1.621056887718538353e-06
   0.700000763 2.99699998 -9.37441375E-11 1.506244050537546566e-06

so my overall output should be

2.60000038 2.99699998 -0.00000000 -1.249582196275393240e-02
2.70000076 2.99699998 -0.00000000 -2.296202816069126129e-02
2.80000114 2.99699998 -0.00000000 -2.527230263998111234e-02
2.89999962 2.99699998 -0.00000000 -2.100552742679913983e-02
2.89999962 2.99699998 -0.00000000 -1.149552522674912181e-03
2.89999962 2.99699998 -5.00000000 -1.141552612675913281e-03
2.89999962 2.99699998 -900000000  -1.346552142676911382e-03
0.500000000 2.99699998 -1.14950405E-09 1.381056887718538353e-04
0.600000381 2.99699998 -1.66670497E-10 2.346095085764924595e-04
0.700000763 2.99699998 -9.37441375E-11 2.136244050537546566e-04
0.800000763 2.99699998 -9.37441375E-11 1.561056887718538353e-06
0.700000763 2.99699998 -9.37441375E-11 1.621056887718538353e-06
0.700000763 2.99699998 -9.37441375E-11 1.506244050537546566e-06

i tried

awk '{for(i=1;i<=NF;i++)if($4==-1.249582196275393240e-02 && -2.100552742679913983e-02)$i=" "}1' input

However, i am facing some problem in solving this.I hope experts may help me.Thanks in advance.




How to use do notation with System.Random.Stateful

I want to use do notation to combine pseudo-random values:

g :: StdGen
g = mkStdGen 100

example1 :: Bool
example1
  = fst
  $ runState
    (do x <- state (uniformR (False,True))
        y <- state (uniformR (False,True))
        return $ x == y
    )
    g

Function uniformR is defined in terms of the System.Random.Stateful module:

uniformR :: (RandomGen g, UniformRange a) => (a, a) -> g -> (a, g)
uniformR r g = runStateGen g (uniformRM r)

so in my example, it seems silly for uniformR to create and run state, only for my example to create and run state again.

Is there a way to rewrite example 1, using System.Random.Stateful and do notation?

This is the only thing I could get to work (which is ridiculous):

example3 :: Bool
example3
  = fst
  $ runStateGen
    g
    (do x <- uniformRM (False,True)
        y <- uniformRM (False,True)
        return $ do x' <- x
                    y' <- y
                    return $ x'==y')

It seems like what I need is some type of monad transformer?




mardi 28 septembre 2021

how do you make a mp4 video to a url link that ends in .mp4

an example is that this guy made one for rick roll https://shattereddisk.github.io/rickroll/rickroll.mp4




Sending a random joke in Discord.py

I want to send a random joke when a user gives a command in discord.py. And I want to get a joke via a website (api). Things I want :

1.A website api that I can get a random joke

2.How can I send the joke? (I want an example code)




How can I assign a random color to each circle in a grid, then get each circle to progress through the color spectrum from the start color?

I am trying to assign a random color to each circle once, and then get that color to progress through the color spectrum. I am a beginner and cannot work out how to stop the random color in draw function from resetting every loop without pulling it into setup function which then makes all the circles start from the same random color. Code below of what I have so far. It also seems to be changing the colors in a slight wave at the moment, I assume this is to do with the 'for'. All i want is a grid of circles that are assigned a random color once and then go on to progress their color through the color wheel at the same speed. Thanks in advance!

let intervals = [10];
let count;
let frameWidth;
let distance;
let diam1;
let col1;
let sat1;
let bri1;
let speed;

function setup() {
  
  createCanvas(800, 800);  
  
  colorMode(HSB, 360, 100, 100, 1);
  
//initiate draw variables
  
  count = random(intervals);
  
  frameWidth = (width*0.8);
  
  distance = (frameWidth/count);
  
  col1 = random(360);
  
  diam1 = distance*0.5;  
  
  speed = 0.005;
  
}

function draw() {
  
  background(0, 0, 0, 1);

// draw grid of circles
  
  for (let x = width * 0.1; x <= width * 0.9; x += distance) {
    
    for (let y = height * 0.1; y <= height * 0.9; y += distance) {
      
      sat1 = 100;
      
      bri1 = 100;
      
      noStroke();
      
      fill(col1, sat1, bri1, 1);
      
      ellipse(x,y,diam1);
      
      col1 = col1 + speed
      
      if (col1 >= 360) {
        
      col1 = 0
      
      }
  
      }
    }
  }  



How to display a random background image derived from an API when a page loads?

My code can showcase image results based on what the user types in, I'm having trouble with displaying a random image from my API when the page loads. I assume math.random is part of it, but I'm having trouble making it work.




Generate Beta distributed random variables on GCC and MS C++17

The below code gives me a beta distributed random variable in MSVC c++17:

std::mt19937 gen;
std::_Beta_distribution<float> beta(0.5, 0.5);
std::cout << beta(gen) << std::endl;

Unfortunately, the same code will not compile on GCC9.3.0. I need code, preferably a single approach that works across both platforms but I will do for separate approaches, to generate a Beta distributed random variable, without using Boost. How to approach this? Is std::_Beta_distribution hidden somewhere else for GCC? Or do I need to write my own code?




replacing values of a column with certain condition

i have a text file that contain four columns of data,I want to modify only 4th column with some conditions which is little bit tricky,

condition : If we see the 4th column, that contain negative and positive values.I just want to keep the negative values of 4th column if it falls within the range -1.249582196275393240e-02 and -2.100552742679913983e-02 and similarly i want to keep the positive values of the 4th column if it falls within the range 1.381056887718538353e-04 and 2.346095085764924595e-04. However remaining negative values of the 4th column should be replaced randomly and that random number should fall in the range -1.145493471994996071e-03 and -1.8445493471994996071e-03 and in the similar way the remaining positive values should fall randomly within the range 1.531056887718538353e-06 and 1.956056887718538353e-06.

0.00000000 2.99699998 -2.84957702E-09 -5.307858809828758240e-04
0.100000381 2.99699998 -4.68360684E-09 -6.632010918110609055e-04
0.200000763 2.99699998 -5.35559996E-09 -6.618221911291281021e-04
0.300001144 2.99699998 1.45702295E-09 -6.119244499132037163e-04
0.399999619 2.99699998 5.45327616E-10 -9.009421531421442375e-05
0.500000000 2.99699998 -1.14950405E-09 1.381056887718538353e-04
0.600000381 2.99699998 -1.66670497E-10 2.346095085764924595e-04
0.700000763 2.99699998 -9.37441375E-11 2.136244050537546566e-04
0.800001144 2.99699998 -1.36117896E-12 -7.592248342310388601e-06
0.899999619 2.99699998 -5.71992106E-13 -3.888342762365937233e-04
1.00000000 2.99699998 -6.03400088E-13 -3.404438806076844353e-04
1.10000038 2.99699998 -1.03240001E-13 -1.001964362027744396e-05
1.20000076 2.99699998 -0.00000000 7.743958073357740677e-04
1.30000114 2.99699998 -0.00000000 8.257767185568809509e-04
1.39999962 2.99699998 -0.00000000 3.288088676830133028e-05
1.50000000 2.99699998 -0.00000000 -1.937364577315747738e-04
1.60000038 2.99699998 -0.00000000 6.337644299492239952e-01
1.70000076 2.99699998 -0.00000000 7.002819329500198364e-01
1.80000114 2.99699998 -0.00000000 7.997010834515094757e-01
1.89999962 2.99699998 -0.00000000 3.407316592832406181e-01
2.00000000 2.99699998 -0.00000000 -1.045938600630809818e-04
2.10000038 2.99699998 -0.00000000 -4.584837394456068855e-04
2.20000076 2.99699998 -0.00000000 -4.834951056788365227e-04
2.30000114 2.99699998 -0.00000000 1.355664474734415701e-04
2.39999962 2.99699998 -0.00000000 8.168490603566169739e-04
2.50000000 2.99699998 -0.00000000 3.781475049133102280e-04
2.60000038 2.99699998 -0.00000000 -1.249582196275393240e-02
2.70000076 2.99699998 -0.00000000 -2.296202816069126129e-02
2.80000114 2.99699998 -0.00000000 -2.527230263998111234e-02
2.89999962 2.99699998 -0.00000000 -2.100552742679913983e-02
3.00000000 2.99699998 -0.00000000 -1.145493471994996071e-03
3.10000038 2.99699998 -0.00000000 -8.956699942549070084e-04
3.20000076 2.99699998 -0.00000000 -2.074862675120433316e-03
3.30000114 2.99699998 -0.00000000 -3.787500162919362531e-03
3.39999962 2.99699998 -0.00000000 -5.514865741133689880e-03
3.50000000 2.99699998 -0.00000000 -5.781509603063265772e-03
3.60000038 2.99699998 1.23875296E-07 -3.731979367633660779e-03
3.70000076 2.99699998 8.67075073E-07 -7.905315142124891281e-04

I tried with Replacing a string with a random number using awk, but couldnot do it.I hope experts may help me overcoming this problem.Thanks in advance.




Random Number Generator in Excel (pre-2010)

I have found reference to the fact that Excel started using the Mersenne Twister algorithm for random number generation in Excel 2010.

Does anyone have any reference or idea as to what algorithm was used in previous versions (2007, 2003, etc.)?




INTERACTION_TYPE

  # load necessary packages

import pandas as pd import contextlib import urllib.request import gzip

def DownloadAndProcessPathwayCommonsData(filename="PathwayCommons.csv"): """Download PathwayCommons data from txt format - long .sif file (see details here: https://www.pathwaycommons.org/pc2/formats) The data are converted into DataFrame.

   read_csv method from pandas library is applied to load a small chunk of data (1000 rows of txt file). Next the data are filtered
   as follows:
   * only those edges of the network are taken which has in interaction_type column only those values listed in 'interactions' vector
   * column MEDIATOR_IDS is deleted  

Keyword arguments:
filename --- path to the file where data will be downloaded, as a default in the current directory under the name "PathwayCommons.csv"

Outputs:
result --- a text "data downloaded" which is printed when data are downloaded successfully
"""
# url where PathwayCommons is located
url = "https://www.pathwaycommons.org/archives/PC2/v12/PathwayCommons12.All.hgnc.txt.gz"
# list with all important interactions type
interactions = ["controls-expression-of","interacts-with", "controls-phosphorylation-of",
            "controls-state-change-of", "controls-production-of", "catalysis-precedes",
            "controls-transport-of", "controls-transport-of-chemical", "chemical-affects",
            "consumption-controlled-by","used-to-produce", "reacts-with"]
# empty list where whole database will be loaded
pathwaydata = []
with contextlib.closing(urllib.request.urlopen(url=url)) as rd: # open url
    gzip_fd = gzip.GzipFile(fileobj=rd) # extract zip file
    for df in pd.read_csv(gzip_fd, chunksize=1000,sep="\t"): # load 1000 entries of PathwayCommons (chunksize=1000)
        data=df.loc[ df['INTERACTION_TYPE'].isin(interactions)] # get only those rows where type of interaction is of this listed in list interactions
        data = data.drop(columns = "MEDIATOR_IDS") # drop "MEDIATOR_IDS" column as this column is not necessary
        # <here further process the data>
        data= data.values.tolist()  # convert dataframe to list
        data = [item for sublist in data for item in sublist]
        pathwaydata.append(data) # add the  data to pathwaydata list
pathwaydata= [item for sublist in pathwaydata for item in sublist] # make the list flat
pathwaydata = [pathwaydata[i:i+6] for i in range(0, len(pathwaydata), 6)]  # create nested list
col_names = ["PARTICIPANT_A","INTERACTION_TYPE","PARTICIPANT_B","INTERACTION_PUBMED_ID","PATHWAY_NAMES"]   # add column names
pathwaydata = pd.DataFrame(pathwaydata, columns=col_names)   # convert the data to pandas dataframe
pathwaydata.to_csv(filename)  # save data
return "data downloaded"

if name == 'main': # download PathwayCommons database result=DownloadAndProcessPathwayCommonsData(filename="C:\Ruby\data\PathwayCommons.csv") print(result)

HI NEED HELP FROM LINE 36-42 CODE CHANGES In the above script how can I do changes to get the data in the form of csv file from online databases specifically in "INTERACTION_TYPE" to get data from only signaling pathways not from protein-protein interaction pathway. Can anybody help me? Thanks in advance




Is there a way to make a random variable into one that isn't random?

I am experimenting and studying a lot about programming lately. I want to write a guessing game in python, where the pc guesses a number in a range defined by the user. The way I have written this part is like so:

low = int(input("Choose the smaller number: "))
high = int(input("Choose the higher number: "))
num = random.randint(low, high)
pc_guess = input("Is this number correct: "+ str(num)+ "?")

If the answer isn't correct the computer will ask if their guess was high or low. What I wanted to do, was set a new range based on the computer's guess (for example, if the guess was too high, the new ceiling would be the guess minus 1). The guessing game concept isn't new to me, I wanted to try and write it more dynamically, test myself. But I realized I didn't know the answer to this question, is there any way to take the value of a previous random number, and assign it to a variable that isn't random?




lundi 27 septembre 2021

Random smooth 2D path in MATLAB

I want to plot a random path between 2 points, say (0,0) to (10,10), where the path should not have crossings. It may be a road with few smooth bends.

I found few cases but did not match to my requirements. Example 1 Example 2




Random strange behavior

I've created just for fun this method to find out how long it takes until this random method goes into a loop and what the seed is when this occurs:

public static void main(String[] args) {
      HashMap<Integer,Integer> map = new HashMap<>();
      for (int i = 0; i < 1000; i++) {
        int key = firstRepeatingSeed();
        Integer integer = map.get(key);
        map.put(key, integer == null ? 1 : integer+1);
      }
      System.out.println(map);
    }
  }

  public static int firstRepeatingSeed(){
    Random random = new Random();
    HashSet<Integer> loopDetector = new HashSet<>();
    while (true) {
      int gen = random.nextInt();
      random.setSeed(gen);
      if (!loopDetector.add(gen))
        return gen;
    }
  }

These are the results:

-1381274646=2,
 -1686548232=2,
 154051178=717,
 -381624123=1,
 -334394727=1,
 -1261880000=1,
 -1128634575=1,
 658182704=1,
 364776881=141,
 -1985197764=11,
 1266282155=13,
 -1108864769=1,
 266843583=9,
 -1939453764=2,
 349725186=4,
 1525333558=2,
 -106280330=1,
 -1865148662=1,
 -296326218=1,
 -84817968=2,
 332765684=1,
 -1181949977=1,
 -595175830=59,
 -206288251=1,
 -2043038133=1,
 1220626100=1,
 -541517940=1,
 1373871195=14,
 1890953100=3,
 -1529367891=1,
 -1022666507=3

My question is why does 154051178 and 364776881 show up so often?




sampling NumPy 1d array with controlled randomness

I have a 1d NumPy array a of length l and I want to sample int(np.log(l)) instances from it, but I want the samples to be:

  1. uniformly distributed, and

  2. random.

  • By 1 I mean I want to avoid having two samples with distance less than int(l/int(np.log(l))).
  • By 2 I mean I don't want to get the same instances as the sample each time.
  • I also need to stress that I can't change the randomness seed.

One way is to split the array into int(np.log(l)) sub-arrays and then randomly sample one from each sub-array, but I am looking for a more efficient implementation since I need to run it several times on a considerable number of data.

import numpy as np
a = np.array([np.random.randint(1000) for _ in range(1000)])
a = thresholds = np.sort(a)
l = len(a)
random_indices = np.random.randint(0, l, int(np.log(l)))
samples = a[random_indices]
samples = np.sort(samples)
samples
# array([183, 536, 644, 791, 925, 999])

I appreciate any comments, suggestions, and helps.




How to generate numbers 0-5 randomly. But each number should be used twice only [duplicate]

How to generate random numbers from 0-5 twice each. For example the result should be something like this 0,1,0,2,1,3,4,2,3,4 but it should be randomly. The numbers should be used twice only. When i run it again the result should random again but the numbers should be used twice.




How to generate random numbers from 0-5 twice each. The numbers should be used twice only [closed]

How to generate random numbers from 0-5 twice only. For example the result should be like this 0,0,1,1,2,2,3,3,4,4,5,5 but it should be randomly. The numbers should be used twice only.




dimanche 26 septembre 2021

Get random number of rows from an excel sheet in a dictionary Python

I have a dictionary with name "new". I has around 200 key values naming "5,10,15...1000". Each Key has a dataframe with two columns (length varies for each key).

{'5':      C         V
 0     1.398926   3.284607
 1     1.399078   3.287659
 2     1.399078   3.290710
 3     1.399231   3.293152
 4     1.399384   3.295288
 ...        ...        ...
 7732  0.156128   4.247131
 7733  0.150513   4.246826
 7734  0.151444   4.246826
 7735  0.151993   4.246826
 7736  0.144974   4.246521

I want to extract random percentage of rows in same sequence (20% to 80% of total rows) from each key and store it in a another dictionary "Name".

random.seed(100)      # to get same random number always
Name = {}
for sheet in new:

k = round(random.uniform(0.2,0.8),2) #generate a random number between 0.2 and 0.8 
Name[sheet] = new[sheet].sample(frac=k, random_state=50)

I tried this. With this I am getting percentage of total rows but each row is being picked up from a random position. They are not in sequence as shown below.

{'5':     C          V
 6994  1.167145  4.249268
 1248  1.402283  3.587341
 3530  1.402588  3.820190
 4585  1.402283  3.962708
 4058  1.402283  3.894653
 ...        ...       ...
 6603  1.401367  4.211426
 1348  1.402435  3.599243
 6383  1.401672  4.196167
 7716  0.157791  4.247131
 5413  1.401978  4.063110

But I need the rows picked up to be in sequence. Please let me know how I can do that.




How to be able to take more than 1 argument with loop?

I've been stuck on a function for my homework for hours. I've gotten the basic gist:to shorten the code. You have to print the first letter, "...", then the last letter. That part I got. But I can't figure out how to make it a loop to take more than 1 conditional arguments. Can anyone please help? It's supposed to be that if i type shorten_text("house","tree","major") it would print h...e, t...e, m...r on three seperate lines. Can anyone please help with the loop? Heres my code so far.

def shorten_text(word_list):
word_list[0]+"..."+word_list[-1]
print(word_list[0]+"..."+word_list[-1])
if word_list == "":
    print("Input is empty")



Why I get high observation when I generate data from t-distribution in R [migrated]

I want to generate 200 samples from t-distribution with the degree of freedom=1 and sample size is 10 and in R

I use this code

set.seed(1234)
B <- matrix(rt(10*200, 1), 200)

But when I see the sample number 167 (B[167,]) I found this high number 602.1691029

And this strange thing in the t-distribution. What is wrong here?




Efficient way to fill a 1D numpy array of variable length with random numbers in different ranges

I need to fill a length n 1D numpy array with random numbers from the ranges [1,2,...,n], [2,3,...,n], [3,4,...,n], ..., [n-1,n] and [n] respectively. I am looking for a vectorize solution to this problem. Thanks very much in advance.




How to increase random.randrange from maybe (10,20) to (12,24)

Just need a little help since I'm trying to find a way to do something like

if shp == ("upgrade damage +10") rnda + something to increase rnda(23,30) to rnda (33,40")

idk just started :D




Making a custom class using java.util.Random, keeps returning NullPointerException [duplicate]

I am a new student at a university learning how to code in Java. So far the assignments have been going fine, but I've encountered this odd error with my most recent one which I can't seem to find a fix for.

The assignment asks me to create my own class called MyRandom which allows the user to define a range containing a lower bound and an upper bound. The methods in the class will use this range to generate a completely random integer and double which must be located within the range. The tricky part is that the assignment has specified me to use speficially java.util.Random as an object variable to use for the methods. In Visual Studio the code does not seem to display any errors, yet when I attempt to run it in a test client I receive a java.lang.NullPointerException which seems to start off at the method which is supposed to create a random whole number.

So far this is what I've got:

import java.util.Random;
public class MyRandom {

    //Object variables
    public Random randomGen;
    public int nextNumber;
    public double nextDecimal;
    public int lower;
    public int upper;

    public MyRandom(){ //The constructor MyRandom
    }
    

    

    public int nextNumber(int lower, int upper){ //Randomly generated whole number in range
        nextNumber = randomGen.nextInt(upper - lower) + lower;
        return nextNumber;
    }

    public double nextDecimal(double lower, double upper){ //Randomly generated decimal in range
        nextDecimal = randomGen.nextDouble()*(upper - lower) + lower;
        return nextDecimal;
    }
}   

Any help with this is really appreciated, as I am a bit lost on why it even gives me an exception when the code seems to be fine according to VS.




How to skip multiple times call a function in class?

I designed a class named Funcskip. I want to randomly call function which are defined into the class. But I also want to skip functions which are called already. How can I do this from following code.

import random
class Funcskip:
    def __init__(self,
                 min_ops=2,
                 max_ops=4):
      self.min_ops                =   min_ops
      self.max_ops                =   max_ops
      self.ops              =   [self.__add, self.__sub, self.__mult, self.__div]

    def __initParams(self):
      self.num_ops          =    random.randint(self.min_ops,self.max_ops)

    def __add(self, a, b):
      print("1. add")
      return a+b
    def __sub(self, a,b):
      print("2. sub")
      return a-b

    def __mult(self, a, b):
      print("3. mult")
      return a*b
    def __div(self, a,b):
      print("4. div")
      return a//b

    def callF(self,a,b):
        self.__initParams()
        print(self.num_ops)
        total = 0
        for _ in range(self.num_ops):
            total+=random.choice(self.ops)(a,b)
        return total

    

  
obj = Funcskip()
a = 10
b = 5
_total = obj.callF(a,b)
print(_total)
                 



samedi 25 septembre 2021

Complexity of randomized binary search

So I have been trying this problem, the randomized binary search (RBS). We are given a sorted array A[] of n elements. We need to find if some random number x is present in A or not. In binary search we always used middle element, here we will randomly pick one element in given range, uniformly.

It is clear to me that the expected number of queries depends on the length of the array, T(n), and I have figured out a recurring relation for it, but this recurring relation does not seem to give a clear logarithmic growth for T(n): $$T(n) = 1 + \frac{2}{n^2} \sum_{j=1}^n j T(j) $$

My main issue is that in the internet there seem to be a lot of resources that present a proof, but I don't seem to understand the logic and when I run the numbers I obtain much worse complexity for the RBS. The proof goes as follows:

After we choose one random pivot, array size reduces to some size say k. In this way, T(n) is one plus sum of time of all possible sizes after choosing pivot multiplied by probability of choosing that pivot. This gives the formula $$T(n) = 1 + \sum_{k=1}^{j-1}T(j) / n $$

This is the formula that I can't seem to understand, as in my mind it's much more probable that you get larger intervals (As the key itself is also uniformly distributed at random). Specifically, if the key is in the middle of the range, we cannot ever reduce the size of the interval to one. Maybe this distinction between the key number x being random or not changes the complexity, but that makes no sense conceptually.

This proof is presented in the following "independent" sources:




Making arrays containing random & unique numbers - JavaScript

I have an array which contains number from 0 to 20 .
var array1 = [0,1,2,.....18,19,20];
I want to make three arrays and each array will contain seven random and unique numbers from array1
How can I do this with JavaScript ?
Example:
[2,9,6,13,5,17,20]
[3,18,7,12,15,1,4]
[8,10,14,16,11,0,19]




How to build an Equation with given him a result and values

I was trying to make some codes with javascript can change a "?" to correct operator some think like that 10 ? 20 ? 15 ? 3 ? 190 ? 10 ? 400 to 102015%319010*400 I was trying to make it like that But it just works when I give him a 2 value when I wanna give him 3 or more it does not work can anyone help me?

const OPMAP = {
    '*': (n1, n2) => n1 * n2,
    '/': (n1, n2) => n1 / n2,
    '+': (n1, n2) => n1 + n2,
    '-': (n1, n2) => n1 - n2,
    '%': (n1, n2) => n1 % n2
}

var op = ["+","/","-","*","%"]

let i = 1
let firstValue = 5, secondValue = 5

while(true){
  var operator = OPMAP[op[Math.floor(Math.random() * op.length)]]
  var x =  operator(firstValue, secondValue)
  if (x === i){
    console.log(operator)
    console.log(x)
    break
  }

} 



I Have a problem with the random TSP index

Good mornings friends, I have a problem with random TSP indexes. I want to get the actual tsp path at random its index, but only the 'intermediate coordinates' index is random while the start and end point coordinates stay the same. even if the tsp index is random, the actual random tsp path will still start at index 0 as the starting point. this is my code

  public List<Coord> randVertex(int max) {
        List<Coord> result = new ArrayList<>(listVertex); // copy of vertexList

        Collections.shuffle(result);

        Random r = new Random();

        if (max < result.size()) {
            // result is shuffled and therefore randomized
            // no duplicate vertex appear in the result here
            result = result.subList(0, max);
        } else { // add randomly more elements
            while (result.size() < max) {
                result.add(result.get(r.nextInt(result.size())));
            }
        }

        return result;
    }



How to call a variable again GML

I have a variable called global.goldchance = irandom(99);. I use it to get a random number from 0 to 99. However, I need to be able to run it again so that it chooses a different number. Writing var goldchance = irandom(99); doesn't work because the variable will be destroyed afterwards. Writing the variable again won't work because that's not calling it again; that's simply stating it. How do I do this?




How do I pull a randomly chosen string from an array into PIL's text function and use in metadata

If I pull a random element of an array of strings, how do I need that specific element to be written with a certain font, color, placement, etc, and placed on top of a png file that I created?

   def create_new_image():
    new_image = {}
    new_image ["soft_skill"] = random.choices(soft_skill)[0]
    
    if new_image in all_images:
        return create_new_image()
    else:
        return new_image

for i in range(TOTAL_IMAGES):
    new_trait_image = create_new_image()
    all_images.append(new_trait_image)

im10 = ImageDraw.Draw(img)
im10.text((88,912),"PLACE_HERE", font=myFont, fill = (0,255,10))

In the "random.choices(soft_skill)", soft_skill is simply an array of about 100ish strings. One of them is picked randomly, and the result is then sent to a metadata file. I need to pick whatever string that was chosen in that line, and place it in the spot that says "PLACE_HERE" so that I can layer it on top of the png, while still keeping it in the metadata. This might be a simple question, but please help. Thank you.




Is python random.choices biased?

I might be forgetting some statistics basic in this one.

I ran the following experiment in python:

import random as r
bigger_than_zero=0
smaller_than_zero=0
for k in range(0,100):
    a=0
    for i in range(0,10000):
        a=a+r.choices([-4,-3,-2,1,0,1,2,3,4])[0]
    if a>0:
        bigger_than_zero+=1
    elif a<0:
        smaller_than_zero+=1
print(bigger_than_zero)
print(smaller_than_zero)

and the output was

100
0

well, since i determined no weights, shouldn't r.choices output a random integer between -4 and 4 each time? And since the probabilities are equal, shouldn't the average sum result after 10000 iterations be close to zero? And since it should be random, close to zero and normally distributed, shouldn't the bigger_than_zero and smaller_than_zero final results be at least close to each other (instead of the 100 and 0 results)?




MySQL: A simple, but odd "join" between two tables

This is so simple, I'm embarrassed to have to ask the question:

I'm trying to return a single row consisting of an element from a column from table A and an element from a column from table B, chosen at random. I've never done such a thing and I'm stumped. There is no relationship between the two tables (intentionally). I can issue the commands individually and get what I desire, but I can't put them together in a single query. A UNION between the two queries (my first thought) results in TWO rows, but I desire a single row. Any thoughts?

    (SELECT column_a FROM table_x ORDER BY rand() LIMIT 1) 
       UNION
    (SELECT column_b FROM table_y ORDER BY rand() LIMIT 1)


    DESIRED OUTPUT:
                  column_a        column_b
                  ---------------------------
    Row 1:        x.element_a     y.element_b

Each individual query performs as expected (albeit costly). Joining the two without any common key is the problem.




how to set a randomizer correctly

I'm not really sure if the problem is in the randrange() function. I'm trying to create a basic snake game in pygame and if the snake eats the food it will respawn in a different place, but in the first try the snake eats the food and everything is fine but when the food respawns in a different place the snake can't eat it for some reason.

import pygame, sys
from pygame.locals import *
from random import randrange

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 400))
pygame.display.set_caption('Hello World!')
green = (0,255,0)
randomnum = [20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 10]
times = 5
list = (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
green = (0,255,0)
FPS = 10
FpsClock = pygame.time.Clock()
playerY = 0
playerX = 0
plus = 20
rectcordinatesx = 200
rectcordinatesy = 200
isgoingdown = False
isgoingright = False
isgoingleft = False
isgoingUp = False
color = (255, 0, 0)


while True:
    BG = pygame.draw.rect(DISPLAYSURF,(255, 255,255),(0,0,400,400))
    rect = pygame.draw.rect(DISPLAYSURF,(color),(rectcordinatesx, rectcordinatesy,20, 20))
    player = pygame.draw.rect(DISPLAYSURF,(green),(playerX, playerY,20, 20))
    keys = pygame.key.get_pressed()
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        #ALL COLLISION CONDITIONS
    if playerX == rectcordinatesx and playerY == rectcordinatesy :
        rectcordinatesx = randrange(0, 40) * 10
        rectcordinatesy = randrange(0, 40) * 10


        #LOOKING FOR KEYS
    if keys[pygame.K_s]:
        isgoingdown = True
        isgoingright = False
        isgoingleft = False
        isgoingUp = False
    if keys[pygame.K_d]:
        isgoingdown = False
        isgoingright = True
        isgoingleft = False
        isgoingUp = False
    if keys[pygame.K_z]:
        isgoingdown = False
        isgoingright = False
        isgoingleft = False
        isgoingUp = True
    if keys[pygame.K_q]:
        isgoingdown = False
        isgoingright = False
        isgoingleft = True
        isgoingUp = False

        # MOVING CONDITIONS
    if isgoingdown == True:
        playerY += plus
    if isgoingleft == True:
        playerX -= plus
    if isgoingUp == True:
        playerY -= plus
    if isgoingright == True:
        playerX += plus
    if playerY + 20 >= 400:
        isgoingdown = False
    if playerY <= 0 :
        isgoingUp = False
    if playerX + 20 >= 400:
        isgoingright = False
    if playerX <= 0:
        isgoingleft = False

    print ('x ' + str(playerX) + 'y' + str(playerY) + 'food x' + str(rectcordinatesx) +'food y ' + str(rectcordinatesy))


    pygame.display.update(player)
    pygame.display.update()
    FpsClock.tick(FPS)

I don't know if the problem is in the randomizer.




vendredi 24 septembre 2021

Can't reposition images stored in a list correctly | Pygame

I am making a game based on balloons and a gun that's job is to shoot the balloons. The 7 balloon images are stored into a list called colors, and another list called balloon_list has all the randomly generated x values for the placement of the balloons. What should happen when you hit a balloon is it should disappear and then randomize the x-position of the balloon again. My problem is that when I hit a certain balloon, instead of randomizing the x position and blitting it to the screen, it continually does that and it shows the balloon popping up at different places at once. What I tried was shuffling the list (balloon_list) of all the x values. Here is my code:

import random as r
import sys


pg.init()


radius = 30
diameter = 2 * radius
num_balloons = 7

bullets_colors_ls = []
iterator = -1




def create_balloons():
    global balloon_list
    global colors

    for i in range(num_balloons):
        while True:
            candidate = r.randint(0, 500)
            if all(abs(candidate-x) >= diameter for x in balloon_list):
                break
        balloon_list.append(candidate)

def draw_balloons(y):
    for i in range(num_balloons):
        screen.blit(colors[i], (balloon_list[i] , y-50))


def check_collisions(x, y):
    global hit_var
    global hit
    global score
    global scoretext
    
    for i in range(num_balloons):
        gun_rect = gun.get_rect(topleft = (x,y))
        gun_mask = pg.mask.from_surface(gun)

        balloon_rect = colors[i].get_rect(topleft = (balloon_list[i], y-100))
        balloon_mask = pg.mask.from_surface(colors[i])

        offset = (balloon_rect.x - gun_rect.x), (balloon_rect.y - gun_rect.y)
        if gun_mask.overlap(balloon_mask, offset):
            hit = True
            hit_var = i
            print(f'hit balloon: {i}')
            colors[i].fill((0,0,0))
            screen.fill((0,0,0))

            


            
        


        
# Vars #
x = 0
y = 250
velocity = 5
score = 0
hit = False
testvar1 = True
clock = pg.time.Clock()


screen = pg.display.set_mode((688 ,387)) # Size of the screen #
screen.fill('#ffffff')
caption = pg.display.set_caption("Remember") # Title of the window #

balloon_list = []
b1 = pg.image.load('balloons/1.png').convert_alpha()
b1 = pg.transform.scale(b1, (63,131))
b2 = pg.image.load('balloons/2.png').convert_alpha()
b2 = pg.transform.scale(b2, (63,131))
b3 = pg.image.load('balloons/3.png').convert_alpha()
b3 = pg.transform.scale(b3, (63,131))
b4 = pg.image.load('balloons/4.png').convert_alpha()
b4 = pg.transform.scale(b4, (63,131))
b5 = pg.image.load('balloons/5.png').convert_alpha()
b5 = pg.transform.scale(b5, (63,131))
b6 = pg.image.load('balloons/6.png').convert_alpha()
b6 = pg.transform.scale( b6, (63,131))
b7 = pg.image.load('balloons/7.png').convert_alpha()
b7 = pg.transform.scale(b7, (63,131))
colors = [b1, b2, b3, b4, b5, b6, b7]




gun = pg.image.load('game-gun.png').convert_alpha()
gun = pg.transform.scale(gun, (150,150))

create_balloons()



pg.display.flip() # Updating #

running = True # Game loop bool #

while running: # Game loop #
    clock.tick(60)
    
    if hit == True:
        r.shuffle(balloon_list)
        
        
        
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                pg.quit()
                sys.exit()

    draw_balloons(y)
    keys = pg.key.get_pressed()

    x += keys[pg.K_RIGHT] - keys[pg.K_LEFT] * velocity
    x -= keys[pg.K_LEFT] - keys[pg.K_RIGHT] * velocity
   
    if keys[pg.K_SPACE]:
        check_collisions(x, y)
        print(balloon_list)
        

        



        
        
     
    screen.blit(gun, (x, y))
    pg.display.update()

The gun and balloon images can be downloaded here: IMAGES

I think the problem is related to blitting the images inside of the while loop so it is continually shuffling the x position in the balloon_list forever, but I'm not sure how to fix it.

Appreciate any help, Thank you




Getting user input in the middle of text

I want to get the users input and put in the middle of the text, so if user types 7, it will say

Sorry, 7 is too high. Guess again.

Here's my code:

import random

def guess(x):
    random_number = random.randint(1,x)
    guess = 0
    while guess != random_number:
        guess = int(input(f"Guess a number between 1 and {x}: "))
        if guess < random_number:
            a = input()
            print("Sorry, (a) is too low. Guess again.")
        elif guess > random_number:
            print("Sorry, (a) is too high. Guess again.")

    print(f"Yay, congrats! {random_number} was the right number!")


guess(10)



How can I modify the following algorithm so that it works on floats?

The following algorithm is designed to generate random list of integers with a minimum distance. More details are here: Python: Random list of numbers in a range keeping with a minimum distance

I want to know how is it possible to modify so that it works for floats instead, I did some attempts but I get some exceptions where the minimum distance is not obeyed (just by a fraction but it's enough to mess my algorithm).

def ranks(sample):
    """
    Return the ranks of each element in an integer sample.
    """
    indices = sorted(range(len(sample)), key=lambda i: sample[i])
    return sorted(indices, key=lambda i: indices[i])


def sample_with_minimum_distance(n, k, d):
    """
    Sample of k elements from range(n), with a minimum distance d.
    """
    i = round(random.uniform(0, 1), 2)
    sample = random.sample(sorted(np.linspace(n - (k - i) * (d - i), 0)), k) #generate a sample from the float list
    list_dist = [s + (d - i) * r for s, r in zip(sample, ranks(sample))]
    return(list_dist)



Let bot select and send random messages in Pycharm

Hey is it possible to make a list with words so the bot can select one and send it on command? in pycharm




Does shuffling the elements of an array on top of a code that randomly picks an element in an array increases randomness?

OS: Windows 10 Pro Version 20H2 (OS Build: 19042.1237)
Application: Microsoft 365 Version 2108

I just finished creating a custom function that shuffles an array of values and generates a random string from it but then this question struck me. Does shuffling the elements of an array increases (or decreases) randomness? Would I be better off without it and why? The code already picks elements randomly even without shuffling. Here's a basic concept of what I've done.

Sub GenerateRandomString()
 
'Variable declaration
    Dim ArrNums() As Integer
    Dim i As Integer
    Dim rNum As Integer
    Dim Cache As Integer
    Dim RandomString As String
    Dim ShuffleSwitch As Integer
    
    'Switch for the shuffle for testing, 1 to turn on, 0 to turn off..
    ShuffleSwitch = 1

'Main procedure
    'Fill array with values
    ReDim ArrNums(0 To 9) As Integer
    For i = 0 To 9
        ArrNums(i) = i
    Next i
    
    Randomize
    
    'Shuffle array elements
    If ShuffleSwitch = 1 Then
        For i = LBound(ArrNums) To UBound(ArrNums)
            rNum = Int(Rnd * (UBound(ArrNums) - LBound(ArrNums) + 1) + LBound(ArrNums))
            Cache = ArrNums(i)
            ArrNums(i) = ArrNums(rNum)
            ArrNums(rNum) = Cache
        Next i
    End If

    'Generate eight random strings
    For i = 1 To 8
        rNum = Int(Rnd * (UBound(ArrNums) - LBound(ArrNums) + 1) + LBound(ArrNums))
        RandomString = RandomString & ArrNums(rNum)
    Next i

'Debug code
    Debug.Print RandomString

'Housekeeping
    Erase ArrNums
    i = vbEmpty
    rNum = vbEmpty
    Cache = vbEmpty
    ShuffleSwitch = vbEmpty
    RandomString = vbEmpty

'End of the line indicator
    Debug.Print "alright.."

End Sub

I tried researching about this subject on the internet but all articles are geared towards explaining how to accomplish it.

I would appreciate any clarification from you guys. Thank you all very much..




angular typescript write test for random username method

i started learnin Angular and Typescript and i have to test this method but i dont know how to test Random return . if you can help me would really appreciate

botRandName(): string {
        const x: number = Math.floor(Math.random() * 3);
        if (x === 1) return (this.botName = 'player1');
        else if (x === 2) return (this.botName = 'player2');
        else return (this.botName = 'player3');
    }



Randomly selecting subsamples from dataframe using python

I have dataframe df. I would like to select the 6 sab samples randomly that contain fixed data (=100) size and does not have repetitive values. So far, I have written the following codes:

df_ = df.sample(n=6000)
n = 6  # specifying number of sample need
size = int(df_.shape[0]/n)
chunks = list()
for i in range(0, df.shape[0], size):
    chunks.append(df.iloc[i:i+size])

But when I select a sample, say subsample_1=chunks[1] then the results are not random but are in order. Any advice, how to select 6 random subsamples from given df that are not repetitive data?




jeudi 23 septembre 2021

R: Randomly Selecting Items from a List

I am working with the R programming language. I want to create a problem in which:

  • There are 4 people : "person 1", "person 2", "person 3" ,"person 4"

  • There is a list of food items: "pizza", "apples", "tacos", "ice cream", "grapes", "olives", "sushi", "chocolate", "cake", "nachos", "pasta", "cookies", "popcorn", "soup"

  • There is a list of days in the year: 1 to 365

In this problem, the list of people is randomly sorted. The order of this list decides who get to "pick first".

According to the order of the list, the person at the start of the list will be assigned 4 random numbers:

  • Rand_1_1 (Person 1, First Random Number) : The first random number will decide the number of "food items" the first person is allowed to pick (e.g. 3)

  • Rand_1_2 (Person 1, Second Random Number) : The second random number will decide which "food items" the first person will pick with the number of "food items" corresponding to "Rand_1_1" (e.g. "tacos", "nachos", "soup")

  • Rand_1_3 (Person 1, Third Random Number): The third random number will decide the one of the bound for the days for the first person

  • Rand_1_4 (Person 1, Fourth Random Number): The fourth random number will decide the other bound for the days for the first person (e.g. Person 1 might be assigned days "41 to 160").

This is random number assignment process is then completed for all people : Rand_1_1, Rand_1_2, Rand_1_3, Rand_1_4 , Rand_2_1, Rand_2_2, Rand_2_3, Rand_2_4, Rand_3_1, Rand_3_2, Rand_3_3, Rand_3_4, Rand_4_1, Rand_4_2, Rand_4_3, Rand_4_4

However, there is one logical constraint:

  • A "person" can not choose "food items" that have already been chosen by the "person" before them (e.g. if Person 1 was selected to choose before Person 2, and if Person 1 chose "pizza" then Person 2 can not choose "pizza")

  • A "person" can not choose a "range of days" that has already been chosen by the "person" before them

  • After all 4 people have finished choosing, it is possible that some "food items" and some "date ranges" can remain unselected. On the other hand, suppose if Person 1 chooses first and he happens to select all the "food items" - then of course, the other people will have no "food items". The same logic applies for "date ranges".

Now, I am trying to code this in R:

First, I loaded the libraries:

#load libraries

library(dplyr)
library(gtools)

Second, I created the data:

#create data

#variable 1: days of the year 

days <- 1:365

#variable 2 : food

food <- c("pizza", "apples", "tacos", "ice cream", "grapes", "olives", "sushi", "chocolate", "cake", "nachos", "pasta", "cookies", "popcorn", "soup")
food_data <- data.frame(food)
food_data$id <-  1:nrow(food_data)

# people 
people <- c("person 1", "person 2", "person 3" ,"person 4")

Third, I created the order in which the people will pick:

# randomize order of people : this decides the order of who picks "days" and "food"

set.seed(123)

order_of_people = permute(people)

# in this example, "person 3" will pick first, "person 4" will pick second, "person 1" will pick third and "person 2" will pick last

order_of_people
[1] "person 3" "person 4" "person 1" "person 2"

My Problem: I know how to assign every person a random number, but I do not know how to assign the random numbers such that the logical constraints are respected. For example:

#choices for person 3 (according to the random seed, person 3 will pick 5 food items)

set.seed(120)

dim = dim(food_data)

#number of items selected by person 3

Rand_3_1 <- sample.int(dim[1], 1)

#which food items selected by person 3 (corresponding to the food_id : "3, 9, 6, 7, 4")
set.seed(120)

Rand_3_2 = c( sample.int(dim[1], 1), sample.int(dim[1], 1), sample.int(dim[1], 1),  sample.int(dim[1], 1), sample.int(dim[1], 1))

#which days selected by person 3 (according to this random seed, "65 to 87")

set.seed(120)

Rand_3_3 <- sample.int(365, 1)
Rand_3_4 <- sample.int(365, 1)

Thus, I can create "selection frames" for each person:

#Person 1
Rand_1_1 <- sample.int(dim[1], 1)

Rand_1_2 = c( #fill randomly with amount of items specified by Rand_1_1)

Rand_1_3 <- sample.int(365, 1)
Rand_1_4 <- sample.int(365, 1)

#Person 2
Rand_2_1 <- sample.int(dim[1], 1)

Rand_2_2 = c( #fill randomly with amount of items specified by Rand_2_1)

Rand_2_3 <- sample.int(365, 1)
Rand_2_4 <- sample.int(365, 1)


#Person 3
Rand_3_1 <- sample.int(dim[1], 1)

Rand_3_2 = c( #fill randomly with amount of items specified by Rand_3_1)

Rand_3_3 <- sample.int(365, 1)
Rand_3_4 <- sample.int(365, 1)

#Person 4
Rand_4_1 <- sample.int(dim[1], 1)

Rand_4_2 = c( #fill randomly with amount of items specified by Rand_4_1)

Rand_4_3 <- sample.int(365, 1)
Rand_4_4 <- sample.int(365, 1)

But I don't know how to do this such that the logical constraints are respected. In the end, I am trying to produce something like this:

#desired results
Person 1 : "apples, tacos" and "4-51"
Person 2: "cookies, nachos, cake, olives", and "56-180"
Person 3: "ice cream", and "200-214"
Person 4: "sushi, popcorn" and "350-365"

Can someone please show me how to do this?

Thanks




Random items in a list [closed]

I want the user to input a number into the input and with that number select random items from a list, how can I do this?

import random

numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

nr_letters= int(input("How many letters would you like in your password?\n"))




In Julia set random seed and not generating same values if calling a function from different parts of program

I have a Julia program which runs some montecarlo simulations. To do this, I set a seed before calling the function that generates my random values. This function can be called from different parts of my program, and the problem is that I am not generating same random values if I call the function from different parts of my program.

My question is: In order to obtain the same reproducible results, do I have to call this function always from the same part of the program? Maybe this questions is more computer science related than language programming itself.

I thought of seeding inside the function which generates my random values but I still do not get same results.




Mail with some HTM and what does this code mean? [closed]

The code is:

<frameset onload="document.location.href=window.atob('aHR0cHM6Ly9ibG9jay1jaGFpbi1ib3gudGsvbXpwaWwvP3J2b3R3bG5vd3RxayA=');" />  

This file type is HTM I don't know what the hell that is and i dont trust it, It's looks weird and just weird




how to display top 10 feature importance for random forest

was just wondering if it's possible to only display top 10 feature_importance for random forest? here's my code.

model1 = RandomForestClassifier() model1.fit(X_train, y_train) pd.Series(model1.feature_importances_, index=X_train.columns)

i tried the above and the result i get is the full list of all 70+ features, and not in any order. :(

MonthlyMinutes 0.048203

TotalRecurringCharge 0.028393

MonthlyRevenue 0.041576

DirectorAssistedCalls 0.019973

Thank you.




What is precision of MYSQL RAND() function? and how to generate huge random numbers?

MYSQL RAND() function is told to return floating-point number. But how precise is it? I.e. what is the maximum integer range [0,N] in which I can generate uniformly distributed random integer numbers with FLOOR(RAND()*N)?

How to generate numbers, which are bigger than N?




Python - Reduce variability random numbers in MC simulation

I am interested in estimating the price of a European Call Option using the Montecarlo simulation, to get a good approximation of the analytical Black Scholes formula, so a very simple task. Performing the simulation, I have noticed one thing: if I change the seed for the random numbers, I get different results. Is there any procedure that allows me to get the same price, regardless of the chosen seed? (maybe not exactly the same price, but some strategy to reduce the effect of chosen seed).

As we can see from this pictures, here we have the difference in absolute value between the analytical price and estimated one, with different seed. Here we can see that the best seed is the number 100.

enter image description here

Here I have attached the code used to generate the MC simulation for different kind of seed.

from math import log, sqrt, pi, exp
from scipy.stats import norm
from datetime import datetime, date
import numpy as np
import pandas as pd
from pandas import DataFrame

def Option_MC(s0, K, T, j, sigma, r, q, seed):
    Rand = np.random.RandomState()
    Rand.seed(seed)
    S = np.ndarray(shape=(2, j), dtype=np.double)
    S[0] = s0
    Brownian_Motion = Rand.normal(-.5 * sigma * sigma * T, sigma * sqrt(T), (1, j))
    S[1] = S[0] * np.exp(Brownian_Motion)
    P = np.maximum(S[1] - K, 0)
    mean = np.average(P)
    return mean

def d1(S,K,T,r,sigma):
    return (log(S/K)+(r+sigma**2/2.)*T)/(sigma*sqrt(T))
def d2(S,K,T,r,sigma):
    return d1(S,K,T,r,sigma)-sigma*sqrt(T)
def bs_call(S,K,T,r,sigma):
    return S*norm.cdf(d1(S,K,T,r,sigma))-K*exp(-r*T)*norm.cdf(d2(S,K,T,r,sigma))

analytical = []
for i in arrays:
    analytical.append(bs_call(i,1.,1,0,0.5))

arrays = np.linspace(1,1.2,100)
seeds = [1,10,100,1000]
price_tot = []
for seed in seeds:
    price = []
    for i in arrays:
        price.append(Option_MC(i,1.,1,200000,0.5,0,0,seed))
    price_tot.append(price)

for p,seed in zip(price_tot,seeds):
    plt.plot(arrays,abs(np.array(p)-np.array(analytical)),label=f'Seed = {seed}')
plt.legend()
plt.show()

for p,seed in zip(price_tot,seeds):
    plt.plot(arrays,p,label=f'Seed = {seed}')
plt.legend()
plt.show()



Multipline line in Jmeter CSV file

I tried to create JSR223 Sampler where I need to take csv file and get random count of strings from this csv and put this strings to request. How can I do this?




how to use fastrand in a numpy array

I'd like to use fastrand library provided on this GitHub page, which works fine when used to generate random numbers one at a time. For instance,

#pip install fastrand==1.2.4
import fastrand

print(fastrand.pcg32bounded(1001))
975

However, I would like to use this method in a numpy array to generate multiple numbers for certain indices where the upper bound is the number existing in the corresponding index. Suppose I have a 2 by 5 numpy array.

import fastrand
arr = np.array([[np.random.randint(2,10) for i in range(5)]for j in range(2)])
print(arr,"\n")

[[8 7 4 9 9]
 [9 9 9 7 7]] 

Now, I substract random numbers for the first two numbers in the second row. I can easily do this by using np.random.randint as shown below.

arr[1,:2]-=  np.random.randint(arr[1,:2]) 
print(arr)
[[8 7 4 9 9]
 [4 1 9 7 7]]

My goal is to use fastrand instead of np.random.randint to increase the performance. Is this possible by any chance?




mercredi 22 septembre 2021

Preventing overlap of random points

Ok hear me out, I'm looking for non-brute force way of generating random coordinates that don't overlap. I know these types of questions have been asked before and the solutions offered are usually something brute force-y like this. I'm looking for something more efficient if possible.

What I have is a function that generates random Points in C# in a way that I generally like (the points are denser in the center and become less dense in outer regions of the 'circle'):

public static IPoint[] GeneratePointsAsCircle(int maxPoints, float scale, float radius=26)
{
    IPoint[] points = new IPoint[maxPoints];
    int count = 0;

    while (count < maxPoints)
    {
        double r = rdm.NextDouble();  // rdm declared outside function, in class
        double theta = rdm.NextDouble() * 2.0 * Math.PI;
        double phi = rdm.NextDouble() * Math.PI;
        double cosTheta = Math.Sin(theta);
        double sinPhi = Math.Sin(phi);
        double cosPhi = Math.Cos(phi);

        double x = r * cosPhi;
        double y = r * sinPhi * cosTheta;

        IPoint point = new Point(x * scale, y * scale);

        /* Here is where people usually suggest a for-loop that checks the overlap
           by calculating the distance to see if its range of the radius (see function args),
           and then finding a new point if it does overlap. Problem is, its inefficient for larger number of points.

        example in pseudo-code:
        overlapping = false;
        foreach(other in points) {
            distance = GetDistance(point, other);
            if (distance < (radius*scale) + (radius*scale))
                 overlapping = true;
                 break;
        }

        if (!overlapping)... */
        points[count++] = point;

        // let run x-amount of times before breaking the loop to prevent a forever loop.

    }

    return points;
}

Now, technically, if the point is on screen has a radius of one, I don't think there is overlap. However in Unity (ugh yes I know, everyone uses it now), I have a UI Image with a radius of 32. So is there away to efficiently account for the radius so it doesn't overlap in the way I've been able to generate the randomized points?

Alternatively, is there a Poisson Disc type of algorithms for circle shapes rather than a grid? ALTERNATIVELY alternatively, what other ways can I prevent overlapping of random points in a circle that is not brute-force (again if possible)?

I know its a lot but any suggestions are appreciated.




How can i define 4 main mathematic operators such as +,-,*,/ as an dictionary and call them randomly by randint() function? [closed]

I need to randomly generate the mathematical symbols (+, -,/, *) for my questions.




Random string generating same values in different iterations of loop

Im making referenceIDs in a function and adding the values to a list.

Dim myListOfItems As New List(Of BasketItem)      
Dim refID As String = String.Empty
    
    For Each i In myListOfNames
        refID = HelpClass.GenerateRandomString(20)

        Dim x As New BasketItem
        x.RefID = refID
        myListOfItems.Add(x)

    Next

The Function looks as follows:

Public Shared Function GenerateRandomString(ByVal length As Integer) As String

        Dim chara As Char() = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray()
        Dim randomString As String = String.Empty
        Dim objRandom As New Random()
        For i As Integer = 0 To length Step 1
            Dim x As Integer = objRandom.Next(1, chara.Length)
            If Not randomString.Contains(chara.GetValue(x).ToString()) Then
                randomString += chara.GetValue(x)
            Else
                i = i - 1
            End If
        Next
        Return randomString
    End Function

This all works great on my local visual studio run. But when i upload to my webserver several of the items get the same values.

This is the output on live server:

> Biljettinnehavare: 1 | 1XIh4YqBlHmipkPKV576C  
> Biljettinnehavare: 2 | 1XIh4YqBlHmipkPKV576C 
> Biljettinnehavare: 3 | 1XIh4YqBlHmipkPKV576C 
> Biljettinnehavare: 4 | 1XIh4YqBlHmipkPKV576C 
> Biljettinnehavare: 5 | qvmupeZhcoQ9YgOWtCLN4 
> Biljettinnehavare: 6 | qvmupeZhcoQ9YgOWtCLN4  
> Biljettinnehavare: 7 | qvmupeZhcoQ9YgOWtCLN4  
> Biljettinnehavare: 8 | qvmupeZhcoQ9YgOWtCLN4  
> Biljettinnehavare: 9 | qvmupeZhcoQ9YgOWtCLN4  
> Biljettinnehavare: 10 | qvmupeZhcoQ9YgOWtCLN4 
> Biljettinnehavare: 11 | DdxK4jibcu9s7gXJw6a3m  
> Biljettinnehavare: 12 | DdxK4jibcu9s7gXJw6a3m  
> Biljettinnehavare: 13 | DdxK4jibcu9s7gXJw6a3m 
> Biljettinnehavare: 14 | DdxK4jibcu9s7gXJw6a3m
> Biljettinnehavare: 15 | 32SWpkFfdgbqMtJGa1siw 
> Biljettinnehavare: 16 | 32SWpkFfdgbqMtJGa1siw

Dont really know what is causing this problem. Any ideas?

Is the server executing the loop so quick and basing it on the clock makes the same values appear, what would be the way to counter that in that case?




How to scrape random followers of a certain User on Twitter (via Python/Tweepy)

I am a newbie to coding at all. Is there a way to collect a random sample of followers of a certain User? So a random sampIe of 100 followers of that User? I think now I am scraping the followers which followed the certain account recently.

def scrape_user_followers(username):
followers_scraped = []
user = api.get_user(username)
for i, _id in enumerate(tweepy.Cursor(api.followers_ids, screen_name = username).items(100)):
    followers_scraped.append(_id)
return followers_scraped



Python random module, instead of different generated numbers show the same one [duplicate]

import random

def randColumnRow():
    b = [random.randint(1, 1000) for i in range(8)]
    return b


print(randColumnRow())

I have this programm, the output shows 8 different numbers between 1 and 1000. How do i change it to show me the same number 8 times?




random string java and find string in java string

  • Create 2 classes Server_UDP and Client_UDP
  • Build the program to meet the following requirements
  1. Client sends any string to Server
  2. Does the server check if there is a string with the string "java" in it? • If there is a server, return the client string "Has the word java" • If not return string "doesn't exist" (Hint can use indexOf method of String class)



mardi 21 septembre 2021

I'm having trouble getting random elements from ArrayList

First, I have Arraylist "listVertex" storing "coordinates" of DTNHost. Second, I created a method to get random elements for the selected index from listVertex ArrayList. However, the following methods generate new coordinate points and the values x and y change from the initial value I have specified. Please guys, help me to get random elements from theVertex list without having to generate new coordinate points and the value x, y does not change. Thanks for the attention.

//retrieve node coordinates from DTNHost.
public void getVertex() {

        List<DTNHost> allNode = SimScenario.getInstance().getHosts();

        for (DTNHost host : allNode) {
            if (host.toString().startsWith("kota")) {
                listVertex.add(host.getLocation());
            }
        }
    }

    //get for random elements from the listVertex ArrayList
    public ArrayList<Coord> randomVeretx(int max) {
        Random r = new Random();
        ArrayList<Coord> result = new ArrayList<Coord>();
        for (int i = 0; i < max; i++) {
            result.add(new Coord(r.nextDouble() * max, r.nextDouble() * max));
        }
        return result;

    }



Are LSB bits less random? how does it work?

I recently read somewhere that values with less significant bits tend to be less random than with more significant bits, could someone explain this better? If you can pass me some paper that talks about this and about random numbers I would be very grateful, as long as it doesn't have a lot of complex math




How can I make a function in Python that prints random integers between 10 and 20, and stops when the value of 20 is obtained?

I am trying to make a function in Python that generates random numbers using the random.randrange() function. I need it to print a set of integers in no specific order from 10 to 20, until it stops at when a value of 20 is obtained. I've attached my code of what I have tried.

import random

def number_function():
    my_number = random.randrange(10,21)

    if (my_num == 21):
        print(my_number)
    else:
        #(not sure here)
        
def main():
    number_function()
    
main()



Filling multiple arrays with random numbers in C [duplicate]

Basically what my program needs to do is generate 100 random arrays ranging from size 2-100. My only problem is when attempting to use srand() inside a loop I can increment it giving me a new value for next incrementation but then each array has the same numbers except for the very last one. For example:

1,5
1,5,8
1,5,8,4
1,5,8,4,7

So my question is what is a tactic that would give srand() a different value every time so that it is re-seeding differently for each call.




Deterministic OpenSimplexNoise across Godot versions

For a given version of Godot, you can deterministically generate OpenSimplexNoise using seed (documentation).

However, in the documentation for RandomNumberGenerator there is the following:

Note: The underlying algorithm is an implementation detail. As a result, it should not be depended upon for reproducible random streams across Godot versions.

Some workarounds for the above issue are described here, the short answer is to write a custom portable RNG.

Is there any way to insert a custom RNG for OpenSimplexNoise to manage determinism? Is there another solution?




Math.random() VS crypto.randomInt() - Node.js

What is the difference between the way Math.random() and crypto.randomInt() work in node.js? And if I will run them in a loop for a long time, is it possible for me to get the same result an amount of times that exceeds the statistics?




Select the best random variable

Let's assume I am offered to keep one of three slot machines, each with unknown and unique reward distributions. Each machine can output a -1, 0 or a 1 after each try. Given the following collected data:

Slot machine 1 data: Attempts: 100, Average reward: 0.3

Slot machine 2 data: Attempts: 10, Average reward: 0.4

Slot machine 3 data: Attempts: 4, Average reward: 0.5

If we want to keep the slot machine that maximizes the reward, which one would it be and why?

Some context: I understand that with more attempts I can be more certain about the expected reward, which is desired. For example, the 3rd machine has the best reward but has been attempted fewer times, meaning that there is a high risk involved. Is there a statistical formula that helps to make this decision?

This is not a Multi-Armed Bandit problem, I don't get to try the slot machines again to make another decision, the question is about making a decision now given the data.




How to display tasks that are not "checked" on the other screen?

I am looking at my code and wondering for 2 hours now without luck so I will ask for help here.

I have a button, when I press it, it displays a random item from the list view. The problem is I also have a check box on the list view with each item. I do not want it to (Shuffle through the items with the checkbox ticked) only to shuffle through the Task in the list view that are unchecked/unticked/are not done.

Here is my code

class TaskData extends ChangeNotifier {
  List<Task> _tasks = [
    Task(name: "item1"),
    Task(name: "item2"),
    Task(name: "item3"),

  ];

  UnmodifiableListView<Task> get tasks {
    return UnmodifiableListView(_tasks);
  }

  int get taskCount {
    return _tasks.length;
  }
// <<Here is the code that shuffles through list
  Future<String> rann() async {
    return (_tasks.toList()..shuffle()).first.name;
  }
 
  void addTask(String newTaskTitle) {
    final task = Task(name: newTaskTitle);
    _tasks.add(task);
    notifyListeners();
  }

  void updateTask(Task task) {
    task.toggleDone();
    notifyListeners();
  }

In another script I have this one

class Task {
  final String name;
  bool isDone;

  Task({required this.name, this.isDone = false});

  void toggleDone() {
    isDone = !isDone;
  }
}

In another script file I have this code

        Padding(
          padding:
              const EdgeInsets.symmetric(horizontal: 20, vertical: 0),
          child: FutureBuilder(
            future: Provider.of<TaskData>(context).rann(),
            builder: (context, snapshot) {
              return Align(
                alignment: Alignment.center,
                child: Text(
                  "${snapshot.data}",
                  //softWrap: true,
                  textAlign: TextAlign.center,
                  //textWidthBasis: TextWidthBasis.longestLine,
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 30,
                      fontWeight: FontWeight.w700),
                ),
              );
            },
          ),
        ),

In another script I have this one

class TasksList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<TaskData>(
      builder: (context, taskData, child) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final task = taskData.tasks[index];
            return TaskTile(
              taskTitle: task.name,
              isChecked: task.isDone,
              checkboxCallback: (checkboxState) {
                taskData.updateTask(task);
              },
            );
          },
          itemCount: taskData.taskCount,
        );
      },
    );
  }
}

Any help would be appreciated!

Edit : I also forgot to include this part of code

class TaskTile extends StatelessWidget {
  final bool isChecked;
  final String taskTitle;
  final Function(bool?) checkboxCallback;
  final VoidCallback longPressCallback;

  TaskTile(
      {required this.isChecked,
      required this.taskTitle,
      required this.checkboxCallback,
      required this.longPressCallback});


  @override
  Widget build(BuildContext context) {
    return ListTile(
      onLongPress: longPressCallback,
      title: Text(
        taskTitle,
        // at the bottom, it sets decoration of text if isChecked is true, if its not its null
        style: TextStyle(
            decoration: isChecked ? TextDecoration.lineThrough : null),
      ),
      trailing: Checkbox(
        activeColor: Colors.blue,
        value: isChecked,
        onChanged: checkboxCallback,
      ),
    );
  }
}



Generate random numbers with two constraints (sum and local maximum) in Python

I have a dataframe where I want to create random numbers in a new column. The random numbers must fulfill two constraints:

  1. The random numbers must add up to a specified sum (in the example, the sum is 300)
  2. For each observation, the random numbers must not exceed a value in the constraint column.

In the example below, the constraints are fulfilled because the sum is 300 and the random number does not exceed the constraint column.

Example:

GEOID CONSTRAINT RANDOM
010010000001 100 80
010010000002 50 40
010010000003 75 60
010010000004 75 60
010010000005 100 60

It seems having random numbers totaling a sum has been demonstrated but I do not see an example with a second constraint.




Creation of list with random value pairs

I want to create a list with 500 or more value pairs with the following outcome and some boundaries, but I stuck a lot with the correct syntax.

The outcome should look like following:

SiO2 = 35, Al2O3 = 12, CaO = 41, MgO = 12, T = 1498
SiO2 = 38, Al2O3 = 7, CaO = 46, MgO = 9, T = 1512
...

and so on.

I got the following code snippet so far:

from random import randint

CaO = randint(34, 40)
SiO2= randint(30, 40)
MgO = randint(5, 15)
Al2O3 = randint(5, 15)
T = randint(1400, 1550)

liste = []

for i in range(1000):
    if not CaO + SiO2 + MgO + Al2O3 == 100:
        continue
    elif CaO / SiO2 > 1.3 & CaO / SiO2 < 0.85:
        continue
    elif (CaO + MgO) / (SiO2 + Al2O3) < 0.84 & (CaO + MgO) / (SiO2 + Al2O3) > 1.25:
        continue
    else: 
        liste.append(CaO, SiO2, MgO, Al2O3, T)
        
    print(liste)

If anybody could give me some hints it would be great.

Cheers




how to get a reference number in html email which is sent to customer after form summited

I created a wordpress plugin to calculate medical cost, and send email to customer who use that calculator after click on start saving button. the email is going to client perfectly, but I would like to send him a reference number also in that email and want that same reference number on my email which is collecting the customer information. Simply I want to generate a random code "1 to 9999999" to that email. Please help me




How to add spaces to a randomly generated list in Python

I want to generate random numbers, right now it only gives out the numbers. But I want to add spaces between the numbers. so its not only numbers but also randomly placed spaces between the numbers. How to I do that?

import random

def randPic():
    a = ([random.randint(1, 1000) for j in range(10)])
    return a

for i in range(10):
    a = randPic()
    print(*a, sep = ".jpg, ", end = ".jpg, \n")



Display random page on homepage - Wordpress [closed]

I have created several simple pages in the back-office, one displays a picture, another a video, another a sound, etc.

The idea of the website is to only display one page on the homepage taken out randomly from the pool of pages available in the back-office.

In case it's relevant, I use the elementor page-builder and the theme Hello Elementor.

Do you have an idea how to do that?




Create multiple files with same programm but different results

so Im having a problem with my code:

for i in range(10):
    a = ([random.randint(1, 1000) for j in range(10)])
    print(*a, sep = ".jpg, ", end = ".jpg, \n")
    f = open("test.cvs", "x")
    f.close()
        

my current output looks like this:

689.jpg, 715.jpg, 772.jpg, 639.jpg, 903.jpg, 264.jpg, 226.jpg, 629.jpg, 306.jpg, 
758.jpg, 
458.jpg, 355.jpg, 262.jpg, 889.jpg, 244.jpg, 849.jpg, 613.jpg, 439.jpg, 646.jpg, 
766.jpg, 
481.jpg, 954.jpg, 192.jpg, 742.jpg, 598.jpg, 373.jpg, 522.jpg, 685.jpg, 404.jpg, 
164.jpg, 
12.jpg, 202.jpg, 600.jpg, 365.jpg, 635.jpg, 938.jpg, 189.jpg, 492.jpg, 871.jpg, 
611.jpg, 
67.jpg, 256.jpg, 102.jpg, 587.jpg, 637.jpg, 759.jpg, 252.jpg, 175.jpg, 561.jpg, 
965.jpg, 
470.jpg, 744.jpg, 897.jpg, 367.jpg, 765.jpg, 455.jpg, 848.jpg, 258.jpg, 615.jpg, 
910.jpg, 
111.jpg, 344.jpg, 605.jpg, 292.jpg, 511.jpg, 548.jpg, 452.jpg, 836.jpg, 285.jpg, 
152.jpg, 
582.jpg, 716.jpg, 33.jpg, 387.jpg, 335.jpg, 855.jpg, 487.jpg, 57.jpg, 668.jpg, 
41.jpg, 
765.jpg, 424.jpg, 196.jpg, 124.jpg, 898.jpg, 549.jpg, 590.jpg, 42.jpg, 944.jpg, 
462.jpg, 
682.jpg, 728.jpg, 145.jpg, 206.jpg, 246.jpg, 734.jpg, 519.jpg, 618.jpg, 903.jpg, 
662.jpg

which is perfect, i want it exactly like that, but i want to create a file for every output. It cant be the same result in multiple files. Is it possible to let the numbers generate then put the output inside a file and then again let the numbers generate again and put it in a new file. The goal is to create .cvs files Thank you in advance.




lundi 20 septembre 2021

ip: Host name lookup failure in python

Hello Developer's here my code and i'm getting Error..

import random
import time
import os

sec = int(input(" input time to change Ip in Sec: "))
limit = int(input('how many time do you want to change your ip: '))

ip = ".".join(map(str, (random.randint(0, 255) for _ in range(4))))
# main fuction
for _ in range(1,5):
    ip = ".".join(map(str, (random.randint(0, 255) for _ in range(4))))
    time.sleep(6)
    os.system('sudo ifconfig wlo1 down')
    os.system('sudo ifconfig wlo1 ip')
    os.system('sudo ifconfig wlo1 up')
    print('Your Current IP Address is ',ip)

and error is ...............

input time to change Ip in Sec: 2
how many time do you want to change your ip: 3

ip: Host name lookup failure
ifconfig: --help gives usage information.
Your Current IP Address is 212.49.83.22
ip: Host name lookup failure
ifconfig: --help gives usage information.
Your Current IP Address is 199.147.166.42




How to use tf.random for tensors whose shape is None

x = tf.placeholder(tf.float32, (None, 2))
noise = tf.random_uniform(shape=x.get_shape)  # error
x += noise

TypeError: Expected binary or unicode string, got <bound method Tensor.get_shape of <tf.Tensor 'Placeholder:0' shape=(?, 2) dtype=float32>>

TypeError: Failed to convert object of type <class 'method'> to Tensor. Contents: <bound method Tensor.get_shape of <tf.Tensor 'Placeholder:0' shape=(?, 2) dtype=float32>>. Consider casting elements to a supported type.

How can I add noise to the tensor whose shape is None. The input parameter shape of tf's random function does not seem to be None, so what should I do?




Randomly Select Nodes Using NDLib Library and NetworkX

I am trying to randomly select nodes using NDLib and Network X. Instead I am coming up with the same number repeated throughout the list. Is there anyway to adjust this code to randomly choose a number

import networkx as nx
import numpy as np
from networkx.drawing.nx_pydot import graphviz_layout
import ndlib.models.ModelConfig as mc
import ndlib.models.epidemics as ep
import operator
import random

G= nx.erdos_renyi_graph(1000, 0.1)##This might be a bad example

def simulate_threshold(G, importance_measure=None, iterate=50, n=1, threshold=0.25):
    if importance_measure:
        # select seed nodes
        sorted_node = sorted(importance_measure(G).items(), key=operator.itemgetter(1))[::-1]
        
        highest_nodes = [n for n, _ in sorted_node[:n]]
        infected_nodes=highest_nodes
        config = mc.Configuration()
        config.add_model_initial_configuration("Infected", infected_nodes)
    else:
        fraction=float(n)/len(G.nodes)
        fraction = random.uniform(0,fraction)
        config = mc.Configuration()
        config.add_model_parameter('fraction_infected', float(n)/len(G.nodes))
        

    # Model selection
    model = ep.ThresholdModel(G, seed = 42)
   
    
    
    for i in G.nodes:
        config.add_node_configuration("threshold",i,threshold)
    model.set_initial_status(config)

    # Simulation execution
    iterations = model.iteration_bunch(iterate)
    return [it['node_count'][1] for it in iterations]


I=50
N=5
T=0.3
random.seed(42)


node_count_random = simulate_threshold(G, importance_measure=None, iterate=I, n=N, threshold=T)



numpy.random.choice with percentages not working in practice

I'm running python code that's similar to:

import numpy

def get_user_group(user, groups):
    if not user.group_id:
        user.group_id = assign(groups)
    return user.group_id

def assign(groups):
    for group in groups:
        ids.append(group.id)
        percentages.append(group.percentage) # e.g. .33

    assignment = numpy.random.choice(ids, p=percentages)
    return assignment

We are running this in the wild against tens of thousands of users. I've noticed that the assignments do not respect the actual group percentages. E.G. if our percentages are [.9, .1] we've noticed a consistent hour over hour split of 80% and 20%. We've confirmed the inputs of the choice function are correct and mismatch from actual behavior.

Does anyone have a clue why this could be happening? Is it because we are using the global numpy? Some groups will be split between [.9, .1] while others are [.33,.34,.33] etc. Is it possible that different sets of groups are interfering with each other?

We are running this code in a python flask web application on a number of nodes.

Any recommendations on how to get reliable "random" weighted choice?




How to use toString() on linkedlist of randoms? [closed]

I am creating a program that creates a linked list of n length with random ints up to the random limit rLimit. However, I am relatively new to toString() methods and am not sure how to create one that would return the linked list to me. Do you have any suggestions on how to return my linked list in this scenario? Here is what I have so far:

public myLinkedList(int rLimit, int n) {
    LinkedList<Integer> list = new LinkedList<Integer>();
    //number of nodes
    n = 15;
    //boundary of random numbers to choose from i.e. 0,1,2...limit-1
    rLimit = 10;
    Random r = new Random();
    for (int i = 0; i < n; i++) {
        list.add(r.nextInt(rLimit));
    }
}

public String toString() {
    return myLinkedList;
}



Repeat a line of code without writing it again

      import random
     a = [[random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)]]

     for i in a:
    for c in i:
        print(c, end = " ")
    print()

that is just a part if my programm. I need 10x10 random generated numbers. Is there a way to write/formate it better. Maybe in less lines.

Thank you in advance.