mardi 31 mars 2015

C# random choice if result

I am trying to code a random choice script in C# for example something like this:



foo = ['a', 'b', 'c']
result = random.choice(foo)

if result == "a":
webBrowser1.Navigate("http://www.google.com/");
if result == "b":
webBrowser1.Navigate("http://www.yahoo.com/");
if result == "c":
webBrowser1.Navigate("http://www.bing.com/");


The random script example above is in Python but don't know how to make a similar script like it in C# and couldn't find out how to do it by goggling my problem. If anyone knows how to code a random if result to randomly pick which code to run, please share. Thanks in Advance!





Magento random item on homepage

i am new at Magento, and i encountered my first problem. That items will show randomly on homepage.


I have this code:



<?php

$_productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$_items = $_productCollection->getItems();
?>

<?php if ($_collectionSize && $tmpHtml = $this->getChildHtml('block_category_above_collection')): ?>
<div class="block_category_above_collection std"><?php echo $tmpHtml; ?></div>
<?php endif; ?>

<?php if(!$_collectionSize): ?>
<?php if ($tmpHtml = $this->getChildHtml('block_category_above_empty_collection')): ?>
<div class="block_category_above_empty_collection std"><?php echo $tmpHtml; ?></div>
<?php else: ?>


And when is change it to



<?php
$_productCollection=$this->getLoadedProductCollection();
$_collectionSize = $_productCollection->count();
shuffle($_productCollection);


?>


it's showing me fatal error.


I even tried this



<?php
// $_productCollection = $this->getLoadedProductCollection();
$_helper = $this->helper('catalog/output');
$_category = Mage::getModel('catalog/category')->load($this->getCategoryId());
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addCategoryFilter($_category)
->setVisibility(array(2,3,4));
$_productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$_productCollection->setPage(1, 4);

?>


But nothing helped. What am i doing wrong ?





I need a button NOT to disapear

I am making a javascript code that has a button and when I click on it, it displays one of 5 symbols but when I click the button, it shows the random symbol but the button disapears. I'm new to javascript so can I please get some help?



<script>

function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0)
{
document.write("\u2663");
}
if (slot1 == 1)
{
document.write("\u2665");
}
if (slot1 == 2)
{
document.write("\u2666");
}
if (slot1 == 3)
{
document.write("\u2660");
}
if (slot1 == 4)
{
document.write("7");
}

}

</script>
<button type="button" value="Spin" name="SPIN"onClick="slots(); return false;"></button>

</body>
</html>




Creating a random circle that can be clicked on like a button but is a circle

so here is my predicament i cannot seem to find this anywhere on the internet. My question is simple. I am creating a game app for android. The game will generate random circles on the screen that a user can click on then once the user does click on one of these random circles an action will occur. This is just like the function of the button, but different because the whole circle will be able to be clicked. I will post the random number generator that generates the circles. This is not the main class this is a separate class that extends view. I have attempted to do this below in the onTouchEvent method, but now i get errors in the logcat i have posted those below as well a long with the main class. please i feel as if i am very close to finding a solution to this problem. if anyone could tell me what i am doing wrong in this class that would be very helpful thanks everyone



public class DrawingView extends View {



public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub

}
RectF rectf = new RectF(0, 0, 200, 0);

private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth =(int) (random.nextInt(getWidth()-radius/2) + radius/2f);
int randomHeight = (random.nextInt((int) (getHeight()-radius/2 + radius/2f)));

private final Runnable updateCircle = new Runnable() {
@Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
invalidate();
handler.postDelayed(this, 1000);

}
};



@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}

@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here

canvas.drawCircle(randomWidth, randomHeight + radius/2f, radius, paint);
}

@Override
public boolean onTouchEvent (MotionEvent event) {

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN :
randomWidth = (int) event.getX();
randomHeight = (int) event.getY();
invalidate();
break;
}

return true;

}


tell me if this can even be done or if im going to have to completely change my code thank you here is my main class if that helps any this is the only other code i have so here it is please disregard the comments i was trying to learn this on my own and horribly failed each time



public class Main extends Activity {
DrawingView v;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);


LinearLayout layout1 = new LinearLayout (this);
FrameLayout game = new FrameLayout(this);
DrawingView v = new DrawingView (this);

TextView myText = new TextView(this);

//int w = getResources().getInteger(DrawingView.redColor);
//Button redCircle = (Button) findViewById(w);



//redCircle.setWidth(300);
//redCircle.setText("Start Game");


layout1.addView(myText);
// layout1.addView(redCircle);
//redCircle.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

//game.addView(myText);
game.addView(v);
game.addView(layout1);
setContentView(game);
//redCircle.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
Intent intent = new Intent(this, Main.class);
startActivity(intent);

// re-starts this activity from game-view. add this.finish(); to remove from stack
}

@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}


I get these errors now in the log cat



03-31 01:48:52.594: E/AndroidRuntime(2395): FATAL EXCEPTION: main
03-31 01:48:52.594: E/AndroidRuntime(2395): Process: com.Tripps.thesimplegame, PID: 2395
03-31 01:48:52.594: E/AndroidRuntime(2395): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Tripps.thesimplegame/com.Tripps.thesimplegame.Main}: java.lang.IllegalArgumentException: n <= 0: -115
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.app.ActivityThread.access$800(ActivityThread.java:144)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.os.Looper.loop(Looper.java:135)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-31 01:48:52.594: E/AndroidRuntime(2395): at java.lang.reflect.Method.invoke(Native Method)
03-31 01:48:52.594: E/AndroidRuntime(2395): at java.lang.reflect.Method.invoke(Method.java:372)
03-31 01:48:52.594: E/AndroidRuntime(2395): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-31 01:48:52.594: E/AndroidRuntime(2395): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-31 01:48:52.594: E/AndroidRuntime(2395): Caused by: java.lang.IllegalArgumentException: n <= 0: -115
03-31 01:48:52.594: E/AndroidRuntime(2395): at java.util.Random.nextInt(Random.java:182)
03-31 01:48:52.594: E/AndroidRuntime(2395): at com.Tripps.thesimplegame.DrawingView.<init>(DrawingView.java:37)
03-31 01:48:52.594: E/AndroidRuntime(2395): at com.Tripps.thesimplegame.Main.onCreate(Main.java:30)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.app.Activity.performCreate(Activity.java:5933)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
03-31 01:48:52.594: E/AndroidRuntime(2395): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
03-31 01:48:52.594: E/AndroidRuntime(2395): ... 10 more




Randomly assign race names to companies

My school is keeping a track meet and we have some sponsors that paid for branding right to a race or multiple races and such i should write a program that randomly assigns races to each sponsor.





How to generate unique chars when populating a 2D array?

How do I make it so that when I output the grid when I run the code, no two numbers or letters will be the same? When I currently run this code I could get 3x "L" or 2x "6", how do I make it so that they only appear once?



package polycipher;

import java.util.ArrayList;

public class Matrix {
private char[][] matrix = new char[6][6];
private int[] usedNumbers = new int[50];

{for(int x = 0; x < usedNumbers.length; x++) usedNumbers[x] = -1;}

private final char[] CIPHER_KEY = {'A','D','F','G','V','X'};
private final String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

public Matrix() {
int random;
for(int i = 0; i < CIPHER_KEY.length; i++) {
for(int j = 0; j < CIPHER_KEY.length; j++) {
validation: while(true) {
random = (int)(Math.random()*validChars.length()-1);
for(int k = 0; k < usedNumbers.length; k++) {
if(random == usedNumbers[k]) continue validation;
else if(usedNumbers[k]==-1) usedNumbers[k] = random;
}
break;
}
matrix[i][j] = validChars.split("")[random].charAt(0);
}
}
}

public String toString() {
String output = " A D F G V X\n";
for(int i = 0; i < CIPHER_KEY.length; i++) {
output += CIPHER_KEY[i] + " ";
for(int j = 0; j < CIPHER_KEY.length; j++) {
output += matrix[i][j] + " ";
}
output += "\n";
}
return output;
}
}




How do i generate multiple keywords from sentence in php

I want to generate keywords from a sentence like this:


Sentence : This is test



this
this is
test this
is this
this is test
test is this
vice versa


I have to retrieve values from two fields from mysql table and then generate randomized keywords stated above. Then i will store generated keywords in another field of table.


How do i achieve this in PHP?





C++ rand() why give me the same number How can i have different [duplicate]


This question already has an answer here:





if (ii == 3){//车辆只停了一个小时,有3/4的概率离场
srand((unsigned)time(NULL)*100);
int a = 1+rand() % 4;
int b = 1+rand() % 4;
int c = 1+rand() % 4;
cout << "++++3 " << a << "++++" << endl;//用作测试判断是否离场函数
cout << "++++3 " << b << "++++" << endl;
cout << "++++3 " << c << "++++" << endl;
cout << "*************" << endl;
if ((a == 1 && b == 2 && c == 3)||(a==2&&b==1&&c==3)||(a==3&&b==2&&c==1)||(a==3&&b==2&&c==1))
return true;
else
return false;
}![enter image description here][1]


