dimanche 31 janvier 2016

How to randomly generate password Rails 4?

I have completed Railstutorial.org book. Now I want to change that only admin can register a new user with name and email. Password is automactically generated and sent to user'email. I'm stuck on how to randomly generate password for user. Can someone help me ? thank a lot.

model/user.fb
class User < ActiveRecord::Base
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }, on: :create // this line will be removed

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

   # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    return false if remember_digest.nil?
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end
end

controller/admin/user_controller.rb
class Admin::UsersController < ApplicationController
  before_action :admin_user 
  before_action :logged_in_user 
  def new
    @user = User.new
  end

  def index
    @users = User.where(admin: false)
  end

  def show
    @user = User.find(params[:id])
    @subjects = @user.subjects
  end

  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "create new user successfully"
      redirect_to admin_users_url
    else
      render 'new'
    end  
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated!"
      redirect_to admin_users_url
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted!"
    redirect_to admin_users_url
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation, :address, :phone, :admin)
    end
end

views/admin/new.html
<% provide(:title, 'Sign up') %>
<h1>add user</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for [:admin, @user] do |f| %>
      <%= render 'shared/error_messages', object: @user %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :address %>
      <%= f.text_field :address, class: 'form-control' %>

      <%= f.label :phone %>
      <%= f.text_field :phone, class: 'form-control' %>

      <%= f.label :password %> // this line will be removed
      <%= f.password_field :password, class: 'form-control' %>// this line will be removed

      <%= f.label :password_confirmation, "Confirmation" %>// this line will be removed
      <%= f.password_field :password_confirmation, class: 'form-control' %>// this line will be removed

      <%= f.label :admin, 'Is this admin?' %>
      <%= f.select :admin, options_for_select(['false', 'true']) %><br>

      <%= f.submit "Save", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>




Why is my random array & sort program not working?

I've tried looking up similar questions but I haven't seemed to find anything which solves my problem.

I need to write a program which generates an array of random numbers and sorts them via insertion sort. The actual randomness of the array isn't that important; the important thing is that the code itself generates them. I read here that rand() % n+1 is sufficient for my needs to generate a number between 1 and n.

The code for my program is:

/*
 * Task 1, question e
 */
#include <stdio.h>
#include <stdlib.h>

//Random Array Length
#define L 10
#define MAX 100

void naive_sort(int[]);

int main(){

    int i, a[L];

    //Generate an array of random numbers
    for(i=0; i<L; i++)
        a[L]= rand() % (MAX+1);

    //Unsorted Array
    printf("\nUnsorted array: ");
    for(i=0; i<L; i++)
            printf("%d    ", a[i]);

    //Sorted Array
    naive_sort(a);

    return 0;
}

void naive_sort(int a[]){
    int i, j, t;

    for(i=1; i < L; i++){
        t=a[i];
        j=i-1;
        while((t < a[j]) && (j >= 0)){
            a[j+1] = t;
            j--;
        }
        a[j+1]=t;
    }

    printf("\nSorted array: ");
    for(i=0; i<L; i++)
        printf("%d    ", a[i]);
}

I notice that the array generated has numbers larger than 100, despite defining MAX to be 100. The sorting also doesn't work. This is what I get as an output:

Output

Any help with the issue would be greatly appreciated, I've even tried duck debugging but that doesn't seem to work either!




Random number generator repeating some numbers to often golang

I'm writing a lottery draw simulation program as a project. The way the game works is you need to pick the 6 numbers that are draw from the 49 to win. Your chance of winning is 1/13,983,816 because that's how many combinations of 6 in 49 there are. The demo program (google playground) generates six new numbers each time around the loop forever. Each time a new set of numbers is generated I test to see if it already exists and if it does I break out of the loop. With 13,983,816 combinations you would think it would be a long time before the same 6 numbers would repeat but, in testing it fails always before 10000 iteration. Does anyone know why this is happening?




Lehmer PRNG - why is the divisor 4294967291 and multiplicator 279470273?

A lot of implementations of the Lehmer PRNG use 4294967291 = 2^32 - 5, a prime-number, as divisor and 279470273 as multiplicator. How is this integer 279470273 calculated? How has suggest this pair of integers?




How can I use send() to send a random port number using TCP?

I am trying to send a client a random port number that the client can then use to connect to the server again. I am really having trouble getting this to happen for some reason.

Also, a bonus question: Why does using rand() not give me random numbers? It will give me a random number the first time I run the program and then every time after that it gives a slightly increased version of the first "random" number (so the first time I run it might give 2000, and then the next time it gives 2004 and so on).

srand(time(0));
int random = rand() % 1025 + 64511; 
char rand_port[sizeof(random)];
*((int*)rand_port) = random;

send(Client, r_port, (int)strlen(r_port), 0);

Everything other than this one part of my code works fine and it all works fine if I replace "r_port" with a string like "6500". I really just can't figure out how to get the function to let me do this.

This should be the easiest part of this program yet I have spent hours trying to make this work and I have not been able to find anything helpful on the internet.




DeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future

I have a matrix named data, which is filled with numbers. I wanted to pick a random row from it, so I did:

centroids.append(
data[np.random.randint(0, len(data), size=1)]
.flatten().tolist())

Now, I also have this dictionary:

category = { "World news": [0, 56 , 87], "Politics": [352654], ... }

and I would like to get a random row from data, but now I would like to pick the index from the i-th key's list.

Here is what I tried:

centroids.append(data[
  category.get(category.keys()[i])[
    np.random.randint(0, len(category.get(category.keys()[i])), size=1)
  ]
].flatten().tolist())

and I am getting this warning:

DeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future

What is happening? Is it simply the version of numpy the issue here?

