vendredi 30 juin 2017

To generate a string by using n characters

I want to generate many string consist of only 3 char ,'R','S' and 'W', in java for testcases .Randomly ,no patterns required to be followed




how to get random pixel index from binary image with value 1 in python?

I have a binary image of large size (2000x2000). In this image most of the pixel values are zero and some of them are 1. I need to get only 100 randomly chosen pixel coordinates with value 1 from image. I am beginner in python, so please answer.




How can I shuffle a very large list stored in a file in Python?

I need to deterministically generate a randomized list containing the numbers from 0 to 2^32-1.

This would be the naive (and totally nonfunctional) way of doing it, just so it's clear what I'm wanting.

import random
numbers = range(2**32)
random.seed(0)
random.shuffle(numbers)

I've tried making the list with numpy.arange() and using pycrypto's random.shuffle() to shuffle it. Making the list ate up about 8gb of ram, then shuffling raised that to around 25gb. I only have 32gb to give. But that doesn't matter because...

I've tried cutting the list into 1024 slices and trying the above, but even one of these slices takes way too long. I cut one of these slices into 128 yet smaller slices, and that took about 620ms each. If it grew linearly, then that means the whole thing would take about 22 and a half hours to complete. That sounds alright, but it doesn't grow linearly.

Another thing I've tried is generating random numbers for every entry and using those as indices for their new location. I then go down the list and attempt to place the number at the new index. If that index is already in use, the index is incremented until it finds a free one. This works in theory, and it can do about half of it, but near the end it keeps having to search for new spots, wrapping around the list several times.

Is there any way to pull this off? Is this a feasible goal at all?




random shuffle return list of None

I'm trying to create a card game, I create a Deck object with a list of objects of the Card type. When I try to sort the list, I get a list with Objects of type NoneType.

import random


SUIT = {'C': 1, 'D': 2, 'H': 3, 'S': 4}
VALUE = {'A': 1, '2': 2, '3': 3,'4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13}


class Card:
    def __init__(self, string):
        self.v = VALUE[string[1]]
        self.s = SUIT[string[0]]


class Deck:
    def __init__(self):
        self.__cards = [Card(f'{s}{v}') for s in SUIT.keys() for v in VALUE.keys()]
        self.shuffle()
        print(self.__cards)

    def shuffle(self):
        random.shuffle(self.__cards)

printing self.__cards return list of None, help me please. Thanks!




How to select random rows where the sum of a column equals to X - MySQL

How i can select random rows of a table when the sum of a column equals to a value ? (MySQL)

    Value : 3

    Name               Price
    ------------------------
    A                  1
    B                  2
    C                  1
    D                  3
    E                  2

I wan to get all possibilities (A + B, D, E + C...).

Thank's Thibeault




How to randomise a matrix element for each iteration of a loop?

I'm working with the popbio package on a population model. It looks something like this:

library(popbio)

babies <- 0.3 
kids <- 0.5 
teens <- 0.75
adults <- 0.98

A <- c(0,0,0,0,teens*0.5,adults*0.8,
         babies,0,0,0,0,0,
         0,kids,0,0,0,0,
         0,0,kids,0,0,0,
         0,0,0,teens,0,0,
         0,0,0,0,teens,adults
)
A <- matrix ((A), ncol=6, byrow = TRUE)

N<-c(10,10,10,10,10,10)
N<-matrix (N, ncol=1)

model <- pop.projection(A,N,iterations=10)
model

I'd like to know how I can randomise the input so that at each iteration, which represents years this case, I'd get a different input for the matrix elements. So, for instance, my model runs for 10 years, and I'd like to have the baby survival rate change for each year. babies <- rnorm(1,0.3,0.1)doesn't do it because that still leaves me with a single value, just randomly selected.

Hope you can help.




How does the distribution of Math.random()*50 + Math.random()*20 compare to Math.random()*70?

How does the distribution of:

var randomNumber = Math.random()*50 + Math.random()*20;

compare to that of:

var randomNumber = Math.random()*70;




Is there a way to call methods of a specific class randomly in ruby?

I was wondering if it is possible to do something like this:

class Something
  def A
    puts "A"
  end
  def B
    puts "B"
  end
  def C
    puts "C"
  end
  def D
    puts "D"
  end
end

y = Something.new
x = Random.new
x.rand(y)

then get a random result of "Something" class




Math game, answer box

So I'd like to get some help on this project i'm working on. Basically i'm doing a math game. There's three boxes where answer options are available. My problem is i don't know how to randomize where the correct answer is (it has to be in one position for it to work) Here is the code, and if anyone'd help me i'd be pleased.

Note: settings.pyis just a file where i've got variables defined such as WIDTH, HEIGHT etc.

import pygame, sys, random
from settings import *
class Game:
    def __init__(self):
        pygame.init()
        pygame.display.set_caption(TITLE)
        self.gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))
        self.font = pygame.font.SysFont(None, 35, True)
        self.plusorminus = random.choice(['+','-'])
        self.No1 = random.randrange(1, 101)
        self.No2 = random.randrange(1, 101)
        self.random1 = str(random.randrange(1,101))
        self.random2 = str(random.randrange(1, 101))
        self.AnswerInput = None
        self.score = 0
        pygame.display.update()
        self.clock = pygame.time.Clock()
        self.GameLoop()

    def displayText(self, text, color, coordinates):
        self.text = self.font.render(text, 1, color)
        self.gameDisplay.blit(self.text, coordinates)

    def CalculateAnswer(self):
        if self.plusorminus == '-':
            if self.No1 > self.No2:
                self.answer = self.No1 - self.No2
            else:
                self.answer = self.No2 - self.No1
        else:
            if self.No1 > self.No2:
                self.answer = self.No1 + self.No2
            else:
                self.answer = self.No2 + self.No1
        return str(self.answer)

    def CheckAnswer(self):
            if self.AnswerInput == 1:
                self.displayText("Correct answer", RED, [WIDTH / 2 - 100, HEIGHT / 2 + 200])
            elif self.AnswerInput == 0:
                pass
    def Update_Score(self):
        self.displayText("Score: {}".format(self.score), WHITE, [10,10])
    def CheckNewQuestion(self):
        if self.AnswerInput == 1:
            self.CheckAnswer()
            #Regenerate the numbers
            self.No1 = random.randrange(1, 101)
            self.No2 = random.randrange(1, 101)
            self.random1 = str(random.randrange(1, 101))
            self.random2 = str(random.randrange(1, 101))
            self.plusorminus = random.choice(['+', '-'])
            self.CalculateAnswer() #Recalculate everything
            self.DrawObjects() #Run function again
            self.AnswerInput = None

    def DrawObjects(self):
        self.gameDisplay.fill(BLACK) #Fill screen black
        #Draw text box
        pygame.draw.rect(self.gameDisplay, WHITE, [WIDTH / 2 - 150, HEIGHT / 2 - 65, 300, 50])
        #Write text
        if self.No1 > self.No2:
            self.displayText("What is {} {} {}?".format(self.No1, self.plusorminus, self.No2), RED, [WIDTH / 2 - 108, HEIGHT / 2 - 52])
        else:
            self.displayText("What is {} {} {}?".format(self.No2, self.plusorminus, self.No1), RED, [WIDTH / 2 - 108, HEIGHT / 2 - 52])
        #Draw the three answer boxes
        self.Answerbox1 = pygame.draw.rect(self.gameDisplay, WHITE,[WIDTH / 2 + 150, HEIGHT / 2 + 104, 150, 50])  # Randbox1
        self.Answerbox2 = pygame.draw.rect(self.gameDisplay, WHITE,[WIDTH / 2 - 75, HEIGHT / 2 + 104, 150, 50])  # Randbox3
        self.Answerbox3 = pygame.draw.rect(self.gameDisplay, WHITE,[WIDTH / 2 - 300, HEIGHT / 2 + 104, 150, 50])  # Ranbox3
        #Write the answer options
        self.displayText(str(self.answer), RED, [self.Answerbox1[0] + 60, self.Answerbox1[1] + 15])
        self.displayText(str(self.random2), RED, [self.Answerbox2[0] + 60, self.Answerbox2[1] + 15])
        self.displayText(str(self.random1), RED, [self.Answerbox3[0] + 60, self.Answerbox3[1] + 15])

    def GameLoop(self):
        print()
        print(self.CalculateAnswer())
        self.gameExit = False
        while not self.gameExit:
            for self.event in pygame.event.get():
                if self.event.type == pygame.QUIT:
                    self.gameExit = True
                elif self.event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    if self.Answerbox1.collidepoint(pos):
                        self.AnswerInput = 1
                        self.score += 10
                        self.CheckNewQuestion()
                    if self.Answerbox2.collidepoint(pos):
                        self.AnswerInput = 0
                    elif self.Answerbox3.collidepoint(pos):
                        self.AnswerInput = 0
                    else:
                        self.AnswerInput = 2
            self.DrawObjects()
            self.Update_Score()
            self.CheckAnswer()
            self.CheckNewQuestion()
            pygame.display.update()
            self.clock.tick(FPS)
        pygame.quit()
        sys.exit()
Game()




Order Id generator algorithm for Firebase

i want a unique and readable id for the orders/invoices generated on firebase with the cloud functions. I think that a random id based on the uid and timestamp is a good solution because a user cannot send two orders at the same time.

What do you think?

i have edited this gist => http://ift.tt/1E1nSWn

and this is the results:

export default (() => {
  const PUSH_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz';

  let lastPushTime = 0;
  let lastRandChars = [];

  return (uid) => {
    if (uid.length != 28) throw new Error('UID length should be 28.');

    let now = new Date().getTime();
    const duplicateTime = (now === lastPushTime);
    lastPushTime = now;

    // CONVERT TimeStamp to CHARS
    const timeStampChars = new Array(8);
    let i;
    for (i = timeStampChars.length - 1; i >= 0; i--) {
      timeStampChars[i] = PUSH_CHARS.charAt(now % 36);

      now = Math.floor(now / 36);
    }
    if (now !== 0) throw new Error('We should have converted the entire timestamp.');

    let id = timeStampChars.join('');

    // ADD 2 random CHARS
    for (i = 0; i < 2; i++) {
      id += PUSH_CHARS.charAt(Math.floor(Math.random() * 36)).toLowerCase();
    }
    Math.max

    // ADD random chars of UID
    if (!duplicateTime) {
      for (i = 0; i < 6; i++) {
        lastRandChars[i] = Math.floor(Math.random() * 28);
      }
    } else {
      for (i = 5; i >= 0 && lastRandChars[i] === 27; i--) {
        lastRandChars[i] = 0;
      }
      lastRandChars[i]++;
    }
    for (i = 0; i < 6; i++) {
      id += uid.charAt(lastRandChars[i]).toLowerCase();
    }

    // The id must be 16
    if (id.length != 16) throw new Error('Length should be 16.');

    return id;
  };
})();