just like this picture programe give me the same number ,but i need different,how can i do it.





Is it a bad practise to recursively instantiate the same object in any of its method?

I tried to write a weighted lottery drawing class in Ruby, and it proved useful to recursively instantiate the same class in any of its method definition:



class Weighted_draw
attr_accessor :elements_with_weights,:sum_of_weights,:sorted_elements_with_weights,
:elements_with_cumulated_weights

def initialize(w)
@sum_of_weights=w.map{|z| z[1]}.inject(:+)
if sum_of_weights != 1.0 then
@elements_with_weights=w.map{|z| [z[0],z[1].fdiv(sum_of_weights)]}
else
@elements_with_weights=w
end

@sorted_elements_with_weights=elements_with_weights.sort_by{|z| z[1]}
@elements_with_cumulated_weights=sorted_elements_with_weights.collect.with_index.map{|z,i| [z[0],sorted_elements_with_weights[0..i].map{|q| q[1]}.inject(:+)]}
end



def pick
r=rand
self.elements_with_cumulated_weights.find{|z| z[1]>=r}[0]
end

def pick_n(n)
if n>elements_with_weights.size then
return nil
else
ret=[]
wd=Weighted_draw.new(elements_with_weights)
for i in 1..n do

picked_element=wd.pick

ret.push picked_element
wd=Weighted_draw.new(elements_with_weights.reject{|z| z[0]==picked_element})

end
return ret.sort
end
end
end
end


Then I can use it as:



w=[[1,0.25],[2,0.1],[3,0.25],[4,0.1],[5,0.3]]
wd=Weighted_draw.new(w)
wd.pick_n(2)


Is it an allowed practise?





How can i put my random values into an array in java?

I'm making a program that uses selection sort on a set of integers, but im making it better by allowing the user to ask how many integers they want to be sorted, if they want to input the integers or want the integers randomly generated. Ive coded the program to be able to generate the random integers so far, but i haven't gotten to the user being able to generate their own numbers.


How am i able to take those randomly generated numbers, and put them into an array so that i can use Selection sort on those values.


Thanks



package sortingexcersices;

import java.util.Scanner;
import java.util.Random;

public class SortingExcersices {

public static int myarray[], numOfElements, arrValues, n;

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("How many integers do you want to sort?");
numOfElements = in.nextInt();

myarray = new int[numOfElements];

boolean found = false;

do {

System.out.println("If you would like random numbers, press 1.");
System.out.println("If you would like to generate your own numbers, press 2.");

n = in.nextInt();

if (n == 1) {
found = true;
} else if (n == 2) {
found = false;
} else {
System.out.println("Your input was invalid.");
}

} while (n != 1 && n != 2);

if (found = true) {
Random values = new Random();

for (int i = 1; i <= myarray.length; i++) {
arrValues = 1 + values.nextInt(50);
System.out.print(arrValues + " ,");


}
}

}
}




Avoid basic rand() bias in Monte Carlo simulation?

I am rewriting a monte carlo simulation in C from Objective C to use in a dll from VBA/Excel. The "engine" in the calculation is the creation of a random number between 0 and 10001 that is compared to a variable in the 5000-7000 neighbourhood. This is used 4-800 times per iteration and I use 100000 iterations. So that is about 50.000.000 generations of random numbers per run.


While in Objective C the tests showed no bias, I have huge problems with the C code. Objective C is a superset of C, so 95% of the code was copy paste and hard to screw up. I have gone through the rest many times all day yesterday and today and I have found no problems.


I am left with the difference between arc4random_uniform() and rand() with the use of srand(), especially because a bias towards the lower numbers of 0 to 10000. The test I have conducted is consistent with such a bias of .5 to 2 % towards numbers below circa 5000. The any other explanation is if my code avoided repeats which I guess it doesn´t do.


the code is really simple ("spiller1evne" and "spiller2evne" being a number between 5500 and 6500):