Note that category.get(category.keys()[i] returns (for example) [4367, 7777].




Putting a number at random spots in 2D array

I have a 2D Array that has 5 rows and 5 columns. I want it so that at 8 random spots in that 2D array (make it pick a random row and column) to put a char of '1'.

What I did was call the Random class and generate a number between 0 and 4 (for the 5 spots of the array) then I have two for loops that run 8 times (for the 8 random spots I want), one that goes through the row, the other through the column.

This is the code I have so far:

char[][] battleship = new char[5][5];
//I didn't include this but I have a for loop that populates all the rows and columns with a char of '0'
        Random random = new Random();
        int randomNum = random.nextInt(4);

        for (int i = 0; i < 8; i++)
        {
              for (int o = 0; o < 8; o++)
        {

            battleship[randomNum][randomNum] = '1';

        }
        }

The issue I am getting is that instead of it putting the '1' at 8 random spots, it's putting in 5 spots back to back.

How do I correct this?

Here is an example of the output:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0

The '1' isn't in 8 random spots.

Where did I go wrong?




Need to include the sum of participation

I am using Math.random to include participation of students from a group (separate class). I successfully created the output, but now need to know how to show the sum of participation of students within the group.

public class student  
{
String firstName; 
String lastName; 
String participation;  

student (String a, String b, String p) 
{ 
firstName = a; 
lastName = b; 
participation = p; 
} 
String getName() 
{ 
return firstName + " " + lastName + " " + participation; 
} 
String whatsUp()
{
double r;
int myNumber;
String participation="";
r = Math.random();
myNumber = (int) (r * 3.0)+1;

switch(myNumber)
{
case 1:
participation = "participation is " + Math.floor((Math.random() 
* 10) + 1);
break;
case 2:
participation = "participation is " + Math.floor((Math.random() 
* 10) + 1);
break;
case 3:
participation = "participation is " + Math.floor((Math.random() 
* 10) + 1);
break;
}

return participation;
}
} 




Need help adding feature into my program

I'm making this program that generates raffles and selects winner. The bit I'm stuck on is adding feature where a user clicks on a button called enter draw and is automatically given a random raffle.does anyone know to add feature where a user clicks enter draw and the random raffle is stored and used to select random raffle here's my code.

See More efficient algorithm to randomly select raffle winners in Python And scroll down to the end where you will see my code




Why is a const random device not possible

I am asking me the question why:

#include <random>

struct A{

   std::random_device rd; // or any other generator std::mersenne_twister...

   void doStuff() const {
       auto v = rd();
   }

}

const A a;  
a.doStuff(); // does not work since random_device::operator() is not const...

I thought maybe the random device ca still be used when constant but it cannot be seeded again but that is not the case (internal state is obviously not mutable in std::random_device)...

I want to make class A being properly defined (doStuff() is a const method) and now I suddenly need to use mutable std::random_device rd;isnt that ugly?

Is there any reason for this design?




Generating an array of partially random boolean values based on certain criteria

I am trying to generate random data based on some criteria. I am stuck on how to start so I don't have any code.

I just want some guide on how I can achieve that. You need not provide complete code.

So, coming to the problem, lets say we have this existing data:

Total - 10
Won   -  7
Lost  -  3
Longest Winning Streak - 5
Longest Losing Streak - 2

Now I need to generate an array of random boolean values (true representing a win and false representing a loss) which fulfills the above criteria.

So, in this case the output can be any of the following:

0011011111
1111101100
1010011111
..........

Its the streak part that bothers me. If it weren't for the streak, I could have generated seven 1(s) and three 0(s) and then randomly shuffled them.

Note: I would prefer solutions in C#, VB.NET, JavaScript, or Python but any language is welcome.




Seeding value for random function c++

I need to seed a random function with a seed 2222. The shuffleDeck() function calls random_shuffle from the std library.

Note: The problem is, every time I run the program with no_deals=5, and cards_per_hand=5, I get the same pattern:

Jack of Spades, King of Diamonds, 10 of Hearts, 4 of Clubs, King of Spades, 8 of Diamonds, 3 of Diamonds, 3 of Diamonds, 7 of Hearts, 5 of Clubs, 3 of Hearts, 10 of Hearts, 6 of Diamonds, King of Spades, Jack of Diamonds, 7 of Hearts, 3 of Diamonds, King of Diamonds, Jack of Hearts, 3 of Diamonds,

Shouldn't there be a change? Am I inputting the seed 2222 correctly?

srand(2222);

for (int i=0; i<no_deals; i++)
{
   // test.shuffleDeck();
         for(int j=0; j<cards_per_hand; j++)
      {
                //test.dealCard();

                check.at(j)=test.dealCard();
                cout<<check.at(j)<<", ";
                test.shuffleDeck();
      }

       cout<<endl;

}




How to subtract randomly slides from revolution slider?

I know this is a hard one and very specific, too. I tried so hard and couldn’t find any solution for this problem.

I need to find a way with php to filter elements (which means slides from a slider) form the $slides array inside a revolution slider set up. What I want to achieve is to tell certain slides (by ID) randomly not to be put into the slider. So let’s say I have at the end of my slider 3 different slides with team members and I want to show randomly only one of them each time the page gets loaded.

Possibly this has to be done inside the “rev slider_output.class.php” but I am not very good with php.

I tried also solutions with js and css which are in fact very easy (i.g. randomly attach display none classes) but this makes the slider break I guess because slide counts will get confused inside. So it seems I need to do this in some of the php files.

Anyone out there how achieved something similar? Would be so awesome! Thanks.




Code to randomly select raffle from generated ones

I'm trying to find a code to select a random winner from all generated raffles and is there a faster way Python can generate more raffles quicker and generate millions if so how. Here's my code so far.

import random 

def genNumber(n = 4):
    return "".join([str(random.randint(0,9)) for i in range(n)])

for i in range(12365):
    word = random.choice(['blue', 'aqua', 'jade','plum', 'gold', 'navy', 'pink', 'grey', 'ruby', 'rose', 'teal',"lime",]) 
    print("{} {} {}".format(word.title(), genNumber(4), genNumber(4)))
random.choice(word)




Check the value of a constant in Swift

So I'm coding my first app, yeah, from scratch and I never done anything like it before so please bear with me. I wanna take the randomised value of the first constant and use it to determine the content shown on screen through a label upon a view controller, this might be quite easy for some people but I am really struggling here. I commented out my code so you know what i intend it to do. Now, I know I could approach this many different ways such as not having a label at all and photoshop phrases on images but nah.... I wanna CODE!

Any ideas? Thank you all very much :3 <3

import UIKit

class ViewController: UIViewController {
    let random = Int(arc4random_uniform(11)) //Randomised int values from 0 to 11 (-1)
    @IBOutlet weak var text: UILabel!
    @IBOutlet weak var phrase: UIButton! //this button should reset the entire process over again
    @IBOutlet var imageauthor: UIImageView!
    override func viewDidLoad() {
            super.viewDidLoad()
        self .imageauthor.image = UIImage(named:"0\(random).jpg") //Viewcontroller displays a random image out of randomised value
        self .text.text = ("''") //this should somehow check what the randomised value is and call the Uilabel text bellow it
    }


    var string1 = ("My fist app has many holes1")
    ... string2 = ("My fist app has many holes2")
    ... string3.... 




samedi 30 janvier 2016

A Random(r, g ,b) color generator

I've just starting to learn JavaScript, So I know only a few things about it. I have searched this question and I found the right code for it that works fine with hexadecimal color format. But before that i was trying sth on my own, Can you help me to turn it to an RGB color generator. Every time I add this code to my page it won't work.

      document.getElementById("myButton").onclick = function() {
        var r =Math.random();
        r = 255*r;
        r = Math.floor(r);

        var g =Math.random();
        g = 255*g;
        g = Math.floor(g);

        var b =Math.random();
        b = 255*b;
        b = Math.floor(b);

        var color= "rgb(" + r +"," + g +"," +b ")";

        document.getElementById("myDiv").style.background: color;
     }



Random BLANK textedit file generated -- '%A1%B1%A1%AF'

I'm a rails developer seeking a fix to an annoying problem. Recently, I've been noticing some random textedit file being generated in wherever directory I was working. The file looks like this. Click this Image

After spending some time, I was able to find out that the file was generated every time I opened up Terminal. Even after I delete that random file, it gets regenerated if I open the Terminal app.

It says that the file is a TextEdit document, with 0 bytes of size. When I open the file, there's no text.

It is so annoying because it gets tracked by git, and I have to delete it every time I am committing/pushing my work.




Create an array of combinations checking an item in it

I'm trying to generate a random list of combinations. Each combination has a number from 1 to 6, and a letter from a to cc (z, aa, bb, cc). When the number appears again, the letter will be the next.

For instance:

ID | COMBINATION
1A = 5,1,2
2A = 2,2,1
3A = 1,3,1
4A = 1,4,3
5A = 1,5,4
6A = 1,6,4
1B = 9,1,2

The list of combinations is generated randomly, and checking the last 3 items, so the combination won't be repeated. I get something like:

3416352645234156342561456235

I don't add the letter in code, but it would be something like:

3A 4A 1A 6A 3B 5A 2A 6B 4B 5B 2B 3C 4C 1B

And so on.

Well, now I would like the code to check the previous combinations and check if the first number of the last 3 combinations is different than the current one.

So, if the generated combinations were:

3A = 1,3,1
4A = 1,4,3
1A = 5,1,2
6A = 1,6,4
3B = 2,3,1

The combination id is different so is ok, but the first item of combination 3A and 4A are the same, so it would be consecutive and I don't want it.

In that case, 4A would be replaced with 4B, which would be something like:

4B = 2,4,3

Then there's 1A, which first item is different than 4B and 3A, so is ok.

But then there's 6A, which first item is the same as 3A's first one. So it would be replaced with 6B, which would be:

6B = 2,6,4

But then 6B first item, is the same as 4B, so it would be replaced with 6C, which would be:

6C = 5,6,4

But then 6C first item is the same as 1A, so it would replaced with 6D....

And so on.

At the end, the skipped items, will be readded. So, in last cases 4A and 6A were replaced, which means when 4CC is used, the next to be added will be 4A, and when 6CC is used, the next to be added will be 6A. Until every combination (29 per number) will be used.

I'm not sure if you get me, but if you don't, leave a comment before thinking it's related to another question. I have already done a lot of research about this, without success.

Here are my current code, and a picture of the combinations. In the code I tried creating a class for combinations, but I'm out of ideas about the logic to achieve what I want.

Code:

import java.io.*;
import java.util.*;

public class Randomizer {

    public static int[] one = { 5, 9, 11 },
            two = { 2, 3, 5, 6, 10, 11, 13, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 13, 1, 2, 6, 7, 9, 10, 11, 12 },
            three = { 1, 2, 4, 1, 2, 3, 7, 8, 1, 2, 4, 6, 7, 8 }, four = { 1, 2, 4, 5, 6 },
            five = { 1, 2, 5, 6, 9, 11, 12 }, six = { 1, 2, 5, 6, 9, 11, 12 };

    public static int posuno = 0, posdos = 0, postres = 0, poscuatro = 0, poscinco = 0, posseis = 0;

    public static void main(String[] args) {

        int[] nums = new int[2000];

        for (int i = 0; i < nums.length; i++) {

            Integer[] arr = new Integer[6];
            for (int j = 0; j < arr.length; j++) {
                arr[j] = j + 1;
            }

            Collections.shuffle(Arrays.asList(arr));

            for (int j = 0; j < arr.length; j++) {
                if (i < nums.length) {
                    nums[i] = arr[j];
                }
            }

        }

        String numbers = Arrays.toString(nums);
        numbers = numbers.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(",", "").replaceAll(" ", "");

        StringBuilder solution = new StringBuilder();
        int[] nextValidPos = { -1, -1, -1, -1, -1, -1 };
        int pos = 0;
        while (solution.length() < 203) {
            int nextNumber = Integer.valueOf(numbers.substring(pos, pos + 1));
            if (nextValidPos[nextNumber - 1] <= solution.length()) {
                solution.append(nextNumber);
                nextValidPos[nextNumber - 1] = solution.length() + 3;
                if (nextNumber == 1)
                    nextValidPos[nextNumber - 1] += 4;
            }
            pos++;
        }
        // show(solution.toString());

        int[] list = getIntArrayFromString(solution.toString());
        generateFile(list);

        List<Combo> comboUno = new ArrayList<Combo>();
        List<Combo> comboDos = new ArrayList<Combo>();
        List<Combo> comboTres = new ArrayList<Combo>();
        List<Combo> comboCuatro = new ArrayList<Combo>();
        List<Combo> comboCinco = new ArrayList<Combo>();
        List<Combo> comboSeis = new ArrayList<Combo>();

        for (int a = 0; a < list.length; a++) {
            switch (list[a]) {
            case 1:
                for (int b = 0; b < one.length; b++) {
                    comboUno.add(new Combo(list[a], one[b]));
                }
                break;

            case 2:
                for (int b = 0; b < two.length; b++) {
                    comboDos.add(new Combo(list[a], two[b]));
                }
                break;

            case 3:
                for (int b = 0; b < three.length; b++) {
                    comboTres.add(new Combo(list[a], three[b]));
                }
                break;

            case 4:
                for (int b = 0; b < four.length; b++) {
                    comboCuatro.add(new Combo(list[a], four[b]));
                }
                break;

            case 5:
                for (int b = 0; b < five.length; b++) {
                    comboCinco.add(new Combo(list[a], five[b]));
                }
                break;

            case 6:
                for (int b = 0; b < six.length; b++) {
                    comboSeis.add(new Combo(list[a], six[b]));
                }
                break;
            }
        }

    }

    public static void show(String s) {
        for (int i = 0; i < s.length(); i++) {
            System.out.print(s.substring(i, i + 1));
            if (i != s.length() - 1)
                System.out.print("-");
        }
    }

    public static int[] getIntArrayFromString(String s) {
        int[] array = new int[203];
        for (int i = 0; i < array.length; i++) {
            array[i] = Integer.valueOf((s.substring(i, i + 1)));
        }
        return array;
    }

    public static void generateFile(int[] array) {
        PrintWriter writer;

        int cur = -1;

        try {
            writer = new PrintWriter("combos.txt");

            for (int i = 0; i < array.length; i++) {
                if (cur + 7 == i) {
                    cur = i;
                    writer.println(array[i]);
                } else {
                    writer.print(array[i]);
                }
            }

            writer.close();

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

    }

    private static class Combo {

        int id, c;

        public Combo(int id, int c) {
            this.id = id;
            this.c = c;
        }

        public int getId() {
            return id;
        }

        public int getC() {
            return c;
        }

    }

}

Picture: http://ift.tt/20enB1v

In the picture they have a letter too 1A = C5, P1, Z2 But I think those letters (c,p,z) could be ignored in the code.

Thanks in advance.




Random PHP txt create

I have a question. I made a small project that will want to be like other text pasting an keeping software. This is the main little code:

fopen("text/$file.txt", "w+");

fwrite($file, $data);

fclose("text/$file.txt");
}
else {
die('No post data to process');
}
?>

The problem is that it gives me these errors:

Warning: fwrite() expects parameter 1 to be resource, integer given in /home/u257807476/public_html/ready.php on line 8

Warning: fclose() expects parameter 1 to be resource, string given in /home/u257807476/public_html/ready.php on line 10

I don't know why. Please help me!




Generate a non random value between two integers

I'd want to know how to get return a int between to others and always be the same, not random. I've coded this:

 public static int getIndex(int a, int b)
    {
        if (a > b+b || a == b) return b / 2;
        else if ((a + b / 2) > b) return (a + b) / 4;
        else return (a + b) / 2;
    }

Is there a better way to do this?




jQuery - How to randomize within an array of arrays?

I'm building a game with answers in a 4x4 grid wall, the answers will initially be in groups of four which need to be randomized at the start of each game. The player then has to re-arrange the answers into groups (in case that doesn't make sense, http://ift.tt/1TtmwNW, shows examples of what I'm trying to achieve).

I have set up a grid with arrays of answers as follows:

var grid = [
  ['oak','cedar','fir','pine'],
  ['red','blue','green','yellow'],
  ['villa','spurs','city','united'],
  ['table','chair','door','stool']
];

Using the Fisher-Yates shuffle as follows I can get the grid to randomize the arrays:

function shuffle(grid){

var i = grid.length;
var j;
var temp;

while(--i>0){
    j = Math.floor(Math.random()*(i+1));
    temp = grid[j];
    grid[j] = grid[i];
    grid[i] = temp;
}
return grid;
}

The problem is that it only shuffles the whole lines, rather than the items within each array so that, for example, 'chair' will never be next to 'city'. Does anyone have any suggestions as to how this might be done?




How to get random salt from OpenSSL as std::string

I would like to generate a random string with OpenSSL and use this as a salt in a hashing function afterwards (will be Argon2). Currently I'm generating the random data this way:

if(length < CryptConfig::sMinSaltLen){        
    return 1;
}
if (!sInitialized){
    RAND_poll();
    sInitialized = true;
}

unsigned char * buf = new unsigned char[length];
if (!sInitialized || !RAND_bytes(buf, length)) {      
    return 1;
}

salt = std::string (reinterpret_cast<char*>(buf));
delete buf;

return 0;

But a std::cout of salt doesn't seem to be a proper string (contains control symbols and other stuff). This is most likely only my fault.

Am I using the wrong functions of OpenSSL to generate the random data?

Or is my conversion from buf to string faulty?




Generating a random, non-repeating sequence of all integers in .NET

Is there a way in .NET to generate a sequence of all the 32-bit integers (Int32) in random order, without repetitions, and in a memory-efficient manner? Memory-efficient would mean using a maximum of just a few hundred mega bytes of main memory.

Ideally the sequence should be something like an IEnumerable<int>, and it lazily returns the next number in sequence, only when requested.

I did some quick research and I found some partial solutions to this:

  • Using a maximal linear feedback shift register - if I understood correctly, it only generates the numbers in increasing sequence and it does not cover the entire range
  • Using the Fisher-Yates or other shuffling algorithms over collections - this would violate the memory restrictions given the large range
  • Maintaining a set-like collection and keep generating a random integer (perhaps using Random) until it doesn't repeat, i.e. it's not in the set - apart from possibly failing to satisfy the memory requirements, it would get ridiculously slow when generating the last numbers in the sequence.
  • Random permutations over 32 bits, however I can't think of a way to ensure non-repeatability.

Is there another way to look at this problem - perhaps taking advantage of the fixed range of values - that would give a solution satisfying the memory requirements? Maybe the .NET class libraries come with something useful?




Switch statement: Random generator

I want to make a quiz with a switch-case statement. Before entering it I generate a random number between 1 and for example 10. Then there are 10 cases, one for each number. In each of them there is a question, meaning, that the program displays a random question at the beginning. When the question is answered correctly i want the program to pick a random question again by generating a number but not the one who was already picked. How do i do that?




Generic algorithm implementation to select a random subset

Suppose we are to select a random subset of size m from a total set of size n. Since each element in the total set can be identified using a unique index from S = {0, 1, 2, ..., (n - 1)}. The problem is equivalent to randomly select m distinct elements from S.

A trivial algorithm would be repetitively invoking a pseudo-random number generator rand to generate random numbers from S. If a number has been generated before, just try again. The algorithm terminates until m distinct numbers are generated. This algorithm has an optimal space complexity of O(1), but may invoke rand more than m times.

I'm more concerning about the time complexity instead of space complexity, and would happily trade space for time if reasonable. So I implemented the following algorithm. It invokes rand exactly min{m, (n - m)} times, but at the price of an increased space complexity of O(n). (original code can be found here)

template <typename Clock = std::chrono::high_resolution_clock>
auto tick_count() {
  return Clock::now().time_since_epoch().count();
}

template <typename OutIt, typename RAND = std::minstd_rand,
          typename Uint = typename RAND::result_type>
void random_subset(std::size_t m, std::size_t n, OutIt it, RAND&& rand =
                   RAND(static_cast<Uint>(tick_count()))) {
  assert(n - 1 <= rand.max());
  assert(m <= n);
  if (m == 0) return;
  auto swapped = false;
  auto tmp = n - m;
  if (tmp < m) {
    m = tmp;
    swapped = true;
  }
  std::vector<std::size_t> indices(n);
  std::iota(indices.begin(), indices.end(), static_cast<std::size_t>(0));
  auto back_it = indices.end();
  for (std::size_t i = 0; i < m; ++i) {
    auto idx = rand() % (n - i);
    std::swap(indices[idx], *--back_it);
  }
  swapped ? std::copy(indices.begin(), back_it, it) :
            std::copy(back_it, indices.end(), it);
}

I'm wondering whether the algorithm can be further improved in terms of performance. Improvements to the generic implementation are also welcome.




Code to randomly select raffle & generate millions

I'm currently making this program that allows a user generate as many raffles as they need to put into the draw.the bit I'm stuck on is finding a code that randomly select raffle winner from all generated raffles.And also do any of you know if it's possible that Python can generate millions as it crashes at 2k.Heres my code so far import random

def genNumber(n = 4): return "".join([str(random.randint(0,9)) for i in range(n)])

for i in range(6666): word = random.choice(['blue', 'aqua', 'jade','plum', 'gold', 'navy', 'pink', 'grey', 'ruby', 'rose', 'teal',"lime",]) print("{} {} {}".format(word.title(), genNumber(4), genNumber(4))) random.choice(word)

PLEASE TEST THE PROGRAM




Code to generate random winner

I'm making this program that lets a user choose how raffle entries they want in a draw.Im stuck on choosing a winner does anyone know a code that selects random winner here's my code so far and also Python can't generate many as millions as it crashes between 2k is there a way you can exceed that thanks.

import random 

def genNumber(n = 4):
    return "".join([str(random.randint(0,9)) for i in range(n)])


for i in range(6666):
    word = random.choice(['blue', 'aqua', 'jade','plum', 'gold', 'navy', 'pink', 'grey', 'ruby', 'rose', 'teal',"lime",]) 
    print("{} {} {}".format(word.title(), genNumber(4), genNumber(4)))
random.choice(word)




vendredi 29 janvier 2016

how to improve this random number generator code in c++?

I am c++ student and i am working on creating a random number generator by myself. I know about library functions but i want to make one myself. Here is the function.It just selects a possible number within a defined range. Problems are listed below. Any help would be appreciated.Please help any suggestions or tricks anything. I am making this for about 2 months.

   int rn(int lowerlt,int upperlt)
    {
/**
This function returns a random number generated using loops.
I have tried to generate a random number by taking an integer array and storing all the possible values within the defined
range in the calling part. The theory is that a variable named pointer starts getting greater and breaks the main loop
when the seed taken from system time becomes equal or greater than the pointer.

MAIN PROBLEMS:-
-The problem is that the seed which is system time is very predictable and it is very same most times which lessens the degree of randomness.
-It also takes time more than usual which is undesirable(about 10 secs).
-If range is very large then degree of randomness is very less and results are predictable.

 *But over short ranges results are very effective.
 I want to make it effective for big ranges.
**/

const int size=upperlt-lowerlt;          //Constant size of the integer array.

int ar[size];                         //Array to store all possible values within defined range.
int i,x,ret;                   //Variables to control loops and return value.
long pointer=0;     //pointer variable. The one which breaks the main loop.


//Loop to initialize the array with possible values..
for(i=0,x=lowerlt;x<=upperlt;i++,x++)
    ar[i]=x;

long seed=time(0);

//Main loop . To find the random number.
for(i=0;pointer<=seed;i++,pointer++)
{
    ret=ar[i];
    if(i==size-1)
    {
        for(;i>=0;i--)    //Reverse loop.
            {
                ret=ar[i];
            }
    }
}

return ret;     //The return statement .
}




How do I get a randomly selected hash key in Perl 6?

A quick and hopefully easy question;

I need the means to select from among a given set of hash keys at random. I'll keep poking after this post, but the perl6.org documentation on neither rand nor hash offer many hints.

my %a = 1,2,3,4,5,6;

Given the above,

%a.keys;

returns (5 1 3)... and if I simply try

%a.rand;

however, I get pseudorandom float rather than any one key.




How to do Random word search to check the time taken?

I have a method to search for a word from multiple files. Now I am trying to do random word search to calcualte the efficiency of different methods. But I dono where to start. Can some one please advice me how to do this.

My current code :

private static HashMap search(String stringToLookFor) throws IOException {

HashMap<String, Integer> result = new HashMap<String, Integer>();
for (File file : list) {
  String fileName = file.getName();
  // System.out.println(fileName);
  FileInputStream fstream = new FileInputStream(file);
  BufferedReader in = new BufferedReader(new InputStreamReader(fstream));
  String readLine = "";
  int count = 0;
  while ((readLine = in.readLine()) != null) {
    String[] words = readLine.split("\\W");
    for (String text : words) {
      if (text.equalsIgnoreCase(stringToLookFor)) {
        count++;
      }
    }
  }
  if (count != 0) {
    result.put(fileName, count);
  }

  in.close();
}

return result;

}

How to get random words(like 3 M words) to search in the given files ?




java random number with "variable Max/Min"

So stop me if you've heard this one. I've already looked all over this and other forums to see if anyone had tried this, and I can't find it for the life of me.

I'm trying to generate a random number, but the Max/Min are variables. The values are derived from a text file and can be changed at will by the user.

Is there a way to make a single rn.nextInt such that the Max/Min could be both negative, both positive, one positive and one negative, or the same number (including both being 0)?

The purpose is to have a setting in my game where the user can choose a markup value on purchasable items, but I want to allow discounts as well. I also want them to have the option to set both values to 0 and just use the stock value of the items.

I have tried a few workarounds already, including:

//for Max = 0, Min = 0
int n = (rn.nextInt((a) + (b + 1000))) - 1000

which I really hoped would work.

Any help would be greatly appreciated.




How to create a random list using integers of different lengths - Python

I'm trying to write a line of code that will allow me to create a random list of 5 values, whose lengths I can vary in size. For example, I want the numbers in the list to have a length of 2 or 3 integers, like this: [11, 34, 67, 88, 93] or [100, 450, 622, 875, 998].

So far I have this:

import random
mylist = []
for i in range(5):
 p=p+[random.randrange(?????)
 print(p)

Can anyone help me as I've been trying to do this all day and it's driving me crazy! Thanks.




How to generate a random cryptographically secure string in php

I need to create session key. I want to generate a completely random string to than hash it with password_hash().

What would be a good way to generate a completely random string in my current situation?




jeudi 28 janvier 2016

I need help making my raffle game

Hi I have a code which basically generates raffle numbers such as blue 3433 9421 but do you know a code which stores raffle entries and selects random winner.

import random 
word = random.choice(['blue', 'aqua', 'jade','plum', 'gold', 'navy', 'pink', 'grey', 'ruby', 'rose', 'teal',"lime",]) 
number = random.sample(range(10000000,99999999), 1)[0] 
print("{} {} {}".format(word.title(), int(number/10000), int(number%10000)))

Sometimes when I generate raffles it comes out like Aqua 4552 65 And not like Aqua 4552 6532 Could you fix this please.




How to check if an input answer to a randomly generated mathematical equation is correct

I have a Java program that generates 2 random numbers and asks a user for a mathematical operator and uses those 3 elements to ask the user an equation. I am trying to check if the answer the user inputs is correct and display either correct or incorrect.

RandomGenerator rand = new RandomGenerator();
x=rand.nextInt(-10,10);
y=rand.nextInt(-10,10);

op=readLine("Choose an operator (+, -, /, or *): "); 
equ = x + op + y + "= "; 
val = readInt(equ); 
z = x + op + y 
if(z == val) { 
    println("CORRECT!!"); 
} 
if(z != val) { 
    println("Incorrect."); 
}




Fuzzy Timer (random within boundaries) (Arduino)

I need a little help trying to make a timer a little fuzzy. I want to use a fixed interval of timing like this:

____|_______|____|_____|_________|_____|___|_______|

where the pipe is the event occurrence and the underscore is the delay in an array like this:

int myIntervals = { 1000, 2000, 750, 850, 1200, 850, 500, 1000};

but the values are arbitrary.

I would like to create a slight randomness to the event, but not allow the randomness to affect the overall timing:

___*|*_____*|*__*|*___*|*_______*|*___*|*_*|*_____*|

where the randomness is described as the time contained by asterisks.

So the event always happens at the interval +- a random delay:

int fuzzyPeriod = random(-75, 75);

I've experimented around this but to no avail... I'm finding myself in a recursion when the fuzzy period is negative, or like this I get a millis() overflow problem, obviously.

int sequence[] = {1000, 750, 950, 1150, 1200, 1500, 1000, 1900, 2000};
unsigned int index;
unsigned long startMillis = 0;
unsigned int fuzzy = sequence[0];

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop()
{
  if (startMillis < millis())  // will have rollover issues <<<<<<<
  {
    if (millis() - startMillis >= fuzzy)
    {
      digitalWrite(13, !digitalRead(13));
      startMillis += sequence[index];   // advance startMillis by the last interval used
      index++;
      if (index >= sizeof(sequence) / sizeof(sequence[0]))
      {
        index = 0;
        Serial.println("Restarted Sequence");
      }
      fuzzy = sequence[index] + random(-75, 76); // arbitrary offset needs to be positive or negative
      Serial.print("fuzzy = ");
      Serial.println(fuzzy);
    }
  }
}

I hope I've done a good job explaining... I cannot for the life of me get this done and I know I'm to the point where I need a little help!




generate random integers with fixed sum and constraints

How to generate 6 random integers which add up to 8, and each one is less than 2?

eg. 1,2,1,2,2,0

For far I have found the method which give the random integers with fixed sum but how to impose the constraints on these integers.




Is there a system call for random numbers?

As everyone knows, if you want a truly random number (perhaps to pass to srand()), you open /dev/random or /dev/urandom and read a few bytes. But is there a lighter-weight way to do it, perhaps a system call?

[P.S. Yes, I know, opening and reading /dev/random isn't going to take very long, either. But I'm just wondering if there are other options.]




How to generate random numbers with specific interval between every random number

I am trying to generate 8 random numbers between range say for example 1 to 100. I am generating fine but I need to generate random numbers with specific difference between all the generated random numbers and both min max range values excluded. Say in 1 to 100 I have to generate numbers as 2,12,22,32,42,52,62,72. Is there anyway I can generate random numbers like this.

Thanks in advance.




Generate Random URL, but URL length can't be changed fro some reason?

As of recently I've been working on a site as a bit of a hobby during class. On this site there is some basic text a single button and a text field. when you press the button it generates a random URL and then you can add your own extension to it. At the moment it's to send people to random .onion domains. My current problem is that I cant get the length of the URL to be set to a random length. Here is my code, if you can recommend a fix that would be great. `

<body>
  <script>
    var 'x' = Math.random() * 20
  </script>
  <script language="javascript" type="text/javascript">
    function randomString() {
      var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
      var string_length = 'x';
      var randomstring = '';
      for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
      }
      document.randform.randomfield.value = randomstring;
    }
  </script>
  <form name="randform">
    <input type="button" value="Generate A New Base URL" onClick="randomString();">&nbsp;
    <input type="text" name="randomfield" value="">
  </form>
</body>



display random text from a list on submit from textarea

I'd like to achieve the following:

I have a text area with an input ( Button type).

The user fill the text area, otherwise, on submit, the text which is being display ( in another div) should be different ( taken randomly from a list or other word ).

On the moment I have the following:

<div class="row">
    <div clas="col-md-12">
        <form name="myForm">
Content to be added:
<textarea name="myContent">ADD YOUR NAME</textarea>
<input type="button" value="Add content" onClick="addContent('result', document.myForm.myContent.value); setCookie('content', document.myForm.myContent.value, 7);">
</form>
</div>
</div>

<script>

function addContent(divName, content) {
     document.getElementById(divName).innerHTML = content;
}

</script>

which make appear the text added in the area in my other div. I have just no idea of the path I should take to display another text fro a specific list randomly instead.

Any highlight, will be amazing !

Thank you for your time




Random Number Order in C++ using

I have the following code, that I wrote to test a part of a larger program :

#include <fstream>
#include <random>
#include <iostream>
using namespace std ;

int main()
{
  mt19937_64 Generator(12187) ;
  mt19937_64 Generator2(12187) ;
  uniform_int_distribution<int> D1(1,6) ;

  cout << D1(Generator) << " " ;
  cout << D1(Generator) << " " << D1(Generator) << endl ;
  cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;

  ofstream g1("g1.dat") ;
  g1 << Generator ;
  g1.close() ;
  ofstream g2("g2.dat") ;
  g2 << Generator2 ;
  g2.close() ;
}                                                            

The two generators are seeded with the same value, and therefore I expected the second row in the output to be identical to the first one. Instead, the output is

1 1 3
1 3 1

The state of the two generators as printed in the *.dat files is the same. I was wondering if there might be some hidden multi-threading in the random number generation causing the order mismatch.

I compiled with g++ version 5.3.0, on Linux, with the flag -std=c++11.

Thanks in advance for your help.




Random Integer between 2 separate intervals

I have the following question.

How can you generate a random Integer between e.g. 1-7 and 10-26

I think it's quite easy but I don't seem to find a solution.

I apologize if my question has already been asked.

I'd appreciate any kind of help :)




Will this code generate a duplicate on the long run?

I have been banging my head for two days now trying to make sure the random generator method won't generate a duplicate. This I had to do with loops only without importing any libraries. I have come to this solution, will this code generate a duplicate on the long run? If yes please help.

    int [] vargu1 = new int [5]; 

    for ( int i = 0; i < vargu1.length; i++)
    {
        int numriSekret = (int) (Math.random() * 10)+1;
        vargu1[i] = numriSekret;

    } 
    System.out.println(vargu1[i]);  
}
    System.out.println();
    for ( int i = 0; i < vargu1.length; i++){
        for ( int j = 0; j < i; j++){
            if (vargu1[i] == vargu1[j])
                vargu1[i]++;
            }
            System.out.println(vargu1[i]);  
        }




mercredi 27 janvier 2016

Java math not returning expected value

According to http://ift.tt/1nzO08Q, if a^(n-1) does not equal 1 mod n, then the number is a composite number. As we know, 3 is a prime number while 9 is not. My Java skills are very outdated and I'm likely forgetting something very simple. Keep in mind this is only the beginning of the test as well, not the full implementation of the test. The example code below returns false for both numbers, while only 9 should return false.

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

public class LucasTest
{
    private static int n;
    private static boolean primeResult;

    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }

    public static boolean isPrime(int num)
    {
        int a = randInt(2, num - 1);
        int b = num - 1;
        double c = Math.pow(a,b);

        if (c != (1.0 % num)) {
            return false;
        }

        return true;
    }

    public static void main(String args[])
    {
        System.out.println("Enter an integer:");

        Scanner pNum = new Scanner(System.in);

        n = pNum.nextInt();

        primeResult = isPrime(n);

        System.out.println("Number is likely prime?: " + primeResult);
    }
}




My Random array is giving me the same answer when it should be different

I got my code to work in the expected way, but when i try to make more than one list of permutations it gives me the first one and doesn't change it around. I need to make a list of permutations from 1 to 10 using an Arraylist and to catch one error that can occur in the code. Then we have to duplicate that code so that we get 9 DIFFERENT lines of permutations.

 import java.util.ArrayList;
import java.util.Random;
public class Permutations
{

    ArrayList <Integer> Perm = new ArrayList <Integer> ();
    ArrayList <Integer> Print = new ArrayList <Integer> ();
    int counter = 9;
    int List = 1;
    public void ArrayList()
    {
        Perm.add(1);
        Perm.add(2);
        Perm.add(3);
        Perm.add(4);
        Perm.add(5);
        Perm.add(6);
        Perm.add(7);
        Perm.add(8);
        Perm.add(9);
        Perm.add(10);
    }

    public void PermutationGenerator()
    {
        ArrayList();
        Random rand = new Random();
        int value = rand.nextInt(10) + 1;
        while(Print.size() < 10)
        {
            try
            {
                while(Print.contains(value))
                {
                    value = rand.nextInt(10) + 1;
                }
                Print.add(value);
                Perm.remove(value);
            }
            catch(IndexOutOfBoundsException a)
            {
                System.out.println("");
            }
        }
        System.out.println("List" + List + ":" + Print.toString());
        List++;
        if(List < 10)
        {
            PermutationGenerator();
        }
    }

This is what is printed out:

List1:[9,6,5,4,10,2,8,7,1,3]    
List2:[9,6,5,4,10,2,8,7,1,3]    
List3:[9,6,5,4,10,2,8,7,1,3]    
List4:[9,6,5,4,10,2,8,7,1,3]    
List5:[9,6,5,4,10,2,8,7,1,3]    
List6:[9,6,5,4,10,2,8,7,1,3]    
List7:[9,6,5,4,10,2,8,7,1,3]    
List8:[9,6,5,4,10,2,8,7,1,3]     
List9:[9,6,5,4,10,2,8,7,1,3] 




RANDOM #s. Type two statements using nextInt() to print two random integers between 0 and 9. End with a newline. Ex: 5 7

Hey all I'm having trouble figuring this out. Just learning java for the first time. Any help would be awesome thanks!

Type two statements using nextInt() to print two random integers between 0 and 9. End with a newline. Ex: 5 7

import java.util.Scanner;

import java.util.Random;

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

Random randGen = new Random();

int seedVal = 0;

randGen.setSeed(seedVal);

  `enter code here`/* Your solution goes here  */


return;
   }
}




How to open multiple QWidgets randomly and close them randomly on python3.5?

I want to open multiple colored boxes randomly and want them to be closed after some random time automatically. I am using python 3.4 and PyQt5. I can do opening and closing part, but I couln't succeed to colorize those popup windows. What can I do?




Repeated set of UUIDs from java's UUID.randomUUID()

We have observed that set of almost 200,000 UUIDs has replayed two months apart, and I'm wondering if anyone has seen anything similar.

The UUIDs are generated using UUID.randomUUID(). In digging into this (looking at java source), randomUUID() uses SecureRandom() under the hood, which in turn is using NativePRNG. It is my understanding that NativePRNG uses /dev/urandom to acquire its seed. The implication of course is baffling - that somehow /dev/urandom returned the same seed to NativePRNG two months apart. From what I can tell, once instantiated the PRNG does not re-seed. This is a long running job which s listening for messages and using a UUID as an ID for it. The pseudocode is simply:

< receive message> String uuid = UUID.randomUUID().toString(); String fname = h.composeArtifact(uuid);

The OS is Centos 6, on an AWS EC2 instance running JDK1.6. Is this something that anyone has seen/experienced in the past? Seems like the kind of thing that should 'never happen'...




Search for a number in an array java

I have code that first generates the array with 100 elements, then places randomly generated numbers in each element. I am trying to do a search for a number and if found, print out its index. the code I have so far is:

import java.util.Scanner;

public class Lab01 
{

    public static void main(String[] args) 
    {
        int[] nums = new int[100];

        for (int i = 0; i < nums.length; i++)
        {
            nums[i] = (int)((Math.random() * 100) + 1);
            System.out.print(nums[i] + " , ");
        }
     System.out.println();
     Scanner input = new Scanner(System.in);
     int num;
     System.out.println("What number would you like to search for?");
     num = input.nextInt();
     boolean found = false;        
     for (int i = 0; i < nums.length; i++) 
        {
            if (num == nums[i]) 
            {              
               found = true;
               break;
            }

            if (found)
            {
                System.out.println("That number was found at index" + i);
                break;
            }
            else
            {
                System.out.println("That number was not found.");
                break;
            }
        }       
    }
}

I put in the print statements to see the values, so I could verify that it was working, but it ALWAYS returns "Not found". What am I missing here?




Pull random 10 entries without duplicating every time when ajax calls

Possible to pull random 10 entries (without duplicating entries) with ajax everytime when scroll to the bottom, right now it loads random 10 entires but it duplicates and some entries never shows up. Any ideas? thanks

index.html:

{exp:channel:entries channel="channel_A|channel_B|channel_C" orderby="random" limit="10"}
  {content}
{/exp:channel:entries}

ajax/index.html

{exp:channel:entries channel="channel_A|channel_B|channel_C" orderby="random" limit="10"}
  {content}

  {paginate}
    {pagination_links}
      <ul class="lepaginate">
        {page}
          <li><a href="{pagination_url}" class="page-{pagination_page_number} {if current_page}active{/if}">{pagination_page_number}</a></li>
        {/page}
      </ul>
    {/pagination_links}
  {/paginate}

{/exp:channel:entries}

jquery:

  var counter = 10;

  $(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() == $(document).height()) {


        var response;
        $.ajax({ type: "GET",   
          url: ""+document.location.origin+"/ajax/P"+counter+"",
          async: false,
          success : function(text) {
            response = text;
          }
        });

        counter += 10 ;
        newItems = $(response).appendTo('.grid');
        $grid.isotope('appended', newItems );


          var $grid = $('.grid').isotope({
            masonry: {
              columnWidth: 360,
              gutter: 30
            }
          });

    }

  });

this is using pagination, so it loads like '/ajax/P10' '/ajax/P20' ..., etc




Generating random numbers in a particular range

I am trying to generate n random numbers between 0-31 in my Android code. Below is the code that I am using:

int max_range = 31;
SecureRandom secureRandom = new SecureRandom();
int[] digestCodeIndicesArr = new int[indices_length];
int i = 0, random_temp = 0;

while (i != indices_length-1) {
    random_temp = secureRandom.nextInt(max_range);
    if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp)) {
        digestCodeIndicesArr[i] = random_temp;
        i++;
    }
}

indices_length is the number of random numbers that I need. It's generally 6,7 or 9. But when I print the generated array, I generally end up seeing duplicates. Can someone point out the mistake I am making. I have added the below line of code to filter out random duplicates:

if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp))

Thanks in advance!




Random integer from an array

I'm fairly new to Java and I'm just practicing my skills using multiple classes and using System.out.println.

I'm trying to make a program in which you have a 'conversation' with the computer. What I'd like to try and do is instead of the computer having the same age every time the console is run, use an array to list a load of random ages, which will then be randomly selected. In my computer class I've got:

    static int [] compAge = {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};

and in my main conversation class, I've got:

int Uage = input.nextInt(); // (Uage is user age)
System.out.println("That's cool! You're " +Uage+ ". I'm " + (Computers age here) + " myself. Where do you live?");

I've read around a bit and found code such as

compAge[new Random().nextInt(compAge.length)]

But in all honestly my knowledge of arrays and using the random function (I have imported it) is very limited and I'm not really sure where to go.

Any help would be massively appreciated. Thanks all.




What does these number in random no. generator do?

Basically i understand the program but not the math/numbers used here.

import random

def r_int():
  x = int(abs(10 * random.random() % 20))
  return x

I figured out this is equivalent to random.randint(0,9). What does the % and 20 do here?




How to get random number only once JavaScript [duplicate]

This question already has an answer here:

Guys I have array with five strings inside. Then I have loop and inside loop I have Math.random to get 1,2,3,4 and 5 numbers. So as you guess I want to change array's each string randomly, but if I changed one of them once I want to re-random a number and change the next string. The problem is that only re-randoms once but I want it to do until it gets to unchanged string.

<button id="button" onclick="change()">me</button>
<p id="par"></p>

var holder = ["empty","empty","empty","empty","empty"];


var change = function(){
for(var i=0; i<holder.length; i++){
var rand = Math.floor((Math.random() * 5) + 1);

switch (rand) {
    case 1:
        if (holder[0] === "empty"){
            holder[0] = "ocupied"
        }else{rand = Math.floor((Math.random() * 5) + 1)}
        break;
    case 2:
        if (holder[1] === "empty"){
            holder[1] = "ocupied"
        }else{rand = Math.floor((Math.random() * 5) + 1)}
        break;
    case 3:
        if (holder[2] === "empty"){
            holder[2] = "ocupied"
        }else{rand = Math.floor((Math.random() * 5) + 1)}
        break;
    case 4:
        if (holder[3] === "empty"){
            holder[3] = "ocupied"
        }else{rand = Math.floor((Math.random() * 5) + 1)}
        break;
    case 5:
        if (holder[4] === "empty"){
            holder[4] = "ocupied"
        }else{rand = Math.floor((Math.random() * 5) + 1)}
        break;
}


    document.getElementById('par').innerHTML = holder;
};




Make random number generator to not repeat same number twice [duplicate]

This question already has an answer here:

This is my first question, since I have started programming not very long ago. I have been trying to get a random number generator using two loops to not generate the same number twice. Last night I did spend 5 - 6 hours researching for the question did find some solutions but none worked for me. I have posted a code with my progression but it keeps generating the same number more than once.

I am sorry if the question I have posted has been answered before, if so please send me the link. This is a homework so the number generator method should not be changed as I have commented it.

Thank you in advance.

        int [] a1 = new int [5]; 
        for ( int i = 0; i < a1.length; i++) 
        {
            int numriSekret = (int) (Math.random() * 100)+1; // This should not be changed, every other part can change. 
                a1[i] = numriSekret;
                for(int j = 0; j < i; j++){
                if (a1[i] == a1[j]){
                    i--;
                    break;
                }   
            }
            System.out.println(vargu1[i]);  
            }




Random image with javascript

Without knowing javascript at all I somehow created random image generator:

<script language="JavaScript"><!-- 
document.write("<img src=\"image-"+Math.floor(Math.random()*12+1)+".jpg\" />");
//--></script>

I does show random images as it should but there are some limitations so I need your help.

  1. Sometimes I have more than 9 images for some pages and their name is "mad-01", "mad-02"... "mad-11" to keep them sorted but code above can't show images with 0 before second digit. I have named images with and without 0 before second digit: "mad-01", "calm-1". How can this be solved? Or is it better to just remove 0 from images?
  2. Is there a way to make this code that way so I won't need to keep writing how many images is there to show?

I would like to have this code as shortest as possible that's why I'm not using array.




mardi 26 janvier 2016

Sympy reconfigures the randomness seed

The use of Python symbolic computation module "Sympy" in a simulation is impossible, I need to have reliable fixed inputs, for that I use the seed() in the random module. However every time I call a simple sympy function, it seems to overwrites the seed with a new value, thus getting new output every time. I have searched a little bit and found this. But neither of them has a solution.

Consider this code:

from sympy import * import random random.seed(1) for _ in range(2): x = symbols('x') equ = (x** random.randint(1,5)) ** Rational(random.randint(1,5)/2) print(equ)

This outputs

(x**2)**(5/2) x**4

on the first time, and

(x**2)**(5/2) (x**5)**(3/2)

On the second time, and every-time I run the script it returns new output. I need a way to fix this to enforce the use of seed().




How to make my room sorter more random?

So I'm working on a program which is supposed to randomly put people in 6 rooms (final input is the list of rooms with who is in each room). So I figured out how to do all that.

        //this is the main sorting sequence:
        for (int srtM = 0; srtM < Guys.length; srtM++) {
        done = false;
        People newMove = Guys[srtM]; //Guys is an array of People 
        while (!done) {
            newMove.rndRoom(); //sets random number from 4 to 6
            if (newMove.getRoom() == 4 && !room4.isFull()) {
                room4.add(newMove); //adds person into the room4 object rList
                done = true;
            } else if (newMove.getRoom() == 5 && !room5.isFull()) {
                room5.add(newMove);
                done = true;
            } else if (newMove.getRoom() == 6 && !room6.isFull()) {
                room6.add(newMove);
                done = true;
            }
        }

The problem now is that the code for reasons I don't completely understand (something with the way I wrote it here) is hardly random. It seems the same people are put into the same rooms almost every time I run the program. For example me, I'm almost always put by this program into room 6 together with another one friend (interestingly, we're both at the end of the Guys array). So how can I make it "truly" random? Or a lot more random than it is now?

Thanks in advance!




Sudoku Blanks - c++

I have to write a program that takes in a Sudoku square(with all slots filled) and randomly assigns 25 blanks to be filled in. This is what I have so far but because this code has the chance to generate the same position in the array more than once I'm getting a varying number of blanks(17-21). I'm wondering if there is a simple way to get it to output 25 blanks no matter what. My print function inserts a blank if the value is zero at any spot in the array.

void insertBlanks(int square[9][9])
{
    srand(time(NULL));
    int i = 0;
    while(i < 25)
    {
        int tempOne = rand() % 9;
        int tempTwo = rand() % 9;
        square[tempOne][tempTwo] = 0;
        i = i + 1;
    }
}




Generate integer from 0 to 1 with equal proabability

I am trying to get around this problem of my own making. I want to generate 0 or 1 with another function(gr0_4()) which generates random number from 0 to 4.

I am wondering if I can approach this way:

a). if gr0_4() = 0 or 1 then I will use 0

b). if gr0_4() = 2 or 3 then I will use 1

c). if gr0_4() = 4 I will repeat the a) and b) steps.

Is my understanding correct that the "a" and "b" step each has 50% probability of happening?

def gr0_1():
  while True:
    x = gr0_4()
      if x == 0 or x == 1:
        return 0
      elif x == 0 or x == 1:
        return 1

What if I want to use gr0_1() to create gr1_7() i.e. create number between 1 to 7 with equal probability?

Can I use below reasoning to create that function gr1_1().

As 7 consists of 3 bits. I can generate each bit with equal probability using gr0_1(). So I will call gr0_1() three times and based on that value I get, I will set/unset the corresponding bits to generate a number between 1 to 7 including the numbers 1 and 7. However I can get the number 0 but I don't want that so I will repeat the process again. Will the probability of each number generation between 1 to 7 will be 1/7 in that case also?

Some simple mathematical calculation will be nice to answer this. I tried to read up on rejection sampling but couldn't understand much.




Generating random poll numbers

I struggle with this simple problem: I want to create some random poll numbers. I have 4 variables I need fill with data (actually an array of integer). These numbers should represent a random percentage. All percentages added will be 100% . Sounds simple.

But I think it isn't that easy. My first attempt was to generate a random number between 10 and base (base = 100), and substract the number from the base. Did this 3 times, and the last value was assigned the base. Is there a more elegant way to do that?

My question in a few words:

How can I fill this array with random values, which will be 100 when added together?

int values[4];




PHP: range and foreach

I'm working with percents and rand(), I'm trying to create an array from 0 to 25 then 25 to 50 then 50 to 80. But I got this array:

[0] => 55
[1] => 56
[2] => 57
[3] => 58
[4] => 59
[5] => 60
[6] => 61
[7] => 62
[8] => 63
[9] => 64
[10] => 65
[11] => 66
[12] => 67
[13] => 68
[14] => 69
[15] => 70
[16] => 71
[17] => 72
[18] => 73
[19] => 74
[20] => 75
[21] => 76
[22] => 77
[23] => 78
[24] => 79
[25] => 80

I want to create an array from 0 to 80. My code is:

foreach($list_percents as $redir) {
    $percent_array=range($inicial,($inicial+$redir->percent));
    $percent_array=array_fill($inicial, $redir->percent, $redir->url);
    $inicial=($inicial+$redir->percent);
}
print_r($percent_array);




Permuting columns of a matrix in MATLAB

Say I have an n by d matrix A and I want to permute the entries of some columns. To do this, I compute permutations of 1 ... n as

idx1 = randperm(n)'
idx2 = randperm(n)'

Then I could do:

A(:,1) = A(idx1,1)
A(:,2) = A(idx2,2)

However, I dont want to do this using a for-loop, as it'll be slow. Say I have an n by d matrix A and an n by d index matrix IDX that specifies the permutations, is there a quicker equivalent of the following for-loop:

for i = 1:d
    A(:,i) = A(IDX(:,i),i);
end




Get Random Number Between Given Range in Java [duplicate]

This question already has an answer here:

How to Get Random Number Between Given Range in Java if minimum is more than 1? for example if i want to get random number between 6 to 20. currently i am using this code

Random rand = new Random(); 
int  rnd = rand.nextInt(499) + 1;

it is working well, but if i change 1 to some high number for example 6, it will not work properly, i want to get random number that is between 6 and 20. is it possible using above function ?




copy of objects random engine

I wrote a cpp class that generates a random process. I defined the random engine as a public attribute of my class.

My question is : what happens with the engine when I use the operator= :

Proc A; 
// operations on A 
Proc B;
B=A;

will it create a new engine for B initialised randomly ? Or will it create a engine that will generate pseudo-random numbers from where the engine of A stopped ?

Here is how I wrote the class :

class Proc {
  public:
mt19937 eng {random_device{}()};
double Tps;
vector<int> prc;
... }

Thanks for your help !




Generate locations which are touching in a 2d array

Problem: I want to generate random locations on a grid which are touching. The total number of locations is 5. Is there a more efficient/different way of doing the following code (I call this 5 times with the use of recursion and use other code which stores it):

 /*
 * 8        1       2
 * 7    [original]  3
 * 6        5       4
 */
    int rand = 1 + (int)(Math.random() * ((8 - 1) + 1));
    if(rand >= 2 && rand<= 4)
    {
        newx++;
    }
    else if(rand >=6 && rand<=8)
    {
        newx--;
    }

    //change y according to number
    if(rand == 8 || rand == 1 || rand==2)
    {
        newy++;
    }
    else if(rand >= 4 && rand<= 6 )
    {
        newy--;
    }




Random Flipping of View

i am realy new with Android Code. I try to show a random Image on my Layout. With the Code below the first Image after onCread is random. But after that the others are in Order. Is there a way to show after every View a random other view ?

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {


        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

            mViewFlipper = (ViewFlipper) rootView.findViewById(R.id.view_flipper);
            mViewFlipper.setAutoStart(true);
            mViewFlipper.setFlipInterval(4000);
            Random mRandom = new Random();
            mViewFlipper.setDisplayedChild(mRandom.nextInt(400));
            mViewFlipper.startFlipping();



Android - Is it possible to iteratively generate random numbers while toggle button is on?

I am trying to create an app in Android that generates number repetitively while the toggle button is on. So, when the user taps the toggle again to turn it off it will stop generating random numbers. But I am not sure if it is possible, because my code keeps on getting a run-time error because of infinite loop. Is it possible to iteratively generate random numbers while toggle button is on?




matlab genetic algorithm mobil robot path planning creating random numbers related to links

I want to create a genetic algorithm for mobil robot path planning.there are obstacles and there are only 15 nodes at all. Each node linked to 2,three or four other nodes. For creating 64 bit random numbers how can I create related to this links? number of nested if else statements is very high when I tried to start.

firstlink=[1,3,4]; 
link2=[0,2];
link3=[1,5,11];
link4=[0,6,8];
link5=[0,5,6];
link6=[2 4 10];
link7=[3,4,7];
link8=[6,9,13];
link9=[3,13];
link10=[7,10,15];
link11=[5,9,11];
link12=[2,10,12];
link13=[11,15];
link14=[7,8,14,15];
link15=[13,15];
link16=[9,12,13,14];

after that, I select randomly each of this link but number of conditions are very high. Is there an easy way to do it? thanks,




Choosing a random function

else {
    alert('That was wrong!')
    alert('Too bad, try again!')
}

I want the else to pick a random alert, for example if I have the answer wrong it pick a random alert and if I have the answer wrong again I want it to pick another random alert. How do I do this in jquery? Thanks in advance.




Elm random list implementation

Elm standard library offers a function to generate random lists that works fine. By taking a look at its implementation, we can see that the list is constructed in a functionnal style, i.e. from the end to the beginning. When enough elements have been generated, the reversed list is returned:

if n < 1 then
    (List.reverse list, seed)

I'm wondering why do we need to reverse this list? Is it necessary to ensure "correct" randomness?




lundi 25 janvier 2016

Printing 2D array is more organized than it's supposed to be

I am attempting to randomly place the letter "x" into slots in a 2D array as an initializer for a Conway Game of Life.

        string[,] initialArray = new string[rowMax, colMax];

        for(int row = 0; row < rowMax; row++)
        {
            for(int col = 0; col < colMax; col++)
            {
                if(randomNumber() < 7)
                {
                    initialArray[row, col] = " ";
                }
                else
                {
                    initialArray[row, col] = "x";
                }
                tbGrid.Text += initialArray[row, col];
            }
            tbGrid.Text += "\r\n";
        }

What I want to appear is a somewhat random placement such as :

       x     x           x            xx        xx      x
                    x            x           x         

etc.
However, what I'm ending up with is more grouped together such as:

        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Just for example.

Any idea why that might be? At first I thought it was because I had the tbGrid.Text statement inside the IF statement. Taking that out helped, but it still didn't perform as desired.

The random number generator is set as follows:

    public static int randomNumber()
    {
        Random randomNum = new Random();
        int random = randomNum.Next(1, 10);
        return random;      
    }

If that's helpful. Ideas? Suggestions?




How to generated random number from lognormal distribution with known parameters mu and sigma?

I have a known mu and sigma for lognormal distribution, and I don not know the lower and upper bound or interval for the random variable. I need to generated a random number from the lognormal distribution with known mu and sigma using Java. Thank you.




Proper use of rand()?

So the idea with this is that it takes in the 9x9 array that's in main, and swaps around rows. It can only swap rows 1-3 with 1-3, 4-6 with 4-6 and 7-9 with 7-9. For some reason every once in awhile it will swap one from 4-6 with one from 7-9, and also sometimes it will give me absolute garbage for one of the rows 7-9. I've spent the better part of 2 hours trying to figure out the proper way to use rand() in this context and I am sure I am not doing it correctly. Any ideas?

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

using namespace std;

void printSudoku(int square[9][9]) // Prints out the 9x9 array
{
    for(int i = 0; i < 9; i++)
    {
        for(int j = 0; j < 9; j++)
        {
            cout << square[i][j];
        }
        cout << endl;
    }
}

void swapRows(int square[9][9]) // Randomly generates numbers, within bounds, and swaps those rows with each other
{
    int temp[1][9];
    srand(time(NULL));
    int n = (rand() % 2) + 0;
    int m = (rand() % 2) + 0;
    for(int i = 0; i < 9; i++)
    {
        temp[0][i] = square[n][i];
    }
    for(int j = 0; j < 9; j++)
    {
        square[n][j] = square[m][j];
    }
    for(int k = 0; k < 9; k++)
    {
        square[m][k] = temp[0][k];
    }
    int a = (rand() % 5) + 3;
    int b = (rand() % 5) + 3;
    for(int i = 0; i < 9; i++)
    {
        temp[0][i] = square[a][i];
    }
    for(int j = 0; j < 9; j++)
    {
        square[a][j] = square[b][j];
    }
    for(int k = 0; k < 9; k++)
    {
        square[b][k] = temp[0][k];
    }
    int c = (rand() % 8) + 6;
    int d = (rand() % 8) + 6;
    for(int i = 0; i < 9; i++)
    {
        temp[0][i] = square[c][i];
    }
    for(int j = 0; j < 9; j++)
    {
        square[c][j] = square[d][j];
    }
    for(int k = 0; k < 9; k++)
    {
        square[d][k] = temp[0][k];
    }
}


int main() {
int square[9][9] = {1,2,3,4,5,6,7,8,9,
                    4,5,6,7,8,9,1,2,3,
                    7,8,9,1,2,3,4,5,6,
                    2,3,4,5,6,7,8,9,1,
                    5,6,7,8,9,1,2,3,4,
                    8,9,1,2,3,4,5,6,7,
                    3,4,5,6,7,8,9,1,2,
                    6,7,8,9,1,2,3,4,5,
                    9,1,2,3,4,5,6,7,8,};
printSudoku(square);
swapRows(square);
cout << endl;
printSudoku(square);
    return 0;
}




How to ensure the consistency of a multi-threaded simulation in C++?

I have implemented a certain simulation that is multi-threaded for the sake of runtime. However, this causes an inconsistency between my different runs since I'm using an RNG for my simulations. Even thought the RNG is seeded the same way across the threads, and even though GNU's gsl_rng is supposed to be thread-safe(I think it is) it looks like some form of race condition between the threads leads some to generate numbers before other threads do and as such there are small discrepancies between various runs. I was thinking that one way to fix this would be to pre-compute a fixed number of random numbers and then assign them manually to the threads. However, there would be a huge overhead to store the random numbers (in the order of millions). I was wondering if there was any better way to deal with this race condition?




Can you write your own java randomizer?

I know how to use Math.random() in my code, but my question is specifically how does the function actually work? How does it pick a random number and is it possible to create your own randomizing function in java?




I'm having trouble understanding how to make Random methods in java. Also, what do you recommend for working with Array Lists?

"Right now, I am having a spot of trouble understanding how to make random methods of my own and array list methods of my own. I'm learning Java on Udemy and after every chapter is complete, I toy around with the methods I have learned on my own, but I'm not sure how to toy around with Random or ArrayLists. Can anybody here recommend techniques or ways of remembering?"

"It should be worth noting that I am NOT good with remembering arguments. I am pretty sure I have parameters down when it comes to calling a method, but using arguments within a method is kind of tough right now."

"For example? . get(i) or the line Random rand?"

My cousin recommended that I memorize the grammar rather than the definitions themselves, but that is proving rather difficult to know how to write without knowing what to write, you know?"

"Also, does every array list have to work with a loop? Because this is hard stuff to memorize."

import java.util.Random;

import java.util.ArrayList;

public class Chap11Part10

 {    

  public static void main(String[] args)

          {

        ArrayList<Integer> numbers = new ArrayList<Integer>();

              buildAL(numbers, 5); 

                 int max = maximum(numbers);

                     display(numbers);

                      System.out.println("The maximum value is " + numbers.get(max));

                       }

       static void display(ArrayList arr) 
       {

       for (int i = 0; i < arr.size(); i++)

            System.out.print(arr.get(i) + " "); 

                System.out.println(); 

               }

       static void buildAL(ArrayList<Integer> arr, int num) {

            Random rand = new Random(System.currentTimeMillis());

              for(int i = 0; i < num; i++)

                 arr.add(rand.nextInt(101)); 

                     }

            static int maximum(ArrayList<Integer> arr){

                  int maxPos = 0; 

                     for (int i = 1; i <arr.size(); i++)

                      if (arr.get(i) > arr.get(maxPos)) 

                        maxPos = i; 

                         return maxPos;
                              }

                       }




Django: How can I store in database a variable which I generate in a random function?

My web application is in django and it displays random images every time the user press the 'next' button. I try to store the name or better the number of the image which is concatenated on its name. For example, if the name is 'image4.jpg' then I want to store the number 4 as number or as text.

So, first I have a class in the models.py file.

class Session(User):
    image_number = models.IntegerField()

The type of the variable is probably wrong because I don't want to get this from a form. I generate the number in the views.py file. So, I just want to store it.

As I said I have a function in the views.py file which generates the random numbers.

def func_random(self):
    random_im_list = random.sample(xrange(1,20),5)
    return {1v: random_im_list[0],
            2v: random_im_list[1],
            ... etc}

So, here I generate a list of 5 numbers, because I want to display 5 images in every session. The user presses 5 times the 'next' button and each time he can see a new random image.

I have also in views.py five classes for the five Pages.

class Image1(Page):

class Image2(Page):

class Image3(Page):

class Image4(Page):

class Image5(Page):

Here I need some help because I don't wait any input from the user. I already have generated the list with the random numbers. So, how can I store them on the database? The database after the first session must have 5 columns with one number in each column.

And after that I have the template file:

{% if Page == 1 %}

    <div>
         <im src="{{static_url}}images/image{{ 1v }}.jpg" />   
    <div>
{% elif Page == 2 %}
    <div>
         <im src="{{static_url}}images/image{{ 2v }}.jpg" />   
    <div>

etc....




Javascript - Random, if statement, and event.target

I'm new to Javascript and I have an issue with event.target. The thing is that I use Math.random to display a number, then use an if statement so that if you click on the image corresponding to the number, it gets bigger, and if you click on another image, its opacity changes. It works perfectly in Chrome and IE, but not in Firefox (which is a classic, I know).

Here's my code:

<html>
<body>
  <input class="img" type="image" id="soleil" src="img/soleil.jpg" alt="soleil">

  <input class="img" type="image" id="jour" src="img/jour.jpg" alt="jour">

  <input class="img" type="image" id="nuit" src="img/nuit.jpg" alt="nuit">

 <script>

var sunrise_sunset = [19, 20 ,6, 7];
   var night = [21, 22, 23, 0, 1, 2, 3, 4, 5];
   var day = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
   var hours = sunrise_sunset.concat(night).concat(day);

   var randomHour = Math.floor(Math.random() * hours.length);

{document.getElementById("soleil").addEventListener("click", function(){checkAnswer(sunrise_sunset)}, false);
                          document.getElementById("nuit").addEventListener("click", function(){checkAnswer(night)}, false);
                          document.getElementById("jour").addEventListener("click", function(){checkAnswer(day)}, false);
}

function checkAnswer(array) {  
  var isCorrect = false;
  for(var i = 0; i<array.length; i++) {
    if(array[i] == randomHour){
        isCorrect = true;
      break;
    }
  }

  if(isCorrect){

        event.target.style.width=500;

  }else{

      event.target.style.opacity = 0.5;
  }
};
</script>
</body>
</html>

So my question is, how can I make it work in Firefox? Should I just change my if statement? I read tons of posts in which they redefine the event through a function, but I don't see how I can do that with the random value and the if statement. I'm not saying there is no way, just that I don't see it...

Anyway, thank you in advance for your help guys! :)




rand,srand make calculations

Can someone tell me more examples of rand(),and calculations? 1: output (1-ournumber)->> we do this x = rand() % ournumber + 1; I need help for (a,b) and can someone tell me more than two exapmles please for practice to do?




What is a full stack developer? [on hold]

I'm a self taught Android developer, and I'm trying to get a coding job. I've been seeing more and more postings asking for full stack developers. I looked up this, and I'm getting answers that's all over the place on Google.

Based on all the job postings, I'm assuming it's someone who works on both the front and back end of things. Am I right? If not, then please fill me in on this?




dimanche 24 janvier 2016

numpy's random vs python's default random subsampling

I observed that python's default random.sample is much faster than numpy's random.choice. Taking a small sample from an array of length 1 million, random.sample is more than 1000x faster than its numpy's counterpart.

In [1]: import numpy as np

In [2]: import random

In [3]: arr = [x for x in range(1000000)]

In [4]: nparr = np.array(arr)

In [5]: %timeit random.sample(arr, 5)
The slowest run took 5.25 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 4.54 µs per loop

In [6]: %timeit np.random.choice(arr, 5)
10 loops, best of 3: 47.7 ms per loop

In [7]: %timeit np.random.choice(nparr, 5)
The slowest run took 6.79 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 7.79 µs per loop

Although numpy sampling from numpy array was decently fast yet it was slower than default random sampling.

Is the observation above correct, or am I missing the difference between what random.sample and np.random.choice compute?




How can I compute a random value with multimodal distribution?

I would like to compute a random value with a multimodal distribution composed of N normal distributions.

I have an array with N elements of normal distribution parameters (std deviation, mean).

My language (VHDL) and my library allow me to calculate the following basic distributions: - uniform distribution [-1.0; 1.0] - normal distribution (Box Muller transformation) - Poisson distribution

How can I calculate random values so that the histogram looks like N overlapping normal distributions?

two normal distributions

Types and helpers:

type T_NORMAL_DIST_PARAM is record
    StdDev : REAL;
    Mean   : REAL;
  end record;
  type T_JITTER_DIST is array(NATURAL range <>) of T_NORMAL_DIST_PARAM;
  constant JitterDistribution : T_JITTER_DIST := (
    0 => (0.2, -0.4),
    0 => (0.2,  0.4)
  );

The problems core:

procedure getMultiModalDistributedRandomNumber(Seed : T_SIM_SEED; Value : REAL; JitterDistribution : T_JITTER_DIST) is
  variable rand   : REAL;
  variable Result : REAL;
begin
  -- ...
  for i in JitterDistribution'range loop
    getNormalDistributedRandomValue(Seed, rand, JitterDistribution(i).StdDev,  JitterDistribution(i).Mean);
    -- how to accumulate rand?
  end loop;
  Value := Result;
end procedure;

It's used in:

procedure genClock(signal Clock : out STD_LOGIC; Period : TIME) is
  constant TimeHigh : TIME := Period / 2;
  constant TimeLow : TIME := Period - TimeHigh;
  variable rand : REAL;
begin
  initializeSeed(Seed);
  while (not isStopped) loop
    getMultiModalDistributedRandomNumber(Seed, rand, JitterDistribution);
    Clock <= '1';
    wait for TimeHigh + (Period * rand);
    Clock <= '0';
    wait for TimeLow;
  end loop;
end procedure;




Random image generator from Imgur album

I'm looking to create an Apache site using PHP so that each time a person directs to it, it will grab a random image from a previously created Imgur album full of images and display the image onload without ever leaving the website. I am thinking I would need to use the Imgur API to make this sort of thing with php but I don't know where to start. Does anybody know how I may be able to do this?

I made this javascript alternative using arrays but this only fetches images listed in the javascript code, I would like to make use of the Imgur API and automatically fetch all the images' URLs from the Imgur album and randomly pick one to display every time the user loads the webpage.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Random</title>

<script type="text/javascript">
function randomlinks(){
    var myrandom=Math.round(Math.random()*263)
    var links=new Array()
links[0]="http://ift.tt/1ZLDy9Y"


    window.location=links[myrandom]

}
</script>

  </head>
  <body onload="randomlinks()">

  </body>
</html>




Receiving an AttributeError all of a sudden

I have a block of code which choose a word from a list and displays it on a label and the user has to retype it correctly to move on.

import random
try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

WORDS = ['Games', 'Development', 'Keyboard', 'Speed', 'Typer', 'Anything',
         'Alpha']
score = 0

def choose_word():
    global word
    entry.focus_set()
    word = random.choice(WORDS)
    label.config(text=str(word.lower()))

def check_entry(event):
    global score
    if entry.get().lower() == word.lower():
        score += 1
        print(score)
    elif entry.get().lower() != word.lower():
        score -= 1
        print(score)
    choose_word()
    entry.delete(0, tk.END)

root = tk.Tk()

label = tk.Label(root)
entry = tk.Entry(root)

label.pack()
entry.pack()

choose_word()
root.bind('<Return>', check_entry)
root.mainloop()

I've been using this same code throughout ALL versions of my code since I started working on it a few months ago. I haven't altered it one bit and it's worked perfectly up until now. The error is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\ernxs\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "C:\Users\ernxs\Downloads\speedtypr\Speedtypr FINAL\speedtyper.pyw", line 685, in choose_word
    label.config(text=str(word.lower()))
AttributeError: 'generator' object has no attribute 'lower'

I noticed this error last week as it occurred rarely but now I can't get past the first word without it throwing this error. My code has gone through MAJOR changes throughout the past months but I have left these functions and anything related to them completely untouched and I have no idea why it worked perfectly for 3 months then has now stopped working.

I've tried the above code and it works perfectly but when I run it inside my full program I get the error despite nothing else being related to the functions I mentioned.

I've tried included even more of my program (which I hope is not too much) but it still won't throw the same error:

try:
    import tkinter as tk

except ImportError:
    import Tkinter as tk

import time
import random

correct_words = []
WORDS = ['Basic', 'Christmas', 'Summer', 'Sports', 'Winter', 'Negative',
         'Beach', 'Country', 'Christmas', 'Food', 'Games', 'Music', 'Family']

time_score = 0 
word_count = 0
max_words = 12
skips = 0
total_words = 0
words_found = 0

def end_game():
    root.destroy()
def choose_word():
    global word, start_time
    go_btn.pack_forget()
    start_time = time.time()
    entry.focus_set()
    if word_count < max_words:

        word = random.choice(WORDS)

        label.config(text=str(word.lower()))
        time_score_label.config(text="Time: " + str(time_score) + "s")      

    else:
        end_game()

def check_entry(event):
    if entry.get().lower() == word.lower():
        update_right()

    elif entry.get().lower() != word.lower():
        update_wrong()

    if len(entry.get()) < 1:
        update_skip()

    update_time()    
    choose_word()
    entry.delete(0, tk.END)

def update_time():
    global time_score
    time_score += time.time() - start_time
    time_score = round(time_score,2)

def update_skip():
    global skips
    skips += 1
    skip_counter.config(text="Skips: " + str(skips))
    wrong_label.config(text="SKIPPED!", fg='red')
    time_score_label.config(text="Time: " + str(time_score) + "s")

def update_right():
    global word_count, words_found

    word_count += 1
    words_found += 1
    WORDS.remove(word)
    correct_words.append(word)

    time_score_label.config(text="Time: " + str(time_score) + "s")
    word_counter.config(text="Words: " + str(word_count))
    wrong_label.config(text="")

def update_wrong():    
    wrong_label.config(text="WRONG!", fg='red')
    time_score_label.config(text="Time: " + str(time_score) + "s")

def display():
    for i in (label, time_score_label, word_counter, skip_counter, wrong_label,
        entry):
        i.pack()
    choose_word()

root = tk.Tk()
go_btn = tk.Button(root, text="GO!", command=display, width=17)
go_btn.pack()
label = tk.Label(root, font=("Helvetica", 60))
time_score_label = tk.Label(root, text="Time: " + str(time_score) +
                                "s", font=('Helvetica', 14))
word_counter = tk.Label(root, text="Words: " + str(word_count),
                            font =("Helvetica", 14))
skip_counter = tk.Label(root, text="Skips: " + str(skips),
                            font =("Helvetica", 14))
wrong_label = tk.Label(root, text="", font =("Helvetica, 14"))
entry = tk.Entry()

root.bind("<Return>", check_entry)
root.mainloop()

This is everything related to this function and I can't reproduce the error. I won't post my full program since it is way too long so is there anything else I can try?




Random divisable at least one of two integers in c#

I've got an integer that I'd like to assign a value to by using Random. The randomly chosen number must be divisable by 2 or 5 (or both). For divisable only by two I would just multiply the Random result * 2, but it's not an option here.

How to do this?

edit: I came up with this code, it's probably very inefficient though:

static void Main(string[] args)
        {
            int[] tab = new int[5];
            Random random = new Random();
            int i = 0;
            while (i < tab.Length)
            {
                int tempInteger = random.Next(101);
                if (tempInteger % 2 == 0 || tempInteger % 5 == 0)
                {
                    tab[i] = tempInteger;
                    i++;
                }
            }
        }




Python 3.x battle

I am making a game. I am in the process of making a battle for my new game. However, the enemy keeps on killing the player. Please tell me what is wrong with the code. This is only one part of the battle. I will have it happen over and over again. Thank you. And sorry the some of the code is in the box and some isn't.

(This is for python 3.5.1)

I posted the code here.