Randomly Mixing An Array, But In A Calculated Way

I am trying to figure out a way to "randomly" mix a large array with more than 500,000 integers. I can currently randomly mix the array with:

let offset = Int(randomNumber(uni: pixelCount-1))
array.append(offset)
let pixel = rgba.pixels[index]
let newIndex = rgba.pixels.index(index, offsetBy: (offset-index), limitedBy: pixelCount)

But this is not really what I'm looking for since the mixed array will be different each time I create it. What I am looking for is a way to mix the array, but in a calculated manner that can be repeated so I can reverse the array back to its original state. Can anyone help?




jeudi 29 juin 2017

How can I randomly partition, by rows ,in two text file in Bash? Example 70% and 30%

imput:

5 a

5 b

5 c

4 d

6 t

1 f

7 h

5 i

6 j

5 k

output 1:

5 b

6 t

5 k

Output 2 contains the remaining values




GROUP BY / ORDER BY DESC,(rand)

i have a problem, i hope that somebody can help. In code i have:

"SELECT * FROM app_generator_cviky WHERE partie = '$transformnazvu' AND stupen <= '$urovenkonkretnihocviku' AND (pohlavi = 'Obě' OR pohlavi = '$pohlavir') GROUP BY zarazeni ORDER BY poradi DESC, RAND() LIMIT $limitcvikuvpartii " - but its dont random. I always get the first one in group .... the rest of this is running ok.Whats wrong?:-) thx a lot

the db look like: db look like




javascript random value between two variables? [duplicate]

This question already has an answer here:

I have this function here:

function example() {
    totalNum -=(Math.floor(Math.random() * valMax) + valMin);
}

valMin and valMax are 3 & 6 after being calculated, defined like this:

var valMin = Math.ceil((Math.round(other numbers and vars here));
var valMax = Math.ceil((Math.round(other different numbers and vars here));

but when using that function, i get higher max value up to 8. But min seems to work fine.

What am i doing wrong? appreciate some help, thanks!!




Latin Hypercube Sampling from the Normal Distribution in R

I've been trying to generate random values of collinear variables in R, such that the resulting sets of random variable values are characterized by properties that closely resemble the historical means, standard deviations, skews, and kurtoses of each these variables. I'm basing my approach on a particular method I found published online. This method employs

Distributions[,i] <- sort(rnorm(N, mu, sigma))

to generate random values of a reasonably normally-distributed variable given specified mean and standard deviation. I've found that specifying the mean and standard deviation alone do little to preserve the skews and kurtoses of the variables as distributed in reality (they most closely resemble the normal distribution than any other type of distribution). For this reason, I'm looking to rather than sampling randomly from the normal distribution, do so with Latin hypercube, so as to direct the sampling to take more random values from the tails of the distribution.

Any idea how to go about this in R? Please share. Thanks for your help.




With Python, how could I sample a randomly generated data-set to fit a theoretical distribution?

Here is a general example of what I did...

  1. Start with a physical model of y=m*x + b
  2. Generate uniform distributions of m, x, and b
  3. Created a theoretical distribution of y by specifying y_average and y_standard deviation

The next step is to sample from the data that I randomly generated in (step 2) to obtain the combinations of m, x, and b that fit my theoretical distribution that I created in (step 3).

Below is a picture showing what I would like to do... I have the top graph, and I have created the theoretical distribution line in the bottom graph... I want to create the "blue bars" in the bottom graph using the top graph and the theoretical distribution line

enter image description here




Java putting random symbols in my text file instead of integers

I have a program that is supposed to put a string and random integer into a text file. For some reason my program is putting a random symbol into the file instead of an integer. Anyone know why this is happening?

What the file currently looks like:

Test
賬
Test2
∗

What the file should look like:

Test
36076
Test2
74263

Class that gets the string and random number:

public void newList() {

    boolean newCode = false;

    while (!newCode) {

        System.out.println("NEW LIST");
        System.out.print("List Name: ");

        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        listName = scanner.next();

        System.out.println("The list name has been saved!");
        System.out.println();

        Random generateCode = new Random();
        setGeneratedCode(generateCode.nextInt((99999 - 10000) + 1) + 10000);

        File f = new File(generatedCode + ".txt");
        if (f.exists()) {
            newCode = false;
        }
        if (!f.exists()) {
            newCode = true;
        }
    }

    ListsWriter listsWriterObject = new ListsWriter();
    listsWriterObject.listsWriter(listName, generatedCode);
}

Class that writes the string and number to the file:

public void listsWriter(String listName, int generatedCode) {
    BufferedWriter bw = null;

    File lists = new File("lists.txt");

    try{
        FileWriter fw = new FileWriter(lists, true);
        bw = new BufferedWriter(fw);

        bw.write(listName);
        bw.newLine();
        bw.write(generatedCode);
        bw.newLine();
        bw.close();

    }catch(IOException ex){
            ex.printStackTrace();
    }


    FileCreator fileCreatorObject = new FileCreator();
    fileCreatorObject.fileCreator(generatedCode);
}




How to generate random numbers in R given a pointwise estimated conditional density?

Given random variables (X,Y) which are dependent, the fact that I know the distribution of X ~ N(0.05, 0.0057) and the given data from experiments ((x1, y1), ..., (x100,y100) I estimated a bandwidth and the conditional density f(Y|X=x) via kernel regression. I now want to generate samples of X using x_sample = rnorm(n, mean=0.05, sd=0.0057) and calculate the conditional density for that sample (meaning: f(Y|X=x_sample)). I evaluate the kernel regression on my datapoints (y1, ..., y100)to get a pointwise density for that given X=x_sample (via

f_hat = function(u, v){ (sum(K(abs(u-data$x)/H_n) * (K(abs(v-data$y)/h_n)))) / (h_n * sum(K(abs(u-data$x)/H_n))) }

with H_nand h_nbeing the bandwidths, data$x, data$ybeing my data and K(u)being the gaussian kernel).

See: Picture of the pointwise estimated density for a sampled X=x

and: Using npregbw and npreg to estimate the pointwise density into a still not continous nor integrable "density"

My Question now: How can I sample a big amount of y given X=x_sample? I need this data to afterwards estimate the distribution of Y.




Generating a Random Salt and use it in Bcrypt

Im trying to use the following code to make sure the same salt is being used in hashing:

<?php
        $binarySalt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
        $salt = substr(strtr(base64_encode($binarySalt), '+', '.'), 0, 22);
        $Password="test";
        echo nl2br ("Salt Value is: " . $salt . "\n");
        $cost=8; 
        $EncryptedEnteredPassword = password_hash($Password, PASSWORD_BCRYPT, ['cost' => $cost, 'salt' => $salt]);
        echo nl2br("Encrypted Form: " . $EncryptedEnteredPassword . "\n");
        ?>

The output I got is as follows:

> Salt Value is: aCEjf/TWi50TE..sOlDm8Q  
Encrypted Form: $2y$08$aCEjf/TWi50TE..sOlDm8O10DI8gD9PD3TlwmgdSBzaCQnQezAAFe

The wierd thing is that the salt's last character always doesn't match, i.e. the first output's line was: Instead of getting Q after 8, I got O, which left me with a completely diferent salt value.

Any ideas of how I could fix this?




standard deviation determination for normal distribution

I have 3 intervals :

I have 3 treshold values within the interval [0,1]: 0.05, 0.1 and 0.2. I would like to generate 50 random numbers around this tresholds. These are used later as input for my model. My aim is to generate deviations from the treshold values to see if the response changes.

For now i have used normal distribution to generate these 50 random values.

se.sw <- rnorm(50, 0.005, 0.005/3)
se.m <- rnorm(50, 0.1, 0.095/3)
se.st <- rnorm(50, 0.2, 0.1/3)

My questions are:

- Is there a sensible way to specify the distribution "proporional" to the range between the tresholds?




Wallpaperchanger python

I've been trying to randomize my wallpaper change with python by combining code from different sources. I managed to make this code:

import ctypes
import os
import random
drive = "C:/Users/UserName/Desktop/FolderofWallpaperFolders"
afolder = os.listdir(drive)
folder = drive+ "/" + random.choice(afolder)
aimage = os.listdir(folder)
image = random.choice(aimage)
image_path = os.path.join(drive, folder, image)
SPI_SETDESKWALLPAPER = 20 
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0,image_path, 3)

but when I run it it turns my wallpaper to a completely black screen. Any modification suggestions?




Python: How to check digits in a string against an array

I'm making something that creates 10 random numbers and outputs them as words. Here is my code so far:

import random as ran
nums = []
numarray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,30,40,50,60,70,80,90,'00','000','&']
wordarray = ["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety","hundred","thousand","and"]
for each in range(0,len(numarray)):
    print(numarray[each],"=",wordarray[each])
for each in range(0,10):
    num = ran.randint(0,9999)
    if num < 10:
        num = '000'+str(num)
    elif num < 100:
        num = '00'+str(num)
    elif num < 1000:
        num = '0'+str(num)
    else:
        num = str(num)
    nums.append(num)
print(nums)

I now need to check each digit of the ten random numbers against the arrays "numarray" and "wordarray" so that I can convert it into words. I was wondering would I do this. Could anyone help?

Happy Coding, A Doctor Who




random code generater for android application email verification

I am writing a new android application that require the user to register and provide email. I need to send email and give them a code for verification. I need to generate a 6-digit random code that consisting numbers with uppercase alphabet, for example, 6H94BA. I have done some research and cannot find anything. How to do that?




All numbers in a given range but random order

Let's say I want to generate all integers from 1-1000 in a random order. But...

  • No numbers are generated more then once
  • Without storing an Array, List... of all possible numbers
  • Without storing the already generated numbers.

I think that should be impossible but maybe I'm just not thinking about the right solution.

I would like to use it in C# but I'm more interested in the approche then the actual implementation.




How to properly seed a 64 bit random generator with time

I would like to generate 64 bit integers using the standard c++ std::mt19937_64 without manually seeding it. When defining the seed though, this question occurred to me: is there a proper way of seeding such a random generator using the current time (eg. producing a number based on the current time point, that is at least as big as a 64 bit int)? Something like counting milliseconds from the Unix epoch? Is there an easy way to achieve this?




mercredi 28 juin 2017

how to set random background for cardview in android?

i currently have a android recyclerview and a listitem for it. in the listitem is a cardview for my views. i want to have random backgrounds for each card list this one : http://ift.tt/2soQGIn
my cards now have a solid background and i search every where and used any code but couldn't find a example for view like example.

please help me guys. thx !!!

my list item :

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
    xmlns:android="http://ift.tt/nIICcg"
    xmlns:app="http://ift.tt/GEGVYd"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:id="@+id/card_view_lead"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:cardCornerRadius="10dp"
    app:cardPreventCornerOverlap="false">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/style_lead"
        android:padding="7dp">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="@android:color/transparent"
            android:contentDescription="@string/option"
            android:src="@drawable/ic_option"
            android:tint="@android:color/white" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/large_margin"
            android:orientation="vertical">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <com.makeramen.roundedimageview.RoundedImageView
                    android:id="@+id/lead_img"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:contentDescription="@string/test_pic"
                    app:riv_border_color="@color/colorPrimary"
                    app:riv_border_width="0.1dp"
                    app:riv_corner_radius="100dp"
                    tools:src="@drawable/pic_1" />

                <TextView
                    android:id="@+id/lead_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:layout_marginLeft="@dimen/standard_margin"
                    android:layout_toRightOf="@id/lead_img"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/large_font_size"
                    tools:text="@string/test_name" />

            </RelativeLayout>

            <TextView
                android:id="@+id/lead_city"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/standard_margin"
                android:layout_marginTop="16dp"
                android:textColor="@android:color/white"
                android:textSize="@dimen/large_font_size"
                tools:text="@string/test_city" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/standard_margin">

                <TextView
                    android:id="@+id/lead_price"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/large_font_size"
                    tools:text="30$" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/large_margin"
                    android:layout_marginTop="16dp"
                    android:layout_toRightOf="@id/lead_price"
                    android:text="@string/per_hour"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/large_font_size" />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_marginTop="16dp">

                <TextView
                    android:id="@+id/with"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/standard_margin"
                    android:text="@string/with"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/large_font_size" />

                <TextView
                    android:id="@+id/lead_vehicle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="6dp"
                    android:layout_toRightOf="@id/with"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/large_font_size"
                    tools:text="@string/car" />

                <ImageView
                    android:id="@+id/lead_vehicle_img"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="8dp"
                    android:layout_toRightOf="@id/lead_vehicle"
                    android:contentDescription="@string/car_img"
                    tools:src="@drawable/ic_car" />
            </RelativeLayout>
        </LinearLayout>
    </RelativeLayout>

</android.support.v7.widget.CardView>




Python, random assgin, attribute

I am writing a program that need to randomly assign the gender attribute (Male/Female) for a list of N objects.

In addition to this, the program also takes another input that is percentage. So, based on the percentage, the program will know how many percent of the N population will be assigned as Female attribute.

For example, I have N = 100 objects, and the percentage = 30% So the output would be 30% arbitrary objects (i.e: 30 objects chosen randomly) of N will be assigned as Female.

Could you help me suggest any algorithm or function, module, package in Python that can do that! Thank you very much




How to generate a random number at a random time with python/numpy?

In a 5 seconds period, I want to randomly generate a 0 to 1 number at a random time, then store the number and its time location. I am working on a real-time application system in which the ultimate goal is during a certain time period, random number of impulses are generated. Both its magnitudes and time locations should be recorded. Please help me with this one!




no randomly arranged images after reload

I arranged some pictures randomly above another image. When they were dropped, I print an alert and then I want to reload the page to start again. But in this case, the images are laying in one corner, overlapping completely. I tried to wait after my random-method. But nothing worked.

   $( 'img.box' ).each(function( index ) {
          $(this).css({
            left: Math.random() * ($('img.bod').width() - $(this).width()),
            top: Math.random() * ($('img.bod').height() - $(this).height())
          });
        });

and some lines to restart my page:

         window.confirm("Great you finished");
         window.location.reload(); 




Scala: Write Random Values to JSON and Save in File then Analyze in Spark

I would like to write ten (or a billion) events to JSON and save as files.

I am writing in a Databricks notebook in Scala. I want the JSON string to have randomly generated values for fields like "Carbs":

{"Username": "patient1", "Carbs": 92, "Bolus": 24, "Basal": 1.33, "Date": 2017-06-28, "Timestamp": 2017-06-28 21:59:...}

I successfully used the following to write the date to an Array() and then save as a JSON file.

val dateDF = spark.range(10)
  .withColumn("today", current_date())

But what is the best way to write random values to an Array and then save the Array as a JSON file?




How to randomly update a table?

How can I update a table by attributing random values? I wish to randomize the column isOnline

id | name   | isOnline

1 | johndoe | 1
2 | janedoe | 1
3 | marydoe | 0
4 | teendoe | 0
5 | babydow | 1

Query

UPDATE users
SET isOnline = rand(int)
WHERE isOnline='1' OR isOnline='0';




Generating a Random Salt and use it in Bcrypt

I am trying to generate a random salt to be used in hashing a password. I am a bit new to password hashing, but form what I understand, when using BCrypt algorithm, you will get as a result a 60 characters long hashed string.

22 characters Out of these 60 characters should the salt value, which is prepended to the resulting hash.

I used a simple code to make sure that the randomly generated salt is the same one that is going to be prepended to the actual hash:

$salt = substr(strtr(base64_encode(openssl_random_pseudo_bytes(22)), '+', '.'), 0, 22);
echo "Salt Value is: ".$salt . "\n";

The output was: Salt Value is: XKFB8DHMiXaYTzRAHtRhX7

Then I encrypted a password using the same generated salt as follows:

$cost = 8; 
$EncryptedPassword = password_hash($Password, PASSWORD_BCRYPT, ['cost' => $cost,'salt' => $salt]);
echo "Encrypted Password: " . $EncryptedPassword . "\n";

The output was not what I expected:

Encrypted format: $2y$10$XKFB8DHMiXaYTzRAHtRhXutlLLG8XIZjj5XGeyoUZobEtnkOn/M/S Where the resulting salt is not exactly the one I used for hashing, i.e. that last character of the salt value is always different.

The randomly generated salt is: XKFB8DHMiXaYTzRAHtRhX7

The resulting salt value is: XKFB8DHMiXaYTzRAHtRhXu

My question is what could be the problem, and how could I get the same randomly generated salt value embedded in the password hashed string without getting it changed?




Random generation algorithm in C++

Suppose you need to generate a random permutation of the first N integers. For example, {4, 3, 1, 5, 2} and {3, 1, 4, 2, 5} are legal permutations, but {5, 4, 1, 2, 1} is not, because one number (1) is duplicated and another (3) is missing. This routine is often used in simulation of algorithms. We assume the existence of a random number generator, RandInt(i,j), that generates between i and j with equal probability. Here are is the algorithm:

Fill the array A from A[0] to A[N-1] as follows: To fill A[i], generate random numbers until you get one that is not already in A[0], A[1],…, A[i-1].

Implement this algorithm in C++ and find the complexity. This is my code:

int a;
bool b = false;
A[0] = RandInt(1,n);
for (int i=1;i<n;i++) {
do {
  b = false;
  a = RandInt(1,n);
  for (int j=0;j<i;j++)
     if(A[j] == a)
        b = true;
} while(b);
A[i] = a;
}

Is this code correct? And how can I find the complexity of the algorithm? Since, RandInt(i,j) generates random numbers, I don't know how many times the do while loop will be repeated.




Keep random number for x amount of time

Right now I generate a random number every time a page is reloaded, I use that number to change the background image of my website.

Every page reload is a little too much, how would I only allow the number to change every x minutes?

Code in my header right now is really easy..

$randombg = rand(1,29);

echo '<style type="text/css">
<!--
#header-container{
background: url(images/header-bg' . $randombg . '.jpg) 50% 0;
}
-->
</style>';