srand((unsigned)time(NULL));
for (j=0;j<antala;++j){
[..]
for (i=1;i<450;i++){
chance = (rand() % 10001);

[..]

if (grey==1) {


if (chance < spiller1evnea) vinder = 1;
else vinder = 2;
}
else{
if (chance < spiller2evnea) vinder = 2;
else vinder = 1;
}


Now I don´t need true randomness, pseudorandomness is quite fine. I only need it to be approximatly even distributed on a cummulative basis (like it doesn´t matter much if 5555 is twice as likely to come out as 5556. It does matter if 5500-5599 is 5% more likely as 5600-5699 and if there is a clear 0.5-2% bias towards 0-4000 than 6000-9999.


First, does it sound plausible that rand() is my problem and Is there an easy implementation that meets my low needs?


EDIT: if my suspicion is plausible, could I use any on this:


http://ift.tt/1IicN5f


Would I be able to just copy paste this in as a replacement (I am writing in C and using Visual Studio, really novice)?:



#include <stdlib.h>

#define RS_SCALE (1.0 / (1.0 + RAND_MAX))

double drand (void) {
double d;
do {
d = (((rand () * RS_SCALE) + rand ()) * RS_SCALE + rand ()) * RS_SCALE;
} while (d >= 1); /* Round off */
return d;
}

#define irand(x) ((unsigned int) ((x) * drand ()))


EDIT2: Well clearly the above code works without the same bias so I would this be a recommendation for anyone who have the same "middle-of-the-road"-need as I described above. It does come with a penalty as it calls rand() three times. So I am still looking for a faster solution.





How do I interpret the results from dieharder for great justice

This is a question about an SO question; I don't think it belongs in meta despite being sp by definition, but if someone feels it should go to math, cross-validated, etc., please let me know.


Background: @ForceBru asked this question about how to generate a 64 bit random number using rand(). @nwellnhof provided an answer that was accepted that basically takes the low 15 bits of 5 random numbers (because MAXRAND is apparently only guaranteed to be 15bits on at least some compilers) and glues them together and then drops the first 11 bits (15*5-64=11). @NikBougalis made a comment that while this seems reasonable, it won't pass many statistical tests of randomnes. @Foon (me) asked for a citation or an example of a test that it would fail. @NikBougalis replied with an answer that didn't elucidate me; @DavidSwartz suggested running it against dieharder.


So, I ran dieharder. I ran it against the algorithm in question



unsigned long long llrand() {
unsigned long long r = 0;

for (int i = 0; i < 5; ++i) {
r = (r << 15) | (rand() & 0x7FFF);
}

return r & 0xFFFFFFFFFFFFFFFFULL;
}


For comparison, I also ran it against just rand() and just 8bits of rand() at at time.



void rand_test()
{
int x;
srand(1);
while(1)
{
x = rand();
fwrite(&x,sizeof(x),1,stdout);
}

void rand_byte_test()
{
srand(1);
while(1)
{
x = rand();
c = x % 256;
fwrite(&c,sizeof(c),1,stdout);
}
}


The algorithm under question came back with two tests showing weakenesses for rgb_lagged_sum for ntuple=28 and one of the sts_serials for ntuple=8.


The just using rand() failed horribly on many tests, presumably because I'm taking a number that has 15 bits of randomness and passing it off as 32 bits of randomness.


The using the low 8 bits of rand() at a time came back as weak for rgb_lagged_sum| 2


My question(s) is:



  1. Am I interpretting the results for 8 bits of randomly correctly, namely that given that one of the tests (which was marked as "good"; for the record, it also came back as weak for one of the dieharder tests marked "suspect"), rand()'s randomness should be marginally suspected.

  2. Am I interpretting the results for the algorithm under test correctly (namely that this should also be marginally suspected (perhaps twice as much) as just rand()

  3. Given the description of what the tests that came back as weak do (e.g for sts_serial looks at whether the distribution of bit patterns of a certain size is valid), should I be able to determine what the bias likely is

  4. If 3, since I'm not, can someone point out what I should be seeing?





PCG Random Number Generator and Xcode Undefined symbols (unable to find Kernel)

Before asking the question I have to say that I'm currently using Xcode 6.2 on Yosemite.


I have been experiencing this problem also with another C code of mine which involved the generation of random numbers.


So, I wanted to use this famous library to generate random numbers (In particular I'm trying to compile the file called pcg_basic.c that you can find in the download of Minimal C Implementation 0.9). I created the project with Xcode and compiled. Then I got the following error message:



Undefined symbols for architecture x86_64:
"_main", referenced from:
implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


I googled a bit and it seems that I had to change the Architecture to Universal. Unfortunately it doesn't change a lot because I get the same error for 32bit



Undefined symbols for architecture i386


Then I googled again, thus I added Frameworks and Libraries. Since I didn't know which one I needed, I added all of them. However, I get this error message:



ld: framework not found Kernel
clang: error: linker command failed with exit code 1 (use -v to see invocation)


Which is kind of strange! I'm quite sure the RNG doesn't involve the Kernel.


Does anyone have any idea why I get this error messages? Is it related only with random numbers?





lundi 30 mars 2015

How do I create random Boolean array with at least one 1 in each row in matlab?

I am trying to create roandom boolean arrays in Matlab with atleast one 1 in each row.





Lisp Biased Number Generator

Is there a way to specify bias in a random generator in lisp?


For instance if I had a range of numbers. How can I specify that the numbers in the first half of the range are 3x more likely than those in the last half?


Thanks





From 256bit randomize from array of 54 elements

If I have a 256 bit array (selector),Ho do I select 5 elements from an array of 54 element using the 256 bit array ?. It's possible to take only first K bits from selector array to accomplish it and not use all the 256 bit. The requirements are:



  • Same selector will lead to same 5 elements being picked .

  • Need it to be statistically fair so if I run all every possibility of bits in the selector array it will bring an even spread of times occurrences in the the 5 elements array.


I know that there is 2,598,960 combinations of 5 element can be selected from array of 54, without caring about the order of selecting them.





How to create a Android random with an image

How do I generate a random with a image in android eclipse? I want to have a image randomly show up once one of the three buttons are clicked. So its a guessing game and the user has to choose the correct button and keep going it its not that random image. How would this work?





Add random Span elements in text to prevent scrapping

Is there some class that can add random span tags in text in order to make is more difficult for scrapping. I saw that Proxy Lists sites use methods like that.





random sampling with or without replacement in postgresql

I am looking for the possible ways of random sampling in postgreql, I found couple of methods to do that with different advantages and disadvantages,the naive way to do that is :



select * from Table_Name
order by random()
limit 10;


another faster method is:



select * from Table_Name
WHERE random()<= 0.01
order by random()
limit 10;


(although that 0.01 depends on the table size and the sample size,this is just an example).



in both of these queries a random number is generated for each row and sorted based on those random generated numbers and then in the sorted numbers the first 10 is selected as the final result,so I think these should be sampling without replacement.



now what I want to do is to somehow turn this sampling methods into sampling with replacement,how is that possible? or is there any other random sampling method with replacement in postgresql?





Random set of images using php

I have this code that I've been using to select one random image. Now I need to select four random images.


I've tried to modify the code and it does work but I can't figure out a way to prevent the same images appearing twice. My knowledge of php is basic at best.


Can anyone shed any light please?


Thanks


my code



<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/_/images/banners/';

function getImagesFromDir($path) {
$images = array();
if ( $img_dir = @opendir($path) ) {
while ( false !== ($img_file = readdir($img_dir)) ) {

if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
$images[] = $img_file;
}
}
closedir($img_dir);
}
return $images;
}

function getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 );
$num = array_rand($ar);
return $ar[$num];
}

$imgList = getImagesFromDir($root . $path);

$imgA = getRandomFromArray($imgList);
$imgB = getRandomFromArray($imgList);
$imgC = getRandomFromArray($imgList);
$imgD = getRandomFromArray($imgList);
?>

<img src="<?php echo $path . $imgA ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgA)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgB ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgB)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgC ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgC)) . ' Logo'; ?>">
<img src="<?php echo $path . $imgD ?>" alt="<?php echo ucfirst(preg_replace('/\\.[^.\\s]{3,4}$/', '', $imgD)) . ' Logo'; ?>">




Why would you write your own Random Number Generator? [on hold]

I've read a lot of guides on how to write your own random number generator, so I'm interested in the reasons why you would write your own since most languages already provide functions for generating random numbers:


Like C++



srand(time(NULL));
rand();


C#



Random rand = new Random();
rand.Next(100);


and Java



Random rand = new Random();
rand.nextInt(0, 100);


I'm mainly looking for advantages to using your own.





Identify Random Strings in Python

I'm trying to identify random strings from list of strings in python, I want to read each word and be able to say if it is random or if it is a meaningful word.


ex - rrstm asdfsa qmquas


Other than storing all the english words in a file and comparing them, are there any solution or existing code library already present ?





Generating a (random) sequence of multiple characters in R



  1. I can create a sequence of single letters using



    LETTERS[seq( from = 1, to = 10 )]
    letters[seq( from = 1, to = 10 )]



  2. I can create a random string of various length, using the random package



    library(random)
    string <- randomStrings(n=10, len=5, digits=TRUE, upperalpha=TRUE,
    loweralpha=TRUE, unique=TRUE, check=TRUE)



Unfortunately, I cannot use the set.seed function for example 2.


Is there a way to create the same (random) combination of (unique) strings everytime one runs a R-file?


My result would look like this (with the same result everytime I run the function):



V1
[1,] "k7QET"
[2,] "CLlWm"
[3,] "yPuwh"
[4,] "JJqEX"
[5,] "38soF"
[6,] "xkozk"
[7,] "uaiOW"
[8,] "tZcrW"
[9,] "8K4Cc"
[10,] "RAhuU"




Xorshift pseudorandom number generator with shiftvalues in progmem

I started implementing a xor shift generator. To safe some RAM I tried to put the shiftvalues into the PROGMEM but this actually does make some "strange" results and i dont know why. It seems that it returns the same value for a long time, than get back to regular expected results.


I hope you can help me and show me what I have done wrong.



const uint8_t shift[] PROGMEM =
{
0x01, 0x01, 0x02, 0x01, 0x01, 0x03, 0x01, 0x07, 0x03, 0x01, 0x07, 0x06, 0x01, 0x07, 0x07, 0x02, 0x01, 0x01,
0x02, 0x05, 0x05, 0x03, 0x01, 0x01, 0x03, 0x01, 0x05, 0x03, 0x05, 0x04, 0x03, 0x05, 0x05, 0x03, 0x05, 0x07,
0x03, 0x07, 0x01, 0x04, 0x05, 0x03, 0x05, 0x01, 0x03, 0x05, 0x03, 0x06, 0x05, 0x03, 0x07, 0x05, 0x05, 0x02,
0x05, 0x05, 0x03, 0x06, 0x03, 0x05, 0x06, 0x07, 0x01, 0x07, 0x03, 0x05, 0x07, 0x05, 0x03, 0x07, 0x07, 0x01
}; //needed as hex

static uint8_t y8 = 13;
static uint8_t cur_shift = 0, request_count = 0;

uint8_t rnd()
{
//shift the shifting numbers
request_count++;
if(request_count == 255)
{
request_count = 0;
cur_shift++;
if (cur_shift == 24)
{
cur_shift = 0;
}
}
//shift something around
y8 ^= (y8 << pgm_read_byte(&(shift[cur_shift * 3])));
y8 ^= (y8 >> pgm_read_byte(&(shift[cur_shift * 3 + 1])));
return y8 ^= pgm_read_byte(&(shift[cur_shift * 3 + 2]));
}


Reference to the Numbers for the shift





dimanche 29 mars 2015

Excel how to find real random data set from mean and standard deviation?

It's easy to find mean and std dev from 10 single data, but how to find back the 10 single data from the mean and std dev?


In excel right click view code can use macro coding, how can I do it in excel?





how to make any advertisements in the page to be random

for example when I open whatever.com(example), it will show me amazon advertisement. then when I refresh the page back, it will show me Facebook advertisement. and when I refresh again it will show me different type of advertisements.


can anyone help?





Excel random number keep recalculating

This is my function :



=NORMINV(RAND(),$A$1,$A$2)


When I do something other, the random number recalculate again


How can I make the random number static on the 1st





How do i set the image to appear at the end of the timer in another random place?

Im trying to make image reappear at the end of the timer. i cant figure out what i did wrong. the image appears in a random spot in the beginning but thats it. what i need is for the application to launch and then display the 3 dots in random places and every 1 second appear in another random place



public class Main extends ApplicationAdapter {
SpriteBatch batch;
Texture blue;
Texture red;
Texture green;
Sprite spriteb;
Sprite spriter;
Sprite spriteg;
int x;
int y;
Random random = new Random();
private float counter;
private int number;

@Override
public void create () {
batch = new SpriteBatch();
blue = new Texture("blue.png");
red = new Texture("red.png");
green = new Texture("green.png");
spriteb = new Sprite(blue);
spriter = new Sprite(red);
spriteg = new Sprite(green);
spriteb.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
spriter.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
spriteg.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));


}

@Override
public void render () {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
spriteb.draw(batch);
spriter.draw(batch);
spriteg.draw(batch);
batch.end();
}

public void render (float deltaTime) {
counter -= deltaTime;
if (counter <= 0) {
spriteb.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
counter += 1000; // add one second
batch.begin();
spriteb.draw(batch);
batch.end();
}
}
}




Does rand() ever return zero on OSX?

I have been running this code for almost ten hours with no love:



while ( true ) {
int r = rand();
assert( r != 0 );
}


I am expected rand() to eventually roll a zero and thus assert. I'm on a 2GHz machine if that makes any difference.


Am I doing something wrong or does rand() never return zero? Or have I not been waiting long enough to expect to see it?





If statement won't work in python 2.7.9

I'm writing a twitterbot, and for some reason I got a problem. here's the code (Ommitting my Access/Consumer keys of course). I based this off an earlier code of mine that worked so I don't see the problem. The first one is the new code...



while True:
choice1 = random.choice(choices)
choice2 = random.choice(choices)
api.update_status(status="Turn %s, Dice 1: %s, Dice 2: %s" % (turns, choice1, choice2)
**if choice1 == choice2:**
if doubles == 2:
api.update_status(status="I will not be able to tweet anymore, because I had to go to jail. I have served my purpose.")
break
else:
doubles = doubles + 1
else:
turns = turns + 1
doubles = 0
time.sleep(25)


And the second is the old one.



import random
turns = 1
doubles = 0
choices = [1, 2, 3, 4, 5, 6]
while True:
print 'Turn %s:' % (turns)
choice1 = random.choice(choices)
print choice1
choice2 = random.choice(choices)
print choice2
print ' '
if choice1 == choice2:
if doubles == 2:
print 'You got doubles three times! in a row! Go to jail!'
break
else:
doubles = doubles + 1
else:
turns = turns + 1
doubles = 0


The code that's glitching is nearly the same so I'm confused why it's not working.





Generate random exponential value correctly c++

I want to generate random number belonging to an exponential distribution. I wrote this



int size = atoi(argv[2]);
double *values = (double*)malloc(sizeof(double)*size);

double gamma = atof(argv[1]);
if(gamma<=0.0){
cout<<"Insert gamma"<<endl;
return 0;
}


for(int i=0; i<size; i++){
values[i]=0;

}

srand ( time(NULL) );
for(int i=0; i<size; i++){
x = ((double) rand() / (RAND_MAX));
//cout << random <<endl;
value=(log(1.0-x)/(-gamma));
//count each value
values[value]=values[value]+1.0;
}


But they do not cover all the vector's size. More or less they cover 10% of the vector, the other fields are all 0 and due to the fact that after I need to do a linear interpolation I want to reduce those 'empty space' in order to have at least one value for each cell of the array, How can I do it? for example I have a vector of 100000 only the first 60 fields are filled with values so cells from 60 to 999999 are all 0 and when I do linear regression they impact negatively on formula.





Generating random numbers in range until a max for that number has been met

I'm trying to do something basic - use range 0-4 and generate a 36 number sequence such that each value is generated 9 times.


The var trial_init is just an array of 36 zeros.


I have generated:



trial_seq = []

for i in range(len(trial_init)-1):
while True:
trial_val = random.choice(range(4))
if (trial_seq.count(0) <=9 and trial_seq.count(1) <=9 and trial_seq.count(2) <=9 and trial_seq.count(3) <=9):
break
trial_seq.append(trial_val)


I guess I'm not sure exactly why it doesn't work.


It should generate a number 0, 1, 2 or 3 and to the extent that number has not been included in the trial_seq array more than 9 times, it should add it to the trial_seq array, otherwise it should generate another number, until 36 numbers have been generated.





Same random number each day php

I want to display a quote of the day by finding the id of the post, so I'm using the seeds as the lowest and highest ids, so each day I get a random id, this will display a random post each day. I am using this to generate the same random number each day:



mt_srand(crc32(date('D d F Y')));
echo $random = (mt_rand(1,8288));


This worked perfectly on php version 5.3 or lower however on one of my other servers which is version 5.4.33. It doesn't work and always creates a new one each time. I have changed php versions to test this and it seems that it is the version that affects it. Is there another way to generate a 'consistent random' number each day? I need a number so that I can query the database and show a particular post per day.


I don't want to create another table or add another row to add dates for each post because that'll mean I have to create future dates for each post and there are already too many rows to do that.





NetLogo - Random setup - Random value to each patch - Error

As part of the setup procedure I am trying to use a slider to set the density of patches which will be displayed and assigned a random value. The slider on the interface for density ranges 0 to 100 and the random value of the patch is set using an input on the interface. This will normally be set in the region go 4. So, if 50% is set the the procedure will assign 50% of the patches with a random value.


When i do i get the following error: "Expected command" and the variable 'error-count' is highlighted in the code.



;; The density of patches to be set with a random value is set using variable init-errors on interface.
;; Every patch uses a task which reports a random value.
;; The random value is set using variable error-count on interface
to setup-random
ask patches [
if (random-float 100.0) < init-errors
[setup task random error-count]
]
end




How can I generate a random number?

I tried



use std::rand::{task_rng, Rng};

fn main() {
// a number from [-40.0, 13000.0)
let num: f64 = task_rng().gen_range(-40.0, 1.3e4);
println!("{}", num);
}


but this gives



rust.rs:1:17: 1:25 error: unresolved import `std::rand::task_rng`. There is no `task_rng` in `std::rand`
rust.rs:1 use std::rand::{task_rng, Rng};
^~~~~~~~
error: aborting due to previous error


and I tried



extern crate rand;
use rand::Rng;

fn main() {
let mut rng = rand::thread_rng();
if rng.gen() { // random bool
println!("i32: {}, u32: {}", rng.gen::<i32>(), rng.gen::<u32>())
}
let tuple = rand::random::<(f64, char)>();
println!("{:?}", tuple)
}


and got



rust.rs:5:19: 5:35 error: unresolved name `rand::thread_rng`
rust.rs:5 let mut rng = rand::thread_rng();
^~~~~~~~~~~~~~~~
rust.rs:9:17: 9:44 error: unresolved name `rand::random`
rust.rs:9 let tuple = rand::random::<(f64, char)>();
^~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to 2 previous errors


I am using Rust 1.0.0-dev.





Im trying to draw either a green or a red circle forever on to the android screen

im trying to make a game that when a user clicks on a green button it disappears but when a user clicks on a red button they loose im having trouble displaying multiple random buttons continuously on forever onto the screen here is my code



package com.Tripps.thesimplegame;

import java.util.Random;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Paint.FontMetrics;
import android.util.AttributeSet;
import android.view.View;

public class DrawingView extends View {
int mBackgroundColor = 000000;
String yo = "#";
Paint paint;
final float radius = 230f;
private long lastUpdated = 0;
private int lastColor = Color.BLACK;

public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public DrawingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}


@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas){

String str = "Joke of the day";
super.onDraw(canvas);
paint = new Paint();
Random random = new Random();
Random randomTwo = new Random();

//Rect ourRect = new Rect();
Rect topRect = new Rect();
Rect backGround = new Rect();

paint.setColor(Color.BLACK);
backGround.set(0,0,canvas.getWidth(),canvas.getHeight());
canvas.drawRect(backGround, paint);


while(System.currentTimeMillis() > lastUpdated + 1000){
lastColor = random.nextInt(2) == 1 ? Color.RED : Color.GREEN;
lastUpdated = System.currentTimeMillis();
paint.setColor(lastColor);
canvas.drawCircle(random.nextInt((int) (canvas.getWidth()-radius/2)) + radius/2f, random.nextInt((int) (canvas.getHeight()-radius/2)) + radius/2f, radius, paint);
}
}
}




