lundi 31 juillet 2017

Generate random results every time in mySQL

I have read multiple articles int he forum those were really helpful however does not help me in achieving my target.

I want to generate a random number every time I query, with the query suggested "SELECT myUnique_id from My_table where EID = '1234' and entry_date = '2017-08-01' order by rand()"

Generates same number every time I run this query, but I want to change the number every time the query is executed.

Please help.




Sequentially re-ordering sections of a vector around NA values

I have a large set of data that I want to reorder in groups of twelve using the sample() function in R to generate randomised data sets with which I can carry out a permutation test. However, this data has NA characters where data could not be collected and I would like them to stay in their respective original positions when the data is shuffled.

With help on a previous question I have managed to shuffle the data around the NA values for a single vector of 24 values with the code:

    example.data <- c(0.33, 0.12, NA, 0.25, 0.47, 0.83, 0.90, 0.64, NA, NA, 1.00, 0.42)

    example.data[!is.na(example.data)] <- sample(example.data[!is.na(example.data)], replace = F, prob = NULL)

[1] 0.64  0.83  NA  0.33  0.47  0.90  0.25  0.12  NA  NA  0.42  1.00

Extending from this, if I have a set of data with a length of 24 how would I go about re-ordering the first and second set of 12 values as individual cases in a loop?

For example, a vector extending from the first example:

example.data <- c(0.33, 0.12, NA, 0.25, 0.47, 0.83, 0.90, 0.64, NA, NA, 1.00, 0.42, 0.73, NA, 0.56, 0.12, 1.0, 0.47, NA, 0.62, NA, 0.98, NA, 0.05)

Where example.data[1:12] and example.data[13:24] are shuffled separately within their own respective groups around their NA values.

The code I am trying to work this solution into is as follows:

shuffle.data = function(input.data,nr,ns){
simdata <- input.data
  for(i in 1:nr){
    start.row <- (ns*(i-1))+1
    end.row   <- start.row + actual.length[i] - 1
    newdata = sample(input.data[start.row:end.row], size=actual.length[i], replace=F)
    simdata[start.row:end.row] <- newdata
      }
return(simdata)}

Where input.data is the raw input data (example.data); nr is the number of groups (2), ns is the size of each sample (12); and actual.length is the length of each group exluding NAs stored in a vector (actual.length <- c(9, 8) for the example above).

Would anyone know how to go about achieving this?

Thank you again for your help!




Generating random numbers in C++ using std::random_device

I generate random numbers in C++ using the following piece of code

std::random_device rdev {};
std::default_random_engine generator {rdev()};
std::uniform_int_distribution dist {a, b};

Similarly

std::default_random_engine generator {std::random_device{}()};
std::uniform_int_distribution dist {a, b};

What i'm trying to understand is the mechanics behind generating an engine using a seed value. random_device obtains a seed using various information from your operating system. This value is used to initialize an engine object. For the first snippet of code presented here, if rdev is an object, why do we pass in that value in to the engine as rdev(). Why are we using function notation on an object of a class ?

For the second snippet of code, how are we able to generate a std::random_device object by just using the class name?

I'm not sure if my issue in understanding this is specific to random number generation or something bigger involving the C++ language itself.




Unresolved symbols and types while using HashDRBG from libgcrypt in C

I have a problem using the HashDRBG from libgcrypt. My goal is to get some random data from a seed:

outbuf <--- DRBG_HASHSHA512(seed)

The only option I've seen so far is using libgrypt: (http://ift.tt/2vlZkxb)

Regarding the instructions, I have to use something like:

gcry_control(GCRYCTL_DRBG_REINIT, DRBG_NOPR_CTRAES128, NULL);

to initialize it depending on the DRBG type. But I always get the error: "Symbol 'DRBG_NOPR_CTRAES128' could not be resolved". The same with other DRBG types.

As well as "Type 'drbg_string_t' could not be resolved", when I want to use the additional information string. I have gcrypt.h included and the libraries linked with libgcrypt-config --cflags --libs.

The generation of the random stream should then be done by:

gcry_randomize(outbuf, OUTLEN, GCRY_STRONG_RANDOM);

This function call worked at least for the default parameters.

Has anybody an idea on how to enable these missing functionalities? Thank you.




How to return one or more items from a list?

Currently my code returns the name of the client and a random value from visit_length. I would like it to return the client name and then one or more of the elements from visit_length ie. ("Client 1", 15, 45), ("Client 2", 45, 60), ("Client 3", 30)

N = 20      
randomitems = []
visit_length = [15, 30, 45, 60]
value_range = np.arange(0, N, 1)

for i in value_range:
    visits = ("Client %d" % i, random.choice(visit_length))
    randomitems.append(visits)

Any suggestions? I thought there might be something in the random library but I haven't found anything yet.

Thank you!




Randomize radio button in android [duplicate]

This question already has an answer here:

I want to randomize the radio button. In my radio button 4 options are there choice1 choice2 choice3 and the answer by default I have set the answer as fix now, I want to shuffle so it will check directly and can calculate score

Here is the code what I have done till now. Radio button values are getting randomize not radio button. All 4 radio button are in radio group Suggest some solution or any other idea

Code

            choice1 =(exp.getString("choice1")); 
            choice2 =(exp.getString("choice2")); 
            choice3 =(exp.getString("choice3")); 
            answer =(exp.getString("answer")); 

            ropt0.setText("" + choice1); 
            ropt1.setText("" + choice2); 
            ropt2.setText("" + choice3); 
            ranswer.setText("" + answer);

            ArrayList<String> arrayText = new ArrayList<>(); 

            arrayText.add(choice1); 
            arrayText.add(choice2); 
            arrayText.add(choice3); 
            arrayText.add(answer); 

            Collections.shuffle(arrayText);

            for (int j = 0; j < rdgrp.getChildCount(); j++) { 
                RadioButton rb = (RadioButton) rdgrp.getChildAt(j); 
                rb.setText(arrayText.get(j)); 
                }




How to add an offset to simplex noise?

I am working on a small summer project and this project got me into procedurally generated terrain for the first time. So I found this code online and it worked pretty well.

Code: `

import java.util.Random;

public class SimplexNoise {

/** Source of entropy */
private Random rand_;

/** Amount of roughness */
float roughness_;

/** Plasma fractal grid */
private float[][] grid_;

private int Xoffset_, Yoffset_;

/**
 * Generate a noise source based upon the midpoint displacement fractal.
 * 
 * @param rand
 *            The random number generator
 * @param roughness
 *            a roughness parameter
 * @param width
 *            the width of the grid
 * @param height
 *            the height of the grid
 */
public SimplexNoise(Random rand, float roughness, int width, int height) {
    roughness_ = roughness / width;
    grid_ = new float[width][height];
    rand_ = (rand == null) ? new Random() : rand;
}

public void initialise() {
    int xh = grid_.length - 1;
    int yh = grid_[0].length - 1;

    // set the corner points
    grid_[0][0] = rand_.nextFloat() - 0.5f;
    grid_[0][yh] = rand_.nextFloat() - 0.5f;
    grid_[xh][0] = rand_.nextFloat() - 0.5f;
    grid_[xh][yh] = rand_.nextFloat() - 0.5f;

    // generate the fractal
    generate(0, 0, xh, yh);
}

// Add a suitable amount of random displacement to a point
private float roughen(float v, int l, int h) {
    return v + roughness_ * (float) (rand_.nextGaussian() * (h - l));
}

// generate the fractal
private void generate(int xl, int yl, int xh, int yh) {
    int xm = (xl + xh) / 2;
    int ym = (yl + yh) / 2;
    if ((xl == xm) && (yl == ym))
        return;

    grid_[xm][yl] = 0.5f * (grid_[xl][yl] + grid_[xh][yl] );
    grid_[xm][yh] = 0.5f * (grid_[xl][yh] + grid_[xh][yh] );
    grid_[xl][ym] = 0.5f * (grid_[xl][yl] + grid_[xl][yh]) ;
    grid_[xh][ym] = 0.5f * (grid_[xh][yl] + grid_[xh][yh]) ;

    float v = roughen(0.5f * (grid_[xm][yl] + grid_[xm][yh]), xl + yl, yh + xh);
    grid_[xm][ym] = v;
    grid_[xm][yl] = roughen(grid_[xm][yl], xl, xh);
    grid_[xm][yh] = roughen(grid_[xm][yh], xl, xh);
    grid_[xl][ym] = roughen(grid_[xl][ym], yl, yh);
    grid_[xh][ym] = roughen(grid_[xh][ym], yl, yh);

    generate(xl, yl, xm, ym);
    generate(xm, yl, xh, ym);
    generate(xl, ym, xm, yh);
    generate(xm, ym, xh, yh);
}

/**
 * Dump out as a CSV
 */
public void printAsCSV() {
    for (int i = 0; i < grid_.length; i++) {
        for (int j = 0; j < grid_[0].length; j++) {
            System.out.print(grid_[i][j]);
            System.out.print(",");
        }
        System.out.println();
    }
}

/**
 * Convert to a Boolean array
 * 
 * @return the boolean array
 */
public boolean[][] toBooleans() {
    int w = grid_.length;
    int h = grid_[0].length;
    boolean[][] ret = new boolean[w][h];
    for (int i = 0; i < w; i++) {
        for (int j = 0; j < h; j++) {
            ret[i][j] = grid_[i][j] < 0;
        }
    }
    return ret;
}

public float[][] getGrid_() {
    return grid_;
}




}`

But then I wanted to generate the next chunk so I thought I will have to add some kind of offset somewhere in the noise generation to create the float[][] that would be next to my initial Chunk. Each Chunk has an xID and a yID those tell the renderer where to draw the tiles that are in the chunk. So when the xID and the yID are 0 the tiles will draw from X = 0,Y = 0 till X = 3200, Y = 3200. (Each chunk is 100*100 tiles and each tile is 32*32 pixel). I think the Offset would be the location of the chunk I want to generate so when I want to generate Chunk(1, 0) it would be offsetX = (1 * 3200) and offsetY = (0 * 3200). But where should I add this values? I thought here at first but after re thinking it I saw that it would not work cause that wil cause an ArrayOutOfBounds Exception.

here: int xm = (xl + xh) / 2 + offsetX; int ym = (yl + yh) / 2 + offsetY;

Here are some of my notes (I know my handwriting is awful)ABCD is my initial chunk and BEDF is the chunk that I want to generate.

Notes

So can anyone explain to me how I am going to do this?

(English is not my main language).




Generate random integer between two ranges

I want to get a random number between (65,90) and (97,122) range. I can select random number in range using

import random
random.randint(65,95)

but radiant take the only integer so how can I do?? any idea

Thanks in advance




How to generate random string?

I'm super new in Python coding or i mean every coding. I just want to ask that like taking random number from: Random.randint(a, b)

I just want to ask that how to take random string just like randint but this time with random string. Is there anyway?

Please help me. I'm new in this world and Sorry for my bad english.

#This program will play a little game

import random

a = ''
b = ''
c = ''
d = ''
e = ''
f = ''