Lucky Draw Concept : SQL Query to get random option based on percentage of appearance

I am developing a Lucky draw concept as following

There will be multiple options at database we have to get the random options according to percentage of appearance

Database table is as following

option_id |   option_name |  option_type | option_in_day(%) |  option_status
----------------------------------------------------------------------
1             $2 Off         2             100                 1
2             $3 Off         2             95                  1
3             $4 Off         2             95                  1
4             $5 Off         2             90                  1
5             $8 Off         2             90                  1
6             $60 Cashback   2             10                  1
7             $100 Cashback  2             5                   1
8             Umbrela        2             50                  1
9             Iphone         2             2                   1
10            International
              Tour           2             1                   1
11            Fidget 
              Spinner        2             70                  1
12            Free 
              membership     2             30                  1
13            Samsung S8     2             10                  1
14            $20 Off        2             60                  1
15            Travel Card    2             50                  1
16            Soft Toys      2             70                  1

Now from this table i want to get random 8 option according to percentage

less percentage option chance to retrieve in result will be less

i have tried with random function in sql but can't reach the requiremnt

can suggest an idea to overcome this.




display a1b2c3...z26 by creating 2 process and each process run seperatley with a random sleep of 1 to 5

display a1b2c3...z26 by creating 2 process and each process run seperatley with a random sleep of 1 to 5

is there any way to show off the process 1 has to wait for process 2 respectively p1 will generate abcdef... with sleep $[ ( $RANDOM % 5 ) + 1 ]s p2 will generate 12345..with sleep $[ ( $RANDOM % 5 ) + 1 ]s




mardi 27 juin 2017

Split data based on grouping column

I'm trying to work out how, in Azure ML (and therefore R solutions are acceptable), to randomly split data based on a column, such that all records with any given value in that column wind up in one side of the split or another. For example:

+------------+------+--------------------+------+
| Student ID | pass | some_other_feature | week |
+------------+------+--------------------+------+
|       1234 |    1 | Foo                |    1 |
|       5678 |    0 | Bar                |    1 |
|    9101112 |    1 | Quack              |    1 |
|   13141516 |    1 | Meep               |    1 |
|       1234 |    0 | Boop               |    2 |
|       5678 |    0 | Baa                |    2 |
|    9101112 |    0 | Bleat              |    2 |
|   13141516 |    1 | Maaaa              |    2 |
|       1234 |    0 | Foo                |    3 |
|       5678 |    0 | Bar                |    3 |
|    9101112 |    1 | Quack              |    3 |
|   13141516 |    1 | Meep               |    3 |
|       1234 |    1 | Boop               |    4 |
|       5678 |    1 | Baa                |    4 |
|    9101112 |    0 | Bleat              |    4 |
|   13141516 |    1 | Maaaa              |    4 |
+------------+------+--------------------+------+