Action Script 3.0. How to add random room's template and items with random positions inside

In my flash game are 9 possible rooms. In each room are 3 fixed positions where items can be added. There also are 3 items on every room, but items should be added always in different positions.


For example If here are 3 positions(locations): A(x=1;y=1) B(x=2;y=2) C(x=3;y=3) and Item1 Item2 Item3, sometimes Item1 should be added to A(x=1;y=1), sometimes to B(x=2;y=2) and etc. should be random chance in which positions items will be added.




In this image is shown only 3 rooms, but total I have 9. As you see all rooms have different position for items, but It's fixed on every room and items (blue, pink, yellow) should have ability to change positions everytime It's added to stage.


random rooms


What will be best performance to do It?


It is declared in following:



var room1:Room1 = new Room1();
var item1:Item1 = new Item1();
var item2:Item2 = new Item2();
var item3:Item3 = new Item3();

var room2:Room2 = new Room2();
var item4:Item4 = new Item4();
var item5:Item5 = new Item5();
var item6:Item6 = new Item6();

....


So in Room1 should be added Item1 Item2 and Item3, in Room2 should be added Item4 Item5 and Item6 and etc.


First of all I need to choose randomly 1 of 9 rooms. Should It be something like this?


addChild(Room+randNumber)


Later I need to specify if for every room?