print('Hi. Please enter your name in letters')
name = str(input())
print('Hi ' + name + '. I am going to play a little game. In this game you have to guess a specific name i am thinking right now.')
print('But do not worry. I am going to let you to enter 6 names and i will choose one of them.')
print('After that you have to answer the correct name that i am thinking right now')
print('Please enter the first name in letters')
name1 = str(input())
print('Please enter the second name in letters')
name2 = str(input())
print('Please enter the third name in letters')
name3 = str(input())
print('Please enter the fourth name in letters')
name4 = str(input())
print('Please enter the fifth name in letters')
name5 = str(input())
print('Please enter the sixth name in letters')
name6 = str(input())
name1 = a
name2 = b
name3 = c
name4 = d
name5 = e
name6 = f

print('Alright ' + name + ' . Thank you for entering the names.')
secretname = random.randint(a, f)
for i in range(2):
        print('Now enter the name that i am thinking of.')
        ans = str(input())
        if ans != secretname:
                print('Wrong. Guess another name')

if ans == secretname:
        print('Good job ' + name)
else:
        print('Wrong. The name i was thinking of was ' + secretname)

This is a little game which request from you to enter 6 names and then the game will guess a number between those 6 numbers you have entered but it always gaves me an error. So.. please help me. I want to do it with random string. Help!




dimanche 30 juillet 2017

Indexing the 2 D matrices with the help of one more dimension

If there is code for a random matrix A of m*n dimension using forward space forward time finite difference method i.e.

A(i+1,j ) = some function of (A(i,j)+rand(i,j))

Since A is now random matrix, so to each different run we will get definitely different matrix. So to resolve this, I want to find at least 1000 A matrix, and then I will take average of all and so the new matrix can be considered as the expected matrix. But I am unable to create Matlab code for this. Please help




Get percentage unique numbers generated by random generator

I am using random generator in my code. I want to get the percentage of unique random numbers generated over a huge range like from random(0:10^8). What could be the efficient algorithm in terms of space complexity?




Generate a random number betwen two numbers

I wrote the a procedure bellow:

DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`root`@`localhost` PROCEDURE `numerodasorte` (IN `id` INT, IN `cupons` INT)  begin

declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;

  while v_counter < cupons do
  INSERT INTO numerosorte (cupons_idcupons,numero) VALUES(id,
    (SELECT random_num  FROM ( SELECT floor(100000+RAND()*(599999-100000)) AS random_num ) AS numbers_mst_plus_1 WHERE random_num NOT IN (SELECT numero FROM cupons WHERE numero IS NOT NULL) LIMIT 1)) ;
    /*
    INSERT INTO numerosorte(cupons_idcupons,numero) VALUES(id,numero);
    */
    set v_counter = v_counter + 1;
  end while;
SELECT cupons_idcupons,numero FROM numerosorte WHERE cupons_idcupons=id;

end$$

Based on this post:

How to Generate Random number without repeat in database using PHP?

but when i run this[ SET @p0='6'; SET @p1='200'; CALL numerodasorte(@p0, @p1); ] , sometimes, i get this error:

1062 - Duplicated entry '27397' for key 'numero_UNIQUE'

Someone have any ideia whats is happening?




Random string generation that's URL friendly and isn't hex

Here's the code I'm using to generate some small random keys but I want to include the rest of the English alphabet not just A-F that gets generated using hex.

I've tried a few encodings but they all include many more characters than I want and are not url friendly.

The below works fine I am just curious on how to solve this.

byte[] bytes = new byte[4];
using (var rng = RandomNumberGenerator.Create())
{
    rng.GetBytes(bytes);
}
string key = string.Join("", bytes.Select(b => b.ToString("X2")));




quick-pick a random file from a tree of 15 thousand files

I found this code for picking a random file but it is way too slow, taking a minute or few to run through every file (15000+ files):

setlocal EnableDelayedExpansion
cd /d "%~1"
set n=0
for /r %%f in (*.*) do (
   set /A n+=1
   set "file[!n!]=%%f"
)
set /A "rand=(n*%random%)/32768+1"

echo "!file[%rand%]!"

I need a way faster solution here.




Php rastgele sayı üretme kodu

Aşağıda ki kod bloğu çalışıyor fakat anlamadığım yer, benim rastgele harf fonksiyonuna gönderdiğim parametreyi substr fonksiyonunda kullanmadığı halde doğru çalışıyor, fonksiyona gönderdiğim karakterde kelime oluşturuyor. Nasıl yapıyor bunu?

    function rasgeleharf($kackarakter) 
    { 
    $char= "abcdefghijklmnopqrstuvwxyz"; /// İzin verilen karakterler ? 
    for ($k=1;$k<=$kackarakter;$k++) 
    { 
    $h=substr($char,mt_rand(0,strlen($char)-1),1); 
    $s.=$h; 
    } 
    echo $s."<br>"; 
    return $s; 
    }  

    for($i = 0; $i < 5000; $i++){

    rasgeleharf(5)  ;
    }




How to associate an text to image in Javascript?

I have a simple question to be asked here . I have created a working random generator at here :

var randPics = document.querySelector("#randPics");
var getPics = document.querySelector(".getPics");


getPics.addEventListener("click", function(){ 
//array to store images for the random image generator
var picsGallery = new Array();
    picsGallery = ["http://ift.tt/2eZ59td",
"http://ift.tt/2hdSUtw",
 "http://ift.tt/2eZ5axh"]
 
 //generate random no to select the random images
var rnd = Math.floor(Math.random() * picsGallery.length);
//change the pics locations of the source
  randPics.src=picsGallery[rnd]
  });
#randPics{
        width: 300px;
        height: 300px;
        align-content: center;
}
<body>
<p>Display a random image each time the buttons is clicked!</p>
<p> You get a <span id="text"></span>  </p>

<button class="getPics"> Click ! </button>
<br>
<img id="randPics" src="http://ift.tt/2sNEalD">

</body>

When user clicked on the button, the image source will randomly select one of the images in the array. However, I have a tiny bit of problem. How do I associate text to the images ? For example , if the user click the button and he get the images of pen , the text

You get a

should change to

You get a pen.

Thank you for your help !




How to generate a duplicate random number sequence between SystemVerilog simulators?

I cowork a SystemVerilog project with someone. However, I am used to use Synopsys VCS SystemVerilog simulator and he is used to use Cadence INCISIVE irun.

One testbench module uses random numbers for generating test input pattern to top design module. Thus, I designed a class for generating random numbers:

class RandData;
    rand logic [3:0] randIn;
    function new(int seed);
        this.srandom(seed);
    endfunction
endclass

I can instantiate class RandData with a seed and get a fixed sequence of random numbers in simulations. However, the fixed random number sequence obtained by VCS is different from the fixed sequence by irun even if the same seed is used in two simulators.

Unfortunately, the golden output pattern of the top design module depends on the test input pattern. Thus, if a golden output pattern is generated with an input pattern generated by VCS, the golden output pattern will be mismatched to the top design output simulated by irun.

Thus, how can I make VCS and irun simulators generate a duplicate sequence of random numbers?




MySQL: Copy Multiple Values from random row of another table

I have asked similar questions for Microsoft SQL Server and for PostGresql. Solutions which work there don’t work for MySQL.

I have two tables, stuff and nonsense. I would like to copy multiple values from a random row in nonsense to each row in stuff. Of course, there will be duplicates.

STUFF
+----+---------+-------------+--------+
| id | details | data        | more   |
+====+=========+=============+========+
| 1  | one     | (null)      | (null) |
+----+---------+-------------+--------+
| 2  | two     | (null)      | (null) |
+----+---------+-------------+--------+
| 3  | three   | (null)      | (null) |
+----+---------+-------------+--------+
| 4  | four    | (null)      | (null) |
+----+---------+-------------+--------+
| 5  | five    | (null)      | (null) |
+----+---------+-------------+--------+
| 6  | six     | (null)      | (null) |
+----+---------+-------------+--------+

NONSENSE
+----+---------+-------------+
| id | data    | more        |
+====+=========+=============+
| 1  | apple   | accordion   |
+----+---------+-------------+
| 2  | banana  | banjo       |
+----+---------+-------------+
| 3  | cherry  | cor anglais |
+----+---------+-------------+

I would like to be able to copy into the stuff table with something like:

UPDATE stuff SET data=?,more=?
FROM ?

If it were a single value, I could use a correlated subquery, but it won’t work properly for multiple values from the same row.

Newer PostGresql has the ability to copy into multiple columns from a correlated subquery. SQL Server the OUTER APPLY clause which allows a subquery in the FROM clause to be correlated. Neither approach works for MySQL.

How can I copy multiple values from random rows in another table?




Random posts but with some factors to effect the order in php

I will be happy to get some code snippets, but the question is more of a "direction / ideas" question so fill free to write ideas without the practical specific way to construct them:

What i need is:

Take a random (completely random) posts array that comes from Wordpress's wp_query function and add some tweaks to it.

The posts are actually freelancers from different professions and i want some values to effect there order. so for example: a freelancer with more experience will be "pulled" a little bit higher in the list, a freelancer that attached more media to his "ticket" will be "pulled" a little bit higher in the list and so on...

But i want to be able to still maintain the "randomness" of the list. so generally pull some posts higher by different factors but still make it random so no page refresh will have the same order.

So it will be as if there is some "low gravity posts" inside the general "chaos" :)




(C# 'Random' is a namespace but is used like a variable) I don't understand why

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Welcome To The Random.");    
        System.Threading.Thread.Sleep(1000);

        choosing:

        Console.WriteLine("Roll Standard Dice (D), Flip a Coin (2), 8-Ball (8), or Random Number 1-10 (R)");

        ConsoleKeyInfo result = Console.ReadKey();    
        if ((result.KeyChar == 'D') || (result.KeyChar == 'd'))
        {
            Console.WriteLine("Standard Dice Has been chosen, do you want to continue? Y/N");    
            ConsoleKeyInfo RSD = Console.ReadKey();

            if ((RSD.KeyChar == 'Y') || (RSD.KeyChar == 'y'))
            {
                Console.Write("Rolling");    
                Console.Write(".");    
                Console.Write(".");    
                Console.Write(".");    
            }
            else if ((RSD.KeyChar == 'N') || (RSD.KeyChar == 'n'))
            {
                Console.Clear();
                goto choosing;
            }
        }
        else if ((result.KeyChar == '2'))
        {
            Console.WriteLine("I wont do anything");
        }
        else if ((result.KeyChar == '8'))
        {
        }
        else if ((result.KeyChar == 'R') || (result.KeyChar == 'r'))
        {
        }

        *Random* rnd = new *Random*();
    }
}

The parts in asterix are the part where it is a red line and it says Random is a namespace but it's used like a variable. The Random thing normally works but I'm not sure why it isn't working now if you could please help me that would be appreciated.




Python random.randint() keeps returning 0 after certain time

I was trying to get 3 random numbers within range in python without replacement. I did this

rand_lst = []

while(True):
    rand = random.randint(0, length-1 )
    if(len(rand_lst) == 3):
         break
    if(rand not in rand_lst):
         rand_lst.append(rand)

This code is inside a for loop. This returns only 0 and thus an infinite loop. I also tried numpy.random.randint but some how random is keeping track of previously generated numbers and I endup with value error.




samedi 29 juillet 2017

Flaws in science/engineering/software due to pseudo random generation?

I am trying to see if there were any incidents in the past where using PRNG or not accurate randomness scheme leaded to wrong conclusion in research.

For example, a lot of fields today use simulations to predict natural science results and I was wondering what are the best practices and if there were any flaws due to bad randomness in the past.