Acceptable output from that if I chose, say, a 50/50 split and to be grouped based on the Student ID column would be two new datasets:

+------------+------+--------------------+------+
| Student ID | pass | some_other_feature | week |
+------------+------+--------------------+------+
|       1234 |    1 | Foo                |    1 |
|       1234 |    0 | Boop               |    2 |
|       1234 |    0 | Foo                |    3 |
|       1234 |    1 | Boop               |    4 |
|    9101112 |    1 | Quack              |    1 |
|    9101112 |    0 | Bleat              |    2 |
|    9101112 |    1 | Quack              |    3 |
|    9101112 |    0 | Bleat              |    4 |
+------------+------+--------------------+------+

and

+------------+------+--------------------+------+
| Student ID | pass | some_other_feature | week |
+------------+------+--------------------+------+
|       5678 |    0 | Bar                |    1 |
|       5678 |    0 | Baa                |    2 |
|       5678 |    0 | Bar                |    3 |
|       5678 |    1 | Baa                |    4 |
|   13141516 |    1 | Meep               |    1 |
|   13141516 |    1 | Maaaa              |    2 |
|   13141516 |    1 | Meep               |    3 |
|   13141516 |    1 | Maaaa              |    4 |
+------------+------+--------------------+------+

Now, from what I can tell this is basically the opposite of stratified split, where it would get a random sample with every student represented on both sides.

I would prefer an Azure ML function that did this, but I think that's unlikely so is there an R function or library that gives this kind of functionality? All I could find was questions about stratification which obviously don't help me much.




Max element search function doesn't work when the array is filled randomly and works fine when filled manually

I have an array and I have to find the largest element in it, tell how many times it is in and in what position. I have to use pointers and dynamic memory allocation.

This code works properly:

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

void max_elem (int n, float* vett) {

  int i=0, *pos, p=0, n_ele_pos;
  float max=*(vett);

  pos=(int*)malloc(sizeof(int));
  if (pos==NULL) {printf("BUM\n" ); exit (0);}
  *(pos)=0;
  for (i=1; i<n; i++) {
    if (*(vett+i)>max) {
      max=*(vett+i);
      p=0;
      *(pos)=i;
    }
    else  if (*(vett+i)==max) {
      p++;
      *(pos+p)=i;
    }
  }
  if (p==0) {
    printf("\nmax element is %f, in position %d  ", max, *pos+1);
  }
  else {
    printf("\n max element %f, %d times in position\n", max, p+1);
    for (i=0; i<p+1; i++) {
    printf("%d  ", *(pos+i)+1);
    }
  }
  printf("\n\n");
  free(pos);
}

int main()
{
    int i,n;
    float *element;
    printf("\n\n Pointer : Find the largest element using Dynamic Memory Allocation :\n");
    printf("-------------------------------------------------------------------------\n");
    printf(" Input total number of elements(1 to 100): ");
    scanf("%d",&n);
    element=(float*)calloc(n,sizeof(float));  // Memory is allocated for 'n' elements
    if(element==NULL)
    {
        printf(" No memory is allocated.");
        exit(0);
    }
    printf("\n");
    for(i=0;i<n;++i)
    {
       printf(" Number %d: ",i+1);
       scanf("%f",element+i);
    }

    max_elem (n, element);
    return 0;
}

but the next one doesn't. I have to fill the array with random numbers in a specific range decided by me, even from decimal to decimal extrems for integers random numbers (yes, I know it doesn't make much sense practically). Search when filled with decimal numbers works fine sometimes, with integers I would have just 0s.

Here the code:

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

float rand_float (float *, float *);
int rand_int (float *, float *);
void min_max(float *, float *, float *, float *);
int num_intero(float);
void max_elem (int, float*);

int main () {

  int n, i, t;
  float x1, x2;

  printf ("array size:\t");
  scanf ("%d", &n);
  printf("\ninterval extremes:\t");
  scanf ("%f %f", &x1, &x2);
  do {
    printf("1 for decimal random numbers, 2 for integers:\t");
    scanf("%d", &t);
  } while (t!=1 && t!=2);
  srand(time(NULL));
  switch (t) {

    case 1 :  {

      float *vett;

      vett=(float*)calloc(n, sizeof(float));
      if (vett==NULL) {printf("BUM\n" ); exit (0);}
      for (i=0;i<n;i++) {
        *(vett+i)=rand_float(&x1, &x2);
        printf("%d__\t%10f\n", i, *(vett+i));
      }
      max_elem (n, vett);
      free(vett);

      break;
    }
    case 2 :  {

      int *vett;

      vett=(int*)calloc(n, sizeof(int));
      if (vett==NULL) {printf("BUM\n" ); exit (0);}
      for (i=0; i<n; i++) {
        *(vett+i)=rand_int(&x1, &x2);
        printf("%d__\t%10d\n", i, *(vett+i));
      }
      max_elem (n, (float*)vett);
      free (vett);

      break;
    }
  }

  return 0;
}

void min_max (float*x1, float *x2, float *min, float *max) {

  if (*x1<*x2) {
    *min=*x1;
    *max=*x2;
  }
  else {
    *min=*x2;
    *max=*x1;
  }
}

float rand_float (float *x1, float *x2) {

  float min, max;

  min_max(x1, x2, &min, &max);
  return ((max-min)*(float)rand()/RAND_MAX)+min;
}

int num_intero (float min) {

  if (min/(int)min==1)
    return 1; //e' intero
  else return 0;
}

int rand_int (float *x1, float *x2) {

  float min, max;

  min_max(x1, x2, &min, &max);
  if ((int)min==(int)max) {
    return (int)min;
  }
  else  if (min==0) {
          return (rand()%((int)(max)+1));
        }
        else  if (max==0) {
                return (rand()%((int)(-min)+1)+min);  //funziona anche con ((int)(min)-1)+min
              }
              else if ((int)min!=(int)max) {
                      if (num_intero (min)==1) {
                        return (rand()%((int)(max-min)+1)+min);
                      }
                      else  if (num_intero (max)==0) {
                              return (rand()%((int)(max-min))+min+1);
                            }
                            else return (rand()%((int)(max-min)+1)+min+1);
              }
}

void max_elem (int n, float* vett) {

  int i=0, *pos, p=0, n_ele_pos;
  float max=*(vett);

  pos=(int*)malloc(sizeof(int));
  if (pos==NULL) {printf("BUM\n" ); exit (0);}
  *(pos)=0;
  for (i=1; i<n; i++) {
    if (*(vett+i)>max) {
      max=*(vett+i);
      p=0;
      *(pos)=i;
    }
    else  if (*(vett+i)==max) {
      p++;
      *(pos+p)=i;
    }
  }
  if (p==0) {
    printf("\nmax element is %f, in position %d  ", max, *pos+1);
  }
  else {
    printf("\n max element %f, %d times in position\n", max, p+1);
    for (i=0; i<p+1; i++) {
    printf("%d  ", *(pos+i)+1);
    }
  }
  printf("\n\n");
  free(pos);
}

In addition, when the array is big I have runtime error like this, that I don't have with the first code: error

Example: first code, second code and integers error(bottom)

I'm on Ubuntu 16.04 (gnome) with gcc and atom editor. Thanks and sorry.




Boost Random Generators returning identical values

Looking for a boost random expert... I need to generate random numbers in between many, many different ranges. I've written the below functions:

boost:mt19937 m_oRng;

int generateIntVariate(int p_iMin, int p_iMax){
  boost::uniform_int<> min_to_max(p_iMin, p_iMax);
  boost::variate_generator< boost::mt19937, boost::uniform_int<> > oGen(m_oRng, min_to_max);
  return oGen();
}

float generateFloatVariate(int p_fMin, p_fMax){
  boost::uniform_real<> min_to_max(p_fMin, p_fMax);
  boost::variate_generator< boost::mt19937, boost::uniform_real<> > oGen(m_oRng, min_to_max);
  return oGen();
}

The problem is that both functions return the same exact number for a given range, every time it's executed.

(gdb) p generateIntVariation(0, 10)
$40 = 8
(gdb) p generateIntVariation(0, 10)
$41 = 8
(gdb) p generateIntVariation(0, 10)
$42 = 8
(gdb) p generateIntVariation(0, 10)
$43 = 8

The same thing as above happens with the float function. Is there any way I can accomplish what I'm trying to do using the boost random distros?




Why does this total not amount to 1000?

When I run the program below, the total is not 1000. I have no idea what is wrong.

In 1000 tosses of a dice, there were:

  • 180 for 1
  • 136 for 2
  • 121 for 3
  • 97 for 4
  • 72 for 5
  • 60 for 6.

This totals to 666 rolls of the dice.

I am trying to be specific, if there is anything I am not clear about, please let me know. And thanks everyone:)

#this is a program that simulate how many times that there will be for every sides of a dice, when I trying to throw it 1,000 times.

from random import randrange

def toss():
    if randrange(6) == 0:
        return "1"
    elif randrange(6) ==1:
        return "2"
    elif randrange(6) ==2:
        return "3"
    elif randrange(6) ==3:
        return "4"
    elif randrange(6) ==4:
        return "5"
    elif randrange(6) ==5:
        return "6"

