mercredi 31 mai 2017

Ruby wont print variable

I've been trying to work on a fake little pin-cracking script, but somethings wrong and it's making me frustrated. It randomizes 4 numbers and checks them against 4 other numbers, but for some reason, after the numbers are guessed, it won't print them anymore.

#RubyCodeStart

pass1 = 4
pass2 = 9
pass3 = 2
pass4 = 8
guess = 0
flag1 = 0
flag2 = 0
flag3 = 0
flag4 = 0
loop do
    if flag1 == 0
        crack1 = rand(0..9)
    end
    if flag2 == 0
        crack2 = rand(0..9)
    end
    if flag3 == 0
        crack3 = rand(0..9)
    end
    if flag4 == 0
        crack4 = rand(0..9)
    end
    if crack1 == pass1
        crack1 = pass1
        flag1 = 1
    end
    if crack2 == pass2
        crack2 = pass2
        flag2 = 1
    end
    if crack3 == pass3
        crack3 = pass3
        flag3 = 1
    end
    if crack4 == pass4
        crack4 = pass4
        flag4 = 1
    end
    guess += 1
    puts "#{crack1} \| #{crack2} \| #{crack3} \| #{crack4} === Guess \# #{guess}"
#   if crack == pass
#       break
#   end
end
sleep(30)

Nothing I do works, and it refuses to print it pass it being found. I'll add data if needed.

Output:

8 | 0 | 6 | 1 === Guess # 1
4 | 6 | 1 | 8 === Guess # 2
 | 1 | 3 |  === Guess # 3
 | 1 | 5 |  === Guess # 4
 | 3 | 9 |  === Guess # 5
 | 3 | 3 |  === Guess # 6
 | 5 | 4 |  === Guess # 7
 | 3 | 4 |  === Guess # 8
 | 4 | 3 |  === Guess # 9
 | 0 | 6 |  === Guess # 10
 | 3 | 8 |  === Guess # 11
 | 4 | 5 |  === Guess # 12
 | 2 | 4 |  === Guess # 13
 | 8 | 7 |  === Guess # 14
 | 8 | 4 |  === Guess # 15
 | 9 | 5 |  === Guess # 16
 |  | 7 |  === Guess # 17
 |  | 5 |  === Guess # 18
 |  | 7 |  === Guess # 19
 |  | 7 |  === Guess # 20
 |  | 7 |  === Guess # 21
 |  | 1 |  === Guess # 22
 |  | 2 |  === Guess # 23
 |  |  |  === Guess # 24
 |  |  |  === Guess # 25
 |  |  |  === Guess # 26
 |  |  |  === Guess # 27
 |  |  |  === Guess # 28
 |  |  |  === Guess # 29
 |  |  |  === Guess # 30
 |  |  |  === Guess # 31
 |  |  |  === Guess # 32
 |  |  |  === Guess # 33
 |  |  |  === Guess # 34
 |  |  |  === Guess # 35
 |  |  |  === Guess # 36
 |  |  |  === Guess # 37
 |  |  |  === Guess # 38
 |  |  |  === Guess # 39
 |  |  |  === Guess # 40




Proving that random() will never return 0 or 1

In the python language the random() function is known to never return 0 or 1. My question is how would somebody create a function to prove this fact. In the function I would like to record the amount of trials run and the amount of times that a 0 or a 1 has occurred ( which we know should be 0).

This is a problem in a book I am reading and I cant figure out the solution.




TYPO3: Generate random variable in FLUID Template

I have three images in my FLUID template and would like to show one of these three images at random. Is there any method to do this in the FLUID template or is this impossible and I must go a other way?

I tried the TYPO3 extension "VHS" to generate a random number:

{v:random.number(minimum: 1, maximum: 3, minimumDecimals: 0, maximumDecimals: 0)}

In the frontend I see the generated number. But how can I set the random number to a variable to use it in a if-else-condition?




Mysql order by many columns then randomize

i've a query ordered by 4 columns with asc or desc. I would like order the resulting rows random if there are two rows with equals values. I.E. (with pseudocode):

SELECT Name FROM Users ORDER BY Score, DESC, Win DESC, Draw DESC, Lost ASC, Id RANDOM

is it possible to do?

My rows have to be orderd random if two users are at the same position in the chart!

Thank you




how to group multiple lists into a main list to select from, and how to ask a user for input to select items from them?

Im trying to create a simple program that has list keys, and multiple list values for each. Im getting confused on the differences between lists, dictionaries and libraries.

How do I group multiple lists into a MAIN list to have users choose from?

example:

import random