if(Room+randNumber == Room1) {
addChild(Item1);
addChild(Item2);
addChild(Item3);
}


But in this case how to set 3 static x, y position for every room and set It for every item randomly?





Random picture from class in button (C#)

I have to make a little game for school where you have flags of countries and their names (in a listbox (named lstCountries) for me) and you need to combine them to score points.


I want to get random flags in buttons which I create like this



//Buttons Row 1
for (int i = 0; i < 5; i++)
{
Button btnNew = new Button();
btnNew.Location = new System.Drawing.Point(230 + 110 * i, 100);
btnNew.Name = "btnFlag";
btnNew.Size = new System.Drawing.Size(100, 100);
btnNew.TabIndex = 0;
btnNew.Text = "";
btnNew.UseVisualStyleBackColor = true;
btnNew.Click += new System.EventHandler(buttonToevoegen);
Controls.Add(btnNew);
aButtons.Add(btnNew);
}


And I made a class named Country:



class Country
{
public string Name { get; set; }

public string Flag { get; set; }

public int Number { get; set; }
}


And I created the countries like this:



private void vlaggenDeclareren()
{
Country oAlbanie = new Country();
oAlbanie.Name = "Albanie";
oAlbanie.Flag = "Albanie.png";
oAlbanie.Number = 0;
lstLandVullen(oAlbanie);

Country oAndorra = new Country();
oAndorra.Name = "Andorra";
oAndorra.Flag = "Andorra.png";
oAndorra.Number = 1;
lstLandVullen(oAndorra);

//and so on..
}


I thought I would be able to give each button a random number from 0-40 (have 40 flags and 20 buttons), and link that random number to countryname.Number


If someone would be able to help me out (even if it's a completely different way) that would be awesome.. We're supposed to do this in a group of 3 people but everyone's refusing to do anything so I'm doing this alone ..





Get random emails address from CSV file

anyone know how to randomly show email load from csv file ?


This is my code :



<?php
function random_phrase ()
{
$quotes = file ("Bounced_Email.csv");
$num = rand(1,10 intval (count ($quotes))) * 10;
echo $quotes[$num] . "<br>" . $quotes[$num + 1];
}
?>
<?php random_phrase (10);?>


Actually i want to show 10 emails from my CSV file (randomly) but not sure why still show error.


anyone can help ? please


Thanks





How to loop to check either the ID is exist or not in mysql database with PHP after a random function's id is generated?

I have a database called Customers with Unique ID, so each time insert from php to database I need to generate a new ID for the new customer from a random function but I need to check the id that generated is exists in database or not.


This is the php random function:



function randomDigits($length){
$digits = "";
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}


I tried to pass random length like this:



$cusid = randomDigits(10);
$generate_customer_id = "";

$query_customer_id = dbQuery("SELECT customer_id FROM customers WHERE customer_id = '$cusid'");
$count_customer_id = $query_customer_id->rowCount();

if($count_customer_id == 1)
{

$generate_customer_id = randomDigits(10);

}
else
{
$generate_customer_id = $cusid;
}
$query = dbQuery("INSERT INTO customers(`customer_id`,`username`,`password`,`email`,`first_name`,`last_name`,`dob`,`id_card`,`family_book_id`,`address`,`district`,`province`,`phone`,`mobile`,`father_name`,`mother_name`,`bank_account_no`,`bank_account_name`) VALUES('$generate_customer_id','$username','$password','$email','$firstname','$lastname','$dob','$idcard','$familybook','$address','$district','$province','$homephone','$mobilephone','$fathername','$mothername','$bankno','$bankname')");

if($query == true)
{
$insert_referrer = dbQuery("INSERT INTO referrers (`parent_id`, `customer_id`, `category_id`, `created`,`modified`) VALUES(NULL, '$generate_customer_id', 2, NOW(), NOW())");
if($insert_referrer == true)
{
echo "OK";
}
else
{
echo "There is an error please check your information and try again referrers!";
}
}
else
{
echo "There is an error please check your information and try again customers!";
}


But data return from my AJAX function, if return error I need to click the save customer button many times then i will return success and then data successful saved to database.


But I want user to click only one time then data will insert.


How to implement this please help!





tread 1 error - using rand()function

I have to select random number between 0 and 3. I have to call this function several times. In the beginning it's always working but after some time the error message "Tread 1: EXC_BAD_ACCESS(code =2, address 0x7fff5f3ffff8" appears.


Here is my code. m_p[multiproject][project] is equal to 4;



int selecteer_random_resource(int multiproject, int project)
{ int k=0;
k=rand()%m_p[multiproject][project];
return k;
}


I really don't understand why it's working in the beginning and after some time the error appears. Can somebody help me with this? Thanks in advance!





Easy PHP random code

I'm new there :) I was trying to create a random code in PHP with following results in decimals (precision 2)



From 1.10 to 1.15 = 40%
From 1.16 to 1.20 = 30%
From 1.21 to 1.25 = 20%
From 1.26 to 1.30 = 10%


That's my actual code:



$low = 1.1
$high = 1.3
$multiplier = mt_rand($low*100,$high*100)/100;


Help me please? :(





samedi 28 mars 2015

Postgres function optimisation

I am running the below function. Testing it with a much smaller table works as expected (18 rows - ~400ms). However, when pointed at my real data (315000 rows), it is running 48hrs and still going. This is much longer than I expected under a linear extrapolation.



  1. Is there a better way to do this?

  2. Is there a way to test if it is doing what it should be doing while still running?


Is there any way to optimise the below function?



DO
$do$
DECLARE r public.tablex%rowtype;
BEGIN
FOR r IN SELECT id FROM public.tablex
LOOP
IF (select cast((select trunc(random() * 6 + 1)) as integer) = 5) THEN
UPDATE public.tablex SET test='variable1' WHERE id = r.id;
ELSIF (select cast((select trunc(random() * 6 + 1)) as integer) = 6) THEN
UPDATE public.tablex SET test='variable2' WHERE id = r.id;
END IF;
END LOOP;
RETURN;
END
$do$;




Android app with with "favorites" added to a randomized list

I'm having a hard time correctly implementing a 'favorites' feature for my app. Moving through a list of objects, the user should be able to mark/unmark something as a favorite. Once the activity moves into the onPause(); state, it should save the list of favorites (rather, the complete list of boolean markers that signal whether something is a favorite or not... true for favorite, false for not a favorite.) Obviously, upon moving into the onResume(); state, the list should be loaded so they can view the favorites that they've previously marked.


My issue, I think, truly comes from the fact that the list is randomized upon initialization. I'm sure my algorithm is off, but I've tried various ways to the point where I can hardly bare to look at it anymore.


Main Activity Java



public class MainActivity extends ActionBarActivity {


Global global_main;


@Override
protected void onCreate(Bundle savedInstanceState) {

global_main = Global.getInstance("all");

}



@Override
protected void onResume(){
super.onResume();


SharedPreferences settings = getSharedPreferences(FILE_FAVORITES, 0);

for(int index = 0; index < TOTAL_QUESTIONS; index++){

boolean favFromFile = settings.getBoolean(("savedFavorite_" + String.valueOf(index)), false);
global_main.setFav(index, favFromFile);

}

}



@Override
protected void onPause(){
super.onPause();

SharedPreferences settings = getSharedPreferences(FILE_FAVORITES, 0);
SharedPreferences.Editor editor = settings.edit();

for(int index = 0; index < TOTAL_QUESTIONS; index++){
editor.putBoolean(("savedFavorite_" + String.valueOf(index)), global_main.getFav(index));

// Commit the edits!
editor.commit();
}

}


Practice Java



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Intent intent = getIntent();
selectedSection = intent.getStringExtra(chooseSection.chosenSection);

global = Global.getInstance(selectedSection);

}


Global Class



public class Global {


private static Global global = null;

//Current total of questions which the user has chosen
//EX: if Multiplication was chosen and has 10 questions in the array
//Then this equals 10
int CURRENT_TOTAL;

//This is the position that the first question of the user's choice starts with
//EX: If user chooses Multiplication, and the multiplication questions start at questions[19];
//Then this equals 19
int CURRENT_START;

//This is the position that the last question of the user's choice ends with
//EX: If user chooses Multiplication, and the multiplication questions end at questions[24];
//Then this equals 24
int CURRENT_END;


//Basic question structure
class questionStruct
{

String q;
String a;
int position; //original position in the array;
boolean favorite;

}

//Array of question structures
questionStruct[] questions = new questionStruct[TOTAL_QUESTIONS];


//userChoice is the choice of question type that the user has selected.
//EX: Multiplication, Division, Addition, Subtraction, or All/Default
public static Global getInstance(String userChoice) {
if(global == null)
{
global = new Global();
global.initialize();
}

global.getChoice(userChoice);
global.setQuestionsDefault();
global.randomize();
return global;

}


public void initialize() {
for (int i = 0; i < TOTAL_QUESTIONS; i++) {
questions[i] = new questionStruct();
}

questions[0].q = "Question 1 Text";
questions[0].a = "Answer";
questions[0].position = 0;
questions[1].q = "Question 2 Text";
questions[1].a = "Answer";
questions[1].position = 1;
questions[2].q = "Question 3 Text";
questions[2].a = "Answer";
questions[2].position = 2;
....ETC.
....ETC.
....ETC.
}


public void setQuestionsDefault(){

questionStruct temp = new questionStruct();

for(int index = 0; index < TOTAL_QUESTIONS; index++){

int count = questions[index].position;

temp = questions[count];
questions[count] = questions[index];
questions[index] = temp;

temp = null;
}
}


//Randomize the questions only within the range of the category
//which the user has chosen
public void randomize(){


for(int index = CURRENT_END; index >= CURRENT_START; index --)
{
//Generate random number to switch with random block
Random rand = new Random();
int currentQ = rand.nextInt((CURRENT_END - CURRENT_START) + 1) + CURRENT_START;


//Switch two Question blocks
questionStruct temp = questions[currentQ];
questions[currentQ] = questions[index];
questions[index] = temp;


}
}



public void setFav(int q, boolean b){
questions[q].favorite = b;
}


public boolean getFav(int q){
return questions[q].favorite;
}


That MIGHT be everything pertinent to my issues. I apologize if I left anything out or if something doesn't make sense. Feel free to ask questions. I'm still currently in the middle of altering everything to get it to work, so I might have copied over something that doesn't quite add up.





NumPy random seed produces different random numbers

I run the following code:



np.random.RandomState(3)
idx1 = np.random.choice(range(20),(5,))
idx2 = np.random.choice(range(20),(5,))
np.random.RandomState(3)
idx1S = np.random.choice(range(20),(5,))
idx2S = np.random.choice(range(20),(5,))


The output I get is the following:



idx1: array([ 2, 19, 19, 9, 4])
idx1S: array([ 2, 19, 19, 9, 4])

idx2: array([ 9, 2, 7, 10, 6])
idx2S: array([ 5, 16, 9, 11, 15])


idx1 and idx1S match, but idx2 and idx2S do not match. I expect that once I seed the random number generator and repeat the same sequence of commands - it should produce the same sequence of random numbers. Is this not true? Or is there something else that I am missing?





BATCH For loop generating random numbers

Ok, so this issue I'm having involves CMD scripting and this:



DIR /A-D /B /S > DIR.DAT
FOR /F "TOKENS=*" %%I IN (DIR.DAT) DO (
CALL :DICEROLL

IF %NUMBER%==0 (
ECHO BOOM BADDA BOOM
) ELSE (
ECHO %NUMBER%
)
)
:DICEROLL
SET /A NUMBER=%RANDOM% %% 16


When I run the file I get stuff like this:



15
15
15
15


Instead of what I'm wanting which would be something like this:



14
0
8
10


I'm just very confused on why its not generating random numbers for each line of text it goes through. Instead it appears to only echo the first generated number. Any help would be greatly appreciated and sorry if this is confusing I'm not very good at putting my problems into words and its my first time on one of these sites in general.





Error generating objects in a for loop

When I run the next code, I get this error:



>(Pdb)
>Traceback (most recent call last):
> File "simulacion.py", line 203, in <module>
> env.run( until = 120*10000 )
> File "/usr/local/lib/python2.7/dist-packages/http://ift.tt/1IGZVpW", line 137, in run
self.step()
> File "/usr/local/lib/python2.7/dist-packages/http://ift.tt/1IGZVpW", line 229, in step
> raise exc
>TypeError: not all arguments converted during string formatting
>Exception AttributeError: "'NoneType' object has no attribute 'path'" in ><function _remove at 0xb7254bc4> ignored


The code:



import pdb
import simpy
import random
import itertools
import sys

while(True):
...
r = random.uniform(0,1)
t = random.expovariate(300)
yield env.timeout(t)
....


I found the error, just when I run the yield env.timeout(t) line





Swift updating NSTimer time or delay

I'm new to swift, and I'm creating a random generated game using NSTimer i used this function for timer http://ift.tt/1Npo9HS


my game was working fine until i got a problem with updating the speed of my game depending on the player score using timer, so i can't change the speed of my game


my Gamescene class :



let myGame = Timer.repeat(after: 1) {
//my generated game code here
}
myGame.start()


my game updater function :



let LevelUpdate = Timer.repeat(after: 0.1) {
//update my game and verify player score


here an example of i want to achieve



if(self.score >= 0 && self.score <= 1000){
myGame.delay = 1.0 // Speedup the time of the game
}
}


Please i need to find a way of speeding up my game by player score.





PYTHON solving the integral of a differential equation with odeint get error

I have a problem with the integration of this differential equation R*(dq/dt)+(q/C) = Visin(wt) i want to solve it to get q(t) but i don't get anything with odeint.



def f (R, w, C, Vi):
return R*(dq/dt)+(q/C) = Vi*sin(w*t)
odeint(f,




Functions that refer to the output of other functions - Python

I've been having trouble getting functions to work that rely on the output of another function. When I run the following code (this is a very simplified version)...



from random import randint

def event():
if m == 1:
r = randint(0, 4)
else:
r = randint(3, 7)

def random():
if r == 1:
print "Test A"
elif r == 2:
print "Test B"
elif r == 3:
print "Test C"
elif r == 4:
print "Test D"
elif r == 5:
print "Test E"
elif r == 6:
print "Test F"


m = 1
event()
random()

m = 2
event()
random()

m = 3
event()
random()


...I get NameError: global name 'r' is not defined


I need to keep these in separate functions because in my actual code they are very complicated. How can I get random() to recognise the random number generated by event()?





How to create a true 'Random' with Timer control?

I have a timer that clicks a button, and no matter what speed the timer is at, due to the Random having some kind of association with the clock, the outcome is predictable no matter what the speed.


I have been reading up and learned that when a new Random is initialized, it is done so with the system time, which explains why I'm getting this problem.


Here's what I have:



int win = 0;
int lose = 0;

private void button1_Click(object sender, EventArgs e)
{
Random rn = new Random();
int rnu = rn.Next(2);

if (rnu == 0)
win++;

if (rnu == 1)
lose++;

string winmsg = "Wins: " + win.ToString();
string losemsg = "Losses: " + lose.ToString();

winlbl.Text = winmsg;
loselbl.Text = losemsg;

timer1.Start();

}


And then the timer:



private void timer1_Tick(object sender, EventArgs e)
{
button1.PerformClick(); //interval 500, but always predictable.
}


My goal is to try to create a more 'Random' outcome- one that wouldn't be predictable with the timer control. However, I can't modify the speed of the timer; it must remain constant for the cycle.


I've tried stopping the timer and restarting, but even then it carries on the predictable behavior.


Does anyone know of a way to get around this or some kind of 'trick'? Or is this some C# Random limitation?





Android - Incorporating a favorites feature for randomized list of objects

In short, I'm having a hard time correctly implementing a 'favorites' feature for my app. Moving through a list of objects, the user should be able to mark/unmark something as a favorite. Once the activity moves into the onPause(); state, it should save the list of favorites (rather, the complete list of boolean markers that signal whether something is a favorite or not... true for favorite, false for not a favorite.) Obviously, upon moving into the onResume(); state, the list should be loaded so they can view the favorites that they've previously marked.


My issue, I think, truly comes from the fact that the list is randomized upon initialization. I'm sure my algorithm is off, but I've tried various ways to the point where I can hardly bare to look at it anymore.


MAIN ACTIVITY JAVA



public class MainActivity extends ActionBarActivity {


Global global_main;


@Override
protected void onCreate(Bundle savedInstanceState) {

global_main = Global.getInstance("all");

}



@Override
protected void onResume(){
super.onResume();


SharedPreferences settings = getSharedPreferences(FILE_FAVORITES, 0);

for(int index = 0; index < TOTAL_QUESTIONS; index++){

boolean favFromFile = settings.getBoolean(("savedFavorite_" + String.valueOf(index)), false);
global_main.setFav(index, favFromFile);

}

}



@Override
protected void onPause(){
super.onPause();

SharedPreferences settings = getSharedPreferences(FILE_FAVORITES, 0);
SharedPreferences.Editor editor = settings.edit();

for(int index = 0; index < TOTAL_QUESTIONS; index++){
editor.putBoolean(("savedFavorite_" + String.valueOf(index)), global_main.getFav(index));

// Commit the edits!
editor.commit();
}

}


PRACTICE QUESTIONS JAVA



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Intent intent = getIntent();
selectedSection = intent.getStringExtra(chooseSection.chosenSection);

global = Global.getInstance(selectedSection);

}


GLOBAL CLASS



public class Global {


private static Global global = null;

//Current total of questions which the user has chosen
//EX: if Multiplication was chosen and has 10 questions in the array
//Then this equals 10
int CURRENT_TOTAL;

//This is the position that the first question of the user's choice starts with
//EX: If user chooses Multiplication, and the multiplication questions start at questions[19];
//Then this equals 19
int CURRENT_START;

//This is the position that the last question of the user's choice ends with
//EX: If user chooses Multiplication, and the multiplication questions end at questions[24];
//Then this equals 24
int CURRENT_END;


//Basic question structure
class questionStruct
{

String q;
String a;
int position; //original position in the array;
boolean favorite;

}

//Array of question structures
questionStruct[] questions = new questionStruct[TOTAL_QUESTIONS];


//userChoice is the choice of question type that the user has selected.
//EX: Multiplication, Division, Addition, Subtraction, or All/Default
public static Global getInstance(String userChoice) {
if(global == null)
{
global = new Global();
global.initialize();
}

global.getChoice(userChoice);
global.setQuestionsDefault();
global.randomize();
return global;

}


public void initialize() {
for (int i = 0; i < TOTAL_QUESTIONS; i++) {
questions[i] = new questionStruct();
}

questions[0].q = "Question 1 Text";
questions[0].a = "Answer";
questions[0].position = 0;
questions[1].q = "Question 2 Text";
questions[1].a = "Answer";
questions[1].position = 1;
questions[2].q = "Question 3 Text";
questions[2].a = "Answer";
questions[2].position = 2;
....ETC.
....ETC.
....ETC.
}


public void setQuestionsDefault(){

questionStruct temp = new questionStruct();

for(int index = 0; index < TOTAL_QUESTIONS; index++){

int count = questions[index].position;

temp = questions[count];
questions[count] = questions[index];
questions[index] = temp;

temp = null;
}
}


//Randomize the questions only within the range of the category
//which the user has chosen
public void randomize(){


for(int index = CURRENT_END; index >= CURRENT_START; index --)
{
//Generate random number to switch with random block
Random rand = new Random();
int currentQ = rand.nextInt((CURRENT_END - CURRENT_START) + 1) + CURRENT_START;


//Switch two Question blocks
questionStruct temp = questions[currentQ];
questions[currentQ] = questions[index];
questions[index] = temp;


}
}



public void setFav(int q, boolean b){
questions[q].favorite = b;
}


public boolean getFav(int q){
return questions[q].favorite;
}


That MIGHT be everything pertinent to my issues. I apologize if I left anything out or if something doesn't make sense. Feel free to ask questions. I'm still currently in the middle of altering everything to get it to work, so I might have copied over something that doesn't quite add up.





To high to low game

Hello i am trying to make a java file so when i run it will generate a random number between 1 and 10 and when the awnser it will tell me if its to high to low or good but what i have tried dit not work



public static void main(String[] args) {
Random rand = new Random();
int test = rand.nextInt(10) + 1;
String input;
Scanner user_input = new Scanner( System.in );
System.out.println("Wat is het random nummer");
input = user_input.next();
if(user_input.nextInt() > test) {
System.out.println("Te hoog");
} else if (user_input.nextInt() < test) {
System.out.println("te laag");
} else {
System.out.println("Goedzo!");
}


}





How to randomize the order of radio buttons in pyqt

im making a quiz and i want the radiobuttons to be in different positions. ive got it working to a extent as it would be in random order in the first question however it would then stay in that order for the rest of the quiz. I want it to randomize every time.



class MultipleChoice(QtGui.QWidget):
showTopicsSignal = pyqtSignal()

def __init__(self,parent=None):
super(MultipleChoice, self).__init__(parent)

self.initUI()


def initUI(self):
self.Questions=[]
self.Questionum = QLabel()
self.Questioninfo = QLabel()
self.Correctanswer = QRadioButton()
self.Incorrectans1 = QRadioButton()
self.Incorrectans2 = QRadioButton()
self.Incorrectans3 = QRadioButton()
self.Correctanswer.setAutoExclusive(True)
self.Incorrectans1.setAutoExclusive(True)
self.Incorrectans2.setAutoExclusive(True)
self.Incorrectans3.setAutoExclusive(True)
layout = QVBoxLayout(self)
layout.addWidget(self.Questionum)
layout.addWidget(self.Questioninfo)
randomnumber = randint(0,3)
if randomnumber == 0:
layout.addWidget(self.Correctanswer)
layout.addWidget(self.Incorrectans1)
layout.addWidget(self.Incorrectans2)
layout.addWidget(self.Incorrectans3)
elif randomnumber == 1:
layout.addWidget(self.Incorrectans1)
layout.addWidget(self.Correctanswer)
layout.addWidget(self.Incorrectans2)
layout.addWidget(self.Incorrectans3)
elif randomnumber == 2:
layout.addWidget(self.Incorrectans1)
layout.addWidget(self.Incorrectans2)
layout.addWidget(self.Correctanswer)
layout.addWidget(self.Incorrectans3)
elif randomnumber == 3:
layout.addWidget(self.Incorrectans1)
layout.addWidget(self.Incorrectans2)
layout.addWidget(self.Incorrectans3)
layout.addWidget(self.Correctanswer)


The form is dyanamic so it changes the labels everytime the next button is pressed but im thinking that may be having a influence



def Showquestions2(self):
self.Questionum.setText("Question 2")
self.Questioninfo.setText(self.Questions[0][1])
self.Correctanswer.setText(self.Questions[0][2])
self.Incorrectans1.setText(self.Questions[0][5])
self.Incorrectans2.setText(self.Questions[0][6])
self.Incorrectans3.setText(self.Questions[0][7])
self.ismultichoiceButton.setText("Next question")
self.ismultichoiceButton.clicked.connect(self.Showquestions3)


is there anyway i can fix this? Thanks,





Assign unique random integers in an array (C)

im struggling with this so long, i can fill my array with random numbers but they are not unique. I can't spot the problem in my code :( Can you help me? Thanks



void fillArray(int *p)
{
int i;
for(i=0;i<N;i++)
p[i]=getUniqueNumber(p,i);
}

int getUniqueNumber(int *p, int i)
{
int x,j,found;
do
{
x=rand()%100000 + 1;
found=0;
j=0;
while(j<=i && found==0)
{
if(p[i]==x)
found=1;
else
j++;
}
} while(found==1);
return x;
}




Generate a localized random NSString

Apologies if this has already been asked, but some google search could not find it.


Does anyone please know of any method to generate a random string in iOS which respects the current language of the device?


The idea is that a quick 'unlock code' can be generated using the function; the trouble is that for languages other than English entering the code using the keypad will not be quick or intuitive, particularly if the user does not have the English keyboard enabled.





How to check if an item is already in a listbox in vb6

I'm working with vb6 and I want to generate multiple randum numbers (the range from to is detirmend by user and also the number of generated answers) and send them to a listbox But I don't want to duplicate generated numbers So.. I want before sending the generated number to the listbox to check if it already exists in the lisbox. if it already exists then generate another number if it does't then send it the the listbox


here is what I have till now max and min are the range to chose numbers between answers is the number of generated numbers



Randomize
For i = 1 To answers Step 1
generated = CInt(Int((max - min + 1) * Rnd() + min))
For n = 0 To List1.ListCount
If List1.List(n) <> gen Then
List1.AddItem (gen)
Else
If List1.List = gen Then
'I don't know what to do from here
'(how to go back to generate another number)
Next n
Next i


Thank you in advance keep in minde I need to keep things simple Thank you soo much





Is this way of generating random numbers safe and valid?

I was doing some recreational low-level programming the other day, and somewhere in my code this thing emerged (using pseudocode):


cointoss program



char out = '0';

void thread(){ out = '1';}

int main(){
// Creates a thread that will run the function we provided
// The main() will not wait for this thread to finish
runInOwnThread(thread);

printr("%d", out);
return 0;
}


Now in our shell we run cointoss program x number of times and we will end up with something like this:


0011011100001000


which we can convert to decimal and get a random number


My question is not whether this is an efficient way of creating a random number but more about we can tell if the end result is random enough for use





How do I implement a food generator in a snake game (using c++ and OpenGL) that is not grid-based?

The snake in my game is basically a list of squares. Each square in this list is defined using GL_QUADS, which requires definition of two vertices (x,y and x1,y1) as so:



void Square::draw() const
{
glBegin(GL_QUADS);

glVertex2f(x, y);
glVertex2f(x1, y);
glVertex2f(x1, y1);
glVertex2f(x, y1);

glEnd();
}


The snake moves by insertion of a new element at the front of the list, and deletion of the last. So, if the snake was initially moving towards the left, and receives a command to move upwards, a square would be created above the snake's (previous) head, and the last square in the list will be removed.


To generate food, I have the following code:



void generate_food()
{
time_t seconds
time(&seconds);
srand((unsigned int)seconds);

x = (rand() % (max_width - min_width + 1)) + min_width;
y = (rand() % (max_height - min_height + 1)) + min_height;
x1 = foodx + 10;
y1 = foody + 10;

food = new Square{x,y,x1,y1 };
}


(Note: the width and height are dimensions of the playfield.)


I also implemented a function that grows the snake: if the coordinates of the snake's head match the coordinates of the food. However, when I run the program, the snake's head is never EXACTLY at the same coordinates as the food block... a few pixels off, here and there. Is there any way around this problem which does not require me to re-write all my code with a grid-based implementation?





Using random variable in other class gives always 0 c#

I haven't any errors, but the program always generates 0 for AnimalAge. It should generate numbers from 1-20. This is a simple game where a player should find Age of Animal.



public class losowaniez
{
public int AnimalAge;
public int Age2;
public void losowanie()
{
int AnimalAge;

Random RandomObj = new Random();
AnimalAge = RandomObj.Next(20);
Age2 = AnimalAge;
}
}
public class Animal:losowaniez
{
public void Fish()
{
Console.WriteLine("Zwierze moze miec maksymalnie 10 lat, zgadnij ile ma lat");
int x = Convert.ToInt32(Console.ReadLine());
}
public void zwierze()
{
losowaniez MyAnimal = new losowaniez();
int AnimalAge = MyAnimal.Age2;
Console.WriteLine("Zwierze moze miec maksymalnie 20 lat zgadnij ile ma lat");
int x = Convert.ToInt32(Console.ReadLine());
if (x == AnimalAge)
{
Console.WriteLine("Wygrales gre");
Console.ReadKey();
}
else if (x > AnimalAge)
{
Console.WriteLine("Celuj nizej!");
zwierze();
}
else
{
Console.WriteLine("Celuj wyzej!");
zwierze();
}
}
}




Creating a presorted array

I want to create a random array with a parameter of hi and low that decides the level of the presortndess of the array with a value of 0 ≤ low < hi ≤ 1 which shows the level of order is low when the value is 0 but while its 1 there is total order.





vendredi 27 mars 2015

place a button randomly in layout

my code works like this:buttongame1 is the place where start_time moves on the next i . But buttongame1 should choose it's place randomly, and it does this, but not on i == 0 , so everytime when I open the activity, buttongame1 is not randomly placed



public void onClick(View v) {

textview1 = (TextView) findViewById(R.id.over);

Random r = new Random();

RelativeLayout decorView = (RelativeLayout) buttongame1.getParent();

int screenWidth = decorView.getWidth();
int screenHeight = decorView.getHeight();



if(v == gameover){


i--;

btncounter.setText("GAME OVER");
start_time.setVisibility(View.GONE);
buttongame1.setVisibility(View.GONE);
textview1.setVisibility(View.VISIBLE);
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(50); //You can manage the time of the blink with this parameter
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(123);
textview1.startAnimation(anim);
Toast.makeText(this, "GAME OVER", Toast.LENGTH_SHORT).show();
over1.start();



finish();


}

if (i == 0 ) {
btncounter.setText("0");

//int x0 = (int) buttongame1.getX();
//int y0 = (int) buttongame1.getY();


}
i++;

if (i == 1 ) {
btncounter.setText("1");
startTime = System.currentTimeMillis();
int x1 = (int) buttongame1.getX();
int y1 = (int) buttongame1.getY();
start_time.setX(x1);
start_time.setY(y1);
buttongame1.setX(r.nextInt(screenWidth - buttongame1.getHeight()));
buttongame1.setY(r.nextInt(screenHeight - buttongame1.getWidth()));

mp1.start();
}
if (i == 2 ) {
btncounter.setText("2");
int x2 = (int) buttongame1.getX();
int y2 = (int) buttongame1.getY();
start_time.setX(x2);
start_time.setY(y2);
buttongame1.setX(r.nextInt(screenWidth - buttongame1.getHeight()));
buttongame1.setY(r.nextInt(screenHeight - buttongame1.getWidth()));
mp2.start();
}
if (i == 3 ) {
btncounter.setText("3");
int x3 = (int) buttongame1.getX();
int y3 = (int) buttongame1.getY();
start_time.setX(x3);
start_time.setY(y3);
buttongame1.setX(r.nextInt(screenWidth - buttongame1.getHeight()));
buttongame1.setY(r.nextInt(screenHeight - buttongame1.getWidth()));
mp3.start();
}
if (i == 4 ) {
btncounter.setText("4");
int x4 = (int) buttongame1.getX();
int y4 = (int) buttongame1.getY();
start_time.setX(x4);
start_time.setY(y4);
buttongame1.setX(r.nextInt(screenWidth - buttongame1.getHeight()));
buttongame1.setY(r.nextInt(screenHeight - buttongame1.getWidth()));
mp4.start();
}
if (i == 5 ) {
btncounter.setText("5");
int x5 = (int) buttongame1.getX();
int y5 = (int) buttongame1.getY();
start_time.setX((x5));
start_time.setY(y5);
buttongame1.setX(r.nextInt(screenWidth - buttongame1.getHeight()));
buttongame1.setY(r.nextInt(screenHeight - buttongame1.getWidth()));
mp5.start();
}
if (i == 6 ) {
btncounter.setText("6");
int x6 = (int) buttongame1.getX();
int y6 = (int) buttongame1.getY();
start_time.setX(x6);
start_time.setY(y6);
buttongame1.setX(r.nextInt(screenWidth - buttongame1.getHeight()));
buttongame1.setY(r.nextInt(screenHeight - buttongame1.getWidth()));
mp6.start();
}
if (i == 7 ) {
btncounter.setText("7");
int x7 = (int) buttongame1.getX();
int y7 = (int) buttongame1.getY();
start_time.setX(x7);
start_time.setY(y7);
buttongame1.setX(r.nextInt(screenWidth - buttongame1.getHeight()));
buttongame1.setY(r.nextInt(screenHeight - buttongame1.getWidth()));
mp7.start();
}
if (i == 8 ) {
btncounter.setText("8");
int x8 = (int) buttongame1.getX();
int y8 = (int) buttongame1.getY();
start_time.setX(x8);
start_time.setY(y8);
buttongame1.setX(r.nextInt(screenWidth - buttongame1.getHeight()));
buttongame1.setY(r.nextInt(screenHeight - buttongame1.getWidth()));
mp8.start();
}
if (i == 9 ) {
btncounter.setText("9");
int x9 = (int) buttongame1.getX();
int y9 = (int) buttongame1.getY();
start_time.setX(x9);
start_time.setY(y9);
mp9.start();


}

else if (i == 10) {
mp10.start();
btncounter.setText("10");
start_time.setVisibility(View.GONE);
buttongame1.setVisibility(View.GONE);

long difference = (System.currentTimeMillis() - startTime);



String thetime = String.format("%d,%03d sec",difference/1000,difference%1000);

Toast.makeText(this, (thetime), Toast.LENGTH_SHORT).show();




C# Random numbers with squares in a 2d display

Can someone tell me why my second column is not the square of the fist? Here is what I have:



const int NUM_ROWS = 10;
const int NUM_COLS = 2;

int[,] randint = new int [NUM_ROWS,NUM_COLS];
Random randNum = new Random();

for (int row = 0; row < randint.GetLength(0); row++)
{
randint[row,0] = randNum.Next(1,100);
randint[row,1] = randint[row,0]*randint[row,0];

Console.Write(string.Format("{0,5:d} {0,5:d}\n", randint[row,0], randint[row,1]));




C# - Cannot tag a random number with a statement

So i'm working on a revision tool that'll ask defined questions randomly using console command C#. I can create the random number but cannot seem to use the Switch function properly. Can anyone help?



// The random Object
Random Number = new Random();

while (true)
{
int Question = Number.Next(1);
Console.WriteLine("{0}", Question);
string Answer = Console.ReadLine();

if (Answer.ToLower() == "finished")
{
break;
}

if(Answer.Length == 0)
{
Console.WriteLine("Write Please");
continue;
}

switch (Question)
{
case 0:
{
Console.WriteLine("What is the nucleus of an atom made of");
if (Answer == "neutrons and protons")
{
Console.WriteLine("Well Done!");
}
if (Answer == "protons and neutrons")
{
Console.WriteLine("Well Done!");
}
Console.WriteLine("Try Again");
break;
}
}

}
}
}


}