def roll_dice(n):
    count1 = 0
    count2 = 0
    count3 = 0
    count4 = 0
    count5 = 0
    count6 = 0
    for i in range(n):
        dice = toss()
        if dice == "1":
            count1 = count1 + 1
        if dice == "2":
            count2 = count2 + 1
        if dice == "3":
            count3 = count3 + 1
        if dice =="4":
            count4 = count4 + 1
        if dice == "5":
            count5 = count5 + 1
        if dice == "6":
            count6 = count6 + 1
    print ("In", n, "tosses of a dice, there were", count1, "for 1 and", 

count2, "for 2 and", count3, "for 3 and", count4, "for 4 and", count5, "for
 5 and",count6, "for 6.")

roll_dice(1000)




While loop conditioned on whether a vector contains another vector

Let's say I have 3 classes, a,b, and c in that I want to be distributed in a 3:2:1 ratio, respectively. A vector containing a minimally 'balanced' set of these classes in this ratio would look something like this:

class_1<-"a"
class_2<-"b"
class_3<-"c"

ratio_a<-3
ratio_b<-2
ratio_c<-1
min_set<-c(rep(class_1,ratio_a),rep(class_2,ratio_b),rep(class_3,ratio_c))

This minimum set would look something like this:

min_set
"a""a""a""b""b""c"

If I were to make a df containing all permutations of min_set as such:

    library(combinat)
library(data.table) 
myList <- permn(min_set)
all_out <- data.table(matrix(unlist(myList),byrow = T,ncol = 6))

and then create a matrix containing my three classes, called block_1:

lamb<-10

block_1<-matrix(0,lamb,length(min_set))
for (i in 1:lamb){
  block_1[i,]<-min_set
}

and then randomly sample from block_1, storing the results in a vector, block_2:

block_2<-vector('numeric',length=dim(block_1)[1]*dim(block_1)[2])

How could I create a while loop that stops once I have the min_set in block_2?

I've tried something like this, but I can't get it to work:

for (i in 1:(dim(block_1)[1]*dim(block_1)[2])){
  while (min_set %in% block_2=F){ 
#while block_2 does not contain the min_set
    block_2[i]<-sample(as.vector(block_1),i,replace=F)
   }
}

I was thinking of using all_out (all permutations of min_set) as part of a solution, as well.




How to generate samples for different uniform distributions given first-two moment matrix

Consider a concrete example, I have three different uniform distributions, i.e., x~U(-40,20),y~(-20,40),z~(-20,20). So I can calculate E[x+], E[x-], E[y+],E[y-],E[z+],E[z-], where x+ denotes max{0,x}, x- denotes min{0,x}.

Based on the uniform distribution, the moment matrix is calculated by E[(x+,x-,y+,y-,z+,z-)^T(x+,x-,y+,y-,z+,z-)]. At the same time, I restrict E[x+x-]=0 in the moment matrix. For simplicity, assume x,y,z are i.i.d

My question is how to randomly generate samples (x+,x-,y+,y-,z+,z-) under my setting given the first-two moment in matlab or R? I have searched a lot and found no method existed to solve the problem I am facing.

Appreciate for all of your help or suggestion on this look-simple question.

Relevant link for generate multivariate uniform distribution is referred to : http://ift.tt/2tg6Uru But it cannot solve my problem because it only considers all variates following the same specific uniform distribution.




design a random(5) using random(7)

Given a random number generator random(7) which can generate number 1,2,3,4,5,6,7 in equal probability(i.e., the probability of each number occurs is 1/7). Now we want to design a random(5) which can generate 1,2,3,4,5 in equal probability(1/5).

There is one way: every time we run random(7), only return when it generates 1-5. If it is 6 or 7, run again until it is 1-5.

I am a little confused. The first question is:

How to proof the probability of each number occurs is 1/5 in mathematical way? For example, assume probability of returned number 1 is P(1). If B means 'the selected number is in 1-5' and A means 'select 1', then according to conditional probability, P(1) = P(A|B) = P(AB) / P(B). Obviously P(B) is 5/7. But if P(1)=1/5, P(AB) should be 1/7, why? I think P(A)=1/7. Is there anywhere wrong?

The second question is, this method will run until random(7) not return 6 or 7. What if it runs for a long time not returning 1-5? I know the chance is very very small but is there any way to prevent it?

Thanks!




How to generate a variable length random number in Go

I'm trying to generate a random integer with variable length in Go but I always get the number filling the total length. Here's my code:

package main

import (
    "fmt"
    "math/big"
    "crypto/rand"
)

const ResultsPerPage = 30

var (
        total = new(big.Int).SetBytes([]byte{
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
                0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40,
        })
        pages = new(big.Int).Div(total, big.NewInt(ResultsPerPage))
        random *big.Int
        err error
)

func main() {

fmt.Println(pages)
fmt.Println(randomString(pages))
}

func randomString(l *big.Int) string {
  random, err = rand.Int(rand.Reader, l)
  fmtrandom := fmt.Sprint(random)
  return string(fmtrandom)
}

Outputs

3859736307910539847452366166956263595094585475969163479420172104717272049811
3479662380009045046388212253547512051795238437604387552617121977169155584415

Code sample: http://ift.tt/2tfuB3p

Any help is appreciated. Thank you.




lundi 26 juin 2017

Programming a randomization scheme, while loops

I'm trying to simulate a randomization process. I think I'll have to use a while loop, and I'm unfamiliar with how to best structure what I'm trying to accomplish in my R code.

Let's say I have 3 classes, a,b, and c in that I want to be distributed in a 3:2:1 ratio, respectively. A vector containing a minimally 'balanced' set of these classes in this ratio would look something like this:

class_1<-"a"
class_2<-"b"
class_3<-"c"

ratio_a<-3
ratio_b<-2
ratio_c<-1
min_set<-c(rep(class_1,ratio_a),rep(class_2,ratio_b),rep(class_3,ratio_c))

This minimum set would look something like this:

min_set
"a""a""a""b""b""c"

Let's then say I want to have 'k' number of this minimally balanced set, I could create that like this:

block_1<-matrix(0,k,length(min_set))
for (i in 1:k){
block_1[i,]<-min_set
}

This would create a new matrix with my min_setvector for k rows.

Let's now say I want to sample from block_1 without replacement (a treatment allocation would be determined by the class (a,b,c) of the sample) This can be done as:

sample(as.vector(block_1),n,replace=F)

However, here is where I'd like some programming help. I'd like to sample from block_1 without replacement until I have sampled the min_set, i.e."a""a""a""b""b""c". I'd like to store these samples from block_1 in some new, empty vector, called block_2.

At this point, I'd like to 'return' the samples which fulfill the min_set back to block_1, and keep all of my discordant samples (those which exceed the min_set ratio) in block_2. I'd like to repeat this process of collecting samples in block_2 until a min_set is achieved, keeping the discordant samples, and returning the samples which achieve the min_set back to block_1 until I have reached some pre-specified number of treatment allocations.

I hope my question is clear, and that the code I provided can be used as a reproducible sample.

Thanks




C# Generation Random Number using r.next(x,y), inside a for loop

Iam trying to generate phi a random number Normal(0,1).However, inside the J loop as I could check (output) r.next(0,10) do not generate a random from o to 10 every J loop. It repeats the same value inside the (FOR J).How can I generate 12 different random (0,10)?and why it does not generate every turn?

// random number generator phi
double phi = 0.0;
double rand = 0;
double rand1 = 0.0;

for (int j = 0; j <= 12; j++)
{
    Random r = new Random();
    rand = (r.Next(0, 10));
    rand1 = rand1 + (Convert.ToDouble(rand) / 10.0);
    Console.WriteLine("j  : {0}, rand {1}, rand1 {2} and 'i' {3} ", j,rand,rand1,i);

}
phi = (rand1 - 6.0);  




Greater than and Less than not working correctly with random number in Python [duplicate]

This question already has an answer here:

I am working on a project that involves random numbers and them being greater or less than another number.

from random import randint number = (randint(0, 100)) guess = raw_input("Guess: ") print number if (guess > number): print str(guess) + " is greater than "+ str(number)

This code was created to help me debug my problem, but nothing worked. No matter what I put in as the variable "guess," it would always say that it was larger than the random number.

For example:
Guess: 0
27
0 is greater than 27.

Is this a problem with my code or with the random numbers? Thanks in advance!




Any algorithm that use a number as a feed for generating random string?

I want to generate a random string with any fixed length (N) of my choice. With the same number as a feed to this algorithm it should generate the same string. (But more than one number might results in the same string) Any approaches for doing this?

(By the way, I have a set of characters that I want to appear in the string, like A-Z a-z 0-9)

I could random each characters one by one, but it would need N different seed for each characters. If I want to do it this way, the question might become "how to generate N numbers from one number" for the seeds.

The end goal is that I want to convert a GUID to something more readable on printed media and shorter. I don't care about conflict. (If the conflict did happen, I can still check the GUID for resolution)




JAVA - How do I generate a random number that is weighted towards certain numbers?

How do I generate a random number in Java, (using Eclipse) that is weighted towards certain numbers?

Example, I have 100 numbers, each can be equally chosen 1% of the time. However, if a certain number, lets say 5, is displayed 8 times in that 100, it now has an 8% chance to be randomly selected, while the other numbers are still at 1%.

How can I write a random generator that gives me 10 numbers and gives the number 5 that 8% advantage to show up?

Thanks and sorry if I did not explain that well.




JavaScript random function returns NaN

I am trying to make a simple inclusive random function, but for some reason it gives me NaN. I copied this function from Mozilla reference. Thanks.

var size = {min:1, max: 1700}; 

function getRndInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}

function generate() {  
document.getElementById("Text1").innerHTML = getRndInt(size.min - size.max);
}




Random data search elasticsearch

Am using elasticsearch , is it possible to generate random query search on elasticsearch ,instead of date ranges

like if I have 50000 doucments in 15 mins, I need only 1000 documents in same 15 mins,kind of random datas.

Any help would be really helpful :)

Thanks, Raj




"Random" numbers are always increasing and not very random

I am using the below code to generate five random numbers between 1 and 20. However, the values chosen are always ascending and do not appear random. I'd also like to increase the entropy across the function being called multiple times. For example, the number 2 appears nearly every time per method call. How can I improve the randomness?

// Gets called multiple times
void x(){

    std::random_device rd;
    std::mt19937 generator(rd());
    std::uniform_int_distribution<int> dist2(1, 20);

    for(int i = 0; i < 5; ++i)
    {
        int y = dist2(generator);
    }
}




determining standard deviation of normal distribution

My model can only have values between 0 and 1. There are 3 tresholds within the interval [0,1], namely:

  • 0.07 - low
  • 0.65 - middle
  • 0.95 - high

I would like to create 50 random values that are distributed normaly around each treshold. I know that for this the function rnorm() can be used. However I do not know the variance (there is no data that can be used to estimate it). I would like the variance to be proportional to the interval in between the values - 0.58 between low and middle, 0.30 between middle and high. For now i have done this:

se.sw <- rnorm(50, 0.07, 0.07/3)
se.m <- rnorm(50, 0.65, 0.58/3)
se.st <- rnorm(50, 0.95, 0.30/3)

I have chosen 3 with no specific reason. I am aware that the values may overlap - for example that value from middle is higher than value from high. that is OK, as long as it is not too much overlay. Ideally it would be around 10%.

What would be a sensible way to achieve this?

Thank you.




random tree by sql query or c#

I have a tree table in sql:

[Id]        INT          IDENTITY (1, 1) NOT NULL,
[Title]     VARCHAR (50) NOT NULL,
[ParentId]  INT          NULL,
[Level]    INT          NOT NULL.

I need to fill it with lots of random data rows. The depth of the tree must be at least 4. The tree must have arbitrary number of children. I need to make it with a help of console application or sql query.




dimanche 25 juin 2017

Can XorShift return zero?

I've been reading about the XorShift PRNG especially the paper here

