mardi 31 janvier 2017

remove duplicate tuple value based on index in tuple

Is there a way to remove a duplicate tuple based on the index in the tuple. Say I have

[(0, 4, 1.0), (1, 4, 1.0), (3, 4, 1.0), (0, 3, 2.0), (1, 3, 2.0), (0, 2, 3.0), (1, 2, 3.0), (2, 4, 4.0), (2, 3, 5.0), (0, 1, inf)]

Can I randomly keep one tuple where each duplicate has the same value at index 2?

So, there are 3 tuples that have value 1.0 at index 2, two tuples that have value 2.0 at index 2, one that has value 3 at index 2, and so on.

So, (0, 4, 1.0) might randomly be selected from the value 1.0 at index 2 and (1, 3, 2.0) might randomly be selected from the value 2.0 at index 2. Say, (1, 2, 3.0) was randomly selected from the value 3.0 at index 2. Then, my list would look like

[(0, 4, 1.0),(1, 3, 2.0), (1, 2, 3.0), (2, 4, 4.0), (2, 3, 5.0), (0, 1, inf)]

I have never come across a function that does this or at least efficiently.




Generating binary matrix with fixed number of 1's

How can I generate a binary matrix that has the following behavior? I have came across this solution but it lacks the random positioning of the binary values.

## all rows contain four 1's at random column

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




Python - How do I append numbers inside the list and

Whenever I try appending numbers from my input to my list, it goes outside one of the brackets instead of inside the two brackets

Is there a way to only have one pair of brackets instead of two?

Also I am trying to add random numbers between 1-3 and i get,

[[2, 1, 3]]

How can you create random numbers in the tenths decimal place

My Code,

import random
array = []

nums = random.sample(range(1, 4), 3)
array.append(nums)
print(array)

for x in range(2):
    nums = int(input("what are your numbers "))
    array.append(nums)
    print(array)

I get,

[[2, 1, 3]]
what are your numbers 3
[[2, 1, 3], 3]
what are your numbers 2
[[2, 1, 3], 3, 2]

Process finished with exit code 0




Need help using randomly generated numbers in a formula using R

This is my code below and all I get is a list of the same values and it doesn't seem like R is taking a randomly generated value, running through the equation and then giving me the results. montecarlo = function(r,v,t,x,k,n) { y=rnorm(n) stockprice = x*exp((-v*sqrt(t)*y)+((r-(.5*v^2))*t)) MCOP=exp(-r*t)*(stockprice-k) return(MCOP) }

The output for this code is just a single value 100 times if I set n = 100




Trustworthy random number generators?

I am taking a course in computational finance, where random number generators have to be high-quality. The professor said to never use the C/C++ provided random number generators. Is this true? If so, what generators are considered trustworthy for computational finance?




How to generate a unique identifier string of length N in Postgres 9.6+?

I've seen a bunch of different solutions on StackOverflow that span many years and many Postgres versions, but with some of the newer features like gen_random_bytes I want to ask again to see if there is a simpler solution in newer versions.

Given IDs which contain a-zA-Z0-9, and vary in size depending on where they're used, like...

3kivYsqh
xysC5hdn
EX41QxTU
YhttHVH5

...or elsewhere...

uXolWvg49Co5EfCo
LOscuAZu37yV84Sa
YyrbwLTRDb01TmyE
HoQk3a6atGWRMCSA

How can you generate them randomly and safely (as far as reducing collisions goes) with an easy way to specify different lengths for different use cases, in Postgres 9.6+?

I'm thinking that ideally the solution has a signature similar to:

generate(length integer) returns text

Where length is customizable depending on your own tradeoffs for lowering the chance of collisions vs. reducing the string size for usability.

Thanks!


PS. I know there's gen_random_uuid() for UUIDs, but I don't want to use them in this case.




R randomly swap values between two columns in dataframe

Dear stackoverflow community,

I repeated an experiment (rep1 and rep2). For each replicate I have two columns (a, sum) and two rows of the tested subjects that belong together (group AA, BB...). For analysis, I would like to randomly assign the collected data (a and sum) to rep1 and rep2. For this, I was trying to randomly select groups and swap "a" and "sum" of rep1 and rep2. I am trying to repeat the random swapping 100 times, creating 100 datasets for analysis.

I came across unique(df$groups) to specify that the data of each group belongs together. Combined to sample(unique(df$group), 2) it randomly samples, let's say, 2 groups. But I don't know how to swap the data of the replicates of these selected groups. Any help or suggestions are greatly appreciated!!

Here is an example of the data:

group = c("A", "A", "B", "B", "C", "C")
rep1_a = c(2, 8, 5, 5, 4, 6)
rep1_sum = c(10, 10, 10, 10, 10, 10)
rep2_a = c(3, 8, 4, 5, 5, 6)
rep2_sum = c(11, 11, 9, 9, 11, 11)
df = data.frame(group, rep1_a, rep1_sum, rep2_a, rep2_sum)

#    group    rep1_a     rep1_sum     rep2_a   rep2_sum
1     A          2         10          3         11
2     A          8         10          8         11
3     B          5         10          4          9
4     B          5         10          5          9
5     C          4         10          5         11
6     C          6         10          6         11

And here is what it should look like, if out of these 3 groups, the replicates of group A are swapped:

    group     rep1_a    rep1_sum    rep2_a    rep2_sum
1     A          3         11          2         10
2     A          8         11          8         10
3     B          5         10          4          9
4     B          5         10          5          9
5     C          4         10          5         11
6     C          6         10          6         11




How to generate passwords in Python 2 and Python 3? Securely?

Here on Stackoverflow exist at least one post related to this topic: Generate password in python

You can find that this topic found some critics even in PEP. It's mentioned here: http://ift.tt/1V2NRUK

So, how to generate random passwords in Python 2 and Python 3 properly and securely?




varying degree of shuffling using random module python

I am using two architecture programs, with visual programming plugins (Grasshopper for Rhino and Dynamo for Revit - for those that know / are interested)

Grasshopper contains a function called 'Jitter' this will shuffle a list, however it has an input from 0.0 to 1.0 which controls the degree of shuffling - 0.0 results in no shuffling 1.0 produces a complete shuffle.

The second of the programs (Dynamo) does not contain this functionality. It contains a shuffle module (which contains a seed value) however it is a complete random shuffle.

Ultimately the goal is to produce a series of solid and glazed panels, but to produce a slight random effect (but avoiding large clumping of solid and glazed elements - hence I want a "light shuffle")

I have written a code which will calculate the number of glazed(True) and solid(False) values required and then evenly distribute True and False values based on the number of items and percent specified.

I have checked out the random module reference however I'm not familiar with the various distributions as described.

Could someone help out or point me in the right direction if an existing function would achieve this.

(I have cheated slightly by adding True False alternately to make up the correct number of items within the list - list3 is the final list, list2 contains the repeated module of true falses)

Many thanks

import math
import random

percent = 30
items = 42

def remainder():
    remain = items % len(list2)

    while remain > 1 :
        list3.append(True)
        list3.append(False)
        remain -= 2

    if remain == 1:
        list3.append(True)

    return list3

#find module of repeating True and False values
list1 = ([True] + [False] * int((100/percent)-1))

#multiply this list to nearest multiple based on len(items)
list2 = list1 * int(items/(100/percent))

# make a copy of list2
list3 = list2[:]

#add alternating true and false to match len(list3) to len(items)
remainder()

#an example of a completely shuffled list - which is not desired 
shuffled = random.sample(list3, k = len(list3))




Create a unique random ID

Since couple of days, i have a problem with my function who generate a random id.

Here is the function :