#lists to describe what trucks people like
person= ['I', 'she', 'he']
emtotion=['loves', 'hates', 'likes']
Trucks= ['chevys', 'fords', 'rams']`

#lists to describe an animals favorite foods
animal= ['dogs', 'cats', 'birds']
emotion_2=['love', 'hates']
food= ['tuna', 'meat', 'seeds', 'garbage']

for the lists above, how do i group the TWO seperate lists of three lists into 2 seperate master type lists? example:

# a main call to describe peoples emotions towards trucks
truck_preference =     
person= ['I', 'she', 'he']
emtotion=['loves', 'hates', 'likes']
Trucks= ['chevys', 'fords', 'rams']

#a main call for all lists describing an animals foods
animal_foods=
animal= ['dogs', 'cats', 'birds']
emotion_2=['love', 'hates']
food= ['tuna', 'meat', 'seeds', 'garbage']

so for example, once i have my TWO main categories, I can ask a user for input to select "animal_foods" or "truck_preference" and randomly display the values to form a string of text, a simple 3 word random text. then ask the user to select a list again, this time "animal_foods" and display the same randomness again.

this is what I have now, to print the random items.

    count = 0
while count < 10:   
        print(random.choice(Person), end= " ")
        print(random.choice(Emotion), end= " ")
        print(random.choice(Trucks), end= " " )
        print('\n')
        count = count +1

 count = 0
    while count < 10:   
            print(random.choice(animal), end= " ")
            print(random.choice(Emotion_2), end= " ")
            print(random.choice(Food), end= " " )
            print('\n')
            count = count +1

But, my biggest problem is how to ask a user to select either the "Truck_preference" to print the items randomly to form the random texts and and then ask the user to select the "animal_foods" list values to form random text about that.

so what Id hope to accomplish summed up is:

import random

truck_preference = [3 key lists and their values]
animal_foods =[3 key lists and their values]

input("which scenario would you like to run")
#user inputs Truck_preference
 output: I love chevys
         he likes fords
        she hates rams
        he loves rams
        i like fords
        ....etc

input("which scenario would you like to run")
#user inputs animal_foods
 output:  Cats hate seeds
          dogs love meat
          dogs hate meat
         birds hate tuna
         cats love tuna
         birds love seeds
        dogs love garbage
         ...etc




Randomly select rows under conditions

On my spreadsheet I have the following dataset

ID         pack
1          a
1          b
1          c
2          a
3          c
4          a
4          c

I would like to use a function in excel that selects randomly one of the rows where the ID is not unique (it's not important which one, but I need it to be the only one per ID), otherwise has to repeat the same row.

The result according to example should be as below:

ID         pack
1          b
2          a
3          c
4          c

I tried to add a third column called count (counts the number of times the ID is repeated in the db) and calculating a new field as

IF(**count**=1,1,RANDBETWEEN(0,1))

but in some cases an ID (with multiple packs) gets always 0, in other cases gets always 1.

ID         pack    count    check
1          a       3        1
1          b       3        0       
1          c       3        0
2          a       1        1
3          c       1        1
4          a       2        0
4          c       2        0

Of course, last step of this is a new column with

IF(**check**=1,**pack_name**,0)




How to get a random category in a switch with the correct siteID - Swift3

Whats here the problem? I have some siteIDs (from 6 to 12). I filter which siteID is used and i want to get a random category. Is a random category in the right siteID found, they should be returned to work with it. Thanks for your help!

    let sideIDS = helper.selectedSideID()
    let category: String
    return (arc4random_uniform(category))//category: String
    switch sideIDS {
    case 6, 8:
        let category = ["Waschmaschinen", "Kühlschrank", "Geschirrspüler", "Wäschetrockner", "Fernseher", "Staubsauger", "Lampen", "Reifen"]
        //return (category[Int(arc4random_uniform(UInt32(category.count)))])
    case 7, 11:
        let category = ["Washing machine", "Fridge", "Dishwasher", "Dryer", "TVs", "Vacuum Cleaners", "Lamps", "Tyres"]
        //return (category[Int(arc4random_uniform(UInt32(category.count)))])
    case 9:
        let category = ["Lavadoras", "Refrigerador", "Lavavajillas", "Secadoras", "Televisores", "Aspiradoras", "Lamparas", "Neumatico"]
        //return (category[Int(arc4random_uniform(UInt32(category.count)))])
    case 10:
        let category = ["Lave-Linge", "Frigo", "Lave-Vaisselle", "Seche-Linge", "TV", "Aspirateur", "Lampes", "Pneu"]
        //return (category[Int(arc4random_uniform(UInt32(category.count)))])
    case 12:
        let category = ["Lavatrici", "Frigo", "Lavastoviglie", "Asciugatrice", "Televisore", "Aspirapolvere", "Lampade Design", "Pneumatico"]
        //return (category[Int(arc4random_uniform(UInt32(category.count)))])
    default:
        XCTFail("No sideID found")
    }




c++ vector with random unique elements with constant sum

I have an std::vector with fixed size N = 5. I want every element of the vector to be randomly selected between two positive numbers, in particular 1 and 12. (zeros are not allowed).Each element should be unique on the vector.

Code so far:

#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <random>

int main() {
    std::random_device rd;
    std::mt19937 gen(rd());

    constexpr int MAX = 20;
    constexpr int LINES = 5;

    int sum{};
    int maxNum = 12;
    int minNum = 1;

    std::array<int, LINES> nums;

    for (int i = 0; i < LINES; ++i) {
        maxNum = std::min(maxNum, MAX - sum);
        minNum = std::min(maxNum, std::max(minNum, MAX - maxNum * (LINES - i)));
        std::cout << minNum << " " << maxNum << std::endl;
        std::uniform_int_distribution<> dist(minNum, maxNum);
        int num = dist(gen);

        nums[i] = num;
        sum += num;
    }

    std::shuffle(std::begin(nums), std::end(nums), gen);
    std::copy(std::begin(nums), std::end(nums), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
}




c++ vector of unique random positive numbers with fixed sum

I thought that it would be easier at the beginning...

I have an std::vector with fixed size (ie 5 elements). I want every element of the vector to be randomly selected between two positive numbers (zeros are not permitted) but the random numbers should sum to a constant value.

For example

vector size = 5;
sum = 20;
element min = 1;
element max = 10;

accepted answer should be [2, 9, 5, 4, 1]

Any ideas on how to do this fast?




Segmentation fault when generating many random numbers - PGI Fortran

I need to generate a large amount of random numbers (from zero to 1, evenly distributed).

I initially had a Do loop and was generating random numbers on the fly as such:

Real :: RandomN
Integer :: N
DO N = 1, 10000
   Call RANDOM_NUMBER(RandomN)
   ... Some Code ...
ENDDO

However, I was getting a segmentation fault when generating the numbers (if I commented out the "call random_number(RandomN)" line, it worked fine).

Then after reading a post on the PGI forums(http://ift.tt/2roejnf). I decided to generate all the numbers first and put them in an array.

Real :: RndNum(1:10000,1:5)
Integer :: time(8), seed(2)
Call DATE_AND_TIME(values=time)     ! Get the current time 
seed(1) = time(4) * (360000*time(5) + 6000*time(6) + 100*time(7) + time(8))
Call RANDOM_SEED(PUT=seed)
Call RANDOM_NUMBER(RndNum)

However, this gives me a segfault straight away. I have also tried a reduced version without the seed:

Real :: RndNum(1:10000,1:5)
Call RANDOM_NUMBER(RndNum)

This works for a few iterations of my code and then produces a segmentation fault as well. Am I using up some sort of memory? is there a way to clear it? or prevent it from being used up?

Any help with generating the random numbers would be much appreciated. Thanks




Python comprehension for random floats

import random as rd
print([round(rd.random(), 3) for num in range(20)])

So this prints 20 random numbers shortened to 3 decimals.
How would I write the code so that it writes only random numbers higher than 0.4 but lower than or equal to 1? Any combination of if statements I try yields an error.




non-Squar random unitary matrix

I want to generate non-Squar random unitary matrix ,and I use following function (randU) , this is a matlab code and I need to do it in python

function U = randU(n);

X = (randn(n) + i*randn(n))/sqrt(2);

[Q,R] = qr(X);

R = diag(diag(R)./abs(diag(R)));

U = Q*R;




How to exactly unselect xy % of grid cells?

From a 10*10 raster I want to unselect for example 90 percent, that is, 10 percent remain visible. To do this I adapted this code, see below. But there is some variation in the resulting pixels (more then 10 or less then 10 pixels remain). Is there a possibility to set precision of random selection?

r<- raster(ncol=10, nrow=10, xmn=0, ymn=0, xmx=10, ymx=10)#create raster
values(r)<- 1:ncell(1) #asigne 1 to each raster cell
#plot(r, col='black') #plot raster

r[runif(10*10) >= 0.15] <- NA # Randomly *unselect* XY% of the data

par(pty="s", mar=c(1,1,1,1))
plot(r, col='black', legend=FALSE, axes=F) #plot raster
box(lty=1, col="black", lwd=5)




Why there is no nextDouble(), nextFloat() and nextLong() which accept a bound in java.util.Random

I was reading java.util.Random class and noticed that there is no nextDouble(), nextFloat() and nextLong() which can accept a bound.

There are many way to get it done like this.

But my question is why java did not provide us with these required method like nextInt(int n) which accept the bound.

Is there any specific reason they did not provide these methods?




Generating a random number with probability [duplicate]

This question already has an answer here:

I have a set of 5 objects:

{one, two, three, four, five}

I want to write a Java program which has a for loop running a million times.

In every run of the for loop, I will randomly pick an object from above set.

However, I want to ensure that 40% times one should be selected, 15% times two is selected, 25% times three is selected, 15% times four is selected and 5% times five is selected.

How do I generate a random number with above probabilities in java ?




mardi 30 mai 2017

Generating "better" random data

I'm trying to build an example chart using ggplot. The context is marketing data and I created some dummy data with these blocks:

# dimensions
channels <- c("Facebook", "Youtube", "SEM", "Organic", "Email", "Direct")
last_month <- Sys.Date() %m+% months(-1) %>% floor_date("month")
mts <- seq(from = last_month %m+% months(-23), to = last_month, by = "1 month") %>% format("%b-%Y")
dimvars <- expand.grid(Month = mts, Channel = channels)

# metrics
rws <- nrow(dimvars)
set.seed(123)
Sessions <- ceiling(rnorm(rws, mean = 3000, sd = 300))
Transactions <- ceiling(rnorm(rws, mean = 200, sd = 40))
Revenue <- ceiling(rnorm(rws, mean = 10000, sd = 100))

# make df
dataset <- cbind(dimvars, Sessions, Transactions, Revenue)

I then build an area plot:

timeline <- ggplot(dataset, aes(x = Month, y = Sessions,fill = Channel, group = Channel)) +
  geom_area(alpha = 0.8) +
  theme(axis.text.x=element_text(angle=90, hjust=1))

Here's how it looks: enter image description here

This image is pretty unrealistic from the standpoint of a marketer, where all channels are moving in line with each other. Short of actually adding in manual values, I wondered if there are any techniques for adding multipliers or similar to "random" data?

For example, without resorting to adding manual values, I'd like to know if I can set the rnorm() to start with a lower mean, then grow, then shrink again along the n values generated. Is there a function that does this? I could create 3 or 4 distributions with different means and then c() them but this would look more like sharp changes rather than gradual ebbs and flows.

Any suggestions for manipulating random data to fluctuate (expand and contract) over the course of n length vector?

I tried fiddling with the sd argument or rnorm but that just made the data look more volatile.

I'm trying to show, somewhat randomly, channels start and ramp up, then level off and decline.




Getting base seed for pRNG given an array of data

I was wondering if, given a known PRNG and a set of values, one could calculate that PRNG's base seed. For example, say I have an array of data

var a = [255, 192, 0, 3, 72]

I know for a fact that each of those values was generated from calls PRNG.nextInt(). So the first call to PRNG.nextInt() returned 255, the next call returned 192, and so on. If you were only given that data set, is there a PRNG algorithm to give me the original seed? So that you could do something like this:

var seed = PRNG.getSeedForData([255, 192, 0, 3, 72])
var prng = new PRNG(seed)

And then with that prng instance, this should be true:

prng.nextInt() == 255
prng.nextInt() == 192
prng.nextInt() == 0
prng.nextInt() == 3
prnt.nextInt() == 72

I looked at this post (Is it possible to reverse a pseudo random number generator?) as well as this one (Given a RNG algorithm and a series of numbers is it possible to determine what seed would produce the series?), but I'm not sure what to do with that information. It doesn't look like either post found a solution to the problem, however, and I don't want to necropost.

Based on what little I understood from those posts, though, it looks like Linear congruential generators might be the way to go?, but I'm not entirely sure how to even approach them.


Just to clarify, I trying to write an PRNG algorithm that can also give me a seed when supplied with a series of numbers. The nextInt() function in the algorithm should ideally always return a value between 0 and 255, but I'm not sure if that is relevant to the question.




Something randomly flashes on my screen

I have this weird problem with my windows 10. I am using a genuine version, and I wiped out the whole thing and reinstall it because of this problem.

Something (I assume it is a cmd window) is flashing on my screen randomly. It happens too quick and randomly to capture. I thought it was some kinda penetration attempt, and wiped the whole thing but the problem continues.

I am wondering if anyone has the same problem with me or solution for me. Also, I would like to know if there is a program to record all foreground apps history to find out the suspicious app.




Python map generation, random.seed performance

I'm using random midpoint displacement algorithm to generate height-maps. In order to keep things depend exclusively on the coordinates and a seed I use the following function and method:

import random    


class HeightMap(object):
    def __init__(self, ..., seed=None, bit_length=64):
         ...
         self.bit_length = bit_length
         self.seed = seed if seed is not None else random.randint(0, 1 << self.bit_length)
         self.coord_min, self.coord_max = (-1 << (self.bit_length >> 1) - 1,
                                           (1 << (self.bit_length >> 1) - 1) - 1)

    ...

    def get_random_at(self, x, y, a, b):
        random.seed(get_seed_at(self.seed, x, y, self.bit_length))
        return random.uniform(a, b)

def get_seed_at(seed, x, y, bit_length):
    return (seed + ((x << (bit_length >> 1)) + y + (1 << (bit_length >> 1) - 1))) % (1 << bit_length)

This might seems a bit spaghetti. What the get_seed_at function does, it the copies the x coordinates and y coordinates into an integer (with size of bit_length) to it's upper and lower bits, adds seed to this and makes sure it stays bit_length wide by taking it's modulo.

Then get_random_at method uses the integer provided to seed the random module's Random singleton. This is thread safe, even though it does not have a designated instance, but more importantly it generates the same map from the same given seed every time no matter which order I request the chunks to be created.

My issue is, after some optimization I manage to narrow the bottle neck to random.seed. At this point it almost takes up half of the run time.

Is there any suggestions how to improve on this? Or a better approach to solve this all together?

Many thanks.




How can I maintain probability across multiple executions in Java

Firstly I am not the greatest with Math, so please excuse any ignorance relating to that. I am trying to maintain probability based randomness across multiple executions but I am failing. I have this input in a JSONObject

{
   "option1": 25,
   "option2":25,
   "option3" :10,
   "option4" :40
}

This is my function that selects a value from the above JSONObject based on the probability assigned:

public static String selectRandomoptions(JSONObject options) {
    String selectedOption = null;

    if (options != null) {

        int maxChance = 0;
        for (String option : options.keySet()) {
            maxChance += options.getInt(option);
        }

        if (maxChance < 100) {
            maxChance = 100;
        }

        Random r = new Random();
        Integer randomValue = r.nextInt(maxChance);

        int chance = 0;
        for (String option : options.keySet()) {
            chance += options.getInt(option);
            if (chance >= randomValue) {
                selectedOption = options.toLowerCase();
                break;
            }
        }
    }
}

the function behaves within a reasonable error margin if I call it x amount of times in a single execution ( tested 100+ calls), the problem is that I am running this every hour to generates some sample data in an event-driven app to verify our analytics process/data but we need it to be somewhat predictable, at least within a reasonable margin?

Has anyone any idea how I might approach this? I would rather not have to persist anything but I am not opposed to it if it makes sense or reduces complexity/time.




Is Display Tag Library secure?

I know this is not a programming question but I would like to know if Display Tag is safe and secure to use. I couldn't find anything in the documentation regarding security. Please let me know if it is fully secured and reliable to use.




C# return a random number twice in while loop [duplicate]

This question already has an answer here:

Hey im trying to return a random number from a method. my code works, it returns a random number, but the problem is that its the same number it returns if i use it twice in the same while loop, how do i fix the problem? if there is a fix to the problem.

My code look like this

 private int ReturnARandomNumber(int min, int max)
 {
    var randomNumber = new Random();
    return randomNumber.Next(min, max);
 }

- Morten syhler




How to make a button in random space in qml [on hold]

I want to make a button when it clicked it goes in random position.for 10 times clicked.i want help.please




Will C# system.Random with 14 characters always be guaranteed to be unique string (hash)

I have a utility function in which I want to have as part of my URL querystring . I need to be sure that it is always unique

public static string RandomString(int length)
{
   const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ=abcdefghijklmnopqrstuvwxyz0123456789";
   var random = new Random();
   return new string(Enumerable.Repeat(chars, length)
     .Select(s => s[random.Next(s.Length)]).ToArray());
}

If say I pass in 14 for the length , This generates hash like

 YS5bwVTjwEBhFp
 sNi6EfU5rUxI2Z
 sQKhqhklw22vb2

If i'm using talking about 20,000 uses a year of this, Is it safe to say that it should always be unique?

Again

http://:mywebsite.com?id=sQKhqhklw22vb2 is how i would use it




Select randomly from array without using Math.random

Q. Is it possible to select randomly from an array without using Math.random?

Background: I have a large array of random numbers between 0 and 48. I'm trying to select randomly from this pool of numbers without selecting duplicates (which I'll use a while loop and indexOf() === -1 as the condition).




rbinom for rolling a 111-side die 104 times in r

i understand if you roll a 100-side die 100 times for a total number of 7s. you get

  rbinom(1,100,0.07)

but how do you roll a 111-sided die 104 times and get the total number of 34s you get? kinda confused.




Multiple choice quiz in python using random function and lists

I'm trying to make a multiple choice quiz using python. It seemed like something simple to make at first but now i'm scratching my head a lot trying to figure out how to do certain things.

I am using two lists; one for the questions and one for the answers. I would like to make it so that a random question is chosen from the questions list, as well as 2 random items from the answers list (wrong answers) and finally the correct answer (which has the same index as the randomly selected question). I've got as far as selecting a random question and two random wrong answers

  • My first problem is getting the program to display the correct answer.
  • The second problem is how to check whether the user enters the correct answer or not.

I would appreciate any feedback for my code. I'm very new to this so go a little easy please! I hope my stuff is readable (sorry it's a bit long)

thanks in advance

import random

print ("Welcome to your giongo quiz\n")
x=0
while True:
    def begin(): # would you like to begin? yes/no... leaves if no
        wanna_begin = input("Would you like to begin?: ").lower()
        if wanna_begin == ("yes"):
            print ("Ok let's go!\n")
            get_username()#gets the user name
        elif wanna_begin != ("no") and wanna_begin != ("yes"):
            print ("I don't understand, please enter yes or no:")
            return begin()
        elif wanna_begin == ("no"):
            print ("Ok seeya!")
    break

def get_username(): #get's username, checks whether it's the right length, says hello 
    username = input("Please choose a username (1-10 caracters):")
    if len(username)>10 or len(username)<1:
        print("Username too long or too short, try again")
        return get_username()
    else:
        print ("Hello", username, ", let's get started\n\n") 
        return randomq(questions)

##########

questions = ["waku waku", "goro goro", "kushu", "bukubuku", "wai-wai", "poro", "kipashi", "juru", "pero"]

answers = ["excited", "cat purring", "sneezing", "bubbling", "children playing", "teardrops falling", "crunch", "slurp", "licking"]

score = 0

if len(questions) > 0: #I put this here because if i left it in ONly inside the function, it didnt work...
        random_item = random.randint(0, len(questions)-1)
        asked_question = questions.pop(random_item)

###########

def randomq(questions):
    if len(questions) > 0:
        random_item = random.randint(0, len(questions)-1)
        asked_question = questions.pop(random_item)
        print ("what does this onomatopea correspond to?\n\n%s" % asked_question, ":\n" )
        return choices(answers, random_item)
    else:
        print("You have answered all the questions")
        #return final_score

def choices(answers, random_item):
    random_item = random.randint(0, len(questions)-1)
    a1 = answers.pop(random_item)
    a2 = answers.pop(random_item)
    possible_ans = [a1, a2, asked_question"""must find way for this to be right answer"""]
    random.shuffle(possible_ans)
    n = 1
    for i in possible_ans:
        print (n, "-", i) 
        n +=1
    choice = input("Enter your choice :")
    """return check_answer(asked_question, choice)"""

    a = questions.index(asked_question)
    b = answers.index(choice)
    if a == b:
        return True
    return False

begin()




Generate a random boolean 70% True, 30% false

I have the following function that generates a random boolean. choose_direction: function () {

 var random_boolean = Math.random() >= 0.5;
    if (random_boolean) {
        trade.call()
        prev_trade.goingUp = true
        console.log('Trade: CALL!!!!!!!!!!!!!!!!!!!!!!')
    } else {
        trade.put()
        prev_trade.goingUp = false
        console.log('Trade: PUT!!!!!!!!!!!!!!!!!!!!!!!!')
    }
}

However, I need the distribution to be unfair. More specifically, I want the output to be 70% of the time true and 30% of the time false.




Scala Shuffle A List Randomly And repeat it

I want to shuffle a scala list randomly.

I know i can do this by using scala.util.Random.shuffle

But here by calling this i will always get a new set of list. What i really want is that in some cases i want the shuffle to give me the same output as before. So how can i achieve that?

Basically what i want to do is to shuffle a list randomly at first and then repeat it in the same order. For the first time i want to generate the list randomly and then based on some parameter repeat the same shuffling.




lundi 29 mai 2017

Create a random quiz mode where every array part is only called once (Android Studio)

I'm a bit new to Android Studio and I want to make small quiz app. On the start screen there are two buttons. With the first button you just click through your questions and you can start at a specific question number if you want (this is already working). With the second button I wand to create a random mode BUT every question should only be asked once. So there should not be the possibility to get the same questions twice.

For that I created an Array:

public ArrayList<Integer> questionsDone = new ArrayList<>();

And got the lenght of the Question Array:

public int maxQuestions = QuestionLibrary.nQuestions.length;

then I have a function for updating the question:

private void updateQuestion(){

    //RANDOM MODE
    if (startNumber == -1) {
        if (questionsDone.size() >= maxQuestions) {
            finishQuiz();
        } else {
            nQuestionNumber = (int) (Math.random() * (maxQuestions));

            do {
                if (questionsDone.contains(nQuestionNumber)) {
                    nQuestionNumber = nQuestionNumber - 1;
                    if (nQuestionNumber == -1) {
                        nQuestionNumber = maxQuestions-1;
                    }
                } else {
                    questionsDone.add(nQuestionNumber);
                    notDone = true;
                }

            } while (notDone = false);
        }
    }
    nQuestionView.setText(nQuestionLibrary.getQuestion(nQuestionNumber));
    nButtonChoice1.setText(nQuestionLibrary.getChoice1(nQuestionNumber));
    nButtonChoice2.setText(nQuestionLibrary.getChoice2(nQuestionNumber));
    nButtonChoice3.setText(nQuestionLibrary.getChoice3(nQuestionNumber));

So my idea was that when I start random mode, i pass the value "-1". If the size of the array (questions done) equals the number of the available questions the quiz should stop. If not, I just get a random number and multiply it with the number of questions. Then there is a do-while function which makes sure that if the questionsDone-Array already contains the number it will get a new number and after getting a number which is not in the array it will be stored in the array.

This is what the app does when I click on random mode:

It always shows a random question but sometimes one questions is asked twice and more. And suddenly it stops (the app is loading the result page) but the stop does not come with a pattern. When I have 7 questions, every questions is minimum asked once and sometimes it stops afer 15, sometimes after 20 questions and so on.

Does someone know why?




How do I create a random property inside a randomly selected object?

For example, if I have:

var weapon = [
"sword",
"mace",
"staff"];

var swordtype = [
"long",
"short"];

var stafftype = [
"quarter",
"magic"];

and my script randomly selects 'Sword' to display in my html p tag from the weapon variable.

How can I say that if my code randomly selects "Sword" from the weapon variable, it will also randomly select a "swordtype" to go with it? Making the output either "long sword" or "short sword"?




How to setup Thread.sleep to be a random number (Selenium Java)

Quite simple question, however, I have trouble with this. I want to use sleep.thread to click on buttons in a random range of numbers, for example 30-50 seconds. This must be a sleep command. There is a loop that clicks on the elements and my attempt to do that(I found this in another answer, not working for me)

List<WebElement> textfields = driver.findElements(By.className("_84y62"));


    System.out.println("total buttons " + textfields.size());

        for (WebElement e : textfields) {
            e.click();

                Thread.sleep((long)(Math.random() * 11 + 10));
            }




I cant Clean the Label

    private void cmdStart_Click(object sender, EventArgs e)
    {
        Random r = new Random();
        int iRnd = new int();
        int iRnd1 = new int();
        int iRnd2 = new int();
        iRnd = r.Next (0, 6); 
        iRnd1 = r.Next(0, 6); 
        iRnd2 = r.Next(0, 6); 

        if (iRnd == 0)
            pbTärnigVisa1.Image = pbTärning0.Image;
        else if (iRnd == 1)
            pbTärnigVisa1.Image = pbTärning1.Image;
        else if (iRnd == 2)
            pbTärnigVisa1.Image = pbTärning2.Image;
        else if (iRnd == 3)
            pbTärnigVisa1.Image = pbTärning3.Image;
        else if (iRnd == 4)
            pbTärnigVisa1.Image = pbTärning4.Image;
        else 
            pbTärnigVisa1.Image = pbTärning5.Image;
        //Dice1 IRnd
        //Dice2 IRnd1
        //Dice3 IRnd2

        bool r1 = (iRnd == iRnd1);
        bool r2 = (iRnd == iRnd2);
        bool r3 = (iRnd1 == iRnd2);
        bool r4 = (iRnd1 == iRnd2);
        var allEqual = new[] { r1, r2, r3 }.Distinct().Count() == 1;


        if (r1)
            lbl_resultat.Text = " 1 pair";
        if (r2)
            lbl_resultat.Text = " 1 pair";
        if (r3)
            lbl_resultat.Text = " 1 pair";
        if (allEqual)
            lbl_resultat.Text = " 3 Pair";
        else
            lbl_resultat.Text.Remove(0);

I cant clean the lable lbl_resultat. Can somne of you see the problem? The lable only types out " 3 pair" if not one of the prv values Thanks for Answers. And if you got any improvements feel free :D




How to bound the sample of Poisson Random Variates to simulate arrivals

I want to make a montecarlo simulation on which I generate 10 scenarios, each of them is characterized by a random number of arrivals in a time horizon.

I use the scipy.stats.poisson http://ift.tt/2qsJDSx to generate the samples of arrivals for each scenario, assuming that the mean is 12.

from scipy.stats import poisson
arrivals = poisson.rvs(12, 10)
print arrivals

The output is a list of random numbers:

[11 13  9 10  8  9 13 12 11 23] 

The mean is 11.9 which is good enough, but the problem is that in this case, in the last scenario there are 23 arrivals which is far from the mean 12.

Since before running this simulation I had to select a population, I have to make the size of that population large enough to comply with the Poisson Random Variates. So let's say that I select a population with size 1.5 * 12 = 18, unfortunately in the last scenario I will get an error since the sample is larger than the population itself.

My first question is: which is the minimum size of the population that I have to select in order to sample these arrivals with a list of Poisson Random Variates, without getting an error?

My second question is: is there a better way to manage this kind of problem by using another probabilistic distribution?

Please note that in this case mean=12 but I have to simulate other contexts on which mean=57 and mean=234.




How to control fractional active noise in fbm

I am implementing fractional brownian motion in Matlab using wfbm(H,L) function, but i want to have some more control over the wfbm. I want to have diffusion constant as a parameter in the function, to control the noise generated, how can I implement that ?




Most pythonic way to select at random an element in a list with conditions

I have two list:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [1, 4, 5]

I want to select an element from list1 but it shouldn't belongs to list2.

I have a solution using a while loop but I would like to have a one liner more pythonic and elegant.




Generate random number using numpy in python

I want to use round(random.uniform(1.5, 1.9),2) to generate random number and also use numpy.random.random((5,10)) to generate a list includes 5 elements and every element has 10 items. Can I do them simultaneously?




JavaScript biased results?

Let's say I have two items in an array, e.g:

["a", "b"]

Now let's say I have a function called random that chooses a random item from this array, e.g:

function random() {
  // do awesome random stuff here...
  return random_choice;
}

How can I get the random function to return "a" 80% of the time and "b" 20% of the time?

I'm not really sure as to what this is called but for example if I ran the console.log(random()); 10 times the result should look a little something like this:

>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "b"
>>> "b"

"a" get's returned 8/10 times and "b" gets returned 2/10 times.

NOTE: the "results" above are just an example, I understand that they won't always be that perfect and they don't have to be.




Large random pattern

I've been trying to create a special random pattern for some time. For example random black dots, like this:

http://ift.tt/2qyFhEI

However, I need a much larger image with about 100,000 points / circles. In principle, no problem, however, the SVG with several MB then becomes too large to open it, for example, with Inkscape, because each circle is drawn individually. Any ideas how this could be realize better resulting in a smaller file. I have already tried something with pattern. Problem is that it should be a truly random, non-repeating pattern.

It's not necessary to do this with dots it could also look like this: [enter image description here][1] http://ift.tt/2r3Wzxa

For ideas / suggestions, I am grateful.

greetings Olli




Assigning numbers to members of a list

I need some ideas to implement in my project. I need to assign a ticket number to persons on this list.

ListaUtente.Add(new Utente(100001, "John", 914754123, "john@gmail.com", GetRandomColor()));
        ListaUtente.Add(new Utente(100002, "Peter", 974123214, "peter@gmail.com", GetRandomColor()));
        ListaUtente.Add(new Utente(100003, "Tidus", 941201456, "tidus@gmail.com", GetRandomColor()));
        ListaUtente.Add(new Utente(100004, "Poppy", 987453210, "pops@gmail.com", GetRandomColor()));

Utente class is:

class Utente
{
    // Class Atributes

    private int numUtenteSaude;
    private String nome;
    private int telefone;
    private String email;
    private ConsoleColor color;





    public Utente(int numUtenteSaude, String nome, int telefone, String email, ConsoleColor color)
    {
        this.numUtenteSaude = numUtenteSaude;
        this.nome = nome;
        this.telefone = telefone;
        this.email = email;
        this.color = color;
    }



    public void display()
    {
        Console.ForegroundColor = this.color;
        Console.WriteLine("Pessoa: Numero Utente Saude: " + numUtenteSaude + " Telefone: " + telefone + "  " + "Nome:" + nome + " Email: " + email);
    }

    public override string ToString()
    {
        return String.Format("{0} {1} {2} {3} {4}", numUtenteSaude, nome, telefone, email, color);
    }
}

}

This is like an hospital and the people on the list are arriving at the medical center. I need to assign a ticket number to people in the list. How can I do this?




Unity 3D - Shuffle voxel cubes in a game object

I am trying take a group of voxel ground cubes and have them shuffled or randomly placed differing from how they are placed on the game area. I am attempting to make it where the grass is not in a pattern and has more of a visual appeal. I have tried several solutions I have found and none quite fit the bill, I even tried one that was suppose to take multiple cubes and fill the space defined in the object group. That failed miserably with more than undesirable effects. I have read a few other posts that are similar in nature but not the same of what I am after. Simply put I want to take a group of prefabs and replace all the blocks in an object group randomly with the blocks provided to the script. I am even open to creating a cube to define the space that is to be filled. Keep in mind I am not new to programming, however I am new to Unity Game Development, so keep that in mind. I used the following from a post however it only allows for 1 prefab and it does not conform to the areas that the ground tiles are placed in the object group.

Thanks folks!




Ruby prepending static string to a random string?

I figured out how to generate random strings a certain amount of times per line. Now, I'm trying to figure out how to add a fixed, static string to the prefix of all the randomly generated strings.

for example, if this code spits out gCOABGSS as a random string, I want to modify the script so it adds for example HEY-NOW to each of the outputs, resulting in HEY-NOWgCOABGSS

def generate_code(number)
  charset = Array('A'..'Z') + Array('a'..'z')
  Array.new(number) { charset.sample }.join
end


5.times { puts generate_code(8) }

How to go about this?




dimanche 28 mai 2017

C# - Random color generator not working

So I'm having a bit of a problem with a simple random color generator class that despite all effort will not stop generating the same set of colors everytime the application starts.

This is an issue that only happens the first time it is used. However the time between the initialization of the Random object and the first generation call is user-determined. So I really have no idea what is causing it

Here's my code:

        /// <summary>
    /// Random number generator
    /// </summary>
    static Random Random;

    public static void Initialize()
    {
        //Intializes the random number generator
        Random = new Random();
    }

    /// <summary>
    /// Generates a random color
    /// </summary>
    /// <returns></returns>
    public static Color GenerateOne()
    {
        while (true)
        {
            Color clr = Color.FromArgb(RandByte(), RandByte(), RandByte());

            float sat = clr.GetSaturation();

            if (sat > 0.8 || sat < 0.2)
            {
                continue;
            }

            float brgt = clr.GetBrightness();
            if (brgt < 0.2)
            {
                continue;
            }

            return clr;
        }
    }

    /// <summary>
    /// Generates a set of random colors where the colors differ from each other
    /// </summary>
    /// <param name="count">The amount of colors to generate</param>
    /// <returns></returns>
    public static Color[] GenerateMany(int count)
    {
        Color[] _ = new Color[count];

        for (int i = 0; i < count; i++)
        {
            while (true)
            {
                Color clr = GenerateOne();

                float hue = clr.GetHue();
                foreach (Color o in _)
                {
                    float localHue = o.GetHue();

                    if (hue > localHue - 10 && hue < localHue + 10)
                    {
                        continue;
                    }
                }

                _[i] = clr;
                break;
            }
        }

        return _;

    }

    /// <summary>
    /// Returns a random number between 0 and 255
    /// </summary>
    /// <returns></returns>
    static int RandByte()
    {
        return Random.Next(0x100);
    }
}

Screenshot of repeating color scheme if needed

Thanks in advance :)




a problrm when i turn a html form inputs into php array

My html file contains the following form

<form action="action.php" method="get">
First name:<br>
<input type="text" name="name[]" /><br>
Second name:<br>
<input type="text" name="name[]" /><br>
Third name:<br>
<input type="text" name="name[]" /><br>
Forth name:<br>
<input type="text" name="name[]" /><br>
<input type="submit" value="submit">
</form>

and I want the output to be one random value of the inputs , so my action.php looks like

<?php

    $output = $_POST['name'];

 $key = array_rand($output);
echo $output[$key];

                   ?>

but this doesn't work and gives me the following

Notice: Undefined index: name in C:\xampp\htdocs\myfiles\action.php on line 8

Warning: array_rand() expects parameter 1 to be array, null given in C:\xampp\htdocs\myfiles\action.php on line 10

can any one help please?




Need Help printing five random numbers (like dice throws) for computer and player. I need to use ( randomeValue= ) statement seen in code

My code is only producing two random numbers and not five for player and computer like I need it to. Can anybody see the problem?

import java.util.Random;

public class Die{

      private static int HIGHEST_DIE_VALUE=6;
      private static int LOWEST_DIE_VALUE=1;
      private int randomValue;

    public Die(){
                randomValue = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
        }

    private void generateRandom(){
              randomValue = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
    }

    public int getValue(){
        return randomValue;
      }
}

public class FiveDice {

    public static void main(String[] args){

            Die computer = new Die();
            Die player = new Die();

                System.out.println("Computer five random die values:");
                System.out.println("\tDie 1 rolled a " + computer.getValue() + " value");
                System.out.println("\tDie 2 rolled a " + computer.getValue() + " value");
                System.out.println("\tDie 3 rolled a " + computer.getValue() + " value");
                System.out.println("\tDie 4 rolled a " + computer.getValue() + " value");
                System.out.println("\tDie 5 rolled a " + computer.getValue() + " value");

                System.out.println("\nPlayer five random die values");
                System.out.println("\t\tDie 1 rolled a " + player.getValue() + " value");
                System.out.println("\t\tDie 2 rolled a " + player.getValue() + " value");
                System.out.println("\t\tDie 3 rolled a " + player.getValue() + " value");
                System.out.println("\t\tDie 4 rolled a " + player.getValue() + " value");
                System.out.println("\t\tDie 5 rolled a " + player.getValue() + " value");   


        }

}

This is what the output:

Computer five random die values:
Die 1 rolled a 5 value
Die 2 rolled a 5 value
Die 3 rolled a 5 value
Die 4 rolled a 5 value
Die 5 rolled a 5 value

Player five random die values
Die 1 rolled a 4 value
Die 2 rolled a 4 value
Die 3 rolled a 4 value
Die 4 rolled a 4 value
Die 5 rolled a 4 value

I need each die for each player to be random numbers. Any help?




Why rand() is much faster than arc4random()

I'm writing a game AI which requires fast int random number generation. This game is for Mac OS, so there are two choices rand() (the plain C) and arc4random() (BSD). I didn't find any comparison in speed for these two functions, so I wrote a small program to test:

long i;

// Record timestamp here.
srand((unsigned int)time(NULL));
for (i = 0; i < 999999999; ++i) {
    rand();
}
// Record timestamp here.
for (i = 0; i < 999999999; ++i) {
    arc4random();
}
// Record timestamp here and print all three.

I tested several times. Results are quite stable: srand() and 999999999 iterations of rand() takes around 6 s, while arc4random() takes much longer (around 30 s).

Is there any reason that arc4random() takes much longer time? Or is there any flaw in my testing. Thank you!




Modify vanitygen/keyconv to generate deterministic bitcoin address

Vanitygen is a C program software that permits to generate a Bitcoin address starting with a specific string (for example starting with "JohnDoe" like 1JohnDoeXku52yT5jhYht4852HVg547).

Keyconv is part of the Vanitygen toolset, and is a C program that permits to generate a random bitcoin Address/Private key pair, using ECDSA algorithm for the random factor.

Sources can be found here : http://ift.tt/1dRmOqc

How generating Bitcoin PrivateKey/Address works?

Basically, a bitcoin private key is a number, to which are applied mathematical and cryptographic calculations. The result of these calculations is the Bitcoin WIF Private Key (WIF for Wallet Import Format ). Once you have that Private Key you can generate the Bitcoin Address with other mathematical/cryptographic calculations. The valid range for the initial random number is between 1 and 115792089237316195423570985008687907852837564279074904382605163141518161494336 inclusive.

A description of the different calculations performed can be found here : http://ift.tt/1l34mjq

How keyconv works?

It takes a random number from the ECDSA algorithm (included in the OpenSSL library) and then performs the different mathematical/cryptographic calculations to generate Bitcoin Private Key and associated Bitcoin Address.

Here is an extract of keyconv.c with the portion of code that interest us for the problem :

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <assert.h>

#include <openssl/evp.h>
#include <openssl/bn.h>
#include <openssl/ec.h>
#include <openssl/obj_mac.h>

int
main(int argc, char **argv)
{
    char pwbuf[128];
    char ecprot[128];
    char pbuf[1024];
    const char *key_in;
    const char *pass_in = NULL;
    const char *key2_in = NULL;
    EC_KEY *pkey;
    int parameter_group = -1;
    int privtype, addrtype;
    int pkcs8 = 0;
    int pass_prompt = 0;
    int verbose = 0;
    int generate = 0;
    int opt;
    int res;

    while ((opt = getopt(argc, argv, "8E:ec:vG")) != -1) {
        switch (opt) {
        /* ... */
        case 'G':
            generate = 1;
            break;
        default:
            usage(argv[0]);
            return 1;
        }
    }


    OpenSSL_add_all_algorithms();

    pkey = EC_KEY_new_by_curve_name(NID_secp256k1);

    /* How do I print the value of pkey? */

    if (generate) {
        unsigned char *pend = (unsigned char *) pbuf;
        addrtype = 0;
        privtype = 128;
        EC_KEY_generate_key(pkey);
        res = i2o_ECPublicKey(pkey, &pend);
        fprintf(stderr, "Pubkey (hex): ");
        dumphex((unsigned char *)pbuf, res);
        fprintf(stderr, "Privkey (hex): ");
        dumpbn(EC_KEY_get0_private_key(pkey));
        vg_encode_address(EC_KEY_get0_public_key(pkey),
                  EC_KEY_get0_group(pkey),
                  addrtype, ecprot);
        printf("Address: %s\n", ecprot);
        vg_encode_privkey(pkey, privtype, ecprot);
        printf("Privkey: %s\n", ecprot);
        return 0;
    }

/* .... */

What's the purpose of modifying keyconv?

I would like to slightly change the "randomness factor", by being able to avoid the first few trillions at the beginning and at the end of the "huge number" range. To avoid some standard brute force attack.

I would like to modify keyconv code in order to be able to generate a deterministic bitcoin address.

By deterministic bitcoin address, I mean 2 things :

1 - to be able to generate the PrivateKey/Address pair from an input "huge number" (-d for deterministic)

keyconv -d <huge number>

Example : keyconv -d 115792089237316195423570985008687907852837564279074904382605163141518161494336

would return me the Private Key / Address pair for the input number "11579208923731..."

2- to be able to generate the PrivateKey/Address pair from an input range (percentage of the global range of all possible numbers) (-r for range)

keyconv -r <floor percentage> <ceil percentage>

Example : keyconv -r 20 40

will return me a random Private Key / Address pair taking the range 20% of maximal number to 40% of maximal number

Since I'm not really used to C programming, I am trying few things but can't get it to work. From reading the code, I suspect that I will have to pass my huge number value to the functions vg_encode_address() and vg_encode_privkey() but I first need to know what kind of arguments it deals with.

The problem is that we deal with huge numbers, and that the default types included in C do not handle this type of numbers. So we have to create specific types.

First question:

I'm trying to start with getting the "content value" that the pointer pkey is pointing to. I tried to print it via :

printf("pkey value : %s\n", *pkey);

but it returned me the following error :

cc -ggdb -O3 -Wall   -c -o keyconv.o keyconv.c
keyconv.c: In function ‘main’:
keyconv.c:100:30: error: dereferencing pointer to incomplete type ‘EC_KEY {aka struct ec_key_st}’
  printf("pkey value : %s\n", *pkey);
                              ^
<builtin>: recipe for target 'keyconv.o' failed
make: *** [keyconv.o] Error 1

So I understand that I need to specify a type 'EC_KEY' in the print function, but how do I do that?

Second question:

Has anyone already tried to code what I'm trying to do?




Why is Random.NextBytes() "surprisingly slow"?

From Fastest way to generate a random boolean, in the comment, CodesInChaos said:

MS messed up the implementation of NextBytes, so it's surprisingly slow.

[...] the performance is about as bad as calling Next for each byte, instead of taking advantage of all 31 bits. But since System.Random has bad design and implementation at pretty much every level, this is one of my smaller gripes.

Why did he said MS has made a design and implementation at pretty much every level?

How is the Random class wrongly implemented?




jQuery random image

I have an index.html page in which I want to show 1 random image from a folder.

I have found a script that I like because I dont have to write each image url. But I'm not shure what the "10 + 1" means (max 10 images in the folder?)

The thing is, I just don't know what to do with this script!

In the "head", I think I need to link to a jquery librairy. Should the script be in a ".js" file? Or can it be simply put in the "body" of the page? (or elsewhere?)

Thanks for helping!

The HTML would be:

img src="" class="myClass1" width="100px" height="auto" alt="no image" />

And the script:

$('.myClass1').each(function() {

var num = Math.floor(Math.random() * 10 + 1), img = $(this);

img.attr('src', 'http://ift.tt/2qp5sTh' + num + '.jpg'); img.attr('alt', 'Src: ' + img.attr('src'));

});




remove part of line

I have a Text File formated like this. And i am using UNIX

for example:

192.168.178.65|connected 2/5/2017 192.168.178.93|connected 3/5/2017 ...

so basically it's always like this (random ip)|connected (random date) (random ip)|connected (random date) ...

How can i remove everything behind |connected so at the end it will looks like this

for example: 192.168.178.65 192.168.178.93

So that I only have the IP
(random ip) (random ip)

Thank you for your help




Unique integer pairs in Java [duplicate]

This question already has an answer here:

I want to create a list of 10 unique integer pairs and I'm struggling to come up with a way to do it. For example,

1,2
8,3
.
.
.
7,0

I have a 10x10 2d array and I'm using Random to create random integers like so.

Random randGen = new Random();
int X = randGen.nextInt(10);
int Y = randGen.nextInt(10);

And then marking the 10x10 locations using the random pairs as my x and y coordinates.

The problem is I don't always come up with unique pairs of X and Y. Below you can see that 3,9 shows up twice in count 6 and count 8.

X and Y: 8,8 count = 0
X and Y: 7,9 count = 1
X and Y: 8,0 count = 2
X and Y: 8,1 count = 3
X and Y: 8,7 count = 4
X and Y: 2,0 count = 5
X and Y: 3,9 count = 6
X and Y: 0,9 count = 7
X and Y: 3,9 count = 8
X and Y: 0,1 count = 9

   0  1  2  3  4  5  6  7  8  9 
0 [ ][X][ ][ ][ ][ ][ ][ ][ ][X]
1 [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
2 [X][ ][ ][ ][ ][ ][ ][ ][ ][ ]
3 [ ][ ][ ][ ][ ][ ][ ][ ][ ][X]
4 [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
5 [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
6 [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
7 [ ][ ][ ][ ][ ][ ][ ][ ][ ][X]
8 [X][X][ ][ ][ ][ ][ ][X][X][ ]
9 [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]

How should I go about ensuring unique int pairs. Thank you.




Evaluation Needed Regarding Attack and Cryptographic Analysis of a Cipher I Developed

I am working on addition in case of Fully Homomorphic algorithms ( In short its when you send data to a cloud server in encrypted from and cloud server performs math operations on Encrypted data which is decrypted on the sender side )..no worries if you don't know about it..just tag along ..you may still help.

The scenario is that I want to send a number 'n' to a cloud server. I don't want the cloud server to exactly know what number I am sending, so I sandwich this number 'n' between a sequence of random numbers at some random position that only I know.

Let me explain this with an example.

Random numbers are generated using the secrets module in Python which claims to provide cryptographically-secure pseudo-random number generation.

I want to send number '2' to a cloud server. Now I select a random position X, say 13 (which only I know) and sandwich 2 between random numbers at position X.

Encrypted Number :: 1932847190032394758930192938764573929837....and so on

                 _Random nos____'2 at 13th position' ______Random nos_____

Encrypted Number is 2048 characters long.

My Question : Will the cloud on reading the Encrypted Number be able to tell with a good amount of certainty that it was number 2 that I had sandwiched and encrypted? Is it a secure way of sending numbers? (Decryption is done at my side by just grabbing the result from the X th position. Also assume attacker can intercept messages in the network and tries his best to find the encrypted number.)




Random Did not work for me

I have tried all ways to print a Random number ,used all ways by other question on stackoverflow too but It does not work+it has an error-:

Unable to connect to the editor to retrieve text.

and other times it shows

Can't setText on null values

used Codes such as 1)

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
tv.setText(i1);

2)

final int random = Random.nextInt(61) + 20;
final int min = 20;
final int max = 80;
final int random = Random.nextInt((max - min) + 1) + min;

3)

tv.setText("Random Number: " + Math.random());
//Though I wanted the random in a specific range ,this too did not work




In R, how to find the index of the value sampled?

In R, I would like to know how I can find the index/indices of the value(s) sampled, for examaple using function sample.

In Matlab, it appears this is quite easily done by requesting output argument idx in function datasample. Explictly, taken from Matlab's documentation page for function datasample:

[y,idx] = datasample(data,k,...) returns an index vector indicating which values datasample sampled from data.

I would like to know if such a thing can be accomplished in R, and how.




samedi 27 mai 2017

Monte Carlo integration of the Gaussian function f(x) = exp(-x^2/2) in C incorrect output

I'm writing a short program to approximate the definite integral of the gaussian function f(x) = exp(-x^2/2), and my codes are as follows:

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

double gaussian(double x) {
    return exp((-pow(x,2))/2);
}

int main(void) {
    srand(0);
    double valIntegral, yReal = 0, xRand, yRand, yBound;
    int xMin, xMax, numTrials, countY = 0;

    do {
        printf("Please enter the number of trials (n): ");
        scanf("%d", &numTrials);
        if (numTrials < 1) {
            printf("Exiting.\n");
            return 0;
        }  
        printf("Enter the interval of integration (a b): ");
        scanf("%d %d", &xMin, &xMax);      
        while (xMin > xMax) { //keeps looping until a valid interval is entered
            printf("Invalid interval!\n");
            printf("Enter the interval of integration (a b): ");
            scanf("%d %d", &xMin, &xMax);
        }
        //check real y upper bound
        if (gaussian((double)xMax) > gaussian((double)xMin))
            yBound = gaussian((double)xMax);
        else 
            yBound = gaussian((double)xMin);
        for (int i = 0; i < numTrials; i++) {
            xRand = (rand()% ((xMax-xMin)*1000 + 1))/1000.00 + xMin; //generate random x value between xMin and xMax to 3 decimal places             
            yRand = (rand()% (int)(yBound*1000 + 1))/1000.00; //generate random y value between 0 and yBound to 3 decimal places
            yReal = gaussian(xRand);
            if (yRand < yReal) 
                countY++;
        }
        valIntegral = (xMax-xMin)*((double)countY/numTrials);
        printf("Integral of exp(-x^2/2) on [%.3lf, %.3lf] with n = %d trials is: %.3lf\n\n", (double)xMin, (double)xMax, numTrials, valIntegral);

        countY = 0; //reset countY to 0 for the next run
    } while (numTrials >= 1);

    return 0;
}

However, the outputs from my code doesn't match the solutions. I tried to debug and print out all xRand, yRand and yReal values for 100 trials (and checked yReal value with particular xRand values with Matlab, in case I had any typos), and those values didn't seem to be out of range in any way... I don't know where my mistake is.

The correct output for # of trials = 100 on [0, 1] is 0.810, and mine is 0.880; correct output for # of trials = 50 on [-1, 0] is 0.900, and mine was 0.940. Can anyone find where I did wrong? Thanks a lot.

Another question is, I can't find a reference to the use of following code:

double randomNumber = rand() / (double) RAND MAX;

but it was provided by the instructor and he said it would generate a random number from 0 to 1. Why did he use '/' instead of '%' after "rand()"?




Is there anyway to generate character space(32) to ~(126) using sodium.h ? Or other way to generate secure string?

I am creating a C program to generate passwords.

rand() in C keep generating some same set of strings even using srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL)) found in here but better than using srand(time(NULL))

I found this answer, and I finally know how to link libsodium to my project.

After that, I realise I only can set the upper bound for randombytes_uniform(), the lower bound is always 0.

And using randombytes_random() give me all kind of characters that cannot use in password.

Can anyone know how to generate character space(32) to character ~(126) using sodium or any secure way to generate character?

Here is the original code:

#include <stdio.h>
#include <stdlib.h>
#include "sodium.h"
#pragma warning (disable:4996)

void main(int argc, char **argv){

    /* Length of the password */
    int length, num, temp, number;
    num = 10;
    length = 10;
    number = num;

    clear_screen();

    /* Seed number for rand() */
    srand((unsigned int)**generate_standard_password + (unsigned int)&argc + (unsigned int)time(0));

    while (num--)
    {
        temp = length;
        printf("\n\t%2d. ", (number - num));
        while (temp--) {
            putchar(rand() % 56 + 65);
            srand(rand());
        }
        temp = length;
    }
    printf("\n\n\t");
    system_pause();
}

Thanks in advance.




Filling empty cells of a matrix with random values in java

i am trying to make a matrix in java that is going to be filled with random values only in that positions that are empty. i am trying these code but it doesn't work. I made two nested for one for the rows and one for the col. And for every position I ask if it's 0 (I'm not sure how to make a control on that) and if it's not generate a random coordinate and print it in the format (i,j). But it is always printing 0.

   public int[][] getRandomPosition(int matrixlength) {
 int[][] grid = new int[matrixlength][matrixlength];

for (int i = 0; i < grid.length; i++) {
     for (int j = 0; j < grid[i].length; j++) {
        if (grid[i][j] == 0) {
        grid[i][j] = (int) Math.random();
        System.out.print(grid[i][j]);
       return grid;
        }
     }
   }
return null;
}

Thanks in advance for everybody help.




How to generate a random DARK hex color code with PHP?

Please note that I have already read Generating a random hex color code with PHP and I got help from that question too. But my question is different to that question.

I am going to create 1000+ images with some text like below image.

enter image description here

Text color is always white. I need to generate background color randomly. I use following code to generate random color.

<?php

function random_color_part() {
    return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}

function random_color() {
    return random_color_part() . random_color_part() . random_color_part();
}

echo random_color();

?>

This script generate light colors like white, light yellow, light blue too. I need to remove them. Because if the background color is also light colour it is hard to read the text.

So is there way to modify this code generate only dark colors?




SQLite: How to achive RANDOM ORDER and pageintation at the same time?

I have a table of movies, I want to be able to query the database and get a randomized list of movies, but also I don't want it to return all movies available so I'm using LIMIT and OFFSET. The problem is when I'm doing something like this:

SELECT *  FROM Movie ORDER BY RANDOM() LIMIT 50 OFFSET 0

and then when querying for the next page with LIMIT 50 OFFSET 50 the RANDOM seed changes and so it's possible for rows from the first page to be included in the second page, which is not the desired behavior.

How can I achieve a random order and preserve it through the pages? As far as I know SQLite doesn't support custom seed for it's RANDOM function.

Thank you!




Random number generator that returns only one number each time in python

Does exist random number generator in python that returns only one random number each time when next() function is called? Numbers should not repeat.

I need to generate more than million different numbers what sounds very memory consuming in case all the number are generated at same time and stored in a list. Numbers have to be unique - does not repeat.




vendredi 26 mai 2017

How do I write a code for random intervals between a range using numbers in double format?

I am trying to write a program that uses thread.sleep() which only allows integers. My question is how do I create a program that will grab a random number between the range of 2.5-3.5 seconds (or any random range using double) while using all numbers between that range. I am trying to use this to create a randomized auto-clicker for use of understanding of converting these data types. Any help would be appreciated. Thanks!

This is all I have (apologies if this isn't even close I was using all info I could find to help.)

    Robot bot = new Robot();

    int rangeMin=2.5, rangeMax=3.5, pressMax = 0, pressMin = 0;

    int randomvalue1 = (r.nextInt() * ((pressMax - pressMin) + 1)) + pressMin;
    int randomValue2 = (r.nextInt() * ((rangeMax - rangeMin) + 1)) + rangeMax;

    for (int x=0; x<3;x++);
        Thread.sleep(randomvalue1);
        bot.mousePress(InputEvent.BUTTON1_MASK);
        Thread.sleep(randomvalue2);
        bot.mouseRelease(InputEvent.BUTTON1_MASK);
    }




Randomizing Questions In Online Exam System

Good day, i am a php programmer i got a contract of developing an online exam management system. I am having a problem of generating random questions for each student so that no two student will have then same questions. I used the MySql RAND() function but it is not giving the desired result. It shows a random question when a student clicks on the NEXT button and another random question when the student clicks on the PREVIOUS button thereby causing a flaw in the system. I will be grateful if someone helps me through this hard times.

The MySql implementation i used

$FetchQuestion=executeQuery("select * from question where testid=".$_SESSION['testid']." and qnid>=RAND()*(SELECT MAX(qnid)FROM question);");




Create Random number in java

I need to program a code that gives the user an equation if the user solves it a promo code will be given.

1, I need to make the random number from 1 to 9 only.

2, No "random" number displayed in JOptionpane:(!

3, I also need the promo code to be a random number too that contains more than one digits (4 digits are good).

Thanks in advance!

    private void promoCodeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
    Random num1 = new Random();
    Random num2 = new Random();
    Random num3 = new Random();

    //convert Random to String so I use it with JOptionPane
    String n1=num1.toString();
    String n2=num2.toString();
    String n3=num3.toString();

    String equation = "What's the result of "+n1+"+"+n2+"*"+n3+"=?";
    String given = JOptionPane.showInputDialog(null, equation,connection);

    //convert String to int so I can apply equation:
    int numb1 = Integer.parseInt(n1);
    int numb2 = Integer.parseInt(n2);
    int numb3 = Integer.parseInt(n3);
    int result = numb1+numb2*numb3;
    int result1 =Integer.parseInt(given);

    //Random number promo code
    Random promo_code = new Random();

    if(given.equals(result1)){
    JOptionPane.showMessageDialog(rootPane, "Correct Answer! \nHere's your promo code is:"+promo_code+"\nEnjoy! ");
    }

    else{
    JOptionPane.showMessageDialog(rootPane, "Wrong Answer! \nTry again");

    }
}                                             




How to? Rails arrange posts randomly with previous/next view depending on tag_id

So I want to have a link on my rails app which links to a view that shows a random question of a certain tag_id

The use case is a quiz app for my class, and we have N number of tags, with N questions. Each question can have multiple tags.

I want to have a way to be able to randomly display (read: no person should have the same order of questions), but still be able to do all the questions that have a certain tag_id by clicking previous/next in a view.

I figured out how to display all the questions of a certain tag in a view, but I'm still having trouble how to show previous/next randomly for a certain tag. Ex: When a user clicks on a link, it should randomly generate or list all the questions for the tag_id and only be accessible in that view for that tag_id. Everyone will do the same questions, just not in the same order.

I realize there are gems out there, but I want to learn and understand how it's done from scratch first.

questions/show.html.erb

<strong>tags</strong><br>
<%= @question.tags.map{|t| t.name}.join(", ") %>

<%= link_to "Previous Question", @question.previous %>
<%= link_to "Next Question", @question.next %>

Here's my questions_controller.rb

class QuestionsController < ApplicationController

    def new
        @question = Question.new
    end

def index
    if params[:tag_id].present?
        tag = Tag.find(params[:tag_id])
        @questions = tag.questions
    else
        @questions = Question.all
    end
end

    def show
        @question = Question.find(params[:id])  

    end    etc etc ... [rest of code here is redacted as its not relevant]
end

Here's my question.rb model

class Question < ActiveRecord::Base

  has_many :taggings
  has_many :tags, through: :taggings

    #links this to the user.rb model?
    belongs_to :user

    scope :next, lambda {|id| where("id > ?",id).order("id ASC") } # this is the default ordering for AR
    scope :previous, lambda {|id| where("id < ?",id).order("id DESC") }

    def next
      Question.next(self.id).first
    end

    def previous
      Question.previous(self.id).first
    end
end

tag.rb

class Tag < ActiveRecord::Base
    has_many :taggings
    has_many :questions, through: :taggings # notice the use of the plural model name
end

tagging.rb

class Tagging < ActiveRecord::Base
  belongs_to :question  # foreign key - post_id
  belongs_to :tag   # foreign key - tag_id
end




Generating random numbers from a distribution specified in R

I'm trying to generate random values from a given distribution given by the following function in R with the inverse cdf method found here described after the function

sigma=function(x){

  rc=0.5

  y=(x/rc) ; 

  C=(1/rc) ;

  Fun = log(1+C)-( C/(1+C) ) ; 

##### terms  

  a = 1/( y^2 - 1) ; b = 2/( sqrt(y^2 + 1 ) ) ;  c = atan( sqrt((y - 1)/y+1) ) ; 

  ff = a*(1 - b*c) ; 

##### My function   

  cst=2*pi

  sigma1 = (ff)/(cst*(rc^2)*Fun) ## function to generate random values

  # return(sigma1)

}

######## inverse CDF method from "found here" link

den<-sigma

#calculates the cdf by numerical integration
cdf<-function(x) integrate(den,-Inf,x)[[1]]

#inverts the cdf
inverse.cdf<-function(x,cdf,starting.value=0){
 lower.found<-FALSE
 lower<-starting.value
 while(!lower.found){
  if(cdf(lower)>=(x-.000001))
   lower<-lower-(lower-starting.value)^2-1
  else
   lower.found<-TRUE
 }
 upper.found<-FALSE
 upper<-starting.value
 while(!upper.found){
  if(cdf(upper)<=(x+.000001))
   upper<-upper+(upper-starting.value)^2+1
  else
   upper.found<-TRUE
 }
 uniroot(function(y) cdf(y)-x,c(lower,upper))$root
}

#generates 1000 random variables of distribution 'den'
vars<-apply(matrix(runif(1000)),1,function(x) inverse.cdf(x,cdf))
hist(vars)

And then the following error appears :

Error in integrate(den, -Inf, x) : the integral is probably divergent
Called from: integrate(den, -Inf, x)

Unfortunally I can't understand where is the problem in my function. However I tried another approach as follow: (which can be found here)

library(distr)
p <- sigma  # probability density function
dist <-AbscontDistribution(d=p)  # signature for a dist with pdf ~ p
rdist <- r(dist)                 # function to create random variates from p

set.seed(1)                      # for reproduceable example
X <- rdist(1000)                 # sample from X ~ p
x <- seq(-10,10, .01)
hist(X, freq=F, breaks=50, xlim=c(-5,5))
lines(x,p(x),lty=2, col="red")

And when I run the line dist <-AbscontDistribution(d=p), the following error is shown:

Error in seq.default(from = low1, to = upp1, length = ngrid) : 
  'from' cannot be NA, NaN or infinite
Além disso: Warning message:
In sqrt((y - 1)/y + 1) : NaNs produzidos

I'd like to know if someone can help me with this problem pointing me to some possible method that really works ?

I apologize for any error in my question.

If I was not very clear in my doubt, what I'm trying to do is something similar to what was done in this link, but with my function.

Again, thanks in advanced




discreet distribution of a specified range of random numbers

I know I can use std::discreet_distribution like this:

  std::default_random_engine generator;
  std::discrete_distribution<int> distribution {2,2,1,1,2,2,1,1,2,2};

  int p[10]={};

  for (int i=0; i<100; ++i) {
    int number = distribution(generator);
    ++p[number];
  }

However, this is going to generate the numbers in the range of 0-9 as per the weight specified.

What can I do to generate the numbers within a user specified range, say for example, 24-33 or 95-104 etc but still using the distribution specified in discrete_distribution ?

Appreciate any advice!




Getting the minimum and maximum values in a randomly generated array in java

import java.util.Random;


    public class Java 
    {
        public static void main(String args[])
        {

        int arr[] =  new int[10];
        Random Rand = new Random();


        int max=0;
        int min=arr[0];


        for(int i=0; i<10; i++)
        {
            int RandNum = Rand.nextInt(10);
            arr[i] = RandNum;


            if(i==0) { System.out.print("["); } 

            System.out.print(arr[i] + " "); 

            if(i==9) { System.out.println("]"); }


            if(RandNum>max)
            {
                max = RandNum;
            }


            if(i>0)
            {
                if(RandNum<arr[0])
                {
                    min = RandNum;
                }
            }

        }

        System.out.println("Minimum number: " + min);
        System.out.println("Maximum number: " + max);   

        } 
    }

I could get the maximum value, but not the minimum.. please bear with me, I'm a beginner, I've tried comparing the min value with the first array value, but I'm not sure if the min value should be array[0] or just 0.




C# cannot generate a random string [duplicate]

I cannot work out why C# is doing this.

Here's my code;

private string RandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        string randomString = "";

        for(int i = 0; i < length; i++)
        {
            randomString += chars.ToCharArray()[new Random().Next(chars.ToCharArray().Length)];
        }

        return randomString;
    }

First result: "wwwwwwwwwwwwwwwwwwww"

Second result: "ssssssssssssssssssss"

Third result: "mmmmmmmmmmmmmmmmmmmm"




How to take randomly generated letter and make it to do something? C#

I want to have a program that prints out 7 random activities to do for the week, i know how to generate random numbers but I don't know how to make a certain number that's generated print out a certain activity. let's say if the random generated number is 1 it will print out golfing etc. If you could provide an example code that would be great, i'm new to c#. Thank you




How to colliderect() with an item of a list in Pygame?

i stumbled into a little problem:

*When pressing "SPACE Bar" Red Squares keep Spawning randomly on Display

Question How can i colliderect() with Red Squares ? is it possible?

The Code might give you an idea of what I'm talking about...

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

"List the Stores the Squares"
red_square_list = []

gameDisplay_width = 800
gameDisplay_height = 600

pygame.init()
gameDisplay = pygame.display.set_mode((gameDisplay_width, gameDisplay_height))
pygame.display.set_caption("Square-it")
clock = pygame.time.Clock()
red_color = pygame.Color("red")

"White Square"
white_x = 400
white_y = 300
white_width = 10
white_height = 10
white_color = pygame.Color("white")
white = pygame.Rect(white_x, white_y, white_width, white_height)

"Red Squares"
def create_red_square(x, y):
    red_width = 10
    red_height = 10
    red = pygame.Rect(x, y, red_width, red_height)
    return red

while True:

    clock.tick(60)
    gameDisplay.fill((0, 20, 5))
    gameDisplay.fill(white_color, white)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           sys.exit()

    for each in red_square_list:
        gameDisplay.fill(red_color, each)

    pygame.display.update()

    '''White Square Movement'''
    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        white.left = white.left - 4

    if keys[K_RIGHT]:
        white.right = white.right + 4

    if keys[K_UP]:
        white.top = white.top - 4

    if keys[K_DOWN]:
        white.bottom = white.bottom + 4

    "when Space key Pressed, Spawns red Squares"
    if keys[K_SPACE]:
        x = randint(0, gameDisplay_width)
        y = randint(0, gameDisplay_height)
        red_square_list.append(create_red_square(x, y))




Making 6 different random Numbers

I'm not that good at coding right now, i am trying to improve and learn. ATM i was trying to write a code that randomly picks 6 non-repeating numbers, but i fail at it. what should i do?

import random

a = random.randint(1, 100)
b = random.randint(1, 100)
c = random.randint(1, 100)
x = random.randint(1, 100)
y = random.randint(1, 100)
z = random.randint(1, 100)

outa = b, c, x, y, z
outb = a, c, x, y, z
outc = a, b, x, y, z
outx = a, b, c, y, z
outy = a, b, c, x, z
outz = a, b, c, x, y

all = a, b, c, x, y, z

while a in outa or b in outb or c in outc or x in outx or y in outy or z in outz:
    if a in outa:
        a = random.randint(1,100)
    elif b in outb:
        b = random.randint(1,100)
    elif c in outc:
        c = random.randint(1,100)
    elif x in outx:
        x = random.randint(1,100)
    elif y in outy:
        y = random.randint(1,100)
    elif z in outz:
        z = random.randint(1,100)

print(all)




Random pairs of all values in a pandas dataframe

import pandas as pd

df = pd.DataFrame({ 'lat' : range(0,8),
                    'name' : ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b']})
df

Output is:

    lat name
0   0   a
1   1   a
2   2   a
3   3   a
4   4   b
5   5   b
6   6   b
7   7   b

Now, what I would like to do is within each name type, create random pairings and add them together. However, all rows need to be a part of a random pairing.

So the ideal output would look something like:

  name  pairing sum
0   a   0,3      3
1   a   2,1      3
2   b   6,4      10
3   b   7,5      12

However, it's important that no a's are paired with b's, and that all values are in exactly one pair.

How can I accomplish this?




Getting specific random number

i want to generate random number between (1 to 6),is there any way to change the chance of geting number 6 more than other numbers?

for example for this code

    private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
    {
        Random u = new Random();
        m = u.Next(1,6);
        label2.Text = m.ToString();
    }




Remove element from ArrayList when used

I've got an ArrayList of Strings I need to use to set the text of a Label. So far I've tried many solutions but none seems to work.

I'd like to take a string randomly from the ArrayList to set my Label text and then remove this string from the ArrayList, so if I press a button that is located in the same panel, it will present a new string in the label but it never shows a string already shown.

This is what I've done so far.

I tried with remove method from List class, but it seems not to work.

package milionarioesame;

import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import javax.swing.JLabel;

/**
  * Descrive l'etichetta su cui verrà visualizzata la domanda.
 */
public class Question extends JLabel
{
Font cms = new Font("Comic Sans MS", 0, 30);

String d1 = new String("Alessandro Manzoni, noto");
String d2 = new String("Quale di queste città NON fa provincia nel Lazio?");
String d3 = new String("Se si moltiplicano fra di loro tutte le cifre che si trovano sul telefono fisso, si ottiene");
String d4 = new String("Quale di questi animali vive in acque marine?");
String d5 = new String("Cosa significa edulcorare?");
String d6 = new String("Quanti sono i cuccioli di dalmata rapiti in un famoso film Disney?");
String d7 = new String("Quale tra questi noti best-seller di Stephen King è ambientato in una prigione?");
String d8 = new String("Quale di questi pianeti è più vicino al Sole?");
String d9 = new String("Quale tra questi NON è il nome di una moneta?");
String d10 = new String("Quanti sono i magi che si recano a visitare Gesù bambino?");
String d11 = new String("Chi era la bella indiana dai capelli neri dell'omonimo film Disney?");
String d12 = new String("Se sentite tubare, affianco a voi avete");
String d13 = new String("Come si chiama il neonato reale d'Inghilterra?");
String d14 = new String("In quale Land della Germania si trova la città di Monaco?");
String d15 = new String("Tra queste squadre di calcio quale è l'unica ad avere sul suo stemma l'anno di fondazione? ");
String d16 = new String("Quale di questi musicisti NON ha mai fatto parte dei Queen?");
String d17 = new String("Com'è intitolato il settimo libro della celebre saga del mago Harry Potter?");
String d18 = new String("Qual è l'ultima nazione vincitrice del campionato del mondo di calcio?");
String d19 = new String("Sulla tavola degli elementi, \"Au\" indica"); // sequenza di escape
String d20 = new String("Se ammiro il mare da Piazza dell'Unità d'Italia, mi trovo a");

String[] aDomande1 = {d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20};

ArrayList<String> domande1 = new ArrayList(Arrays.asList(aDomande1));

String dom = new String();
int idx = 0;

public Question()
{
    setFont(cms);
    setForeground(Color.WHITE);
    setHorizontalAlignment(JLabel.CENTER);
    setText(setDomanda());
}

public String setDomanda()
{
    Random rand = new Random();
    idx = rand.nextInt(domande1.size());
    dom = domande1.get(idx);
    return dom;
}

}




jeudi 25 mai 2017

Model weights not changing Keras

I am trying to create neural nets with random weights in keras. I am using set_weights() function of models, to assign random weights. However, model.predict() gives the same output on a certain input regardless of weights. The output differs every time I run the program, but it's same while a program is running. Here is the code:

ConnectFourAI.py:

from keras.models import Sequential
from keras.layers import Dense
from minimax2 import ConnectFour
import numpy as np
from time import sleep
import itertools
import random
import time

def get_model():

    model = Sequential()
    model.add(Dense(630, input_dim=84, kernel_initializer='uniform', activation='relu'))
    model.add(Dense(630,kernel_initializer='normal', activation='relu'))
    model.add(Dense(7, kernel_initializer='normal', activation='relu'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

map = {
    'x':[1,0],
    ' ':[0,0],
    'o':[0,1]
}

model = get_model()

def get_AI_move(grid):
    global model
    inp = np.array(list(itertools.chain.from_iterable([map[t] for t in np.array(grid).reshape(42)]))).reshape(1,84)
    nnout = model.predict(inp)
    # print(list(nnout[0]))
    out = np.argmax(nnout)
    while grid[0][out] != " ":
        out = np.random.randint(7)
    print("out = %d"%out)
    return out

shapes = [(w.shape) for w in model.get_weights()]

print(list(model.get_weights()[0][0][0:5]))
def score_func(x, win):
        if win == "x":
            return 10000
        elif win == " ":
            return 2000
        else:
            return x**2




if __name__=="__main__":

    for i in range(100):
        weights = [np.random.randn(*s) for s in shapes]
        # print(list(weights[0][0][0:5]))
        model.set_weights(weights)
        print(list(model.get_weights()[0][0][0:5]))
        game = ConnectFour()
        game.start_new()
        rounds = game._round
        win = game._winner
        score = score_func(rounds, win)
        print("%dth game scored %.3f"%(i+1,score))

        seed = int(time.time()* 10**6)%(2**32)+1
        np.random.seed(seed)

To recreate this error, you need an extra file. Everything is OK in this file, but the only call to random always gives the same value. Here is the file.




sample each two columns together in a data frame in R

I have a very large data frame that contains 100 rows and 400000 columns.

To sample each column, I can simply do:

df <- apply(df, 2, sample)

But I want every two column to be sampled together. For example, if originally col1 is c(1,2,3,4,5) and col2 is also c(6,7,8,9,10), and after resampling, col1 becomes c(1,3,2,4,5), I want col2 to be c(6,8,7,9,10) that follows the resampling pattern of col1. Same thing for col3 & col4, col5 & col6, etc.

I wrote a for loop to do this, which takes forever. Is there a better way? Thanks!




How to Interact with an item of a List in Pygame?

i Started creating a game and i stumbled into a little problem:

*When pressing "SPACE Bar" Red Squares keep Spawning randomly on Display

Question How can i make the Red Squares into obstacles?

im a total begginer and im sorry for asking such a simple question.. :/

The Code might give you an idea:

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

"List the Stores the Squares"
red_square_list = []

gameDisplay_width = 800
gameDisplay_height = 600

pygame.init()
gameDisplay = pygame.display.set_mode((gameDisplay_width, gameDisplay_height))
pygame.display.set_caption("Square-it")
clock = pygame.time.Clock()
red_color = pygame.Color("red")

"White Square"
white_x = 400
white_y = 300
white_width = 10
white_height = 10
white_color = pygame.Color("white")
white = pygame.Rect(white_x, white_y, white_width, white_height)

"Red Squares"
def create_red_square(x, y):
    red_width = 10
    red_height = 10
    red = pygame.Rect(x, y, red_width, red_height)
    return red

while True:

    clock.tick(60)
    gameDisplay.fill((0, 20, 5))
    gameDisplay.fill(white_color, white)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           sys.exit()

    for each in red_square_list:
        gameDisplay.fill(red_color, each)

    pygame.display.update()

    '''White Square Movement'''
    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        white.left = white.left - 4

    if keys[K_RIGHT]:
        white.right = white.right + 4

    if keys[K_UP]:
        white.top = white.top - 4

    if keys[K_DOWN]:
        white.bottom = white.bottom + 4

    "when Space key Pressed, Spawns red Squares"
    if keys[K_SPACE]:
        x = randint(0, gameDisplay_width)
        y = randint(0, gameDisplay_height)
        red_square_list.append(create_red_square(x, y))




for loop never ends with a matrix

for sublistas in matriz:
for espacios in matriz:
    ran = random.choice([p_vivo, p_muerto])
    matriz.append(ran)

I am trying to with a matrix with 2 random choices: p_muerto or p_vivo The problem is, the loop never ends. I think it is because it keeps overwriting the elements of the matrix, so it keeps going indefinitely.

What can I do?




How to interact with a Generated item of a list in Pygame?

i Started creating a game and i stumbled into a little problem:

*When pressing "SPACE Bar" Red Squares keep Spawning randomly on Display

Question How can i make the Red Squares into obstacles?

Here is The Code:

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

"List the Stores the Squares"
red_square_list = []

gameDisplay_width = 800
gameDisplay_height = 600

pygame.init()
gameDisplay = pygame.display.set_mode((gameDisplay_width, gameDisplay_height))
pygame.display.set_caption("Square-it")
clock = pygame.time.Clock()
red_color = pygame.Color("red")

"White Square"
white_x = 400
white_y = 300
white_width = 10
white_height = 10
white_color = pygame.Color("white")
white = pygame.Rect(white_x, white_y, white_width, white_height)

"Red Squares"
def create_red_square(x, y):
    red_width = 10
    red_height = 10
    red = pygame.Rect(x, y, red_width, red_height)
    return red

while True:

    clock.tick(60)
    gameDisplay.fill((0, 20, 5))
    gameDisplay.fill(white_color, white)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           sys.exit()

    for each in red_square_list:
        gameDisplay.fill(red_color, each)

    pygame.display.update()

    '''White Square Movement'''
    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        white.left = white.left - 4

    if keys[K_RIGHT]:
        white.right = white.right + 4

    if keys[K_UP]:
        white.top = white.top - 4

    if keys[K_DOWN]:
        white.bottom = white.bottom + 4

    "when Space key Pressed, Spawns red Squares"
    if keys[K_SPACE]:
        x = randint(0, gameDisplay_width)
        y = randint(0, gameDisplay_height)
        red_square_list.append(create_red_square(x, y))




Generating a number or string that has not been generated before in python

I am creating a black jack inspired game and i generate the deck and hand using the following code:

suits = 'SCHD'
values = '23456789TJQKA'

deck = tuple(''.join(card) for card in itertools.product(values, suits))

dealershand = random.sample(deck, 1)
yourhand    = random.sample(deck, 2)

The problem with this is that there is a small chance that the same card is pulled in the 'dealershand' and 'yourhand' I would like to check if the card already exists, and if it does, to generate another card. Something like this:

while yourhand is in dealershand:
    yourhand=random.sample(deck,2)

any ideas guys???




Override Variables?

This is my first java project so I am still learning a large amount of stuff and how to apply it.

I am making a random load out creator for Titanfall 2 that uses

 double b = (int)(Math.random() * 6 + 1);

to randomly generate a number for which ever variable i use for each set of things I randomize. Based on what the number is, a different text will be displayed, one number for each possible selection in game. My problem is that since you can have two mods for each gun both gun mod blocks in the code are the same but if by chance both random numbers for the mods are the same it displays the same mod, which you cannot do in game. I would like to make it so if b==a then it re-randomizes b, but I cannot figure out how to do this. The entire code will be at the bottom and a picturing showing what i want to avoid, the issue occurs with Gun mod 1 and Gun mod 2, bluej syas that variable b is already defined when I tried to put it the second in the if (b==a)

        //Tacticals
        double t = (int)(Math.random() * 7 + 1);
       if (t == 1) {
           System.out.println("Tactical: Cloak");
        }
       if (t == 2) {
           System.out.println("Tactical: Pulse Blade");
        }
        if (t == 3) {
           System.out.println("Tactical: Grappling Hook");
       }
       if (t == 4) {
           System.out.println("Tactical: Stim");
        }
       if (t == 5) {
           System.out.println("Tactical: A-Wall");
        }
       if (t == 6) {
           System.out.println("Tactical: Phase Shift");
        }
       if (t == 7) {
           System.out.println("Tactical: Holo Pilot");
        }

        //Ordinance
       double o = (int)(Math.random() * 6 + 1);
       if (o == 1) {
           System.out.println("Ordinance: Frag Grenade");
        }
       if (o == 2) {
           System.out.println("Ordinance: Arc Grenade");
        }
       if (o == 3) {
           System.out.println("Ordinance: Fire Star");
        }
       if (o == 4) {
           System.out.println("Ordinance: Gravity Star");
        }
       if (o == 5) {
           System.out.println("Ordinance: Electric Smoke Grenade");
        }
       if (o == 6) {
           System.out.println("Ordinance: Satchel Charge");
        }

        //Primaries
       double p = (int)(Math.random() * 22 + 1);
       if (p == 1) {
            System.out.println("Primary: R201");
        }
       if (p == 2) {
            System.out.println("Primary: R101");
        }
       if (p == 3) {
            System.out.println("Primary: G2");
        }
       if (p == 4) {
            System.out.println("Primary: Hemlock");
        }
       if (p == 5) {
            System.out.println("Primary: Flatline");
        }
       if (p == 6) {
            System.out.println("Primary: Alternator");
        }
       if (p == 7) {
            System.out.println("Primary: CAR");
        }
       if (p == 8) {
            System.out.println("Primary: R-97");
        }
       if (p == 10) {
            System.out.println("Primary: Volt");
        }
       if (p == 11) {
            System.out.println("Primary: L-STAR");
        }
       if (p == 12) {
            System.out.println("Primary: Spitfire");
        }
       if (p == 13) {
            System.out.println("Primary: Devotion");
        }
       if (p == 14) {
            System.out.println("Primary: Double Take");
        }
       if (p == 15) {
            System.out.println("Primary: Kraber");
        }
       if (p == 16) {
            System.out.println("Primary: DMR");
        }
       if (p == 17) {
            System.out.println("Primary: EVA-8");
        }
       if (p == 18) {
            System.out.println("Primary: Mastiff");
        }
       if (p == 19) {
            System.out.println("Primary: Cold War");
        }
       if (p == 20) {
            System.out.println("Primary: EPG");
        }
       if (p == 21) {
            System.out.println("Primary: Softball");
        }
       if (p == 22) {
            System.out.println("Primary: SMR");
        }

        //Primay Gun Mod 1
      double a = (int)(Math.random() * 6 + 1);
      if (a == 1) {
          System.out.println("Gun Mod 1: Extra Ammo");
        }
      if (a == 2) {
          System.out.println("Gun Mod 1: Speed Reload");
      }
      if (a == 3) {
          System.out.println("Gun Mod 1: Gunrunner");
        }
      if (a == 4) {
          System.out.println("Gun Mod 1: Gun Ready");
        }
      if (a == 5) {
          System.out.println("Gun Mod 1: Fast Swap");
        }
      if (a == 6) {
          System.out.println("Gun Mod 1: Tactikill");
        } 

      //Primary Gun Mod 2
      double b = (int)(Math.random() * 6 + 1);
      if (b ==a) {
          double b = (int)(Math.random() * 6 + 1);
        }
      if (b == 1) {
          System.out.println("Gun Mod 2: Extra Ammo");
        }
      if (b== 2) {
          System.out.println("Gun Mod 2: Speed Reload");
      }
      if (b== 3) {
          System.out.println("Gun Mod 2: Gunrunner");
        }
      if (b== 4) {
          System.out.println("Gun Mod 2: Gun Ready");
        }
      if (b== 5) {
          System.out.println("Gun Mod 2: Fast Swap");
        }
      if (b== 6) {
          System.out.println("Gun Mod 1: Tactikill");
        } 

      // Secondary
      double s = (int)(Math.random() * 5 + 1);
      if (s==1) {
          System.out.println("Secondary: RE .45");
        }
      if (s==2) {
          System.out.println("Secondary: Hammond P2016");
        }
      if (s==3) {
          System.out.println("Secondary: Wingman Elite");
        }
      if (s==4) {
          System.out.println("Secondary: Mozambique ");
        }
      if (s==5) {
          System.out.println("Secondary: Wingman B3");
        }

      //Pilot Kit 1
      double c = (int)(Math.random() * 4 +1);
      if (c==1) {
          System.out.println("Pilot Kit 1: Power Cell");
        }
      if (c==2) {
          System.out.println("Pilot Kit 1: Fast Regeneration");
        }
      if (c==3) {
          System.out.println("Pilot Kit 1: Ordinance Expert");
        }
      if (c==4) {
          System.out.println("Pilot Kit 1: Phase Embark");
        }

      // Pilot Kit 2
      double d = (int)(Math.random() * 4 + 1);
      if (d==1) {
          System.out.println("Pilot Kit 2: Wall Hang");
        }
      if (d==2) {
          System.out.println("Pilot Kit 2: Kill Report");
        }
      if (d==3) {
          System.out.println("Pilot Kit 2: Hover");
        }
      if (d==4) {
          System.out.println("Pilot Kit 2: Low Profile");
        }
    }
}

enter image description here