A guy here states that

The number lies in the range [1, 2**64). Note that it will NEVER be 0.

Looking at the code that makes sense:

uint64_t x;
uint64_t next(void) {
   x ^= x >> 12; // a
   x ^= x << 25; // b
   x ^= x >> 27; // c
   return x * UINT64_C(2685821657736338717);
}

If x would be zero than every next number would be zero too. But wouldn't that make it less useful? The usual use-pattern would be something like min + rand() % (max - min) or converting the 64 bits to 32 bits if you only need an int. But if 0 is never returned than that might be a serious problem. Also the bits are not 0 or 1 with the same probability as obviously 0 is missing so zeroes or slightly less likely. I even can't find any mention of that on Wikipedia so am I missing something?

So what is a good/appropriate way to generate random, equally distributed numbers from XorShift64* in a given range?




Create music player random play in C#

currently i created a simple music player by using UWP, but I don't know how to add a random play function to play local music in Assets folder, can you help me, thank you very much




How to update and set random values in MySQL? [duplicate]

Is there a query to attribute random values to a column?

Take this table users for instance:

id | name |

With current values:

1 | user3456
2 | user0934
3 | user4356
...

Is there a way I can randomly attribute DIFFERENT names to all rows that start with user?

UPDATE users
SET name = papadoe, mamadoe, babydoe
WHERE name like "user%"; 




Is there a cryptographically secure alternative to arc4random on iOS?

I'd like to use a PRNG like arc4random_uniform(); however, Wikipedia seems to think that rc4 is insecure. I don't have the wherewithal to confirm myself, but security is a requirement for my use-case.




Sampling big amount of data frames, write directly onto harddrive

Referring to a question I asked earlier, I want to sample a big heap of data frames which would exceed the working memory of my machine (16GB). To circumvent working memory I've heard about the possibility to directly write onto the hard drive, but I have not the faintest idea how I could do this in R.

I give this as an example:

## !!CAUTION: THIS CODE COULD CRASH YOUR MACHINE!!

## Number of random data frames to create:
n <- 1e5

## Sample vector of seeds:
initSeed <- 1234
set.seed(initSeed)
seedVec <- sample.int(n = 1e8, size = n, replace = FALSE)

## loop:
lst <- lapply(1:n, function(i){
  set.seed(seedVec[i])
  a <- rnorm(5e4, .9, .05)
  b <- sample(8:200, 5e4, replace = TRUE)
  c <- rnorm(5e4, 80, 30)
  d <- c^2
  e <- sample(0:1, prob= c(1 - .33, .33), replace = TRUE)
  f <- sample(0:1, prob= c(.33, 1 -  .33), replace = TRUE)
  data.frame(a, b, c, d, e, f)
})




RevitPythonShell random module acting weird?

I am using the RevitPythonShell and after a frustratingly long search for a bug in my code, I found that the problem was due to the random module acting weird. Almost all the functions in the random module seem to leave half of the possibilities untouched.

random.sample is only sampling the first half of the list. random.uniform is generating numbers less than the average of the two bounds. random.random() is only generating numbers between 0 and 0.5.

Below code is form the revitpythonshell terminal. Can anyone help me understand what is going on ?

>>> import random
>>> #random number in the range [0.0, 1.0)
>>> for _ in range(1000):
...     if random.random() >= 0.5: print("hello !!")
... 
>>> # nothing got printed !!!
>>> max = 0
>>> for _ in range(1000):
...     rand = random.random()
...     if rand > max: max = rand
... 
>>> max
0.499520565070528
>>> # looks like the random values are being capped at 0.5 !!
>>> 
>>> nums = list(range(10))
>>> for _ in range(1000): 
...     if random.sample(nums, 1)[0] >= 5: print("hello")
... 
>>> # nothing got printed !!
>>> # half of the range of possibilities goes untouched for some reason
>>> a = 3.5
>>> b = 4.75
>>> half = (a+b)/2
>>> for _ in range(1000):
...     if random.uniform(a,b) > half: print("Hello !!!")
... 
>>> # nothing got printed !! all the values are less than half !!!
>>> #looks like all the functions of the random module have this behavior
>>> 




How to display random images every 5 seconds in swift?

I want to make an app which shows random pictures full screen. So let's say I have 3 images, apple.png, samsung.png and google.png. When the app loads, it shows any of this pics. And every 5 seconds the current pic fades out and the new random image appears with same effect. Also, while the picture is on the screen, I may click on it and it will redirect me to that web page. Let's say current image is google, I click on it and it opens a browser www.google.com

I am very new to this and I am sorry that I can't provide you even a little bit of code. I would appreciate any help that you could provide!(links, code, explanation)

I did found some tutorials, but they show how to make a slide view. I do not want to be able to slide them, I just want them to fade in and out while randomly showing the pics that I have in assets.xassets

One more time, thank you very much in advance!




ABS ( CHECKSUM ( NEWID () ) ) % 4 generates unexpected values

the following transact-sql code works properly. it fills up the table with four integers ( 0, 1, 2, 3 ) as expected.

CREATE TABLE [TBL_INTEGER] (
    [ID] INTEGER IDENTITY ( 1, 1 ) PRIMARY KEY,
    [NUMBER] INTEGER NOT NULL
)

DECLARE @MAX INTEGER
SELECT @MAX = 1000

WHILE ( 0 < @MAX ) BEGIN
    INSERT [TBL_INTEGER] ( [NUMBER] ) SELECT ABS ( CHECKSUM ( NEWID () ) ) % 4
    SELECT @MAX = @MAX - 1
END

and the following code does not. it fails generating the 'Cannot insert the value NULL into column 'NUMBER' error.

CREATE TABLE [TBL_INTEGER] (
    [ID] INTEGER IDENTITY ( 1, 1 ) PRIMARY KEY,
    [NUMBER] INTEGER NOT NULL
)

DECLARE @MAX INTEGER
SELECT @MAX = 1000

WHILE ( 0 < @MAX ) BEGIN
    INSERT [TBL_INTEGER] ( [NUMBER] )
        SELECT
            CASE ABS ( CHECKSUM ( NEWID () ) ) % 4
                WHEN 0 THEN 0
                WHEN 1 THEN 1
                WHEN 2 THEN 2
                WHEN 3 THEN 3
            END
    SELECT @MAX = @MAX - 1
END

if i add

ELSE 99

the code does not fail. but one third of the inserted rows contain the value 99.

is there an explanation ?

thank you in advance !

av




rand() in C with modulo never triggering

I'm trying to implement a real-world simulation involving synchronization, and when I have an event that has an 80% chance of occurring, I'm currently doing

  while((rand()%10)<8){
    up(sCar);
    printf("SOUTH: new car\n");
  }

However, the while loop is never triggering while ran, so I'm not sure if I'm using rand() properly. If I replace the rand() with 7, when it works properly. I currently set

  srand (time(NULL));

earlier in my program as well. Any help would be much appreciated.

EDIT: Here is the full running program. I have modified sys.c to create the system calls for up and down, which act as Semaphores.

#include <linux/unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <time.h>

struct cs1550_sem{
    int value;
    struct listnode *start;
    struct listnode *finish;
};

void up(struct cs1550_sem *sem) {
  syscall(__NR_cs1550_up, sem);
}

void down(struct cs1550_sem *sem) {
  syscall(__NR_cs1550_down, sem);
}