For security purposes it's clear that one has to use encrypt lib random function, but for science or simulation of physical systems I am not sure it's the case. My guts say it should be the same, but I am not sure how to justify it.




PostGresql: Copy data from a random row of another table

I have two tables, stuff and nonsense.

create table stuff(
    id serial primary key,
    details varchar,
    data varchar,
    more varchar
);
create table nonsense (
    id serial primary key,
    data varchar,
    more varchar
);

insert into stuff(details) values
    ('one'),('two'),('three'),('four'),('five'),('six');
insert into nonsense(data,more) values
    ('apple','accordion'),('banana','banjo'),('cherry','cor anglais');

See http://ift.tt/2hcKUJj

I would like to copy random values from nonsense to stuff. I can do this for a single value using the answer to my previous question: SQL Server Copy Random data from one table to another:

update stuff
set data=(select data from nonsense where stuff.id=stuff.id
    order by random() limit 1);

However, I would like to copy more than one value (data and more) from the same row, and the sub query won’t let me do that, of course.

I Microsoft SQL, I can use the following:

update stuff
set data=sq.town,more=sq.state
from stuff s outer apply
    (select top 1 * from nonsense where s.id=s.id order by newid()) sq

I have read that PostGresql uses something like LEFT JOIN LATERAL instead of OUTER APPPLY, but simply substituting doesn’t work for me.

How can I update with multiple values from a random row of another table?




How to generate list of unique random floats in Python

I know that there are easy ways to generate lists of unique random integers (e.g. random.sample(range(1, 100), 10)).

I wonder, whether there is some better way of generating a list of unique random floats, apart from writing a function that acts like range, but accepts floats like this:

import random

def float_range(start, stop, step):
    vals = []
    i = 0
    current_val = start
    while current_val < stop:
        vals.append(current_val)
        i += 1
        current_val = start + i * step
    return vals

unique_floats = random.sample(float_range(0, 2, 0.2), 3)

There must be a better way.




Why does my compiler give me some things one time and others another time without me changing the code

Using my previous question's code I have one question. Why does my compiler: http://www.browxy.com/ sometimes say what I want it to:

Amount of Players total: 11
Amount of Players going up against you: 5
Your team: team2

And other times say:

Amount of Players total: 7
Amount of Players going up against you: 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Game.main(Game.java:110)

If it helps, all of my code is here:

import java.util.Random;

public class Game {
public static void main(String[] args) {
Random m = new Random();
int b;
b = m.nextInt(12);
if (b >= 6) {
  b = b;
} else {
  b = b + 6;
}
int a = b;
int d;
d = m.nextInt(1);
int playerAmount = a;
int c = playerAmount / 2 + d;
System.out.println("Amount of Players total: " + playerAmount);
System.out.println("Amount of Players going up against you: " + c);
int blur;
blur = m.nextInt(3);
int cdp;
cdp = m.nextInt(3);
int red;
red = m.nextInt(3);
if (blur == 0) {
  blur = blur + 1;
}  else if (cdp == blur) {
  cdp = cdp - 1;
}  else if (cdp == 0) {
  cdp = cdp + 1;
}  else if (cdp == blur) {
  cdp = cdp - 1;
} else {
  cdp = cdp;
}
int player;
player = m.nextInt(3);
if (player == blur) {
  player = blur;
} else if (player == red) {
  player = red;
} else {
  player = cdp;
}
if (player == cdp) {
  player = cdp;
} else {
  player = cdp;
}
if (blur == 1) {
  blur = 1;
} else if (cdp == blur) {
  cdp= cdp - 1;
} else {
  cdp= cdp;
}
if (cdp == blur) {
  cdp = cdp - 1;
} else if (cdp == 0) {
  cdp = cdp;
} else {
  cdp = cdp + 2;
}
if (red == blur) {
  red = red + 1;
} else if (red == cdp) {
  red = red + 1;
} else {
  red = red;
}
if (red == cdp) {
  red = red + 1;
} else if (red == blur) {
  red = red + 1;
} else {
  red = red;
}
if (blur >= 0) {
  blur = blur - 1;
} else if (cdp == 0) {
  cdp = cdp + 1;
} else if (red >= 0) {
  red = red - 1;
}
if (red == cdp) {
  red = red + 1;
} else if (red == blur) {
  red = red + 1;
} else {
  red = red;
}
if (red == blur) {
  red = red + 1;
} else if (red == cdp) {
  red = red + 1;
} else {
  red = red;
}
if (cdp == blur) {
  cdp = cdp + 1;
} else if (red == cdp) {
  cdp = cdp + 1;
} else if (red == blur) {
  red = red - 1;
} else {
  red = red;
}
String[] teams = {"blur", "cdp", "red"};
System.out.println("Team1: " + teams[cdp]);
System.out.println("Team2: " + teams[blur]);
System.out.println("Team3: " + teams[red]);
System.out.println("You are on Team " + teams[player]);
System.out.println("Team1 (blur): " + blur);
System.out.println("Team2 (cdp): " + cdp);
System.out.println("Team3 (red): " + red);
}
}

I know it might be a lot of code but all my question is why does my compiler give me some things one time and others another time without me changing the code




Random number issue in golang

This is the code i'm working with :

package main
import "fmt"
import "math/rand"

func main() {
code := rand.Intn(900000)
fmt.Println(code)
}

It always returns 698081. I dont understand what is the problem ? http://ift.tt/2vhv8Ds




How do I make an int have a String's value or is it possible (in java)

I have a good amount of code and it makes it so that you randomly are assigned a team, but right now my compiler comes out with the number of the team, not the team name. Is there any way I can change this?
My code:

import java.util.Random;

public class Game {
public static void main(String[] args) {
Random m = new Random();
int b;
b = m.nextInt(12);
if (b >= 6) {
  b = b;
} else {
  b = b + 6;
}
int a = b;
int playerAmount = a;
int c = playerAmount - 1;
System.out.println("Amount of Players going up against you: " + c);
int teama;
teama = m.nextInt(2);
int teamb;
teamb = m.nextInt(2);
if (teama == 0) {
  teama = teama + 1;
}  else if (teamb == teama) {
  teamb = teamb - 1;
}  else if (teamb == 0) {
  teamb = teamb + 1;
}  else if (teamb == teama) {
  teamb = teamb - 1;
} else {
  teamb = teamb;
}
System.out.println("Teama: " + teama);
System.out.println("Teamb: " + teamb);
int player;
player = m.nextInt(2);
if (player == teama) {
  player = teama;
} else {
  player = teamb;
}
if (player == 0) {
  player = "teamb";
} else {
  player = "teama";
}
System.out.println("You are on: " + player);
}
}

And then what I come out with: Amount of Players going up against you: 6 Teama: 1 Teamb: 0 You are on: 1 Is there even a way to make the teams have names or do I just have to stay like this?
BTW: I have searched for a while and haven't found anything that works.




How to query the seed python uses in random.randint

Let's say my friend one day goes home and writes the following code

random.seed(12)
X = random.randint(1,10)

And let's say X turned out to be 4(I just made that up). He then challenges me to discover the seed given X and the lower and upper bounds supplied to randint, in this case it's 1 and 10. How can I beat his challenge




Generating random visual noise using For loop (C, Arduino)

I'm starting to get into the mild depths of C, using arduinos and such like, and just wanted some advice on how I'm generating random noise using a For loop. The important bit:

void testdrawnoise() {  
  int j = 0;
  for (uint8_t i=0; i<display.width(); i++) {
    if (i == display.width()-1) {
      j++;
      i=0;
    }
    M = random(0, 2); (Random 0/1)
    display.drawPixel(i, j, M); // (Width, Height, Pixel on/off)
    display.refresh();
    }
  }

The function draws a pixel one by one across the screen, moving to the next line down once i is has reached display.width()-1. Whether the pixel appears on(black) or off(white) is determined by M.

The code is working fine, but I feel like it could be done better, or at least neater, and perhaps more efficiently.

Input and critiques greatly appreciated.




Random Sequence Generator in C#

I want to build a sequence randomiser mobile app in c#. I would like to retrieve the smallest and the largest number in an interval from two diffrent text boxes, and after I click the Generate button to display the random sequence of all the numbers in a new text box.

My code only displays one number. What's wrong with it?

Thanks.

 public sealed partial class MainPage : Page
{
    public MainPage()
    {
       this.InitializeComponent();           
    }
   private void button_Click(object sender, RoutedEventArgs e)
    {
        int seed = 345;
        var result = "";
        int min = Convert.ToInt32(textBox.Text);
        int max = Convert.ToInt32(textBox2.Text);
       Random r3 = new Random(seed);
        for (int i = min; i < max; i++)
        {
            ecran.Text = (/*"," + r3.Next(min, max)*/i).ToString();
        }
    }




Add random number at Random time intervals

The thing is i want to add random number to a variable which is initially 0 which has to happen after a random timoeut until the variable reaches 100.

$scope.var1 = 0;

do{
    $timeout(function(){
        $scope.var1 += Math.floor(Math.random * 100 +1);
    },Math.floor(Math.random * 100 +1));
    console.log($scope.var1);

}while($scope.var1<100)

$scope.var1 always stays 0, hence it goes to an infinite loop;




Randomly distributed dots in a ball in C++

I tried to create 5000 uniformly distributed stars (that are represented by each dot) inside a ball of radius R=500, but is seems that the middle gets more points than the surface of the sphere, why ?

this is my attempt:

 R=500*rand()/double(RAND_MAX);
 theta=acos(-1+2*rand()/double(RAND_MAX));
 phi=2*3.14*rand()/double(RAND_MAX);
 x_pos=R*sin(theta)*cos(phi);
 y_pos=R*sin(theta)*sin(phi);
 z_pos=R*cos(theta);

and the result looks like this: enter image description here




java.util.UUID.randomUUID().toString() length

Does java.util.UUID.randomUUID().toString() length always equal to 36?

I was not able to find info on that. Here it is said only the following:

public static UUID randomUUID() Static factory to retrieve a type 4 (pseudo randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo random number generator. Returns: A randomly generated UUID

And that type 4 tells me nothing. I do not know what type 4 means in the case.




vendredi 28 juillet 2017

SQL Server Copy Random data from one table to another

I have 2 tables stuff and nonsense. nonsense is not the same size as stuff; in this case it is has fewer rows, but it may have more.

The structures are something like this:

CREATE TABLE stuff (
    id INT PRIMARY KEY,
    details VARCHAR(MAX),
    data VARCHAR(MAX)
);

CREATE TABLE nonsense (
    id INT PRIMARY KEY,
    data VARCHAR(MAX)
);

The stuff table is already populated with details, but data is NULL for now.

I would like to copy data from one row of nonsense at random into each row of stuff. Since nonsense is smaller, there will naturally be duplicates, which is OK.

This does not work:

UPDATE stuff
SET data=(SELECT TOP 1 data FROM nonsense ORDER BY NewId());

Presumably the sub query is evaluated once before the rest of the query. However that’s the sort of result I would have liked.

How do I achive this?




Evenly distributed random in Bash

I've been using "shuf" and "sort -R" to shuffle my music playlist, but it feels like certain songs get played more than others.

To test this, I used the following command which shuffles the alphabet and records the 1st letter in the shuffle, repeated x1000 and then counts the number of times each letter was picked. If it were truly random there would be an even distribution, but it's always lop-sided:

printf "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz" > alphabet.txt; for i in {1..1000}; do cat alphabet.txt | perl -MList::Util=shuffle -e 'print shuffle(<STDIN>);' | perl -e 'print reverse <>' | head -1 >> results.txt; done; sort results.txt | uniq -c | sort; rm results.txt; rm alphabet.txt

Which results in something like:

 29 w
 30 u
 31 d
 32 i
 33 v
 34 c
 34 m
 36 a
 36 g
 36 k
 36 n
 36 r
 36 z
 38 y
 39 x
 40 b
 40 e
 40 o
 42 p
 43 f
 43 h
 43 s
 44 j
 44 l
 52 q
 53 t

Notice how 't' was selected 53 times, but 'w' only 29. I believe the songs I hear most often are like the 't', and there are songs I rarely get in the mix (like the 'w').

Can anyone come up with a Bash/Perl/Python/etc command that would/could distribute the random results more evenly?




NuSMV Simulation Using Random Traces

I am attempting to run "random" or non-deterministic simulations of a NuSMV model I have created. However between subsequent runs the trace that is produced is exactly the same.

Here is the model:

MODULE main
VAR x : 0..4;
VAR clk : 0..10;

DEFINE next_x :=
    case
        x = 0 : {0,1};
        x = 1 : {1,2};
        x = 2 : {1,0};
        TRUE : {0};
    esac;

DEFINE next_clk :=
    case
        (clk < 10) : (clk+1);
        TRUE : clk;
    esac;

INIT (x = 0);
INIT (clk = 0);

TRANS (next(x) in next_x);
TRANS next(clk) = next_clk;

CTLSPEC AG(clk < 10);

I am running this using the following commands in the interactive shell:

go
pick_state -r
simulate -k -r 30
show_traces 1
quit

Perhaps I have a mistake in my model? Or I am not running the correct commands in the shell.

Thanks in advance!




GOOGLE API TRANSLATE RANDOM ERROR

I am using a script in Wordpress to translate posts. It is working as supposed! But randomly not! Around 5% of the translation requests get not translated and original value is returned instead of error. The randomness is very chaotic, so I have no way to debug. The script has no log :( Instead I relieved the server and decreased the amount of requests. Although API stats never showed any error or over limits. Now the translation non-successes has decreased a bit, like not having two consecutive non-successes. So I suspect that the script quits before it receives response from google with translated value due to server load or/and network latency, etc.

My question is ... Is this scenario possible?




Not getting random list with std::shuffle()?

QStringList outList;
OutList<<"A"<<"B"<<"C"<<"D"<<"E"<<"F";
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(outList.begin(), outList.end(), g);

The outList is aways the same. I thought what I did should make "g" random therefore outList should be random. What am I missing? Thanks.




how to reverse random.seed in Python

I want a way to give me the seed given a random number it could have generated. for example, if I have the following code

import random


seed = 3
lower_bound = 1
upper_bound = 10

random.seed(seed)
random.randint(lower_bound, upper_bound)

given the number these entries generate I want to be able to reverse the process and find out what the seed was. so given the number, I want to find the seed.
Sorry if I was unclear.




Battleships game in Python - random ship placement

I am currently creating the game battleships in Python where a player plays against computer. I have managed to create boards for the both of them and placed ships for the player's board. But I'm stuck on placing the ships randomly using random.randint for the computer board.

I get this error in output: File "python", line 98, in comp_place_ships TypeError: 'function' object is not subscriptable

Here is the code:

#Computer place ships
def comp_place_ships(comp_board, ships):
   for i, j in ships.items():
     ship_not_placed = True
     while ship_not_placed:
       ori = random.randint(0,1)
       x = random.randint(0,9)
       y = random.randint(0,9)
       placement = comp_board[x][y]
       if ori == 0 and placement == '.':
         for k in range(j):
            comp_board[x][y] = i
            comp_board[x+k][y] = i
            ship_not_placed = False

       elif ori == 1 and placement == '.':
         for k in range(j):
           comp_board[x][y] = i
           comp_board[x][y+k] = i 
           ship_not_placed = False

       elif ori != 0 or 1 and placement != '.':
      print('Invalid choice, please try again.')

I know the part "placement = comp_board[x][y]" is the part that makes the error-code but don't know how to solve it. Im using the variable placement to check if the coordinate is equal to '.' which is the standard value of each cell in the two dimensional list. Are there somebody out there who might have any suggestions on how to solve this?

PS! I know the code is poorly structured and I have not added the other if conditions such as how to not go off board with the ship placement. Will add that when I've tackled this problem =)




SparkException: This RDD lacks a SparkContext

I'm trying to create a string sampler using a rdd of string as a dictionnary and the class RandomDataGenerator from org.apache.spark.mllib.random package.

import org.apache.spark.mllib.random.RandomDataGenerator
import org.apache.spark.rdd.RDD
import scala.util.Random

class StringSampler(var dic: RDD[String], var seed: Long = System.nanoTime) extends RandomDataGenerator[String] {
    require(dic != null, "Dictionary cannot be null")
    require(!dic.isEmpty, "Dictionary must contains lines (words)")
    Random.setSeed(seed)

    var fraction: Long = 1 / dic.count()

    //return a random line from dictionary
    override def nextValue(): String = dic.sample(withReplacement = true, fraction).take(1)(0)

    override def setSeed(newSeed: Long): Unit = Random.setSeed(newSeed)

    override def copy(): StringSampler = new StringSampler(dic)

    def setDictionary(newDic: RDD[String]): Unit = {
        require(newDic != null, "Dictionary cannot be null")
        require(!newDic.isEmpty, "Dictionary must contains lines (words)")
        dic = newDic
        fraction = 1 / dic.count()
    }
}


val dictionaryName: String
val dictionaries: Broadcast[Map[String, RDD[String]]]
val dictionary: RDD[String] = dictionaries.value(dictionaryName) // dictionary.cache()
val sampler = new StringSampler(dictionary)
RandomRDDs.randomRDD(context, sampler, size, numPartitions)

But I encounter a SparkException saying that the dictionary is lacking of a SparkContext when I try to generate a random RDD of strings. It seems that spark is loosing context of the dictionary rdd when copying it to cluster nodes and I don't know how to fix it.

I tried to cache the dictionary before passing it to the StringSampler, but it didn't change anything... I was thinking about linking it back to the original SparkContext, but I don't even know if it's possible. Anyone have an idea ?

Caused by: org.apache.spark.SparkException: This RDD lacks a SparkContext. It could happen in the following cases: 
(1) RDD transformations and actions are NOT invoked by the driver, but inside of other transformations; for example, rdd1.map(x => rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.
(2) When a Spark Streaming job recovers from checkpoint, this exception will be hit if a reference to an RDD not defined by the streaming job is used in DStream operations. For more information, See SPARK-13758.




Random generation of X and Y coordinates in javascript for random motion

I am looking for a way to generate a stream of x and y coordinates within a bounding region, for example, a 600x600 box. This stream of data is for a model which contains the position of the element that it represents. I do not want to use a Jquery animate method as this manipulates the top and left the property of the elements usually which goes against what I am trying to do where a model represents the position.

Things like jQuery methods provide the movement I like, however, as I said I want it in x and y coordinates.

One method I thought of was selecting a random point within the region and calculating the line between the current point and the random point and then slowly stepping along that line, there are multiple elements to manage so this should have to be done for each with the appearance of it happening at the same time.

The issue is I can't think of how to do this.




Setting Chance of getting Items for Random (C++)?

I have 5 classes (Legendary Egg, Rare Egg, Common Egg, Dragon food, Gold). All items that are inherited from an Item class.

Supposedly, the output is that the user is playing a gacha machine where they can get any of those items. But I want to set the chance percentage of getting specific items so that it won't be so easy to get the rarer items.

Legendary Egg = 1%
Rare Egg = 10%
Common Egg = 20%
Dragon Food = 20%
Gold = 29%

What is an efficient way to do this? I put all the items in an array at first and used rand()% but I realized that I couldn't set the chance of getting them. I thought of using something like

if (value < 0.1){
std:: cout << "You got a legendary egg!";
}

but I felt that it would be a bit inefficient because I was told to avoid blocks of if else.

*The items are in their own (separate) class because they have different abilities




How Limit JSON Value And Randomize Each Data On Page Load [duplicate]

This question already has an answer here:

Right now I have JSON file of quotes and I get all value every time the codes run. Now how I can get only one (1) value and it change or randomize value every time my page load or refresh.

Even though I got code for randomizing JSON file at how to get random json data and append to div element but it so hard to understand.

How could get one (1) and random JSON value?

JSFIDDLE: http://ift.tt/2uIjNJr

var data=[{
    "quoteText": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "quoteAuthor": "Thomas Edison"
    }, {
    "quoteText": "You can observe a lot just by watching.",
    "quoteAuthor": "Yogi Berra"
    }, {
    "quoteText": "A house divided against itself cannot stand.",
    "quoteAuthor": "Abraham Lincoln"
    }, {
    "quoteText": "Difficulties increase the nearer we get to the goal.",
    "quoteAuthor": "Johann Wolfgang von Goethe"
    }, {
    "quoteText": "Fate is in your hands and no one elses",
    "quoteAuthor": "Byron Pulsifer"
    }, {
    "quoteText": "Be the chief but never the lord.",
    "quoteAuthor": "Lao Tzu"
    }, {
    "quoteText": "Nothing happens unless first we dream.",
    "quoteAuthor": "Carl Sandburg"
    }, {
    "quoteText": "Well begun is half done.",
    "quoteAuthor": "Aristotle"
    }, {
    "quoteText": "Life is a learning experience, only if you learn.",
    "quoteAuthor": "Yogi Berra"
    }, {
    "quoteText": "Self-complacency is fatal to progress.",
    "quoteAuthor": "Margaret Sangster"
    }, {
    "quoteText": "Peace comes from within. Do not seek it without.",
    "quoteAuthor": "Buddha"
    }, {
    "quoteText": "What you give is what you get.",
    "quoteAuthor": "Byron Pulsifer"
    }, {
    "quoteText": "We can only learn to love by loving.",
    "quoteAuthor": "Iris Murdoch"
    }, {
    "quoteText": "Life is change. Growth is optional. Choose wisely.",
    "quoteAuthor": "Karen Clark"
    }, {
    "quoteText": "You'll see it when you believe it.",
    "quoteAuthor": "Wayne Dyer"
    }, {
    "quoteText": "Today is the tomorrow we worried about yesterday.",
    "quoteAuthor": ""
    }, {
    "quoteText": "It's easier to see the mistakes on someone else's paper.",
    "quoteAuthor": ""
    }, {
    "quoteText": "Every man dies. Not every man really lives.",
    "quoteAuthor": ""
    }, {
    "quoteText": "To lead people walk behind them.",
    "quoteAuthor": "Lao Tzu"
    }, {
    "quoteText": "Having nothing, nothing can he lose.",
    "quoteAuthor": "William Shakespeare"
    }, {
    "quoteText": "Trouble is only opportunity in work clothes.",
    "quoteAuthor": "Henry J. Kaiser"
    }, {
    "quoteText": "A rolling stone gathers no moss.",
    "quoteAuthor": "Publilius Syrus"
    }, {
    "quoteText": "Ideas are the beginning points of all fortunes.",
    "quoteAuthor": "Napoleon Hill"
    }, {
    "quoteText": "Everything in life is luck.",
    "quoteAuthor": "Donald Trump"
    }, {
    "quoteText": "Doing nothing is better than being busy doing nothing.",
    "quoteAuthor": "Lao Tzu"
    }, {
    "quoteText": "Trust yourself. You know more than you think you do.",
    "quoteAuthor": "Benjamin Spock"
    }, {
    "quoteText": "Study the past, if you would divine the future.",
    "quoteAuthor": "Confucius"
    }, {
    "quoteText": "The day is already blessed, find peace within it.",
    "quoteAuthor": ""
    }, {
    "quoteText": "From error to error one discovers the entire truth.",
    "quoteAuthor": "Sigmund Freud"
    }, {
    "quoteText": "Well done is better than well said.",
    "quoteAuthor": "Benjamin Franklin"
    }, {
    "quoteText": "Bite off more than you can chew, then chew it.",
    "quoteAuthor": "Ella Williams"
    }, {
    "quoteText": "Work out your own salvation. Do not depend on others.",
    "quoteAuthor": "Buddha"
    }, {
    "quoteText": "One today is worth two tomorrows.",
    "quoteAuthor": "Benjamin Franklin"
    }, {
    "quoteText": "Once you choose hope, anythings possible.",
    "quoteAuthor": "Christopher Reeve"
    }, {
    "quoteText": "God always takes the simplest way.",
    "quoteAuthor": "Albert Einstein"
    }, {
    "quoteText": "One fails forward toward success.",
    "quoteAuthor": "Charles Kettering"
    }, {
    "quoteText": "From small beginnings come great things.",
    "quoteAuthor": ""
    }, {
    "quoteText": "Learning is a treasure that will follow its owner everywhere",
    "quoteAuthor": "Chinese proverb"
    }, {
    "quoteText": "Be as you wish to seem.",
    "quoteAuthor": "Socrates"
    }, {
    "quoteText": "The world is always in movement.",
    "quoteAuthor": "V. Naipaul"
    }, {
    "quoteText": "Never mistake activity for achievement.",
    "quoteAuthor": "John Wooden"
    }, {
    "quoteText": "What worries you masters you.",
    "quoteAuthor": "Haddon Robinson"
    }, {
    "quoteText": "One faces the future with ones past.",
    "quoteAuthor": "Pearl Buck"
    }, {
    "quoteText": "Goals are the fuel in the furnace of achievement.",
    "quoteAuthor": "Brian Tracy"
    }, {
    "quoteText": "Who sows virtue reaps honour.",
    "quoteAuthor": "Leonardo da Vinci"
    }, {
    "quoteText": "Be kind whenever possible. It is always possible.",
    "quoteAuthor": "Dalai Lama"
    }, {
    "quoteText": "Talk doesn't cook rice.",
    "quoteAuthor": "Chinese proverb"
    }, {
    "quoteText": "He is able who thinks he is able.",
    "quoteAuthor": "Buddha"
    }, {
    "quoteText": "Be as you wish to seem.",
    "quoteAuthor": "Socrates"
    }, {
    "quoteText": "A goal without a plan is just a wish.",
    "quoteAuthor": "Larry Elder"
    }, {
    "quoteText": "To succeed, we must first believe that we can.",
    "quoteAuthor": "Michael Korda"
    }, {
    "quoteText": "Learn from yesterday, live for today, hope for tomorrow.",
    "quoteAuthor": "Albert Einstein"
    }, {
    "quoteText": "A weed is no more than a flower in disguise.",
    "quoteAuthor": "James Lowell"
    }, {
    "quoteText": "Do, or do not. There is no try.",
    "quoteAuthor": "Yoda"
    }, {
    "quoteText": "All serious daring starts from within.",
    "quoteAuthor": "Harriet Beecher Stowe"
    }, {
    "quoteText": "The best teacher is experience learned from failures.",
    "quoteAuthor": "Byron Pulsifer"
    }, {
    "quoteText": "Think how hard physics would be if particles could think.",
    "quoteAuthor": "Murray Gell-Mann"
    }, {
    "quoteText": "Love is the flower you've got to let grow.",
    "quoteAuthor": "John Lennon"
    }, {
    "quoteText": "Don't wait. The time will never be just right.",
    "quoteAuthor": "Napoleon Hill"
    }, {
    "quoteText": "One fails forward toward success.",
    "quoteAuthor": "Charles Kettering"
    }, {
    "quoteText": "Time is the wisest counsellor of all.",
    "quoteAuthor": "Pericles"
    }, {
    "quoteText": "You give before you get.",
    "quoteAuthor": "Napoleon Hill"
    }, {
    "quoteText": "Wisdom begins in wonder.",
    "quoteAuthor": "Socrates"
    }, {
    "quoteText": "Without courage, wisdom bears no fruit.",
    "quoteAuthor": "Baltasar Gracian"
    }, {
    "quoteText": "Change in all things is sweet.",
    "quoteAuthor": "Aristotle"
    }, {
    "quoteText": "What you fear is that which requires action to overcome.",
    "quoteAuthor": "Byron Pulsifer"
    }, {
    "quoteText": "The best teacher is experience learned from failures.",
    "quoteAuthor": "Byron Pulsifer"
    }, {
    "quoteText": "When performance exceeds ambition, the overlap is called success.",
    "quoteAuthor": "Cullen Hightower"
    }, {
    "quoteText": "When deeds speak, words are nothing.",
    "quoteAuthor": "African proverb"
    }, {
    "quoteText": "Real magic in relationships means an absence of judgement of others.",
    "quoteAuthor": "Wayne Dyer"
    }, {
    "quoteText": "When performance exceeds ambition, the overlap is called success.",
    "quoteAuthor": "Cullen Hightower"
    }, {
    "quoteText": "I never think of the future. It comes soon enough.",
    "quoteAuthor": "Albert Einstein"
    }, {
    "quoteText": "Skill to do comes of doing.",
    "quoteAuthor": "Ralph Emerson"
    }, {
    "quoteText": "Wisdom is the supreme part of happiness.",
    "quoteAuthor": "Sophocles"
    }, {
    "quoteText": "I believe that every person is born with talent.",
    "quoteAuthor": "Maya Angelou"
    }, {
    "quoteText": "Important principles may, and must, be inflexible.",
    "quoteAuthor": "Abraham Lincoln"
    }, {
    "quoteText": "The undertaking of a new action brings new strength.",
    "quoteAuthor": "Richard Evans"
    }, {
    "quoteText": "I believe that every person is born with talent.",
    "quoteAuthor": "Maya Angelou"
    }, {
    "quoteText": "The years teach much which the days never know.",
    "quoteAuthor": "Ralph Emerson"
    }, {
    "quoteText": "Our distrust is very expensive.",
    "quoteAuthor": "Ralph Emerson"
    }, {
    "quoteText": "All know the way; few actually walk it.",
    "quoteAuthor": "Bodhidharma"
    }, {
    "quoteText": "Great talent finds happiness in execution.",
    "quoteAuthor": "Johann Wolfgang von Goethe"
    }, {
    "quoteText": "Faith in oneself is the best and safest course.",
    "quoteAuthor": "Michelangelo"
    }, {
    "quoteText": "Courage is going from failure to failure without losing enthusiasm.",
    "quoteAuthor": "Winston Churchill"
    }, {
    "quoteText": "The two most powerful warriors are patience and time.",
    "quoteAuthor": "Leo Tolstoy"
    }, {
    "quoteText": "Anticipate the difficult by managing the easy.",
    "quoteAuthor": "Lao Tzu"
    }, {
    "quoteText": "Those who are free of resentful thoughts surely find peace.",
    "quoteAuthor": "Buddha"
    }, {
    "quoteText": "Talk doesn't cook rice.",
    "quoteAuthor": "Chinese proverb"
    }, {
    "quoteText": "A short saying often contains much wisdom.",
    "quoteAuthor": "Sophocles"
    }, {
    "quoteText": "The day is already blessed, find peace within it.",
    "quoteAuthor": ""
    }, {
    "quoteText": "It takes both sunshine and rain to make a rainbow.",
    "quoteAuthor": ""
    }, {
    "quoteText": "A beautiful thing is never perfect.",
    "quoteAuthor": ""
    }, {
    "quoteText": "Only do what your heart tells you.",
    "quoteAuthor": "Princess Diana"
    }, {
    "quoteText": "Life is movement-we breathe, we eat, we walk, we move!",
    "quoteAuthor": "John Pierrakos"
    }, {
    "quoteText": "No one can make you feel inferior without your consent.",
    "quoteAuthor": "Eleanor Roosevelt"
    }, {
    "quoteText": "One fails forward toward success.",
    "quoteAuthor": "Charles Kettering"
    }, {
    "quoteText": "Argue for your limitations, and sure enough theyre yours.",
    "quoteAuthor": "Richard Bach"
    }, {
    "quoteText": "Luck is what happens when preparation meets opportunity.",
    "quoteAuthor": "Seneca"
    }, {
    "quoteText": "Victory belongs to the most persevering.",
    "quoteAuthor": "Napoleon Bonaparte"
    }, {
    "quoteText": "Once you choose hope, anythings possible.",
    "quoteAuthor": "Christopher Reeve"
    }, {
    "quoteText": "Love all, trust a few, do wrong to none.",
    "quoteAuthor": "William Shakespeare"
    }, {
    "quoteText": "In order to win, you must expect to win.",
    "quoteAuthor": "Richard Bach"
    }, {
    "quoteText": "A goal is a dream with a deadline.",
    "quoteAuthor": "Napoleon Hill"
    }, {
    "quoteText": "You can do it if you believe you can!",
    "quoteAuthor": "Napoleon Hill"
    }, {
    "quoteText": "Set your goals high, and don't stop till you get there.",
    "quoteAuthor": "Bo Jackson"
    }, {
    "quoteText": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "quoteAuthor": "Thomas Edison"
    }, {
    "quoteText": "Every new day is another chance to change your life.",
    "quoteAuthor": ""
    }, {
    "quoteText": "Smile, breathe, and go slowly.",
    "quoteAuthor": "Thich Nhat Hanh"
    }, {
    "quoteText": "Nobody will believe in you unless you believe in yourself.",
    "quoteAuthor": "Liberace"
    }, {
    "quoteText": "Be kind whenever possible. It is always possible.",
    "quoteAuthor": "Dalai Lama"
    }, {
    "quoteText": "Do more than dream: work.",
    "quoteAuthor": "William Arthur Ward"
    }, {
    "quoteText": "No man was ever wise by chance.",
    "quoteAuthor": "Seneca"
    }, {
    "quoteText": "Some pursue happiness, others create it.",
    "quoteAuthor": ""
    }, {
    "quoteText": "It's easier to see the mistakes on someone else's paper.",
    "quoteAuthor": ""
    }, {
    "quoteText": "Think how hard physics would be if particles could think.",
    "quoteAuthor": "Murray Gell-Mann"
    }, {
    "quoteText": "Well begun is half done.",
    "quoteAuthor": "Aristotle"
    }, {
    "quoteText": "He that is giddy thinks the world turns round.",
    "quoteAuthor": "William Shakespeare"
    }, {
    "quoteText": "Don't ruin the present with the ruined past.",
    "quoteAuthor": "Ellen Gilchrist"
    }, {
    "quoteText": "Do something wonderful, people may imitate it.",
    "quoteAuthor": "Albert Schweitzer"
    }, {
    "quoteText": "We do what we do because we believe.",
    "quoteAuthor": ""
    }, {
    "quoteText": "Great talent finds happiness in execution.",
    "quoteAuthor": "Johann Wolfgang von Goethe"
    }, {
    "quoteText": "Do one thing every day that scares you.",
    "quoteAuthor": "Eleanor Roosevelt"
    }, {
    "quoteText": "If you cannot be silent be brilliant and thoughtful.",
    "quoteAuthor": "Byron Pulsifer"
    }, {
    "quoteText": "Smile, breathe, and go slowly.",
    "quoteAuthor": "Thich Nhat Hanh"
    }, {
    "quoteText": "Who looks outside, dreams; who looks inside, awakes.",
    "quoteAuthor": "Carl Jung"
    }, {
    "quoteText": "What we think, we become.",
    "quoteAuthor": "Buddha"
    }, {
    "quoteText": "The shortest answer is doing.",
    "quoteAuthor": "Lord Herbert"
    }, {
    "quoteText": "All our knowledge has its origins in our perceptions.",
    "quoteAuthor": "Leonardo da Vinci"
    }, {
    "quoteText": "He is able who thinks he is able.",
    "quoteAuthor": "Buddha"
    }, {
    "quoteText": "The harder you fall, the higher you bounce.",
    "quoteAuthor": ""
    }, {
    "quoteText": "Trusting our intuition often saves us from disaster.",
    "quoteAuthor": "Anne Wilson Schaef"
    }, {
    "quoteText": "Truth is powerful and it prevails.",
    "quoteAuthor": "Sojourner Truth"
    }, {
    "quoteText": "Talk doesn't cook rice.",
    "quoteAuthor": "Chinese proverb"
    }, {
    "quoteText": "Light tomorrow with today!",
    "quoteAuthor": "Elizabeth Browning"
    }, {
    "quoteText": "Silence is a fence around wisdom.",
    "quoteAuthor": "German proverb"
    }, {
    "quoteText": "Society develops wit, but its contemplation alone forms genius.",
    "quoteAuthor": "Madame de Stael"
    }, {
    "quoteText": "Real magic in relationships means an absence of judgement of others.",
    "quoteAuthor": "Wayne Dyer"
    }, {
    "quoteText": "The years teach much which the days never know.",
    "quoteAuthor": "Ralph Emerson"
    }, {
    "quoteText": "We can only learn to love by loving.",
    "quoteAuthor": "Iris Murdoch"
    }, {
    "quoteText": "The simplest things are often the truest.",
    "quoteAuthor": "Richard Bach"
    }, {
    "quoteText": "What you give is what you get.",
    "quoteAuthor": "Byron Pulsifer"
    }, {
    "quoteText": "Everyone smiles in the same language.",
    "quoteAuthor": ""
    }, {
    "quoteText": "A short saying often contains much wisdom.",
    "quoteAuthor": "Sophocles"
    }, {
    "quoteText": "Yesterday I dared to struggle. Today I dare to win.",
    "quoteAuthor": "Bernadette Devlin"
    }, {
    "quoteText": "Victory belongs to the most persevering.",
    "quoteAuthor": "Napoleon Bonaparte"
    }, {
    "quoteText": "No alibi will save you from accepting the responsibility.",
    "quoteAuthor": "Napoleon Hill"
    }, {
    "quoteText": "If you can dream it, you can do it.",
    "quoteAuthor": "Walt Disney"
    }, {
    "quoteText": "From error to error one discovers the entire truth.",
    "quoteAuthor": "Sigmund Freud"
    }, {
    "quoteText": "It is better to travel well than to arrive.",
    "quoteAuthor": "Buddha"
    }, {
    "quoteText": "Life shrinks or expands in proportion to one's courage.",
    "quoteAuthor": "Anais Nin"
    }, {
    "quoteText": "You have to believe in yourself.",
    "quoteAuthor": "Sun Tzu"
    }];

$.each(data, function (i, val) { 
    $("#items").append("<p>"+val.quoteText+"-"+val.quoteAuthor+"</p> ");
});
<div id="items">
</div>



Randomness and probability in java

I'm trying to make a small gambling game in Java where the user has two options.

A TextField where he can write in the amount of how much he wants to bet and a ComboBox where he can choose how many precent chance for him to win. The comboBox provides the options 10%, 20%, 30%, 40% and 50%.

My problem is that I don't know how to apply probability in java. I tried doing following:

public class GamblingGame {

private int rdmNumber;
private int wonValue;

public int winOrLose(int valueBetted, int precentToWin, Label label, int attempts){


    precentToWin = precentToWin/10;

    rdmNumber= ThreadLocalRandom.current().nextInt(precentToWin, 10 +1);


    System.out.println("this is rdmnumber: " + rdmNumber);
    System.out.println("this is precentowin number: " + precentToWin);

    //if the number you rolled is equal to the precent you choose (ie if its 10, the number is 1, if its 20 the number is 2)
    if(rdmNumber == precentToWin) {
        wonValue = valueBetted/precentToWin *2;

        System.out.println("You win!");

        label.setStyle("-fx-text-fill: green");
        label.setText("You won! You recieved: " + wonValue+" coins!");
    }

    else{
        label.setStyle("-fx-text-fill: red");
        label.setText("Gamble failed! You lost: " +valueBetted + " coins. ("+attempts+")");
        wonValue = -valueBetted;

    }


    System.out.println(wonValue);
    return wonValue;



}

}

The problem is that if, for instance, the user puts in 50% in the combobox he won't get a true 50% chance to win.

The number the dice would need to roll here is 5 in order to win, and the max value is 10. So the user would roll a number between 5-10 and when he hits 5, he'd win.

How do I make it so that the precentage of rolling the dice would be a true 50%? (and of course not ruin it so that if i put in a difference precentage as the parameter it wont ruin the method)




jeudi 27 juillet 2017

Random Aframe environment

I want to have random scenarios every time I enter the website. So I'm trying to return the "pickscenario" variable from the js script to aframe:

<a-entity environment="preset: pickscenario"></a-entity>
        <script>
          var scenarios = ['ocean', 'universe', 'forest'];
          var pickscenario = scenarios[Math.floor(Math.random()*scenarios.length)];
          return pickscenario;
        </script>        
  </a-entity>

I bet this is quite simple but I haven't figure it out yet.




Shuffle an array before inserting to database [php]

I have an array like this:

$posts = array(
            array(
                'head' => 'Let\'s pop some Champagne',
                'image' => '/beach/1.jpg'
            ),

            array(
                'head' => 'Sunrise in the beach sand',
                'image' => '/beach/2.jpg'
            ),
        Many more arrays...
 );
DB::table('posts')->insert($posts);

They are inserted to the database table named posts

The insertion works fine but the array are inserted in a sequence i.e Top-to-Bottom

Is there anyway to randomize the arrays insertion? Suppose the array is (1,2,3,4,5) I want it to be (4,2,3,5,1) something like this.




Split a data frame into two random samples with equal proportions of multiple variables

I'm trying to run k-folds cross-validation for a glm model with unequally distributed factor levels, so when I split the data into separate calibration/validation data frames, I inevitably end up with certain factor levels present only in one of the two.

So say I have the following data frame:

set.seed(3.14)
df<-data.frame(x1=sample(0:1,size=20,replace=T),
               x2=sample(0:2,size=20,replace=T),
               y =sample(0:1,size=100,replace=T))
df<-as.data.frame(apply(df,MARGIN=2,FUN=as.factor))
> sapply(df,FUN=summary)
$x1
0  1 
51 49 

$x2
0  1  2 
37 32 31 

$y
0  1 
48 52 

How can I randomly split it into two dataframes with somewhat-equal proportions of factor levels across all variables. For example, the summary for an 80/20 split would look something like this:

calibration:

$x1
0   1
41  39
$x2
0    1   2
30   26  25
$y
0   1
38  42

Validation:

$x1
0   1
10  10
$x2
0   1  2
7   6  6
$y
0   1
10  10

Note: This is a simplified example. The actual data has 20+ variables with as many as 9 or 10 factor levels.




Unity - Cannot generate random number within a class construct

I have been trying to create my own class using C# in Unity but I've come across a small issue. Within my PlayerClass construct I want to generate a string of six random numbers using Random.Range (0, 9) use as a reference number. Currently, the line of code I am using to do this, looks like this:

refNum = Random.Range (0, 9) + Random.Range (0, 9) + Random.Range (0, 9) + Random.Range (0, 9) + Random.Range (0, 9) + Random.Range (0, 9);

I have created the variable refNum outside of the construct at the top of the class. Every time I run my game I get an error saying I cannot generate random numbers from within a class construct. Does anybody know a way around this?

Many Thanks,

Tommy




How to randomize and arry 0 to 10^9 (without duplicate ) [duplicate]

This question already has an answer here:

How can I get random numbers 0 to 10^9 (without duplicate ) and store them in an arry .First of all I faced problem to create an arry of size 10^9(i can declare up to int arry[10^8] ) and store random numbers without duplicate in it.

 #include<bits/stdc++.h>
    using namespace std;

        #define S 100000000
        int main()
        {
            int i;
            std::vector<int>result(S);

            for( i = 1; i < S ; ++i)
            {
                int t = rand() % i; // t - is random value in [0..i)
                result[i] = result[t]; // i-th element assigned random index-th value
                result[t]  =i;        // and, random position assigned i value

            }

    }

Is there any process to get random numbers 0 to 10^9 and store them in an arry




Random number generator issues in matlab

I have an issue I can't quite figure out. For a simulation I generate artificial data randomly, with randomly drawn variance and a mean of 0. To acheive this I first create a vector of possible variances and then randomly draw the index for the vector, like in the following example

%% Covariance Matrix

% Variances of explanatory variables
var1 = 0.1:0.1:100;
var2 = 0.1:0.1:100;
var3 = 0.1:0.1:100;

%% Randomly selecting variances

% if exist('s','var')
%     rng(s) % Loading Random generator settings for replication
% else
%     s=rng; % Saving Random generator settings for replication
% end

ind_1=randi([0 1000]);
ind_2=randi([0 1000]);
ind_3=randi([0 1000]);

var_11=var1(ind_1);
var_22=var2(ind_2);
var_33=var3(ind_3);

For some reason the random number generator seems to give me the same numbers in the first (ind_1=815, ind_2=906, ind_3=127) and in the second run (ind_1=914, ind_2=632, ind_3=97) after restarting matlab, if I generate the vector of variances first. I've been able to replicate that on different PC as well. Is there a feature that I'm overlooking or am I making, and I would imagine I am, a crucial mistake? (I am well aware that there are only pseudo random numbers in matlab, but this seems too pseudo for my taste)

Thanks, Richard




Laravel select random rows from table based on another field

There is a words table with 20000 records:

ID      name      rank
1       word1     3 
2       word2     5019 
3       word3     12334 
4       word4     23
5       word5     544

I want to select 400 words randomly from this table but with this condition :

first 20 words: select 20 words randomly from words with rank between 1 and 1000

second 20 words: select 20 words randomly from words with rank between 1000 and 2000

And so on...

Do I have to do this in 20 separate queries? How? Is there a better way?

I am using laravel 5.4 and Mysql, Also a raw query suggestion would be appreciated. Thank you




mercredi 26 juillet 2017

Generating ID randomly and persisting it in Java efficiently

I need to generate a number of length 12, say variable finalId. Out of those 12 digits, 5 digits are to be taken from another value, say partialid1.

Now finalId = partialId1(5 - digits)+ partialId2(7 digits).

I need to generate partialid2 randomly, where I can use Random class of Java.

Finally i have to insert this finalId in Database, as a Primary key.

So to make sure that newly generated finalId is not existing in Oracle Database, I need to query Oracle Database as well.

Is there any efficient way other than the one i have mentioned above to generate Id in Java and check in database before persisting it?




Negligible difference in performance between RDSEED and RDRAND

Recent Intel chips (Ivy Bridge and up) have instructions for generating (pseudo) random bits. RDSEED outputs "true" random bits generated from entropy gathered from a sensor on the chip. RDRAND outputs bits generated from a pseudorandom number generator seeded by the true random number generator. According to Intel's documentation, RDSEED is slower, since gathering entropy is costly. Thus, RDRAND is offered as a cheaper alternative, and its output is sufficiently secure for most cryptographic applications. (This is analogous to the /dev/random versus /dev/urandom on Unix systems.)

I was curious about the performance difference between the two instructions, so I wrote some code to compare the two. To my surprise, I find there is virtually no difference in performance. Could anyone provide an explanation?

Benchmark

/* Compare the performance of RDSEED and RDRAND.
 *
 * Compute the CPU time used to fill a buffer with (pseudo) random bits 
 * using each instruction.
 */
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <x86intrin.h>

#define BUFSIZE (1<<24)

int main() {

  unsigned int ok, i;
  unsigned long long *rand = malloc(BUFSIZE*sizeof(unsigned long long)), 
                     *seed = malloc(BUFSIZE*sizeof(unsigned long long)); 

  clock_t start, end, bm;

  // RDRAND
  start = clock();
  for (i = 0; i < BUFSIZE; i++) {
    ok  = _rdrand64_step(&rand[i]);
  }
  bm = clock() - start;
  printf("RDRAND: %li\n", bm);

  // RDSEED
  start = clock();
  for (i = 0; i < BUFSIZE; i++) {
    ok = _rdseed64_step(&seed[i]);
  }
  end = clock();
  printf("RDSEED: %li, %.2lf\n", end - start, (double)(end-start)/bm);

  free(rand);
  free(seed);
  return 0;
}

System details

  • Intel Core i7-6700 CPU @ 3.40GHz
  • Ubuntu 16.04
  • gcc 5.4.0



Split Testing With Javascript?

I have a website and I want to split adblocks to test and see which is generating me more money. And I have a code that works by crating a random whole number integer between 1 and 2 and depending on the selection, it will determine which script to run by using an if statement.

However, I want to know if there's an actual JavaScript function that would not choose the numbers at random but rather alternate going back and forth. Let me know.

This is the current script which works at random.

<script type="text/javascript">

test = Math.floor(Math.random() * 2) + 1;

if (test == 1){ 
    document.write("we got number 1");
}  
else if (test == 2){
    document.write("we got number 2");  
}
else {
    document.write("we got nothing");
}
</script>




output random numbers in three different rows

I am working on random numbers VBA and the below code picks a name from sheet2 and copies to sheet 1 and I can repeat these steps to pick 3 different names from that list. This code does a fantastic job when all the three names are in three consecutive rows but fails to pick 3 different names when they are in row 5th, row 10th and row 15th. Can someone help me pick three different names and put them in rows that are 5 rows apart? (1st name in 1st row, 2nd name in 5th row and 3rd name in 15th row) I am new to VBA!

Sub DDQ1()
Application.ScreenUpdating = False
Dim source, destination As Range
Set source = Sheets("sheet2").Range("A60:A81")
Sheets("sheet1").Activate
Set destination = ActiveSheet.Range("B53")
ReDim randoms(1 To source.Rows.Count)
destrow = 0
For i = 1 To destination.Rows.Count
 If destination(i) = "" Then: destrow = i: Exit For
Next i
If destrow = 0 Then: MsgBox "no more room in destination range": Exit Sub
For i = 1 To UBound(randoms): randoms(i) = Rnd(): Next i
ipick = 0: tries = 0
Do While ipick = 0 And tries < UBound(randoms)
tries = tries + 1
minrnd = WorksheetFunction.Min(randoms)
For i = 1 To UBound(randoms)
If randoms(i) = minrnd Then
  picked_before = False
  For j = 1 To destrow - 1
    If source(i) = destination(j) Then: picked_before = True: randoms(i) =        2: Exit For
  Next j
  If Not picked_before Then: ipick = i
  Exit For
End If
Next i
Loop
If ipick = 0 Then: MsgBox "no more unique name possible to pick": Exit Sub
destination(destrow) = source(ipick)
Application.ScreenUpdating = True
End Sub




Random java and Finding random

I have written a program which generates 5 random integers using Random in the java.util package and stores them in an array of objects. The array has as size of 252 (index 0 to index 251) where each index holds 5 values. I then use the Random instance to generate a random number between 0 and 251 to use as an integer. I was wondering since the random implementation is linear, would it be possible to guess the random integer that is generated for the index.




Lottery with Supernumber

I came across the challenge of building a random numbers generator for the lottery. 6 numbers, between 1 and 49, none of which appears twice, in ascending order. One 7th number, the superseven, not sorted, can't be one of the previous numbers.

    <script type="text/javascript">

    const numb = new Array ();
    for ( var i=0; i<6; i++ ) {
    numb[i]= Math.floor (49 * Math.random()) + 1;

    //compare to existing numbs
    for ( var k=0; k < numb.length - 1; k++ )
    {
        if (numb[i] == numb[k] ) {i--; break;}
    }



}
    let supNumb = new Array();
    supNumb = Math.floor (49 * Math.random()) + 1;
    for (var s=0; s<=1; s++ ) {
        // compare supNumb to numb
        for ( var t=0; t < numb.length - 1; t++ )
        {
            if (supNumb == numb[t] ) {s--; break;}
        }
    }




// SORT & DISPLAY NUMBERS 
function sort (a, b) {
    return a-b;
}

numb.sort(sort);
document.write("<p> " + numb );
document.write("<h4>" + "SuperSeven: "+ supNumb);

</script>

I know by trying the super seven (supNumb) is still giving out same numbers as in numb. I can't get it to work and can't find anywhere this being mentioned.

Somebody here can look over it and let me know how I can compare supNumb to numb?

Is this even the right structure?

Thanks in advance!




How do I generate random Strings for a multiple choice game

I am building a game that has a question with 4 multiple choice answers (in android studio). I am going to generate three wrong answers and 1 correct answer for all 45 questions in my app. I have a separate method that generates the question randomly (45 different questions). I am not quite sure how to do this.

public class MainActivity extends AppCompatActivity {

Button startGame;
TextView questionTextView;
questions question = new questions();
ArrayList<String> answers; //gets the correct
int correctAnswer;

public void START (View view) {

    startGame.setVisibility(View.INVISIBLE);

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Random rand = new Random();
    startGame = (Button) findViewById(R.id.startButton);
    questionTextView = (TextView) findViewById(R.id.questionTextview);
    questionTextView.setText(question.getQuestion());


    correctAnswer = rand.nextInt(4);

    for(int i = 0; i < 4; i++ ) {

        if(i == correctAnswer) {


        } else {


        }
    }
}

}

public class questions {

public String [] mquestions = {


        "Who is the 1st president of the United States?",
        "Who is the 2nd president of the United States?",
        "Who is the 3rd president of the United States?",
        "Who is the 4th president of the United States?",
        "Who is the 5th president of the United States?",
        "Who is the 6th president of the United States?",
        "Who is the 7th president of the United States?",
        "Who is the 8th president of the United States?",
        "Who is the 9th president of the United States?",
        "Who is the 10th president of the United States?",
        "Who is the 11th president of the United States?",
        "Who is the 12th president of the United States?",
        "Who is the 13th president of the United States?",
        "Who is the 14th president of the United States?",
        "Who is the 15th president of the United States?",
        "Who is the 16th president of the United States?",
        "Who is the 17th president of the United States?",
        "Who is the 18th president of the United States?",
        "Who is the 19th president of the United States?",
        "Who is the 20th president of the United States?",
        "Who is the 21st president of the United States?",
        "Who is the 22nd president of the United States?",
        "Who is the 23rd president of the United States?",
        "Who is the 24th president of the United States?",
        "Who is the 25th president of the United States?",
        "Who is the 26th president of the United States?",
        "Who is the 27th president of the United States?",
        "Who is the 28th president of the United States?",
        "Who is the 29th president of the United States?",
        "Who is the 30th president of the United States?",
        "Who is the 31st president of the United States?",
        "Who is the 32nd president of the United States?",
        "Who is the 33rd president of the United States?",
        "Who is the 34th president of the United States?",
        "Who is the 35th president of the United States?",
        "Who is the 36th president of the United States?",
        "Who is the 37th president of the United States?",
        "Who is the 38th president of the United States?",
        "Who is the 39th president of the United States?",
        "Who is the 40th president of the United States?",
        "Who is the 41st president of the United States?",
        "Who is the 42nd president of the United States?",
        "Who is the 43rd president of the United States?",
        "Who is the 44th president of the United States?",
        "Who is the 45th president of the United States?",

};


public String getQuestion() {

    String question = "";

    Random rand = new Random();
    //This randomizes the questions!!
    int randomNumber = rand.nextInt(mquestions.length);

    question = mquestions[randomNumber];

    return question;

}

}




Create Vector of Factors from random labelling of rows of a data frame

I have a dataframe with 110 rows which is the pData from a microarray experiment expressionset object. I want to create a vector of factors with 2 levels, randomly assigned to the rows (which represent the samples of the experiment). For example, if there are 110 rows corresponding to 110 subjects in the experiment I would want 55 rows to be set as “G0” and 55 as “G1”. These groups are used in a subsequent function. I am currently trying the following which is wrapped within a function I am trying to modify:

# makes a numeric vector of the number of subjects/rows in the pData
sml<-rep(0,length(colnames(eset))

# ‘populate’ sml with G0 & G1 
sml[sample(sml,(length(sml)/2))]<-"G0"
sml[sample(sml,(length(sml)/2))]<-"G1"
label <- as.factor(sml)

How do I sample such that the G1 group completes the length of sml and leaves the positions already assigned as G0 untouched? Thanks




mardi 25 juillet 2017

Removing random items from a list

So basically i have 10 txt files(named A_1,A_2........A_10), i want to randomly select 3 files out of these 10 in a way, when those 3 files are randomly chosen, they will be removed from the original list and a new list can be created using the randomly chosen 3 files.I tried the following method, but when i try the command print(filelist), it still shows the 10 txt files,Any suggestion or advice will be really helpful.

import random
filelist=[]
for i in list(range(1,11)):
    filelist.append("/Users/Hrihaan/Desktop/A_%s.txt" %i)
Newlist=random.sample(filelist,4)




Why does my code stop at a certain point

I have some code and for some reason, my variable won't do any math past a certain point.
The variable is here:
And my system.out.println also.

...
int finalp = min2 * max2 / multiplier1a + randomc;
int finalpa = finalp - randomf / min2 * multiplier2a / max2;
System.out.println("FinalP(roduct) : " + finalpa);
...

Any idea why this happens and how I can fix this error.




Change one random image in a list

I would like to create a client's logo wall like this : http://ift.tt/NiJHMy scroll down until "TRUSTED BY THE WORLD’S BEST" section.

To create the same effect, I begin to generate a liste of 8 elements from an array : http://ift.tt/2uyhCrS

After that, I tried to change randomly ONLY ONE image : http://ift.tt/2uUAX8U

I don't know how to change only one random image ? And after add the little move effect to from the bottom to the top.

HTML

<div class="list-items"></div>

CSS

.list-items {
    max-width: 500px;
}

.item {
    display: inline-block;
    float: left;
    margin: 10px;
    height: 100px;
    width: 100px;
    line-height: 100px;
    background-repeat: no-repeat;
    background-size: cover;

    img {
        display: inline-block;
        width: 100%;
        height: auto;
        max-height: 100%;
        vertical-align: middle;
    }
}

JQUERY

// List //
var logos = ["http://ift.tt/2uyUWrk", "http://ift.tt/2uUFl8b", "http://ift.tt/2uyFrQ3", "http://ift.tt/2uUTvGl", "http://ift.tt/2uytE4a", "http://ift.tt/2uTXsew", "http://ift.tt/2uy0Zwh", "http://ift.tt/2uV52FC"];

// Generate 8 items //
var i;
for (i = 0; i < 8; ++i) {
    $(".list-items").append('<a href="" class="item"><img src="" alt=""></a>');
}

// Shuffle function //
function shuffle(o) {
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

logos = shuffle(logos);

// Push src in image tag //
$('.item img').each(function(i) {
    $(this).attr('src', logos[i]);
});

// Change image //
count = 0;
  setInterval(function () {
    count++;
    $(".item img").fadeOut(600, function () {
      $(this).attr('src', logos[count % logos.length]).fadeIn(600);
    });
 }, 5000);

The "Change image" part don't work like I would like, it change all the image while I would like one image after the other.




Reading a random seed of a jupyter notebook

Is there a way to read the "state" of the random number generator in a jupyter notebook?

For example, if I ran a cell where I specify a neural network architecture, and then train it on some data without specifying a seed, is there a way I can then read what seed was used to run this?




Randomize a string list from a text file in an array Python?

I have a text file with several countries listed in it called countries.txt. I am trying to take those countries from the text file and place them in an array where they will then be randomized and the randomized list gets printed. I have tried editing the code in a few ways and none of them produce the outcome that I want.

Below is the first way I tried it. I know I'm printing the actual array but I was trying something:

results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(results)
            print(str(results))

And the outcome was as follows:

['Armenia\n']
['Bangladesh\n', 'Armenia\n']
['China\n', 'Armenia\n', 'Bangladesh\n']
['Denmark\n', 'Bangladesh\n', 'Armenia\n', 'China\n']
['Armenia\n', 'Bangladesh\n', 'Denmark\n', 'China\n', 'Estonia\n']
['Armenia\n', 'Estonia\n', 'Bangladesh\n', 'China\n', 'France\n', 'Denmark\n']
['France\n', 'China\n', 'Bangladesh\n', 'Armenia\n', 'Estonia\n', 'Denmark\n', 'Ghana']

The second attempt used the following code below:

results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(results)
            print(str(line))

And the outcome was right in the sense that it listed the countries the way i wanted it, but it did not randomize them. The outcome was:

Armenia
Bangladesh
China
Denmark
Estonia
France
Ghana

The last attempt I made was with the following code:

results = []

def load():
    with open('countries.txt') as inputfile:
        for line in inputfile:
            results.append(line)
            random.shuffle(line)
            print(str(line))

But this function produced the following error:

File "C:\Users\redcode\AppData\Local\Programs\Python\Python36-32\lib\random.py", line 274, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment

And the specific line producing the error is random.shuffle(line).

Am I missing something or is there a different way to do this because I cannot find anything different from what I've been trying.

So how can I get the list from a text file into an array, randomize that list and print the outcome (without []or "\n" and in a normal list format as shown in the second example)?




Visual Basic generate random number

I am new to coding and I want to make a simple program that moves a windows to a random location on your desktop. Right now my code is this:

    Me.Location = New Point(27, 55)
    Me.Location = New Point(502, 624)
    Me.Location = New Point(858, 477)
    Me.Location = New Point(564, 50)
    Me.Location = New Point(898, 41)
    Me.Location = New Point(468, 944)
    Me.Location = New Point(417, 7)
    Me.Location = New Point(841, 697)
    Me.Location = New Point(953, 438)

I had to put in the code myself so it will never be completely random and will always repeat itself. How do I make the numbers a random number?




Random number generator code fix (alternative for srand48/drand48)

Let me start by saying that I know near nothing about C and C++. That being said, I need to wrap some older code so am trying to struggle through it. Now, when trying to run a test, I get the error

Unresolvedexternal symbol srand45...

And the same for drand48.

The code I'm using starts as follows:

#include <stdio.h>
#include "arrays.h"
#include "poker.h"

void srand48();
double drand48();

And continues to use srand48 and drand48 in these snippets of code:

// Seed the random number generator.
srand48(getpid());

And for drand48:

//
//  This routine takes a deck and randomly mixes up
//  the order of the cards.
//
void
shuffle_deck(int *deck)
{
    int i, n, temp[52];

    for (i = 0; i < 52; i++)
        temp[i] = deck[i];

    for (i = 0; i < 52; i++)
    {
        do {
            n = (int)(51.9999999 * drand48());
        } while (temp[n] == 0);
        deck[i] = temp[n];
        temp[n] = 0;
    }
}

The full code can be found here: http://ift.tt/2v3QkN0

But I can't think of a way to fix this issue, even though it seems very minor. That said, speed is absolutely essential, as the code will be run several millions of times. I'm using visualstudio on a x64 machine.




ElasticSearch get random results with multiple filters doesn't work

Not getting proper results from elasticsearch with multiple filters.

I am following the documentation: http://ift.tt/1EZAvRI

It returns results for the very first filter and did not apply others filters like we can add AND operator in SQL statement.




Generating a list of random integers in python 3

I am getting a IndexError: list assignment index out of range error when trying to run this program. My index appears to be fine (0 through 8) and I don't think .append is needed since the equal sign assign the random value each pass. What am I missing?

import random

#The main function.
def main():

  #Welcome message.
  print("Welcome to the lottery number generator program!")
  print()

  #Explain what the program does.
  print("Note: This program will randomly generate a 7 digit lottery number and display it to the screen. ")
  print("________________________________________________________________________________________________")
  print()
  print()

  #Call the generateNumbers function and store its returned list in variable lotteryNumbers.
  lotteryNumbers = generateNumbers()

  #Call the printLottery function and pass the lotteryNumbers list as argument.
  printLottery(lotteryNumbers)


#The generateNumbers function generated 7 random digits between 0  and 9 stores them in a list and returns the list.
def generateNumbers():

  #A list variable to hold empty list.
  lotteryNumbers = []

  #Declare and set loop counter to 0.
  index = 0

  for index in range (0,8):
    lotteryNumbers[index] = random.randrange(0,10)
    index += 1
  return lotteryNumbers


def printLottery(lotteryNumbers):
  print("Here are the 7 lucky numbers: {}".format(lotteryNumbers))

#End main
main()




What would be the Mapping method of SecureRandom (Java 8)

We are using Oracle Java 8 SecureRandom using NativePRNG algo. Where could I find docs about mapping method of that algo?

Thanks.




The random.shuffle doesn't work

Why I can't shuffle this?

from random import shuffle, random
# to listen to all the files in the dir

def listen():
    '''listens to all the mp3 in the dir'''
    folder = os.listdir()
    shuffle(folder,random)
    for files in folder:
        if files.endswith(".mp3"):
            os.startfile(files)

The result is always in the same order... I tried also sample and other stuff, but the result is the same.




Obtaining random double with inclusive max value (Java - ThreadLocalRandom)

I have a method to obtain a random double between a min and a max value. My problem is that if the values are for example 0D and 10D I've never obtain 10D as a posible result because nextDouble second parameter is exclusive.

public static Double randomDouble(Double min, Double max) {
    return ThreadLocalRandom.current().nextDouble(min, max);
}

I've obtain a 10D result if I put this line in my method but I don't know if this is a good practice.

public static Double randomDouble(Double min, Double max) {

    max = max + 0.000000000000001D;

    return ThreadLocalRandom.current().nextDouble(min, max);
}

Is there another solution for this issue?




Should I periodically reSeed SecureRandom or it occurs automatically?

We are using SecureRandom as follows (using Java8):

import java.security.SecureRandom;

private SecureRandom random = new SecureRandom();

The algorithm being used is NativePRNG.

Should we seed periodically? In case we should how would we do that? (perhaps call new(..) again?)




How to strip random Chars at the end of a String with Regex / Strip() in Python?

What is the preferred way to cut off random characters at the end of a string in Python?

I am trying to simplify a list of URLs to do some analysis and therefore need to cut-off everything that comes after the file extension ".php"

Since the characters that follow after ".php" are different for each URL using strip() doesn't work. I thought about regex and substring(). But what would be the most efficient way to solve this task ?

Example:

Let's say I have the following URLs:

http://ift.tt/2tygFON
http://ift.tt/2uV7n2L

And I want the output to be:

http://ift.tt/1dt4zI4
http://ift.tt/1xn4HWI

Thanks for your advice !




Set variables of certain value in a matrix or array to random values in matlab

I have matrix (or an array here for easier understanding), that is filled with values, e.g.:

[0 0 1 0 0 0 1 0 0 0 ]

Now I want to fill every element that is, for example 0 to a random value, but each one should be different.

If I do it like this:

replace_val = 0
x = [ 0 0 1 0 0 0 1 0 0 0 ]
x(x == replace_val) = rand

Then all 0 will be replaced with the same number, e.g.:

[ 0.8361    0.8361    1.0000    0.8361    0.8361    0.8361    1.0000    0.8361    0.8361    0.8361 ]

Now the most straight forward way is to create a loop that will iterate over the vector and at any time the condition is met, it will call the rand function like here:

for i=1:length(x)
  if x(i) == replace_val
   x(i) = rand;
  end
end

However, with matrices or very large arrays this will be very slow. So, I am wondering if there is any kind of fast, matlabish way to get the desired output?




Generating non-repeating 6 numbers asking for maximum number in JS

Hi guys i have some code here asking for maximum number and generate 6 numbers .. but my problem is their a duplicate number generated, can someone tell me guys to correct my code...

<script>
function mygenerated()  { 
var rlts = document.getElementsByName("result");
for(var i=0 ; i<=5; i++)  { 
rlts[i].value=""; // clear results
}
var max=eval("document.lot.maxnum.value");
if (max.length<1) {
alert ("You must choose a number for the maximum value!");
document.lot.maxnum.focus();
return false;
}
for(var i=0 ; i<=5; i++)  { 
rlts[i].value=(Math.floor(Math.random()*max)+1);  
 }     
}
</script>

at first its look good but again there is a duplicate results appear.. :(