public static function generatePin($max)
{
        $key = "";
        $possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $possibilities .= "abcdefghijklmnopqrstuvwxyz";
        $possibilities .= "0123456789";
        $i = 0;
        while ($i <= $max) {
            $detail = Tools::substr($possibilities, mt_rand(0, Tools::strlen($possibilities)-1), 1);
            $key .= $detail;
            $i++;
        }
        return $key;

In my file, when i want to use this function, i used to do that (works fine since many months) :

    $this->my_secure_pin = Tools::encrypt(Class::generatePin(7));

Now, my variable "secure_pin" can't change.. I always have the same ID and it doesn't want to change as it used to do.. My random ID become a same ID for every request.. Grrrr

No changes, No updates, nothing.. Any idea ? :'(

Many thanks for your help !




Why does a random generated number not work but one ive put in manually work correctly

I have created code which asks the user to type in the number version of a number from a word version from a number.

import random
unit = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
teen = ["", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tenth = ["", "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
hundreth = ["", "One Hundred", "Two Hundred", "Three Hundred", "Four Hundred", "Five Hundred", "Six Hundred", "Seven Hundred", "Eight Hundred", "Nine Hundred"]
thousandth = ["", "One Thousand", "Two Thousand", "Three Thousand", "Four Thousand", "Five Thousand", "Six Thousand", "Seven Thousand", "Eight Thousand", "Nine Thousand"]
a = 11
while a>0:
  a = a - 1
  thenumber = str(random.randint(1000,9999))
  if int(thenumber[3]) + int(thenumber[2]) > 10 or int(thenumber[3]) + int(thenumber[2]) < 20:
    teencheck = "correct"
  elif int(thenumber[3]) + int(thenumber[2]) < 11 or int(thenumber[3]) + int(thenumber[2]) > 19:
    teencheck = "wrong"
  else:
    print("not possible")
  if teencheck == "wrong":
    print(thousandth[int(thenumber[0])], hundreth[int(thenumber[1])], "and", tenth[int(thenumber[2])], unit[int(thenumber[3])])
    answer = input(print("What is this number?: "))
  else:
    print(thousandth[int(thenumber[0])], hundreth[int(thenumber[1])], "and", teen[int(thenumber[3])])
    answer = input(print("What is this number?: "))
  if answer == thenumber:
      print("Correct!")
  else:
    print("That is incorrect, unlucky")

whenever the number is a teen, the correct answer is still said to be wrong. If I change the thenumber = str(random.randint(1000,9999)) to thenumber = str(1111) the answer 1111 is said to be right.

I don't understand why the randomly generated teen numbers are considered wrong no matter what answer I put in but if I manually enter a teen number in the code it says it's correct.




Choose an object randomly with different probability

I have the following problem:

I need to choose a random object from an ArrayList. This is simple, if all elements would have the same chance to be picked.

In my case, the chance of an object beeing picked is stored in another ArrayList. So I need a method, that randomly picks an element from the list based on the other ArrayList.

Thank you for any advice.




How to generate 2 non-adjacent random numbers in a range

I need to generate 2 random numbers in a range [A..B] with the restriction that the numbers can not be adjacent. I would like to do it in constant time (I don't want to keep drawing until the 2nd value is good).

I can think of several ways to do this:

  • Pick the first, then pick one that fits after it: Draw V1 from the range [A..B-2], then draw V2 from the range [V1+2..B]
  • Pick the distance between them, then place them: Draw d from [2..B-A] and V1 from [0..B-A-d] then V2=V1+d
  • Pick the first, then pick an offset to the second one: Draw V1 from the whole range, then draw d from the range [A+2-V1..B-V1-1], and set V2= d<=0 ? V1-2+d : V1+1+d
  • Pick the first, then pick the distance to the second with wrapping: pick V1 from [A..B], d from [0..A-B-2], V2 = V1+d; V2 = V2>B ? V2-(B-A)

I want the most random method (generates most entropy, has most even distribution). I think the last 2 are equivalent and more random than the first two. Is there an even better way?




Shuffling numbers in bash using seed

I want to create an array of integers, where the numbers are from 1...N. Each number appears once in this array. For instance array = {1, 3, 5, 2, 4} when N = 5.

In order to produce this array, I use the shuffle method as:

        array=($(shuf -i 1-$N -n $N ))

It works fine. However, I want to add seed to this code to make sure every time I run the code with the same seed, I get the same array. Is it possible to do that using the shuffle method?




Generate random numbers without libraries or time in Python

I have Python on my TI-Nspire CX CAS calculator (PyWrite) and wanted to program so that it would give me random numbers I don't care in which form (floating point between 0 and 1 or just integers) but I don't have the unix time or access to libraries. Is there a way to make it give me random numbers without first me giving it a starting value?




Random number between zero and one in c++

i want to create a random number between 0 and 1 but my codes output is zero.

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

using namespace std;

int main()
{
  srand(time(0));

  for(int x=0;x<100;x++)
  {
      cout<<(rand()%10)/10<<endl;
  }
  return 0;
}




Creating a never-repeating random hexadecimal generator

My company has asked me to develop a 4-byte random hexadecimal generator for some security hardware we have, however I am new to this sort of thing. (To clarify, each code consists of 4 hexadecimal digits).

We currently have a list of 124 hexadecimals that are in use and I need to be able to not repeat those hexadecimals as well as ones that will be generated with this program. I have developed a GUI and a generator, I just need help making sure it never repeats.

This is what I have so far:

# random hexadecimal generator engine 
text = "" 

for i in range(4): 
    rand = random.choice('0123456789abcdef') 
    text = text + rand 
    print(text) 

# creating the window 
root = Tk() # GUI window 
root.title("Hex Generator") 
root.geometry("250x150") 
app = Frame(root) 
app.grid() 
label = Label(app, text="Click to generate a Hexadecimal") 
button1 = Button(app, text="Generate") 
label.grid() 
button1.grid() 
label1 = Label(app, text=text) 
label1.grid() 

# kicking off event loop 
root.mainloop()




Don't understand code that gets random number between two values

So, I understand this seems like a stupid question. With that said however, within my classes concerned with teaching proper code. I came upon this. Min + (Math.random() * ((Max - Min) + 1)) Essentially the code goes. Add your minimum value + a random number between 0.0 and 1.0 multiplied by the max value minus the minimum value plus 1. The book regards this code as a base for retrieving a random value within certain parameters. i.e max=40 min=20. that would get a value between 40 and 20.

The thing is, I know what the code is saying and doing. I was using this to generate a random character by adding (char) to the front and using 'a' and 'z' as the values. The thing is though, I don't understand how, mathematically speaking, this even works. I understand it makes me a pretty poor programmer on my part. I never claimed to be great or brilliant. I know algebra and some basic higher math concepts but there are some stupidly basic formulas like this that leave me scratching my head.

In terms of programming logic, this isn't so much an issue for me, but seeing concepts like this. I'm confused. I don't get the mathematical logic of this code. Am I missing anything? I mean, with a math random value between 0.0 and 1.0, I don't see how it procures a value between the minimum and maximum value. Would anybody be willing to be give me a layman's explanation of how this works?




lundi 30 janvier 2017

How to make randomly pop some gui without stopping the script #python 2.7

I'm relatively new to python, so please bear with me.

My question has two aspects:

  • First, I'm trying to make a GUI that randomly pops different sentences to the user, every time in a new frame.

  • Second, I want the user to be able to close the GUI without stopping the script, like if it was running in the background.

here is my code:

import Tkinter as tk
import random
number = random.randint(0,13)

sentence = {contains 13 sentences
    }

window = tk.Tk()

window.output = tk.Label(text = sentence[number])
window.title("I Always See You")
window.geometry("300x150")

def next():
    rand= random.randint(0, 13)
    window2 = tk.Tk()
    window2.output = tk.Label(text = sentence[rand])
    window2.output.pack(side="top", fill="x", expand=True)
    window2.title("I Always See You")
    window2.geometry("300x150")

window.output.pack(side="top", fill="x", expand=True)

choice()

window.after(1000, next)
window.mainloop()

My problem: when my second frame pops, there isn't any text showing, and if it does have something popping, it appears in the first frame.

also, how can you insert a random float in .after() ?

Thank you so much for your help!

cheers




Programming a macro in excel to generate a random number between a, b

I am building a spreadsheet in excel, the spreadsheet functions as a data keeping table that updates different values as it needs to, one of the values that I'm interested in streamlining is essentially a random number generator. I already have knowledge of the simple RANDBETWEEN() function inside the cells of excel. however this only returns one (1) value, I would like to be able to assign this to a function to get it return a different value every time the button is hit. I can create the button, I have the cell.. I'm not sure exactly why I cannot link the two? Ive tried looking through already asked questions of this but not found anything super close to my problem (though I realize for someone who is adept with excel this might be a trivial problem.) I however am not adept at excel, and am still learning all the inner workings and things I can do with excel.

Long story short, can someone help me get a button that every time it is clicked a cell (lets say cell a1) gets a different value between values a, to b.

again sorry if this is trivial, ive tried all I can to do this on my own and I'm just not having any luck.




What is SQL Server Rand Function algorithm?

  1. I want to know the exact algorithm of SQL 2005 RAND function.
  2. Is there any time factor involved in the logic?

I have searched in the web and couldn't find any details. Our company security team believes that the RAND function is not fully random and by having enough sample they can predict the next one.




How to not get the same random numbers in successive method calls in Java

Consider the following code (using Java 1.8.0_102 and JDistLib 0.4.5):

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

import jdistlib.Exponential;
import jdistlib.generic.GenericDistribution;
import jdistlib.rng.MersenneTwister;
import jdistlib.rng.RandomEngine;


public class RVs {

    public void getEV(GenericDistribution dist, int sampleSize) {
        ArrayList<Double> rvs = this.populateArray(dist, sampleSize);
        System.out.println(rvs);
    }

    public ArrayList<Double> populateArray(GenericDistribution dist, int sampleSize) {
        RandomEngine randomE = new MersenneTwister(System.currentTimeMillis());
        ArrayList<Double> rvs = new ArrayList<Double>();
        IntStream.range(0, sampleSize).forEach($ -> rvs.add(dist.random(randomE)));
        return rvs;
    }

    public void test () {
        IntStream.range(0, 13).forEach($ -> this.getEV(new Exponential(33.33), 10));
    }

}

... implemented like this:

public class CallRVs {
    public static void main(String[] args) {
        RVs alpha = new RVs();
        alpha.test();
    }
}

Unfortunately, this always repeats the same sequences of random numbers about 3-4 times.

Before ending up with the code above, I tried this

  • without setting the RandomEngine explicitly and
  • without setting the random seed for the RandomEngine to the current time

You would think, creating new RandomEngine instances with seed set to the current time should help, but no:

[22.703723551648405, 6.7092516027839855, 190.59060286639905, 1.8735125522919636, 41.022344668942665, 3.877018716199701, 21.49930713290334, 42.05773014708266, 23.00082916381309, 23.24308297023846]
[22.334558402867305, 1.6401554044082725, 84.11326045120587, 18.165389107596983, 83.13647054950233, 32.72909304649951, 31.453740499105955, 93.5956252958078, 4.040938139470317, 19.99121603725849]
[22.334558402867305, 1.6401554044082725, 84.11326045120587, 18.165389107596983, 83.13647054950233, 32.72909304649951, 31.453740499105955, 93.5956252958078, 4.040938139470317, 19.99121603725849]
[22.334558402867305, 1.6401554044082725, 84.11326045120587, 18.165389107596983, 83.13647054950233, 32.72909304649951, 31.453740499105955, 93.5956252958078, 4.040938139470317, 19.99121603725849]
[79.14217486099653, 41.08293664856576, 7.224345566610367, 127.53056431952126, 80.37600520651415, 38.4618180996009, 0.9904925074615941, 12.20987288657261, 36.530623436560845, 32.1600825790288]
[79.14217486099653, 41.08293664856576, 7.224345566610367, 127.53056431952126, 80.37600520651415, 38.4618180996009, 0.9904925074615941, 12.20987288657261, 36.530623436560845, 32.1600825790288]
[79.14217486099653, 41.08293664856576, 7.224345566610367, 127.53056431952126, 80.37600520651415, 38.4618180996009, 0.9904925074615941, 12.20987288657261, 36.530623436560845, 32.1600825790288]
[79.14217486099653, 41.08293664856576, 7.224345566610367, 127.53056431952126, 80.37600520651415, 38.4618180996009, 0.9904925074615941, 12.20987288657261, 36.530623436560845, 32.1600825790288]
[9.273608510364928, 3.489400227955458, 39.90486871467796, 0.62827300597674, 11.400150691547177, 5.284720630096435, 24.384279251275796, 16.08800783422188, 21.318680903820088, 5.974180125899405]
[9.273608510364928, 3.489400227955458, 39.90486871467796, 0.62827300597674, 11.400150691547177, 5.284720630096435, 24.384279251275796, 16.08800783422188, 21.318680903820088, 5.974180125899405]
[9.273608510364928, 3.489400227955458, 39.90486871467796, 0.62827300597674, 11.400150691547177, 5.284720630096435, 24.384279251275796, 16.08800783422188, 21.318680903820088, 5.974180125899405]
[24.382314535207747, 19.911193724734368, 11.447193297362048, 0.9268859488114056, 18.486786238992774, 29.54231307250453, 17.592849710828943, 26.563616563286097, 19.548355104754787, 4.339118659323733]
[24.382314535207747, 19.911193724734368, 11.447193297362048, 0.9268859488114056, 18.486786238992774, 29.54231307250453, 17.592849710828943, 26.563616563286097, 19.548355104754787, 4.339118659323733]

What is the proper way to prevent such repetitions? Locks (would make everything excessively slow, right?)? "Salting" the seed with some counter or counter with random increment (would be an extremely dirty hack the statistical consequences of which would be unclear)?

Or am I doing something wrong? (I also get "RVs.java:22: warning: [deprecation] random(RandomEngine) in GenericDistribution has been deprecated" which might suggest that this is not the right way to do it.)




I need help writing a small program to randomly draw entries from a list

I need help writing a code which randomly selects an adjustable amount of entries from a list and displays them for me. Preferably, I should be able to adjust the entries in the list aswell. So say I have a list with the numbers A through G, and I want the code to draw 7 different entries, it would show for instance "F C D A C G B". I would also like to be able to change the list from A through G to for instance words or other letters. I've tried several codes, but this is too advanced for me. I've read through several other forums and topics, but no one is able to help me. It's important to me that the design is simple, so all I want to have on my screen is a vertical list of entries, a small box to decide how many random draws to preform, and the result being displayed in a horizontal line. I'm not asking anyone to do the job for me, that would be rude, but I'm going about this the wrong way and I desperately need some guidance, because at this point I have no idea what I'm doing and everything I try turns out to be more complicated than what it needs to be.

Thanks in advance to anyone who can help me.




Random direction en 2D lua

I want to create a random direction for my sprite, in Lua 2D.

So, i've tried that :

Sprite.x = Sprite.x + vx
Sprite.y = Sprite.y + vy

Sprite.vx = math.random(-1,1)
Sprite.vy = math.random(-1,1)

So, i managed to create a random direction, but my problem is the speed of the sprite, is directly linked to the number of direction. For example if i want the speed to be 1, it can only have 4 direction. I made a sprite with a lot more, by setting the random speed between -3 and 3, but then it's faster than what i want.

What should i do?

I've seen a few posts talking about random direction, but the description wasn't about lua and i couldn't really understand it..

Thanks!




Function using rand_r() in a source file and multithreading

I have a source file in which I defined a function to fill a vector with random 1 or 0, something like:

int rand_range(int lo, int hi) {
 return lo + rand_r(&seed) % (hi - lo);
}
//fill a vector with n 1 and N-n 0 at random
void random_fill(int vec[], int dim, int n) {
 int i;
 //the condition is n!=0!
 for (i = 0; n; ++i) {
  if (rand_range(0, dim-i) < n) {
   vec[i] = 1;
   --n;
 }
 else
   vec[i] = 0;
 }
 for (; i < dim; ++i) vec[i] = 0;
}

seed is a variable declared in the same source file.

In my main.c file I use openmp() to parallelize my program, but I have to call this function in every thread. If I simply call:

random_fill(vec, dim, n);

inside the parallelized area, do I get issues? What's the most correct way to call a function that generates and works with random numbers in a thread safe way?




What is the distribution of /dev/urandom? Code to verify?

Everywhere I look it says /dev/urandom on linux is "random", but no source I can find cites what kind of random "random" is. My hope is that it is close to uniform on 0x01 to 0xff bytewise. If I wanted to test this, what would be the best way to get an estimate of the distribution? Solution in bash preferred.




I am working on a project.i need to read a value from my table and display the elements randomly in jlabel

public void load(int n) {
try { PreparedStatement ps=c.prepareStatement("SELECT letter FROM manage WHERE slno ="+n); ResultSet rs=ps.executeQuery();

         if(rs.next()==true)
         {
             jlabel.setText(rs.getString("letter"));
              a=rs.getString("letter");
         }


    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}




How to tell that the strings selected randomly out of a list are the same

I have this question; I'll sum it up in steps

  1. Make the program add 7 animals to a list via inputs (DONE)
  2. Make the program select 3 random animals from that list (DONE)
  3. If the animals selected are all the same, print 'Bingo!' ; if not, loop the input until the user presses 'X' or gets a 'Bingo!'.

I'm having trouble with the last step, and I've tried searching everywhere and tried many methods but the code isn't doing the right thing. Here's the code:

import random

bingoList=[]
generatedList=[]

def generateCards():
    for i in range(0,3):   
        print(random.choice(bingoList))
        generatedList.append(a)

for i in range(0,7):
    a=input("Enter an animal: ")
    if (a.isdigit()==False):
        bingoList.append(a)
    else:
        printprint("You are not allowed to input numbers; program stopping...")
        exit()

print("All the animals have been stored, let's start the game..")

generateCards()




Kivy python- class variables passing

i dont know how to pass a variable from the Builder.Load_String to the Send_File() function in another class. i want to send the specific word from the specific button clicked.

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Ellipse, Line
import socket
import sys
import os
import webbrowser
from server import send_file
import thread
import random
import multiprocessing
lines = open("words.txt").readlines()
word_list = []
for x in range(0, 3):
    isexist = True
    line = lines[0] 
    words = line.split() 
    myword = random.choice(words)
    while isexist:
        if myword not in word_list:
            word_list.append(myword)
            print myword
            isexist = False
        myword = random.choice(words)

Builder.load_string("""
<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Start Game'
            on_press: root.manager.current = 'settings'
        Button:
            text: 'quit'

<SettingsScreen>:
    BoxLayout:
        Button:
            text: """ + "'" + word_list[0]+ "'" + """
            size_hint: 0.25,1
            on_press: root.manager.current = 'paint'

        Button:
            text: """+ "'" + word_list[1]+ "'" + """
            size_hint: 0.25,1
            on_press: root.manager.current = 'paint'
        Button:
            text: """+ "'" + word_list[2]+ "'" + """
            size_hint: 0.25,1
            on_press: root.manager.current = 'paint'
        Button:
            text: 'Back to menu'
            size_hint: 0.25,1
            on_press: root.manager.current = 'menu'
<MyPaintScreen>:
    BoxLayout:            
""")

# Declare both screens
class MenuScreen(Screen):
    pass
class MyPaintScreen(Screen):  
    def on_enter(self):
        multiprocessing.Process(target=MyPaintApp().run).start()
class SettingsScreen(Screen):
    pass
class WordsScreen(Screen):
    pass

# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))
sm.add_widget(MyPaintScreen(name='paint'))

class MyPaintWidget(Widget):
    def __init__(self):
        super(MyPaintWidget, self).__init__()
        self.lineSize = 5
    def on_touch_down(self, touch):
        with self.canvas:
            touch.ud['Line'] = Line(points=(touch.x, touch.y), width=self.lineSize)

    def on_touch_move(self, touch):
        touch.ud['Line'].points += [touch.x, touch.y]

class TestApp(App):
    def build(self):
        return sm

class MyPaintApp(App):
    def build(self):
        self.parent = Widget()
        self.painter = MyPaintWidget()

        self.parent.add_widget(finishbtn)

        return self.parent
    def finish(self,obj):
        photo =self.parent.export_to_png("C:\Users\student\Desktop\yoav.png")
        send_file(myword)

if name == 'main': TestApp().run()




Random identifiers: secure VS unique. What to chose?

Some times when we want to identify something we generate IDentifier for this object.

Sometimes we use just rand sometimes we want something more reliable. Currently I am between:

  1. Data::UUID
  2. Crypt::PRNG

Would be there any difference between results of these two methods?

$id = Data::UUID->new->create_bin;    #
$id = Crypt::PRNG::random_bytes(16);  # http://ift.tt/2jv4oou

Both are 16bytes random. Regardless of interface are there further differences?




java random numbers generator [duplicate]

This question already has an answer here:

i was wondering if i could generate numbers from 11-99, excluding the numbers 0-10? Is that even possible to make with a random generator? here's e piece of my code

import java.util.*;

public class clas1 { public int min;

public int[] tabele() {
    Random r = new Random();
    int d;
    int e[]= new int[100];
    for(int i=0; i<e.length;i++){
        d=r.nextInt(99)+11;
        e[i]=d;
        System.out.println(e[i]);
    }

    return e;
}

public void emin(int[] e) {
    Random r = new Random();
    int d;
    for(int i=0; i<e.length;i++){
        d=r.nextInt(100);
        e[i]=d;
        if(e[i]<min){
            min=e[i];
        }
    }

    System.out.println("Vlera me e vogel eshte: " +min);
}

public static void main(String []args){
    clas1 prova = new clas1();
    int[] arr = prova.tabele();
    prova.emin(arr);
}

}




dimanche 29 janvier 2017

How to populate a mssql table continuosly with the data of another table

I am struggling to convert an oracle procedure to mssql one (unfortunately without mssql knowledge), basicly the case is like this; assume that I have a table named as HISTORIC_TABLE with constant rows of data, and I have another table named as REAL_TIME_TABLE (totally empty at the begining). I am trying to generate transactions on REAL_TIME_TABLE by fetching rows in HISTORIC_TABLE randomly and slowly. Here the oracle equivalence of the scenario. Any help would be really appreciated.

`

create or replace procedure test.p_replicate_data() 
is
cursor c1 is 
SELECT *  FROM TEST.HISTORIC_TABLE ORDER BY DBMS_RANDOM.RANDOM;

r1 c1%rowtype;

cmd_sql varchar2(10000);
cmd_values varchar2(10000);

begin 

for r1 in c1 loop

cmd_sql := '';
cmd_values := '';

--start the command sql
cmd_sql := 'INSERT INTO TEST.REAL_TIME_TABLE (' ;

cmd_sql := cmd_sql || 'COL1, ';
cmd_sql := cmd_sql || 'COL2, ';
cmd_sql := cmd_sql || 'COL3, ';
cmd_sql := cmd_sql || 'COL4';


cmd_sql := cmd_sql || ') values (' ;

--prepare the values string
cmd_values := cmd_values || '''' || r1.COL1 || ''',';
cmd_values := cmd_values || '''' || r1.COL2 || ''',';
cmd_values := cmd_values || '''' || r1.COL3 || ''',';
cmd_values := cmd_values || '''' || r1.COL4 || '''';

cmd_sql := cmd_sql || cmd_values;

cmd_sql := cmd_sql || ')';

execute immediate (cmd_sql);
commit;

dbms_lock.sleep(0.05);

end loop;
end;`




Retrieve a string that was assigned into a random index inside of an array

So I need to locate where the "Nut" string is stored at. I thought my code would work just fine but obvious the ide just keep throwing me an error.

   Random rd = new Random();

    String[] hidingSpots = new String[100];

    hidingSpots[rd.nextInt(hidingSpots.length)] = "Nut";
    System.out.println("The nut has been hidden ...");

    int nutLocation = 0;

    while (nutLocation < hidingSpots.length) {
        if (hidingSpots[nutLocation].equals("Nut")) {
            System.out.println("Found it! It's in spot# " + hidingSpots[nutLocation]);
        }

        nutLocation++;

    }




How do i make each of my if statements run individually ? (Java)

Im attempting to program a 'Name Guesser'. This game relies heavily on if statements and randomisation. I have a problem which i don't know how to fix, my if statements can only run in a sequence, and not separately! I want to be able to guess the selected name in any given order, but currently i can only guess the name in one order. Eg. C H R I S is the only way to guess the name correctly, any other sequence of characters will not work. What can i do to fix this?

Note - Chris is the only name implemented so far.

My NameGuesser class:

        import java.lang.reflect.Array;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;
    import java.util.Scanner;


    public class NameGuesser {

        public static class Mark{
            public static  boolean M = false;
            public static  boolean A = false;
            public static  boolean R = false;
            public static  boolean K = false;
        }   


        public static void main(String[] args) {
            // TODO Auto-generated method stub
    Scanner reader1 = new Scanner(System.in);
            String Guessspace = "_ _ _ _";

            boolean Mark = true;
            int Lives = 3;
            int Guessingmode = 0;
    String[] Names = {"Mark", "Adam", "Joel"};
    String Random = (Names [new Random().nextInt(Names.length)]);

    List<String> Markletters = new ArrayList<String>();
    Markletters.add("M");
    Markletters.add("A");
    Markletters.add("R");
    Markletters.add("K");




    System.out.println(Random);

    if (Random == "Mark"){
         Guessingmode = 1;
        }
    if (Random == "Adam"){
            Guessingmode = 2;
        }
    if (Random == "Joel"){
            Guessingmode = 3;
        }

     {







if (Guessingmode == 1){
    String Nameguess = reader1.next();            
         if(Markletters.contains(Nameguess)){


        if (Nameguess.equals("M")){
               NameGuesser.Mark.M = true; 
               GuessSpace GuessSpace;
               GuessSpace = new GuessSpace();
               GuessSpace.GuessSystem();       
        }
              }




               Nameguess = reader1.next();
               if(Markletters.contains(Nameguess)){


            if (Nameguess.equals("A")){
             NameGuesser.Mark.A = true; 
             GuessSpace GuessSpace;
              GuessSpace = new GuessSpace();
              GuessSpace.GuessSystem();
            }
               }



                   Nameguess = reader1.next();
                   if(Markletters.contains(Nameguess)){


                   if (Nameguess.equals("R")){
                NameGuesser.Mark.R = true;
                 GuessSpace GuessSpace;
                 GuessSpace = new GuessSpace();
                 GuessSpace.GuessSystem();
            }
               }



                   Nameguess = reader1.next();
                   if(Markletters.contains(Nameguess)){


            if (Nameguess.equals("K")){
                NameGuesser.Mark.K = true; 
                GuessSpace GuessSpace;
                GuessSpace = new GuessSpace();
                GuessSpace.GuessSystem();
            }
               }


}
 }
    }
}

My GuessSpace class:

   public  class GuessSpace extends NameGuesser{

public void GuessSystem() {
    if( NameGuesser.Mark.M == true){
        System.out.println("M _ _ _");
        }


                    if( NameGuesser.Mark.M == true){
                        if( NameGuesser.Mark.A == true){
                            System.out.println("M A _ _");
                    }
                            }

                                if( NameGuesser.Mark.M == true){
                                    if( NameGuesser.Mark.A == true){
                                        if( NameGuesser.Mark.R == true){
                                                System.out.println("M A R _");
                                }   
                                        }
                                    }


                                            if( NameGuesser.Mark.M == true){
                                                if( NameGuesser.Mark.A == true){
                                                    if( NameGuesser.Mark.R == true){
                                                        if( NameGuesser.Mark.K == true){
                                                            System.out.println("M A R K");
                                                            System.out.println("Well done! You guessed my name!");
                                                            System.exit(0);
                                                        }
                                                    }
                                                }
                                            }

}   
}




Why can't I generate random number between 0 and 1 in C#?

I'm getting 0 every single time, why is this? Can I not start from 0?

Random random = new Random();
int test = random.Next(0, 1);
Console.WriteLine(test);
Console.ReadKey();




Get-Random increased randomness HELP Powershell

I am in need of a little help as to increasing the randomness of get-random thus not repeating so often.

I have been using this with powershell:

$formats =
@("*.mpg")
$dir = Split-Path $MyInvocation.MyCommand.Path
gci "$dir\*" -include $formats | Get-Random -Count 1 |
Invoke-Item

My application is to have a in home virtual television channel that randomly selects 1 file from multiple folders at 6am and plays them all day until midnight, powers off and starts up, repeating the process daily. The problem I am finding is that whatever the get-random command uses had a tendency to choose the exact same file often. Thus after months of running this script, I am seeing the exact same movies chosen day after day and some that are never chosen. I'm guessing because the get-random is using the clock as it's factor for choosing a number?

Is there a way to increase the odds of getting a broader selection of files .mpg's in this instance and less of a repeat of the same .mpg's chosen?

My other option was to find a script that would keep track of the .mpg's chosen and "mark" them, or sort by date accessed and not play the same file twice, until all files of a particular folder have been played once; then "unmarking" all the files and starting over. To me that sounds like advanced scripting that I just don't have the knowledge to procure on my own.

Any insight into my dilemma would be vastly appreciated. Any questions about my specifics to help you ascertain a conclusion to this query will be forthcoming.




How could I randomise the order of questions being asked in my JavaScript quiz? [duplicate]

This question already has an answer here:

Currently I have this code which displays the questions on screen:

var questions = [
new Question("What is the answer to this question?", ["answer1", "answer2", "answer3", "correct answer"], "correct answer"),
new Question("question?", ["answer1", "answer2", "answer3", "correct"], "correct")
];

var quiz = new Quiz(questions);

I have researched various ways of randomising the order of questions, however none of them seem to work with the array I have. I was wondering how I would randomise the order of questions, whilst keeping the format I already have.




how to estimate the value of time with random parameter using mixed logit model in R

I would like to know more specifically how to estimate the value of time with random parameter using mixed logit model.

First, I have created a data set as below.

enter image description here

The estimattion of the fixed parameter using the mlogit is as attached below, and using this result, the value of travel time per hour turned out to be 90.95$.

Referring the result above, I followed the next three steps suggested in “Kenneth Train's exercises using the mlogit package for R(2012)" for mixed logit model.

  1. I assumed lognormal distribution, for both time and cost are negative for all people.
  2. Therefore, I put negative sign for both time and cost to use lognormal distribution.
  3. I estimated the random paramter with mlogit.

As the fixed parameter above, I would like to know which of the method below is the right way to calculate value of time using the estimated random parameter.

  1. Calculating with 'exp(Estimate parameter' or 'median of the random coefficients' for the estimated parameter has lognormal distribution; exp(-2.09959)/exp(-2.37945)*60=0.12250719/0.09260118*60=79.37$/h

  2. Calculating with 'mean of of the random coefficients'; 00.1533085/0.1967394*60 = 46.75$/h

Thank you very much, and I look forward hearing from you.

> ############### loading data ###############
> library(mlogit)
> data<-read.table("c:/1/data.txt", header=T)
> data_fixed<-mlogit.data(data, choice="choice", shape="long", alt.levels=c("highway","freeway"))
> 
> 
> ############### fixed parameter logit ###############
> 
> summary(fixed<-mlogit(choice ~  cost + time, data_fixed))

Call:
mlogit(formula = choice ~ cost + time, data = data_fixed, method = "nr", 
print.level = 0)

Frequencies of alternatives:
highway freeway 
0.47887 0.52113 

nr method
5 iterations, 0h:0m:0s 
g'(-H)^-1g = 2.1E-06 
successive function values within tolerance limits 

Coefficients :
                     Estimate Std. Error t-value  Pr(>|t|)    
freeway:(intercept) -0.516425   0.220266 -2.3446   0.01905 *  
cost                -0.077591   0.045392 -1.7093   0.08739 .  
time                -0.117620   0.017278 -6.8074 9.936e-12 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Log-Likelihood: -211.29
McFadden R^2:  0.14022 
Likelihood ratio test : chisq = 68.918 (p.value = 1.0832e-15)
> -0.117620/-0.077591*60
[1] 90.95385


> ############### MIXED LOGIT ###############
> ############### loading  opposited data ###############
> data_random<-mlogit.data(data, choice="choice", shape="long", alt.levels=c("highway","freeway"), 
+                          opposite=c('time','cost'))
> 
> ############### random parameter logit ###############
> summary(random<-mlogit(choice ~  cost + time, data_random,rpar=c(cost='ln', time='ln'), 
+                        R=500, halton = NA))

Call:
mlogit(formula = choice ~ cost + time, data = data_random, rpar = c(cost = "ln", 
time = "ln"), R = 500, halton = NA)

Frequencies of alternatives:
highway freeway 
0.47887 0.52113 

bfgs method
4 iterations, 0h:0m:10s 
g'(-H)^-1g =  0.99 
last step couldn't find higher value 

Coefficients :
                    Estimate Std. Error t-value  Pr(>|t|)    
freeway:(intercept) -0.55373    0.32828 -1.6867  0.091652 .  
cost                -2.37945    0.86705 -2.7443  0.006064 ** 
time                -2.09959    0.28893 -7.2667 3.684e-13 ***
sd.cost             -1.22766    1.75183 -0.7008  0.483435    
sd.time              0.66975    0.49450  1.3544  0.175611    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Log-Likelihood: -209.78
McFadden R^2:  0.14637 
Likelihood ratio test : chisq = 71.94 (p.value = 8.835e-15)

random coefficients
     Min.    1st Qu.     Median      Mean   3rd Qu. Max.
cost    0 0.04045766 0.09260118 0.1967394 0.2119495  Inf
time    0 0.07797829 0.12250719 0.1533085 0.1924640  Inf
> exp(-2.09959)/exp(-2.37945)*60
[1] 79.37668
> 0.12250719/0.09260118*60
[1] 79.3773
> 0.1533085/0.1967394*60
[1] 46.75479




C random number producing garbage value

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

int main() {

    srand(time(0)); 

    int random = 0, guess, guesses = 1;
    random = rand() % 100 + 1;
    printf("The number has been generated. Input 0 to quit.\n");
    do {
        scanf("%d", &guess); //takes user input for guess
        if (guess > random && guess != 0)
            printf("Lower!\n");
        else
        if (guess < random && guess != 0)
            printf("Higher!\n");
        else
        if (guess == random) {
            printf("Bingo!");
            return 0;
        } else
        if (guess == 0) {
            printf("Thanks for playing, the number was %d\n", &random);
            return 0;
        }
        guesses++;
    } while (guesses != 6); //maximum of 5 guesses

    printf("Thanks for playing, the number was %d\n", &random);

    return 0;
}

Whenever I display the random variable when it has already generated a number a garbage value will be outputted. But the code snippet works of checking the comparison between the guess and the random number, I just can't seem to output the random number correctly.




samedi 28 janvier 2017

How to randomise .text() for li element different each time in jQuery?

I'm looking to make each list element random instead of all the same.

$(document).ready(function() {
    var letters = new Array("A", "B", "C", "D", "E"),
    ran = letters[Math.floor( Math.random() * letters.length )];
    $('li').text(ran);
});




How to shuffle arrays in C?

I'm trying to make a function that will shuffle a playlist but can't figure out how to do it. Been looking at other posts but I can't find anything that helps me solve my problem (in a way that I understand).

This is the function i need help with:

void shuffle(Array *a){
Array temp;

temp.array = (Song *)malloc(sizeof(Song)*a->used);

srand((unsigned int)time(NULL));

if(a->used > 1)
{
    for (int i = 0; i < a->used; i++)
    {
        unsigned int j = rand() % (a->used); //????
        //size_t j = rand() % i;
        temp.array[i] = a->array[j];
        a->array[i] = a->array[j];
        a->array[j] = temp.array[i];
    }
}

freeArray(temp.array);
*a = temp;}

The structs I'm using:

typedef struct song {
char artist[SIZE];
char title[SIZE];
char year[SIZE];} Song;

typedef struct array{
Song *array;
size_t used;
size_t size;} Array;

I want to be able to print out a shuffled list with this function:

(I already have a function that adds each title/year/artist to a->array[i].xxxx)

void printSong(Array *a){
for (size_t i = 0; i < a->used; i++)
{
    printf(
        "\n-----------SONG %d-----------\nSong Title: %sBand/Singer: %sYear: %s",
        i+1,
        a->array[i].title,
        a->array[i].artist,
        a->array[i].year);
}}




Random Number Generator - That Stops

I am using python.

How can I make a code that generates random numbers between 1 and 1000 (inclusive) infinitely until it generates the number 39 and stops?

Here is what I've tried so far, however it has not worked:

import random

print(random.randint(1,1000))

if random.randint=39:

break




vendredi 27 janvier 2017

Python: Randomly choosing a variable and assigning a value to that variable

I am a Python and coding noob. Only started a few weeks ago. I am writing a program that will essentially be a tic-tac-toe game. It uses a simple text based drawing of the board game using - lines and + pluses. In the beginning of the program, I have the 9 spaces in the tic-tac-toe board defined as the following:

valuea1 = " "
valuea2 = " "
valuea3 = " "
valueb1 = " "

And so on through c3... The blank spaces are set up to allow substitution of an X or an O. My board looks like this:

def board():
    """ prints the tic-tac-toe board"""
    print(" +---A------B------C--+")
    print(" |      |      |      |")
    print("1|  " + valuea1 +"   |  " + valueb1 +"   |  " + valuec1 + "   |")
    print(" |      |      |      |")
    print(" ----------------------")
    print(" |      |      |      |")
    print("2|  " + valuea2 +"   |  " + valueb2 +"   |  " + valuec2 + "   |")
    print(" |      |      |      |")
    print(" ----------------------")
    print(" |      |      |      |")
    print("3|  " + valuea3 +"   |  " + valueb3 +"   |  " + valuec3 + "   |")
    print(" |      |      |      |")
    print(" +--------------------+")
    return

Later on in the program, based on an if statement, the symbol the "computer player" will be using (either X or O) is stored in the variable:

computer_mark ## is either "X" or "O" based on player choice

Now here is my main concern and question

randomlist = ("valuea1", "valuec1", "valuea3", "valuec3")
random_result = random.choice(randomlist)
## (REPLACE WITH CODE)
## takes the value stored in random_result, somehow treats the value as a variable,
## assigns that given variable the string value that is stored in computer_mark

I try to randomly choose 1 of 4 spots on the board, and change that spot from a " " string value to the string value stored in computer_mark.

Is there a way to code Python into choosing a random variable, and assigning it a value that is stored in a different variable?




Random Numbers in C Through a Function (Beginner Programmer)

I create a simple game to make the user guess a random number from 1 to 10. It worked fine and then I tweaked it to where I made a function that took 2 arguments, a high and low value, to generate a random number. Doing this through the function always returns the value of the highest number entered as an argument when it should return a random number. Here is my code:

#include "stdio.h"
#include "stdlib.h"
#include "time.h"

int main(void) {

  int storedNum, low, high, userGuess;

  printf("Welcome to my random numbers game! You will choose a lower number and a maximum number and me, the computer, will choose a random number between those two values for you to guess.\n\nFirst, choose the lowest value");
  scanf("%d", &low);
  printf("Now, choose the highest value");
  scanf("%d", &high);

  storedNum = randomNumbers(low, high);
  printf("We have guessed a number between %d and %d. Guess our number!: ", low, high);
  scanf("%d", &userGuess);

  while (userGuess != storedNum){
    if(userGuess < storedNum){
      printf("higher!: ");
      scanf("%d", &userGuess);
    }
    else{
      printf("Lower!: ");
      scanf("%d", &userGuess);
    }
  }

  printf("You are correct the number was %d!", storedNum);
  return 0;
}

int randomNumbers(int maxNum, int minNum){
  int number;
  srand(time(NULL));
  number = rand()%maxNum + minNum;
  return number;
}

The code works fine as long as I generate my random number within the main method, but whenever I use it through a function I always get the same return value. I think the problem lies within the seed being inside the function, but I am not entirely sure. Even if that was the issue I am not sure how I would fix that and get my code working.

Basically, I am trying to write a function that I can reuse in other programs to generate a random number between x and y.

here is some sample output:

Welcome to my random numbers game! You will choose a lower number and a maximum number and me, the computer, will choose a random number between those two values for you to guess.

First, choose the lowest value 1
Now, choose the highest value 10
We have guessed a number between 1 and 10. Guess our number!:  5
higher!:  8
higher!:  9
higher!:  10
You are correct the number was 10! 

No matter what numbers I enter it always returns the max value (in this case 10). Thanks in advance for any and all help and I hope this post finds you well.




Random iterator from a range with a predicate

I have a container, and I'd like to choose an iterator that satisfies a predicate at random. If it helps to be specific, the container is a map.

Naively, I would say this:

std::count_if to get the number of elements in the range.

Choose a random number btwn 0 and num_elements-1.

Create a lambda to make a stateful predicate that counts up to the random number and only returns true then.

std::find_if with the lambda.

Will this work, and is there a better way? Alternatively, I could use count instead of count_if and regenerate the number if it fails the predicate. Could be useful if the predicate is mostly true I suppose, but wouldn't work well for my purposes.




VB.NET - Random selection of rows

I am currently building a multiple choice type of test in vb.net and I want to know how to select it randomly.

I have a table named 'Exercise' and it has column 'Question' and 'Answer' in it.

I want to retrieve the questions (10 items) in-order (and then store it in one textbox each item) but retrieve the answers randomly (one textbox each item as well) to avoid adjacent question and its correct answer.

I'm not used to looping that's why I'm having a hard time. Any help would be much appreciated. Thanks.




Boolean Program clarification for beginner

Consider the following program:

using System;

class BooleanType
{
    static void Main()
    {
        bool male = false;

        Random random = new Random();
        male = Convert.ToBoolean(random.Next(0, 2));

        if (male) 
        {
            Console.WriteLine("We will use name John");
        } else 
        {
            Console.WriteLine("We will use name Victoria");
        }
    }
}

Question 1. why is the line bool male = false; initialised to false? this seems irrelevant to me as the program later decides if it will be true or false.

Question 2. Random random = new Random(); Why do you have to initialise this to new Random(), doesn't Random random create the variable random of type random?




Self-Replicating Scammer Spammer - Randomizing Popup Positioning (Chrome)

Before I start the intended purpose of this project is to mess with Tech Support Scammers, so please try to see the funny side. Also simplicity and low-resource usage is a must.

Purpose: while Scammer is connected to machine, you use a control app on host to set off an annoying self-replicating popup that opens 2 more instances of itself every time you close it. This popup plays a YouTube video (or other flash video, for bonus amusement). Initially it must not slow down the system too much, but when it's told it will create them faster and faster until system halt...

I have most of it down. Funny side note: while testing the "go ape-shiz mode" in Visual Studio it lagged my pc (AMD 8-Core w/ 16GB RAM) to beyond usability in less than 5 seconds, couldn't stop it, open task manager or even start menu! I had no choice but to press physical restart button. Worked a little too well lol.

After some tweaks, first VM test worked great, YT videos loaded in IE and I was happy with the results, had to restart the VM and since then IE hasn't been able to load flash videos. Odd, but I will fix that. IE popups offset nicely and when required it fills up the screen pretty quickly so this is fine.

For now though I want the option for it to make use of Chrome. Everything works but the problem is the popups neatly stack in the top left corner, which is no fun at all. I can't seem to find anything about randomizing the popup position, only offsetting it slightly. I would much rather have it pop up at random locations, it would be the perfect way to piss them off.

Rules:

NO Plugins except those that your average person would use (i.e. Flash player)

HTML, CSS, and JS only!

Keep it SIMPLE!! No 'hundreds of lines of code' unless you feel like writing a detailed explanation, I intend for this to be OpenSource and want novices to be able to understand (plus I don't really know much JS).

Keep resources low! Very important. Will be useless if first 5-10 popups freeze the VM.

To give you an idea, here is the code i'm using to make the popup replicate itself (JS only, I don't need to show you how to implement full-page YT videos):

<script type="text/javascript">
window.onload = function(){ window.open("file:///C:/Windows/System32/popup.html", "", "width=300, height=200") }
window.onunload = function(){ window.open("file:///C:/Windows/System32/popup.html", "", "width=300, height=200") }
</script>

The idea is that the popup is just a HTML file hidden in the VM (hence why no JQuery, AJAX, etc), I chose to put mine in the System32 folder but the "controller" app can create, store and switch between multiple popups, to demo it to a friend earlier I had about 5 different popups and was freely switching between them from my host OS. Was pretty cool other than the neat stacking.

Finally: I would really appreciate the help. Whoever is the first to post the best solution gets best answer, and shoutout in credits of the released app and future YT videos (demos and DIY tutorials). Also be kind, web dev isn't my strong suit!! Thanks guys.




Select random object from list c#

I am making a black jack game (more complicated than it needs to be) and I believe I have setup a Dealer class, and then a game class which has a list of Dealers from in it. see below.

Dealer Class

namespace BlackJackClassLibrary
{
    public class Dealer
    {
        public string Name { get; set; }
        public int Endurance { get; set; }
    }
}

Game Class

namespace BlackJackClassLibrary
{
    public class Game
    {
        public List<Dealer> Dealers { get; set; }
    }
}

And then finally I have a method in my Program which adds dealers to the delaers list like so.

    public void SetupData()
    {
        game.Dealers.Add(new Dealer { Name = "Bill", Endurance = 5 });
        game.Dealers.Add(new Dealer { Name = "John", Endurance = 3 });
        game.Dealers.Add(new Dealer { Name = "Johnny", Endurance = 2 });
        game.Dealers.Add(new Dealer { Name = "Robert", Endurance = 1 });
    {

How can I now randomly select a dealer from this list of dealers?




Generate f(8) function using f(4) function where f(4) generates 1 to 4 randomly? [on hold]

I am facing problem to generate a function named f(8) which will generate 1 to 8 randomly using a defined function f(4) which generates 1 to 4 randomly. need help in this.

EDIT

This question was asked in HackerRank problems. As I don't have any mathematical background I felt hard to solve this. My implementation was like this,

def f8():
    return f4() + f4()

But this implementation is incorrect as it will never be able to produce 1 and the probability of each element is not 1/8 (as by random we mean each and every element in the range has same chance of occurrence)

Some guys thought that this question is not related to programming and I can totally understand the mistake I did and tried to correct that mistake. Hope I am able to convey what I actually did mean.




How can I load a random URL into a specific iFrame?

I am not a programmer but I am familiar with html and CSS coding. I have an iFrame on our corporate website that loads my html pages (long story). Currently it loads "home.html". In a discussion with my boss, he would like it to load a random html page each time the page is visited or refreshed. We currently only have 8-12 pages, but the site should grow. I've seen on this site people wanting to load random iFrames, random images, etc., but I haven't seen an option to load random html pages into a singlular iFrame. I'm assuming it can be done with a simple script added to the iFrame? Maybe a bit more involved? If someone can either help out with the necessary code or point me in the right direction, it would be greatly appreciated! Current page at: http://ift.tt/2k1ypxV




Random Sampling in R

I have a data.frame that is 75 rows by 25 columns. I need to take 10, 20, 30, etc... random samples from the data in the data.frame. How can I take random samples from this data.frame. I do not want to get random rows, but specifically random samples from the data.frame. The sample() function seems to only give me random rows, but I only need 10 random samples from the 1875 data points. How do I do this?




Netlogo: Assign variable using probabilities

How to assign a string or integer variable to turtle, using probabilities of the variables in a group/list? For example it is 0.4 probability that one specific variable is used from specific group/list. The function selects randomly the variable based on probability. I need to use the same method afterwards to choose a variable (string) from a list according to probability. In python it should be:

import random
def random_value(probability_list, values):
    r = random.random()
    index = 0
    while(r >= 0 and index < len(probability_list)):
      r -= probability_list[index]
      index += 1
    value=values[index - 1]
    value_index=index-1
    return value,value_index

I tried it in Netlogo like below (get error that index is -1) but is there a better way?

globals [random_nr probabilities some_list index]
to initialize-variables
  set some_list[]
  set probabilities[]
end
to random_pick
  set random_nr random-float 1
  set probabilities [0.1 0.2 0.4 0.3]
  set some_list ["String1" "String2" "String3" "String4"]
  set index 0
  while [(random_nr >= 0) and (length probabilities < index)] [
   set random_nr random_nr - item index probabilities
   set index index + 1 ]
  set index index - 1
end




Random Direction in 2D Lua

So, i got a newbie question, i want to create a random direction for my sprite, in Lua 2D.

So, i've tried that :

Sprite.x = Sprite.x + vx Sprite.y = Sprite.y + vy

Sprite.vx = math.random(-1,1) Sprite.vy = math.random(-1,1)

So, i managed to create a random direction, but my problem is the speed of the sprite, is directly linked to the number of direction. For example if i want the speed to be 1, it can only have 4 direction. I made a sprite with a lot more, by setting the random speed between -3 and 3, but then it's faster than what i want.

What should i do?

I've seen a few posts talking about random direction, but the description wasn't about lua and i couldn't really understand it..

Thanks !




Rand(Min, Mx) Undefined Variable

Hi I have the following code:

private function doPreEventStart($user) {
    $row = db_fetch_item("SELECT resultid FROM ResultPackage 
        where ResultPackage.slotid like '%{$this->curSlotId}'
        and ResultPackage.PackageID like '%{$user->packageid}%'
        ORDER BY resultid desc LIMIT 1");
    $this->MaxResult = $row['resultid'];


$row = db_fetch_item("SELECT resultid FROM ResultPackage 
    where ResultPackage.slotid like '%{$this->curSlotId}'
    and ResultPackage.PackageID like '%{$user->packageid}%'
    ORDER BY resultid asc LIMIT 1");
$this->MinResult = $row['resultid'];

$this->curResultId = rand($MinResult,$MaxResult);
}

But I am getting this error:

PHP Notice: Undefined variable: MinResult in /var/www/html/betserver.php on line 539 PHP Notice: Undefined variable: MaxResult in /var/www/html/betserver.php on line 539

Please help




Web Application without source code

I am developing an enterprise web application and I want to sell it multiple times. But I don’t want to give the source code to them. So, is there any way I can handover the web app to my clients without source code? If YES, please help. But if NO, then how can I handle this issue?




Ordered Randomness

Can someone please help me with this query?

Questions:

  • ID - Autonum
  • Question - Memo
  • Category - Integer(1-5)

Answers:

  • ID - Autonum
  • FID - Integer
  • Answer - Memo

One question, many possible answers

I need a query that will show all questions from category#1 in random order. After each question, it will show it's possible answers also in random order. Then it will do it for category#2 and so on.

Here's what I have so far:

SELECT Questions.ID, Questions.Question, Questions.Category, Answers.Answer
FROM Questions INNER JOIN Answers ON Questions.ID = Answers.FID
ORDER BY Questions.Category, RND(Questions.ID);

It correctly keeps all the categories together but the rest is random. I'm not sure how to keep the Questions.ID's together (but in a random order) while making the answers order random also.




Single bit random number generator in Verilog

I am trying to generate single bit random number on every clock cycle in Verilog for testing purposes. I am doing this in testbench module. Here is the code;

module tb;

// Inputs
reg clk;
reg in;

// Outputs
wire x;

// Instantiate the Unit Under Test (UUT)
single_bit uut (
    .clk(clk), 
    .in(in), 
    .x(x)
);

integer seed=1;
initial
 begin
  clk=0;
  forever
    #5 clk=!clk;
        in= $random(seed);
end

endmodule

But after simulation, I am getting constant value of 1 in seed and in has x. Any help is appreciated.




RNG should ignore numers that have already been given [Python]

I'm using a random number generater to select a question from a list at random, if the question has already been answered it should skip and reroll until it gets a number that hasn't been given yet.

It works until the options become too limited. It'll roll ~4 times. If it still doesn't have a number that hasn't been given before, it'll give an "index out of range" error.

Sample:

from random import randint
counter = int(0) # Max value, count the amount of questions in the list
done = [] # Already been rolled, ignore these values
list = open('questions.txt').readlines()

for l in list:
    counter +=1

try:
   # While there are less values in <done> than <counter>, roll and add to list
   while len(done) < counter:
       question = randint(1,counter)
       while question in done:
           print('Skipped [%i]' % question) # Check if ignored
           question = randint(1,counter) # Reroll
       else:
           # Add to list so it knows the question has already been asked
           done.append(question) # Add to list with given values
   else:
       print('Finished!\n')
except Exception as e:
   print(e) # Show error if any

I have no clue what i've done wrong, please help.

Thanks :)




Generating Random UNIQUE and converting to binary in C

I have implemented a basic program which generates 10 random and unique numbers from 1 to 10 as shown below. I have added an extra part in which I want the binary representation for each unique and random number. My program looks like this.

   int value=1, loop, loop1, get=0, x, arr[10], array[20], count, i =0, y;
   srand(time(NULL));

for (x = 0; x < 10; x++)
{
    for (count = 0; count < 10; count++) {
        array[count] = rand() % 10 + 1;     //generate random number between 1 to 10 and put in array
    }
    while (i < 10) {
        int r = rand() % 10 + 1;    // declaring int r 

        for (x = 0; x < i; x++)
        {
            if (array[x] == r) {    //if integer in array x is equal to the random number generated
                break;              //break
            }
        }
        if (x == i) {           //if x is equal to i then   
            array[i++] = r;         //random number is placed in array[10]
        }
    }
    for (y = 0; y < 10; y++) {
        printf("unique random number is %d\n", array[y]);
        array[y] = value;

        for (loop = 0; loop < 1000; loop++)
        {
            if (value <= 1) { arr[loop] = 1; break; }       //if value is 1 after dividing put 1 in array
            if (value % 2 == 0) arr[loop] = 0;
            else arr[loop] = 1;

            value = value / 2;
        }
        for (loop1 = loop; loop1 > -1; loop1--)
            printf("%d", arr[loop1]);
        printf("\n");
    }   
   }

My problem is that The binary value for each random unique number is being given as 1. In this program it is seen that I initialised value=1 and this can be the source for my error, however when I remove this I get an error stating that the local variable is uninitialised.

The first part of my program which generates the unique numbers is working fine, however the second part where I am converting to binary is not.

EDIT: I tested The second part of my program and it works well on it's own. The problem must be the way I am combining the two programs together.




jeudi 26 janvier 2017

Change from MySQL Rand() to PHP random_int

We are creating a Random Number Game. We are currently using MySQL Rand() function in the below statement:

private function doPreEventStart($user) {
$row = db_fetch_item("SELECT resultid FROM ResultPackage 
    where ResultPackage.slotid like '%{$this->curSlotId}'
    and ResultPackage.PackageID like '%{$user->packageid}%'
    ORDER BY RAND() LIMIT 1");
$this->curResultId = $row['resultid'];
}

We need to change this to PHP function Random_Int. Please can someone suggest a way of doing this by altering the above code. The random number still needs to be within a certain range as you can see from the WHERE criteria in the SQL statement.




Changing a HTML DOM in an JavaScript file

I'm trying to make a simple "dice rolling" function on a website. I'm using HTML, CSS and JS in three separated files. I have a problem with changing a HTML DOM for example < p> with Math.random() variable in the JS-file. How can i do this?

Some of the code

From html ...

<h1 class='D20'>Let's roll the D20</h1>
<div class=D20></div>
button class=D20>Roll the dice!</button>
<p>0</p>

From JS ...

$('.div').hide();
$(".div.D20").on('click', function(){
var x = Math.floor(Math.random());

I want < p> to always follow x.




How to print a for loop within a for loop in Java

Beginner in Java. Have history in C and Python though.

I'm trying to take this code:

package javaman;
import java.util.Random;
public class JavaMan{


    public static void main(String[] args) {
        Random random = new Random();
        int randomInteger = 0;
        float average = 0;
        System.out.println("The 3 Numbers are:");
        for (int i=0; i<3; i++) {
            randomInteger = random.nextInt(51);
            System.out.println(randomInteger);
            average = average + randomInteger;
        }
        average = average/3;
        System.out.println("The average of the three random numbers (between 0-50) is: " + average);
    }
}

And make it so that it prints out the following:

The 3 Numbers are: 
Number 1 is: 32
Number 2 is: 16
Number 3 is: 0
The average of the three random numbers (between 0-50) is: 16.0

However, I have programmed it such that whenever I use randomInteger, it just runs through the whole for loop when I want the for loop to have its own for loop (the whole "Number x is:" is absent...it just prints the 3 numbers and spits out the average): in the sense that I would be like the following...

("Number", i, "is:", randomInteger) this would look like "Number 1 is: 16"
("Number", i, "is:", randomInteger) this would look like "Number 2 is: 15"
("Number", i, "is:", randomInteger) etc.  

How do I make that in Java?




Randomly placing ID's in specific groups with maximum capacities based on preference

I've been struggling with this process for weeks. I have a process, but it is clunky and cumbersome. Currently, I have a list of 863 unique ID's that need to be placed into 24 different categories that have max capacities. For example, in the table below, "C1" can only hold 33 unique ID's. To make it even more difficult, Each unique ID has a preference of "A", "B", "C", or "D" on a another sheet where a 1, 2, 3, or 4 has been assigned to each letter based on preference (1 being the most desired; 4 being the least).

A unique ID will have a number or numbers assigned to it. So if unique ID has a "6" then it will have to take a space on 6, depending on it's preference of letter. It could have multiple numbers. For example, another unique ID could have a 6, 4, and 3... in which case, it would take up three spots in the table below. If the ID with 6, 4, and 3 had a preference of "D", then it would take a capacity spot under D for rows 3, 4, and 6.

The idea is to randomly place ID's based on their first choice until space is filled, then moving to their second choice, and then third, and so on until all of the space is filled.

Currently, I am assigning a random number using RANDBETWEEN and then sorting that column to "Randomize" the order of the list and then I am literally filtering first choice from letter and highlight rows to get a count for each number. It takes about 30-40 minutes to do manually.

This is something that will need to be done every 6 months with more and more groups so I am hoping to find something that will help minimize the manually filtering and highlighting.

    A   B   C   D
0   25  18  20  25
1   33  25  33  20
2   33  25  30  28
3   45  25  30  28
4   33  35  30  30
5   38  35  33  30
6   51  35  35  35

Thank you for all advice in advance!




angularjs random password generator at least one upper, lower, number and special character

How can I make this random password generator to generate at least one of the components? Currently, it happens that a number is not included in the generated password, or any of other types is left out. How to make it to generate at least of of the types?

        $scope.passwordLength = 12;
        $scope.addUpper       = true;
        $scope.addNumbers     = true;
        $scope.addSymbols     = true;

        $scope.createPassword = function(){
            var lowerCharacters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
            var upperCharacters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            var numbers = ['0','1','2','3','4','5','6','7','8','9'];
            var symbols = ['!', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'];
            var finalCharacters = lowerCharacters;
            if($scope.addUpper){
                finalCharacters = finalCharacters.concat(upperCharacters);
            }
            if($scope.addNumbers){
                finalCharacters = finalCharacters.concat(numbers);
            }
            if($scope.addSymbols){
                finalCharacters = finalCharacters.concat(symbols);
            }
            var passwordArray = [];
            for (var i = 1; i < $scope.passwordLength; i++) {
                passwordArray.push(finalCharacters[Math.floor(Math.random() * finalCharacters.length)]);
            };
            $scope.password = passwordArray.join("");
        };




generating large number of random variates

I'm trying to figure out the best way to generate many random numbers in python. The difficult part is that I won't know how many numbers I'll need before runtime

I have a program that uses random numbers one at a time, but it needs to do this many times.

The things I've tried so far are:

  • generate random numbers one at a time using random.random()
  • generate random numbers one at a time using np.random.rand()
  • generate random numbers in a batch of N using np.random.rand(N)
  • generate random numbers in a batch of N using np.random.rand(N) and make a new batch after the first N have all been used (I've tried two different implementations, and both are slower than just generating one number at a time)

In the following script, I compare these three methods (for both uniform and normally-distributed random numbers).

I don't know whether the p function is really necessary, but I wanted to do equivalent things with the random numbers in each case, and this seemed like the simplest way to do that.

#!/bin/python3

import time
import random
import numpy as np

def p(x):
    pass

def gRand(n):
    for i in range(n):
        p(random.gauss(0,1))

def gRandnp1(n):
    for i in range(n):
        p(np.random.randn())

def gRandnpN(n):
    rr=np.random.randn(n)
    for i in rr:
        p(i)

def uRand(n):
    for i in range(n):
        p(random.random())

def uRandnp1(n):
    for i in range(n):
        p(np.random.rand())

def uRandnpN(n):
    rr=np.random.rand(n)
    for i in rr:
        p(i)

tStart=[]
tEnd=[]
N=1000000
for f in [uRand, uRandnp1, uRandnpN]:
    tStart.append(time.time())
    f(N)
    tEnd.append(time.time())

for f in [gRand, gRandnp1, gRandnpN]:
    tStart.append(time.time())
    f(N)
    tEnd.append(time.time())

print(np.array(tEnd)-np.array(tStart))

A representative example of the output of this timing script is:
[ 0.26499939 0.45400381 0.19900227 1.57501364 0.49000382 0.23000193]
The first three numbers are for uniform random numbers on [0,1), and the next three are for normally-distributed numbers (mu=0, sigma=1).

For either type of random variate, the fastest method (of these three) is to generate all random numbers at once, store them in an array, and iterate over the array. The problem is that I won't know how many of these numbers I'll need until after I run the program.

What I'd like to do is generate the random numbers in large batches. Then when I use all the numbers in one batch, I'll just repopulate the object where they're stored. The problem is that I don't know of a clean way to implement this. One solution I came up with is the following:

N=1000000
numRepop=4
N1=N//numRepop
__rands__=[]
irand=-1

def repop():
    global __rands__
    __rands__=np.random.rand(N1)

repop()

def myRand():
    global irand
    try:
        irand += 1
        return __rands__[irand]
    except:
        irand=1
        repop()
        return __rands__[0]

but this is actually slower than any of the other options.

If I convert the numpy array to a list and then pop elements off, I get performance similar to just using numpy to generate random variates one at a time:

__r2__=[]

def repop2():
    global __r2__
    rr=np.random.rand(N1)
    __r2__=rr.tolist()

repop2()

def myRandb():
    try:
        return __r2__.pop()
    except:
        repop2()
        return __r2__.pop()

Is there a better way to do this?




Using SciPy or NumPy, how can sample experimental data be generated using a function?

Using ROOT, sample experimental data can be generated using a function in a way like the following:

histogram.FillRandom("gaus", 10000)

Here, 10,000 data points are generated using a Gaussian function and stored in a histogram.

How can something similar be done using SciPy or NumPy? Let's say I have a function defined and I want to use it to generate 10,000 sample experimental data points (obviously introducing noise) using it:

from __future__ import division

import numpy
import pyprel

def hardscaled_log_normal(
    x,
    mu      = 0.109695958342,
    sigma   = 1.32148811307,
    scale_x = 0.0137899935922,
    scale_y = 9.26895741647,
    ):

    return scale_y * 1 / (numpy.sqrt(2 * numpy.pi) * sigma * scale_x * x) *\
           numpy.exp(-abs(numpy.log(scale_x * x) - mu) ** 2/(2 * sigma ** 2))

data_x = [
    2.5,
    7.5,
    12.5,
    17.5,
    23.5,
    27.5,
    47.5,
    67.5,
    113.5,
    137.5,
    180,
    197.5
]

data_y = [hardscaled_log_normal(x) for x in data_x]

print(pyprel.Table(
    contents = [["x", "y"]] + [[x, y] for x, y in zip(data_x, data_y)]
))




How to generate random nextInt() without High value

How can I generate random integers who have to be greater than value 100 and no max value restriction?

For example:

int valueTwo = r.nextInt(1000-100)+100;

But my example have got max value 1000. Roughly speaking I need from 100 to infinity.




How to generate random numbers in C++ without using time as a seed

My program is supposed to generate random number with a fixed max of 9999. These numbers are used to create objects. Now the problem is when using time, if I create two objects one after the other both will be created with the same number (as time hasn't changed in the process). My question is hw can I do that more efficiently so I can generate a distinct random number everytime I run the program?

Thanks in advance !




php random price distribution with counter per day

There is going to be a competition code from following prices:

Page will refresh every 5 minutes or at a specific interval of time and it will pick any price either A, B or C to distribute for customers.

Type A - 400 total prices
Type B - 133 total prices
Type C - 100 total prices

Now, when the code runs, it will select randomly either from A, B or C and maximum prices will be as mentioned above.

How can I write this logic in CakePHP or PHP syntax.

Kindly suggest.




Random strings SQL

I'm doing a chart using data into my database in a C# program. I have a list of users and i want to display in pseudo random order.

I've tried this code

void Button1Click(object sender, EventArgs e)
    {
        Connessione.Open();
        MySqlDataAdapter SDA=new MySqlDataAdapter("SELECT RAND() concorrente, id FROM Classifiche WHERE taglia='small' AND categoria='agility'",Connessione);
        DataTable DATA= new DataTable();
        SDA.Fill(DATA);
        dataGridView1.DataSource=DATA; 
        Connessione.Close();
    }

In this case, though, the query show me random numbers instead random strings. How can I fix it?




How to generate n random numbers from a normal distribution using random-fu (Haskell)?

The question seems straightforward to me, yet I couldn't find easily an answer.

Lets say that you want to take a sample of size n from a normal distribution with mean 10 and variance 1 and then get their average and variance to verify that the sample is from a normal distribution.

It would be something like this, I suppose:

values = take n $ sample (normal 10 1)
(avg values, variance values)

I'm trying to use the library random-fu, so if you can provide an answer using that lib, I would really appreciate it.




mercredi 25 janvier 2017

Assigning a random number in C#

I am trying to create a single block Tetris style game in C# for school, in which the blocks are supposed to be assigned a number and when they are in line and add up to 10, they disappear. I have the basic code for the game worked out, but I can't seem to get the random numbers assigned to the blocks as they fall. Can anyone help?




Using util.Random for dice roll but getting constant pattern

My assignment is supposed to simulate a running total of a dice sum depending on how many dice are used and how many rolls the user wants. The sample output shows that the percentage of each sum occurring varies a lot, however, the frequency of mine are all around the same percentage. I'm not sure how to fix this.

    package project1;
   import java.util.Scanner;

   import java.util.Random;

 public class DiceStats {

public static void main(String[] args) {

    int diceCount;
    int rolls;
    int min;
    int max;

    // Ask user how many dice 
    System.out.print("How many dice will constitute one roll? ");
    Scanner dice = new Scanner(System.in);
    diceCount=dice.nextInt(); //store it into diceCount

     min = diceCount; //minimum sum
     max = diceCount*6; //maximum sum

    int[] diceSum = new int[max+1]; //initialize array size

    System.out.print("How many rolls? ");

    //Ask user how many rolls 
    Scanner roll = new Scanner(System.in);
    rolls=roll.nextInt();

    Random sum= new Random(); //random sum generator

    System.out.printf("\n%s%10s%10s\n", "Sum", "     # of times", "     Percentage");

    //for loop to sum up # of times
    for (int i =1; i<= rolls; i++)
    {
        ++diceSum[sum.nextInt((max-min)+1)+min];
    }


    //for loop to print out: sum, # of times, and percentage    
    for (int i = min;i <= (diceSum.length-1); i++)
    {
        double percentage = (double)diceSum[i]/rolls;
        System.out.printf("%d          %d         %.2f%%\n", i,   diceSum[i],percentage*100);

    }


} 

}

This is how my program is being outputted: my output

EDIT: This is the sample output I am comparing mine to: sample output




Is there a way with Rails/Postgres to get records in a random order BUT place certain values first?

I have an app that returns a bunch of records in a list in a random order with some pagination. For this, I save a seed value (so that refreshing the page will return the list in the same order again) and then use .order('random()').

However, say that out of 100 records, I have 10 records that have a preferred_level = 1 while all the other 90 records have preferred_level = 0.

Is there some way that I can place the preferred_level = 1 records first but still keep everything randomized?

For example, I have [A,1],[X,0],[Y,0],[Z,0],[B,1],[C,1],[W,0] and I hope I would get back something like [B,1],[A,1],[C,1],[Z,0],[X,0],[Y,0],[W,0].

Note that even the ones with preferred_level = 1 are randomized within themselves, just that they come before all the 0 records. In theory, I would hope whatever solution would place preferred_level = 2 before the 1 records if I were ever to add them.

------------

I had hoped it would be as intuitively simple as Model.all.order('random()').order('preferred_level DESC') but that doesn't seem to be the case. The second order doesn't seem to affect anything.

Any help would be appreciated!




Hidden cheat code to test game Ruby

In Ruby, how do I add a hidden cheat to my game to display the random number already generated to test it?

def generate_number

return randomNo = 1 + rand(1000)

end

def play_game

    $noOfGuesses=0 
    $gameCount+=1 


number = generate_number 
cheat = [number]




unkown error in arc4random_uniform()

These lines were working with me for 3 days, suddenly it made an error and xcode generated a breakpoint.

The breakpoint appears beside randonTop variable.

Error called bad instruction.

here is my code:

let top = self.frame.maxY
        let bottom = self.frame.minY
        let right = self.frame.maxX
        let left = self.frame.minX
        // getting position
        var position: CGPoint!
        switch edge {
        case "top":
            let randomTop = arc4random_uniform(UInt32((right - left) + 1) + UInt32(left))
            position = CGPoint(x: CGFloat(randomTop), y: top + (globalRadius + (globalRadius * 0.5)))
            break

help please.




generating random numbers with mt19937_64 for multithread monte carlo simulation

I am running a monte carlo simulation on multiple threads. I have a Draw class which handles random number generation. It uses mt19937-64 as the generator of std::uniform_real_distribution.

template<typename T, typename R>
class Draw {
    T _dist;
    typedef decltype(_dist.min()) result_type;

    public:
    // Draw : T R -> Draw
    //! GIVEN
    //!   1. dist - A distribution.
    //!   2. gen - A random number generator.
    Draw(T dist, R gen) : _dist(dist), _gen(gen) {}

    virtual ~Draw() = default;

    // () : -> Value
    //! GIVEN
    //! RETURNS
    //! value drawn from the distribution, which can be any result type
    //!   supported by the distribution.
    result_type operator()() const { return _draw(); }

    // seed : NonNegInt -> Void
    //! GIVEN
    //!   1. seed - A random number generator (RNG) seed.
    //! EFFECT
    //!   Seeds the RNG with the given seed.
    void seed(unsigned long seed) { _gen.seed(seed);}

    private:
    R _gen;

    // draw : -> Value
    // GIVEN:
    // RETURNS: A value drawn from the distribution, which can be any result
    //          type supported by the distribution.
    std::function<result_type()> _draw = bind(_dist,_gen);
};

// standard uniform distribution ~ Unif(a=0, b=1)
class DrawUnif :
public Draw<std::uniform_real_distribution<double>,std::mt19937_64>
{
    typedef std::mt19937_64 genny;
    typedef std::chrono::system_clock clk;
    typedef std::uniform_real_distribution<double> dist;

    public:
    DrawUnif() :
      Draw(dist{0,1}, genny(clk::now().time_since_epoch().count())) {}

    //! GIVEN
    //! -----
    //!   1. seed - A seed for the random number generator.
    DrawUnif(unsigned long seed) : Draw(dist{0,1}, genny(seed)) {}

     virtual ~DrawUnif() = default;
};

Each thread has access to the following shared pointer

  typedef std::shared_ptr<DrawUnif> DrawUnifShrPtr;
  DrawUnifShrPtr    _unif;

Which is initialized by

_unif(DrawUnifShrPtr(new DrawUnif { seed }));

Each thread has several functions which frequently call draw(*_unif) to generate a random number. The results seem correct but I am wondering if two threads call

draw(*_unif) 

at the same time, what would happen?

Then I allocated a new shared_pointer with different seed to each cohort:

 _unif(std::make_shared<DrawUnif>(*c._unif));
 _unif->seed(a_new_seed);

Now the results look wiered! Each thread is getting exact same random!! numbers and provide exact same result. To summarize:

1- what would happen if multiple treads call the draw at the same time?

2- Why different seeds get exact same results.

Thank you




Bootstrap resampling of data using python with upper limit for the occurrence of each point

I would like to measure the uncertainty of a method using the bootstrap resampling. I have 200 data points which I'd like to use for resampling. What is the fastest way that I can resample these data points? I have some pre-requirements such as I would like that the same data point would not repeat in the bootstrap sample more than two times and less than 7 points would get replaced in total. It is very important in my case since the structure of data points get changed drastically.

The speed of resampling process is also very crucial because I would like to repeat both resampling and the measurements of a method more than 5000 times.

Currently, I am doing as following which is very slow and not practical at all:

from collections import Counter

SeqNr=np.arange(cat.shape[0])
np.random.choice(SeqNr,size=cat.shape[0])
maximum=max(Counter(L).values())
occurrence=Counter(L).values().count(2)

where cat contains the numpy array of data and this is inside a while loop to force it to follow aforementioned conditions. I will appreciate if someone recommends a faster approach.




Random numbers between applications

Is it possible for 2 applications (a server and a client) to generate the same sequence of random numbers? What I need is this:

On server:

i1:=randomrange(10,50); //i1 will be 15
i2:=randomrange(10,50); //i2 will be 40
i3:=randomrange(10,50); //i3 will be 20

On client:

i1:=randomrange(10,50); //i1 will be 15
i2:=randomrange(10,50); //i2 will be 40
i3:=randomrange(10,50); //i3 will be 20

The sequence needs to be dependent of a value that the server calculates and sends it to the client




How do I create band-limited (100-640 Hz) white Gaussian noise?

I would like to create 500 ms of band-limited (100-640 Hz) white Gaussian noise with a (relatively) flat frequency spectrum. The noise should be normally distributed with mean = ~0 and 99.7% of values between ± 2 (i.e. standard deviation = 2/3). My sample rate is 1280 Hz; thus, a new amplitude is generated for each frame.

duration  = 500e-3;
rate      = 1280;
amplitude = 2;

npoints   = duration * rate;
noise     = (amplitude/3)* randn( 1, npoints ); 
% Gaus distributed white noise; mean = ~0; 99.7% of amplitudes between ± 2.
time      = (0:npoints-1) / rate

Could somebody please show me how to filter the signal for the desired result (i.e. 100-640 Hz)? In addition, I was hoping somebody could also show me how to generate a graph to illustrate that the frequency spectrum is indeed flat.

I intend on importing the waveform to Signal (CED) to output as a form of transcranial electrical stimulation.




Converting Ruby script to Batch file

I have ruby code that is supposed to create number of different files with some text inside. Exactly one of the files will have different text inside and nobody is supposed to know what file it is (kind of like a random card draw in group of people). It works really nice in ruby like this:

foo = "sample_text_A"
bar = "sample_text_B"
randomizer = [foo]
def create_file(i, text)
  File.open("file_name_#{i}.txt", "w") do |f|
    f.write(text)
  end
end
def randomize(count, text, randomizer)
  i = 0
  (count-1).times do
    randomizer << text
  end
  (count-1).times do
    i += 1
    sample_text = randomizer.delete_at(rand(randomizer.length))
    create_file(i, sample_text)
  end
end
randomize(4, bar, randomizer)

However, I now need to distribute this to number of people and I don't want them to be forced to install anything. So I figured it would be better distributed as a batch file (as far as I know, everyone of them runs Win). I am new to programming, often stumbling even with Ruby, so I wanted to ask for assistance, if anyone would be so kind and wrote similar thing as a .bat




How do I randomise the order of buttons for a Quiz in VB.NET?

So I am currently working on a little project where I am making a quiz in VB. I'm still fairly intermediate so this has been a good project for me to work on so far. I am trying to make it so that the answers (which are written on buttons) are randomised each time. So let's say, the third button isn't always the correct answer.

Currently, my code works as follows. Below is a function to generate a random number from 1-4 in an array and checks there are no repeats. So the array may read arraytofill(3,2,4,1) etc.

 Function RandomNumbers()
    Dim r As New Random
    Dim numfilled As Integer = 1
    Dim arraytofill(4) As Integer
    Dim rnumber As Integer = r.Next(1, 5)
    Dim found = False

    While numfilled < 5 'creating 5 numbers
        rnumber = r.Next(1, 5) 'generate numbers
        For i = 1 To numfilled

            If arraytofill(i) = rnumber Then
                found = True 'there is a repeated number

            End If
        Next

        If found = False Then
            arraytofill(numfilled) = rnumber
            numfilled = numfilled + 1 'add to array and go to next cycle
        Else
            found = False
        End If
    End While

    Return arraytofill
End Function

Then there is the code to ask the questions. The user can pick from as many as 14 categories and each category has 5 questions inside of it.

 Sub NextQuestion()
Dim rnumbers() As Integer
rnumbers() = RandomNumbers()
    buttons = {Answer1Btn, Answer1Btn, Answer2Btn, Answer3Btn, Answer4Btn}

 If questionsincategory <> 5 Then
questionsincategory = questionsincategory + 1
    nQuestion = nQuestion + 1

    QuestionTxtBox.Text = TestQuestions(nQuestion).question
    ButtonArray(rnumbers(1)).Text = TestQuestions(nQuestion).answer1
    ButtonArray(rnumbers(2)).Text = TestQuestions(nQuestion).answer2
    ButtonArray(rnumbers(3)).Text = TestQuestions(nQuestion).answer3
    ButtonArray(rnumbers(4)).Text = TestQuestions(nQuestion).correct
    CurrentCatBox.Text = "The Current Category is: " & TestQuestions(nQuestion).category

    t = t + 1
    QuestionNumTxtBox.Text = "Question " & t & "/" & num * 5
 Else

    ' are there anymore categories?
    questionsincategory = 1
    categorycounter = categorycounter + 1
    If categorycounter < num Then
        'there is at least 1 more category

        For j = nQuestion To 65 'I have 65 questions loaded into the program from a file


            If TestQuestions(j).category = choices(categorycounter) Then
                'outputs question here
                Dim rnumbers() As Integer = RandomNumbers()
                Dim ButtonArray() As Control = {Answer1Btn, Answer1Btn, Answer2Btn, Answer3Btn, Answer4Btn}

                QuestionTxtBox.Text = TestQuestions(j).question
                ButtonArray(rnumbers(1)).Text = TestQuestions(j).answer1
                ButtonArray(rnumbers(2)).Text = TestQuestions(j).answer2
                ButtonArray(rnumbers(3)).Text = TestQuestions(j).answer3
                ButtonArray(rnumbers(4)).Text = TestQuestions(j).correct
                nQuestion = j

                CurrentCatBox.Text = "The Current Category is: " & TestQuestions(j).category
                t = t + 1
                QuestionNumTxtBox.Text = "Question " & t & "/" & num * 5

                'leave for loop to prevent further questions appearing
                Exit For
            End If
        Next
    Else
        'output score and close form
        MessageBox.Show("You scored " & QuizPoints & " points out of " & num * 5)
        MyConnection() 'connect to database and email results
        EmailResults()
    End If
    End If
End Sub

At the moment, when the code runs, it does not randomise the order of the buttons- despite the arraytofill() being correctly randomly ordered when I step through it. The code works like it did before I implemented the random sorting, which is strange to me. Is it not identifying the index correctly?

This is my first time posting on here so I hope I have made myself clear and understandable. Your guidance is very much appreciated.