int main(void){

  srand (time(NULL));
  void * ptr = mmap(NULL, sizeof(struct cs1550_sem)*3, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, 0, 0);

  struct cs1550_sem *nCar = ((struct cs1550_sem *)ptr);
  struct cs1550_sem *sCar = ((struct cs1550_sem *)ptr) + 1;
  struct cs1550_sem *mutex = ((struct cs1550_sem *)ptr) + 2;
  struct cs1550_sem *flag = ((struct cs1550_sem *)ptr) + 3;

  void * northRoad = mmap(NULL, sizeof(int)*(10+1), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
  void * southRoad = mmap(NULL, sizeof(int)*(10+1), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, 0, 0);

  nCar->value  = 0;
  nCar->start= NULL;
  nCar->finish    = NULL;

  sCar->value  = 0;
  sCar->start= NULL;
  sCar->finish  = NULL;

  flag->value  = 0;
  flag->start= NULL;
  flag->finish    = NULL;

  mutex->value  = 1;
  mutex->start= NULL;
  mutex->finish  = NULL;


  if(fork()==0){
    while(1){
      while((rand()%10)<8){
        up(nCar);
        printf("NORTH: new car\n");
      }
      printf("NORTH: no more cars, sleeping for 20 seconds\n");
      sleep(20);
    }
  }
  else if(fork()==0){
    while(1){
      while((rand()%10)<8){
        up(sCar);
        printf("SOUTH: new car\n");
      }
      printf("SOUTH: no more cars, sleeping for 20 seconds\n");
      sleep(20);
    }
  }
  else if(fork()==0){ 
    while(1){
      down(nCar);
      down(mutex); 
      printf("NORTH car allowed through\n");
      up(mutex);
    }
  }
  else{
    while(1){
      down(sCar);
      down(mutex);
      printf("SOUTH car allowed through\n");
      up(mutex);
    }
  }
  return 0;
}




Add daily data/density functions over year in R

I have drawn random samples of heating load for each day. So basically I have a density function of heating load for each day and want to add them to receive th yearly density.

Any idea how to do it?

Thanks!




Drawing samples from different rnorm

this might be somewhat tricky, or at least for me it is...

I have to vectors, one with daily means over a year and one with the associated std. deviations. I want to draw n=1000 samples from each of these normal distributions and save them in a vector. To be more specific....

means vector=(1,2,3,...., 365) sd vector=(1,2,3,.....,365)

Note, that these are examples of the values that indicate that I have 365 different values.

rnorm(n=1000, mean=1, sd=1) which uses the vectors as inputs.

Any idea how to code this?




c/c++ - random number between 0 and 1 without using rand() [duplicate]

This question already has an answer here:

I am trying to generate a (pseudo) random number between 0 and 1 without using any functions like rand() or srand(). I found some answers here but none fit my problem.

I was thinking about something like

  • declaring a variable and getting a pointer to that variable
  • add a number to the pointer to get another pointer to a unknown memory address (I know it is bad practise)
  • doing some modulo operations and some bit shifting on the new variable I would like it to be as distributed as possible

thanks!




Taking a Sequence To Generate a valid input for that sequence

So Here is What i am trying to make first if possible a way to get an if statement from a file and then look at what would be an input that would be true and generate that valid input here is what i have come up with so far this is the test file first A.K.A Test.sh oh btw a Valid input example is 1file and then the other number/letters are just optional

input=
if [[ $input = [0-9]@(|[0-9]@(|[0-9]))File@(|[0-9]@(|[0-9]@(|[0-9]@(|[a-z]@(|[a-z]@(|[a-z])))))) ]]; then
echo "Good"
  else
echo "Bad"
fi

Then what the actual code What i will call the input generator so currently what is does is it counts how many numbers there are or could be in the sequence however from there I don't know what i should do to make this actually generate a valid input now i don't need it to read a the test file I'm fine with it being in the same file as the test with the sequence

file=test.sh
N="\[0-9]"
Al='\[a-z]'
Au='\[A-Z]'
ifstat=$(grep -w if $file)
amn=$(echo "$ifstat" | grep -o "$N" | wc -l)
echo "$amn"

so in summary i want it a generator to make a random input for that if statement that would be "Good"




samedi 24 juin 2017

JavaScript Help, Image Generation with Canvas and MediaRecorder

Hi i will Generate a Noisy Image with Canvas from a Audiostream in JavaScript. I have this Working Code that Generates a Random Noise Image.

function jscreen() {
   setTimeout(fixInline, 60);
   _gaq.push(['_trackEvent', 'jscreen']);
   repositionComponents();
}

function repositionComponents() {

   var position = $("#canvasFrame").position();
   var horizontalMid = window.innerWidth / 2;
   var verticalMid = window.innerHeight / 2;
}

function fixInline() {
   repositionComponents();
   updateTimer = setInterval(drawInline, 5);
}

function drawInline() {
   draw(document.getElementById("canvas"));
}

function draw(cvs) {

   var ctx = cvs.getContext("2d");

   var blockSize = 256;
   var imageData = ctx.createImageData(blockSize, blockSize);
   for (var i = 0; i < blockSize * blockSize; i++) {
      var p = i * 4;
      imageData.data[p + 0] = Math.random() >= 0.5 ? 255 : 0;
      imageData.data[p + 1] = Math.random() >= 0.5 ? 255 : 0;
      imageData.data[p + 2] = Math.random() >= 0.5 ? 255 : 0;
      imageData.data[p + 3] = 255;
   }

   for (var y = 0; y < cvs.height; y += blockSize) {
      for (var x = 0; x < cvs.width; x += blockSize) {
         ctx.putImageData(imageData, x, y);
      }
   }
}

Now I will get the Audiostream from a Mikrophone and Generate the Image from this. Maybe replace the Math.Random or Image Data I don't know. The Audio should not be recorded to a File just put the stream to the canvas. I have this Recording Code.

navigator.mediaDevices.getUserMedia({audio:true})
.then(stream => {
    rec = new MediaRecorder(stream);
    rec.ondataavailable = e => {
        audioChunks.push(e.data);
        rec.start();
    }
})

How can I do this ?




Need a TAN generator in source (Java, Javascript, PHP, Coldfusion, Delphi)

I am looking for someone who uses his/her high maths expertise to create an algorithm to deliver pseudo-random TAN codes. The algorithm starts off with a seed and is able to generate any n-th code. Repeatedly retrieving a code for the same position returns the same value. Repetition of the same value at different position: not before 10^12 values or better.

It is able to generate the next code based on the last one or on the position/index provided as input. The code itself is a string consisting of a set of chars.

The algorithm is able to check a given code if it is a valid code of the sequence created by seed.

The algorithm is able to save and restore its state (serializable). It does not precalculate a list of keys. Repetition of codes is ok,

Some terms:

  • Position: whatever needed to indicate the n-th code in the sequence. Integer, structure, whatever is needed.
  • Alphabet, a set of one or many of those:
  • Lower: all lower case chars a-z
  • Upper, all upper case char A-Z
  • Digits, 0-9
  • Special, non-alfanum chars
  • Safe, eliminates dangerous chars like ilIO0S5

I could imagine something like this in pseudo-code:

Class TANgen.

Constructor (seed, alphabet, codelength) // this initializes the algorithm to be able to start. It shuld assume that we will retrieve one code after another, so the class memorizes how many codes have already been generated.

string function get ()
string function get (position)
// get the next code or the code at position.

string function get_next (position)
string function get_next (code)
// both functions get the next code, following the one given either by a position or a code

string[] function get (position, count)
string[] function get (code, count)
// get count codes starting with the one given by either a position or a code

position function validate (code)
// checks the code and returns its position or null if not valid

boolean function validate (code, position)
// wrapper for validate() != null

position function validate (code, position, windowsize)
// returns the position of a code if found at position, where position is the middle position of a sliding window. So like code in (code[position-windowsize],…,code[position-1],code[position],code[position+1],…,code[position+windowsize])


function save()

function load()

Maybe someone has already done that or knows where I can start off.

Any help or pointers to source is highly appreciated.

Thank you.




Time complexity for recursive function with random input

I'm a beginner in C programming so i need some help for my time complexity function.

int function(int n)
{ if (n <= 1)
    return n;
int i = random(n-1);
return test(i) + test(n - 1 - i);
}

I don't know how to deal with this problem because of the random function which have O(1) complexity which return randomly numbers.




Why function random return repeat only a number?

I use function Math.floor(Math.random() * 28) + 1; random a number. I have create a variable for it below:


 var number = Math.floor(Math.random() * 28) + 1;
 => number //--> repeat only a number 

Please help me explain reason above. Thanks !!




vendredi 23 juin 2017

In python, is there has another way could be recommend for randomly creating a random list with specified boundary?

So far, I use following codes for generating a random list with specified boundary:

def initGen(low,upp):
    ini=[]
    for i in range(len(low)):
        ini.append(random.uniform(low[i],upp[i]))

return ini

May somebody suggest a more compact or alternative way to achieve it? Many thanks in advance!!!




Spliting an array into train and test sets with python

I tried a method to split data between train and test sets, but it seems that it fill the train with zeros and leave the data in test...

In theory, it works :

When I apply the following function which randomly selects some columns of the given array, it worked with the DataLens with numpy matrix but not with others.

def train_test_split(array):
    test = np.zeros(array.shape)
    train = array.copy()
    for user in xrange(array.shape[0]):
        test_ratings = np.random.choice(array[user, :].nonzero()[0], 
                                        size=10, 
                                        replace=False)
        train[user, test_ratings] = 0.
        test[user, test_ratings] = ratings[user, test_ratings]

    # Test and training are truly disjoint
    assert(np.all((train * test) == 0)) 
    return train, test

train, test = train_test_split(ratings)

With simple data it doesn't work :

When using simple data :

ratings :
[[ 1.  1.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 1.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  1.]]

It fill the array with 0 one by one even if train was a copy of ratings at the very beginning :

train :  
 [[ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]]




How to get random documents from Elasticsearch indexes with 50 million documents each

I'd like to sample 2000 random documents from approximately 60 ES indexes holding about 50 million documents each, for a total of about 3 billion documents overall. I've tried doing the following on the Kibana Dev Tools page:

GET some_index_abc_*/_search
{
  ""size": 2000,
  "query": {
    "function_score": {
      "query": {
        "match_phrase": {
          "field_a": "some phrase"
        }
      },
      "random_score": {}
    }
  }
}

But this query never returns. Upon refreshing the Dev Tools page, I get a page that tells me that the ES cluster status is red (doesn't seem to be a coincidence - I've tried several times). Other queries (counts, simple match_all queries) without the random function work fine. I've read that function score queries tend to be slow, but using a random function score is the only method I've been able to find for getting random documents from ES. I'm wondering if there might be any other, faster way that I can sample random documents from multiple large ES indexes.




Move sprite forever with random postion on screen

I tried to move random my sprites (the squares) but all sprite go to same position and ״vibrating״. What is the best way to move sprite forever and with random position?

//Make random shape
func makeShape () {

    //Check if have more than 12 shapes
    if shapesamount <= 4 {

        sprite = shape.copy() as! SKShapeNode
        sprite.name = "Shpae \(shapesamount)"

        shapes.addChild(sprite)

        shapesamount += 1

        moveRandom(node: sprite)
    }
}

//Move shape radmonly
func moveRandom (node: SKShapeNode) {

        move = SKAction.move(to: CGPoint(x:CGFloat.random(min: frame.minX, max: frame.maxX), y:CGFloat.random(min: frame.minY
            , max: frame.maxY)), duration: shapespeed)

        node.run(move)
}

override func update(_ currentTime: TimeInterval) {

    // Called before each frame is rendered
    if istouching && !isOver {
        let dt:CGFloat = 1.0/50.0
        let distance = CGVector(dx: touchpoint.x - circle.position.x, dy: touchpoint.y - circle.position.y)
        let velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt)
        self.circle.physicsBody!.velocity = velocity
    }

    if isOver == false {
        for nodee in shapes.children {
            moveRandom(node: nodee as! SKShapeNode)
        }
    }
}

}

shapes is SKNode




Java Random is print out the same number every time

I have a simple block of that there is a random number, when pressing a button the text replacing with that number.

Random r = new Random();
int numb = r.nextInt(10);

this works fine, while

Random r = new Random(10);
int numb = r.nextInt(10);

this prints always 3. The number is always 3 if I put 10 in to the paranthesis of Random. Why it's always equals to 3? Here the whole code in Android Studio

package com.flafel.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    TextView text;
    Button buton;

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

        text = (TextView) findViewById(R.id.text1);
        buton = (Button) findViewById(R.id.button);

        buton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Random r = new Random(10);
                int numb = r.nextInt(10);

                switch (numb)
                {
                    case 1: text.setText("Number is 1");
                        break;
                    case 2: text.setText("Number is 2");
                        break;
                    case 3: text.setText("Number is 3");
                        break;
                    case 4: text.setText("Number is 4");
                        break;
                    case 5: text.setText("Number is 5");
                        break;
                    case 6: text.setText("Number is 6");
                        break;
                    default:
                        text.setText("Number is bigger than 6 or equals 0.");
                        break;
                }

            }
        });



    }
}

I worked with Python so far and I couldn't understand this behaviour.




How do I run thread-safe random numbers in async actions on ASP.Net?

How do I run thread-safe random numbers in async actions?

It always return zero. I tried to to make a instance in startup.cs which set a static istance of the current but it still always return zero.

I am using ASP.Net Core.

public class SafeRandom
{
    public static SafeRandom Instance { get; private set; }

    public SafeRandom()
    {
        Instance = this;
    }

    private readonly static Random _global = new Random();
    [ThreadStatic]
    private Random _local;

    public int Next(int min,int max)
    {
        Random inst = _local;
        if (inst == null)
        {
            int seed;
            lock (_global) seed = _global.Next();
            _local = inst = new Random(seed);
        }
        return inst.Next(min,max);
    }
}




How can i let a function randomly return either a true or a false in go

I want to have a function that I can call to get a random true or false on each call:

  randBoolean() // true
  randBoolean() // false
  randBoolean() // false
  randBoolean() // true

How can I return a random boolean?

Problem 1: Generating a random number with go produces the same result on each call




how to link an image to a sound randomly

I have this code and it's working, but not as really want to :). I need your help to make me understand (as I'm new to Xcode/Swift/developing apps) how to do some things .. I've made it watching tutorials and using some snippets as examples..but so far is working :)

  1. I'd like to make it work in this way: when I click on playSound and hear it, then I have to choose between leftImage and rightImage..the image that matches with the playSound. I've tried into many ways to get it work.. but nothing...I cannot make the sound index a string to compare as "if a == b .."

  2. when I open the app, it shows me only two bottom buttons.. but not any image. How can I make it to show the first image?

  3. I also like to make it a bit random think... When I click on "nextImage" button, I'd like to shows to different images but only one linked to the sound..so when I play the sound..had to check only the photo who matches with the sound.

  4. At this moment, I have only 8 photos/sounds into the array, but when I click more than 9 times on nextImage.. the images are going on and on.. but the sound starts from beginning and it's not linked anymore. for example, at the 10th image..it playSound says it's at 1. How can I make It to follow the image index?

  5. How to convert the image index into text? for example, if its shows me the image "foto1" .. I'd like to show me under the image a text in the label.

thank you for your time and I hope someone will help me solve this :)

import UIKit

import AVFoundation

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

var soundFiles: [String] = [
    "s0",
    "s1",
    "s2",
    "s3",
    "s4",
    "s5",
    "s6",
    "s7",
    "s8",
    "s9"
]

var images1: [UIImage] = [

    UIImage(named: "foto1.png")!,
    UIImage(named: "foto2.png")!,
    UIImage(named: "foto3.png")!,
    UIImage(named: "foto4.png")!,
    UIImage(named: "foto5.png")!,
    UIImage(named: "foto6.png")!,
    UIImage(named: "foto7.png")!,
    UIImage(named: "foto8.png")!
]

var images2: [UIImage] = [

    UIImage(named: "foto1.png")!,
    UIImage(named: "foto2.png")!,
    UIImage(named: "foto3.png")!,
    UIImage(named: "foto4.png")!,
    UIImage(named: "foto5.png")!,
    UIImage(named: "foto6.png")!,
    UIImage(named: "foto7.png")!,
    UIImage(named: "foto8.png")!
]

var happySad: [UIImage] = [
    UIImage(named: "sad.png")!,
    UIImage(named: "happy.png")!
    ]

var currentImageIndex = 0
var currentImage2Index = 0


@IBOutlet weak var leftImage: UIImageView!

@IBOutlet weak var rightImage: UIImageView!

@IBOutlet weak var sh: UIImageView!





@IBAction func nextImages(_ sender: Any) {
 currentImageIndex += 1
    let numberOfImages = images1.count
    let nextImage1Index = currentImageIndex % numberOfImages
    leftImage.image = images1[nextImage1Index]
    leftImage.isUserInteractionEnabled = true
    self.view.addSubview(leftImage)
    let gesture1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap1))
    leftImage.addGestureRecognizer(gesture1)


 currentImage2Index += 1
    let numberOfImages2 = images2.count
    let nextImage2Index = currentImage2Index % numberOfImages2
    rightImage.image = images2[nextImage2Index]
    sh.image = UIImage(named: "question")
    rightImage.isUserInteractionEnabled = true
    self.view.addSubview(rightImage)
    let gesture2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap2))
    rightImage.addGestureRecognizer(gesture2)

}

func singleTap1() {
    if currentImageIndex == currentImage2Index {
        sh.image = UIImage(named: "happy.png")
        print("ok")
    } else {
        sh.image = UIImage(named: "sad.png")
        print("not ok")
    }
}
func singleTap2() {
    if currentImageIndex == currentImage2Index {
        sh.image = UIImage(named: "happy.png")
        print("ok2")
    } else {
        sh.image = UIImage(named: "sad.png")
        print("not ok2")
    }
}


var player: AVAudioPlayer!

@IBAction func playSound(_ sender: Any) {
    let numberOfImages = images1.count
    let nextImage5Index = currentImageIndex % numberOfImages
    let soundFilePath = Bundle.main.url(forResource: soundFiles[nextImage5Index], withExtension: ".m4a")!
    player = try! AVAudioPlayer(contentsOf: soundFilePath)
    player.prepareToPlay()
    player.play()

}

}




How to display a random quote as soon as page loads?

I am working on a random quote app. Quote is display when click a new quote button but I want quote already display when page loads. I invoked a function but it still does not work. Thank you!

Here is my code:

$(document).ready(function() {
  function randomQuote() {
    $('#get-quote').on('click', function(e){
      e.preventDefault();
      // Using jQuery
      $.ajax( {
          url: "http://ift.tt/1UgX3Vj",
          dataType: "jsonp",
          type: 'GET',
          success: function(json) {
             // do something with data
             console.log(json);
             data = json[0];
             $('#quotation').html('"'+json.quote+'"');
             $('#author').html('-- '+json.author+' --');
             $('a.twitter-share-button').attr('data-text',json.quote);
           },

      });

    });
    $('#share-quote').on('click', function() {
         var tweetQuote=$('#quotation').html();
         var tweetAuthor=$('#author').html();
         var url='https://twitter.com/intent/tweet?text=' + encodeURIComponent(tweetQuote+"\n"+tweetAuthor);
         window.open(url)
    });

  }
  randomQuote();
});
<script src="http://ift.tt/1oMJErh"></script>



Java script random number with allowed to 2 repeat value

How to create the random number to assign in java script array with following condition.

  • need to create random number with (1-28).
  • Number allowed to repeat 2 times. (EX: 1,3,5,4,5). .



jeudi 22 juin 2017

Context Free Grammar for English Sounding Names

I am currently writing an application that will generate random data; specifically, random names. I have made some decent progress, but am not satisfied with many of the generated names. The problem lies in my production rules, which I've attached to the bottom of this post.

The basic idea is: consonant, vowel, consonant, vowel, but some consonants themselves map to vowels (such as b< VO >).

I have not fully created the rules yet, but the final idea would follow the format shown below. However, rather than finishing it, I would like to make a better basis for the production rules.

I have tried to find a reference that discusses either: a cfg already created for english-sounding words, or an english reference that disassembles the basic format of letter combinations for words. Unfortunately, I have not been able to find a useful resource to help me advance farther than I already have. Does anyone know of a place I should look, or a reference I can look at?

ALSO: in your opinion, do you believe a context-sensitive grammar might work better?

//These variables will be the production rules that the functions below use to generate strings
var A = ['a','aa'];
A.probabilities = [90,10]; //probability of each option corresponding to the entries
A.name = "A";
var B = ['br','bl','b<VO>','b'];
B.probabilities = [22,22,21,35];
B.name = "B";
var C = ['ch','cr','ck','c<VO>','c'];
C.probabilities = [25,5,5,25,40];
C.name = "C";
var D = ['d<R>','db<VO>','d<VO>','d'];
D.probabilities = [20,1,35,49];
D.name = "D";
var E = ['e','ee'];
E.probabilities = [90,10];
E.name = "E";
var K = ['k<B>','k<R>','k<VO>','k'];
K.probabilities = [5,15,40,40];
K.name = "K";
var O = ['o','oo'];
O.probabilities = [90,10];
O.name = "O";
var Q = ['qu'];
Q.probabilities = [100];
Q.name = "Q";
var R = ['rh<VO>','r<VO>','r'];
R.probabilities = [8,32,60];
R.name = "R";
var S = ['sh','sc','sw','s<VO>','s'];
S.probabilities = [25,5,5,25,40];
S.name = "S";
var T = ['tr','t<VO>','t'];
T.probabilities = [30,30,40];
T.name = "T";

var CO = ['<B>','<C>','<D>','f','g','h','j','<K>','l','m','n','p','<Q>','<R>','s','t','v','w','x','y','z']; //for now, Y is here
CO.probabilities = [2.41,4.49,6.87,3.59,3.25,9.84,0.24,1.24,6.5,3.88,10.9,3.11,0.153,9.67,10.2,14.6,1.58,3.81,0.242,3.19,0.12];
CO.name = "CO";
var VO = ['<A>','<E>','i','<O>','u'];
VO.probabilities = [21.43,33.33,18.28,19.7,7.23];
VO.name = "VO"

var VOCO = ['<VO>','<CO>'];
VOCO.probabilities = [38.1,61.9];
VOCO.name = "VOCO";

var rules = [A,B,C,D,E,K,O,Q,R,S,T,CO,VO,VOCO]; //this will contain all of the production rule references --> since we know they are rules, we dont need < > here

And to generate a name:

var result = "<CO><VO>".repeat(getRandomInt(1,4));




'dict_keys' object does not support indexing' - Retrieval of random key from dictionary [duplicate]

This question already has an answer here:

color_dic = {"blue": "calm", "red": "angry", "yellow": "happy"]
feellib = ["calm", "angry", "happy", "sad", "excited", "annoyed"]

color = random.choice(color_dic)
feel_update = random.choice(feellib)

color_dic[color] = feel_update

print (color_dic[color])

So what I'm wanting my code to do is select a random color from "color_dic" and then apply a new feeling it. For example it would take the key of blue from "color_dic" and then randomly choose "happy" from "feellib". It would then rewrite {"blue":"calm"} to {"blue":"happy"} . But when I use the code above I get:

color = random.choice(color_dic.keys())
    return seq[i]
TypeError: 'dict_keys' object does not support indexing

I'm able to make this work if I make a separate library of colors in list form:

color_list = ["blue", "red", "yellow"]
color = random.choice(color_list)

The only problem with this is it means I have to update both "color_list" and "color_dic" if I want to add new colors.

Is there any way I can have my code pick a random key from "color_dic"? Any help would be much appreciated!




Probability and random numbers

I am just starting with C++ and am creating a simple text-based adventure. I am trying to figure out how to have probability based events. For example a 50% chance that when you open box there will be a sword and a 50% chance it will be a knife. I know how to make a random number generator, but I don't know how to associate that number with something. I created a variation of what I want but it requires the user to input the random number. I am wondering how to base the if statement on whether or not the random number was greater or less than 50, not if the number the user put in was greater or less than 50.