Exemple #1
0
def main(input, output):
    try:
        with open(input) as file:
            data = json.load(file)
    except json.decoder.JSONDecodeError as E:
        print('Wrong Json file:', E)
        return
    except FileNotFoundError as E:
        print(E)
        return

    if 'Screen' in data.keys():
        screen = data['Screen']
    else:
        print('No \"Screen\" in file')
        return
    if 'Palette' in data.keys():
        palette = data['Palette']
    else:
        print('No \"Palette\" in file')
        return

    shapes_list = readShapesFromJson(data)

    draw.draw(screen['width'], screen['height'], screen['bg_color'],
              screen['fg_color'], palette, shapes_list, output)
Exemple #2
0
def fileUpload():
    file = request.files['file'] 
    destination="/".join([os.path.realpath(os.path.dirname(__file__)), "concept2.json"])
    file.save(destination)
    ###
    concept = getFromJson("concept2")
    try:
      check_import_concept(concept)
    except Exception as e:
      return "{0}".format(e), 400

    a = core.Context(concept["G"],
        concept["M"],
        concept["I"])
    start = datetime.now()
    b = nextNeighbour.nextNeighbours(a)
    end = datetime.now()

    draw_start = datetime.now()
    draw.draw(b, OUT_FILE_NAME)
    draw_end = datetime.now()

    resp = dict({
      'latticeImg': encodedFile(OUT_FILE_NAME),
      'lattice': b.toJson(),
      'concept': a.toJson(),
      'constructTime': (end - start).total_seconds(),
      'drawTime': (draw_end - draw_start).total_seconds(),
      'json': json.dumps(dict(G = a.G, M = a.M, I = a.I)) 
    })
    return jsonify(resp)
Exemple #3
0
def start(game, inputs_record):
    pygame.init()

    screen = pygame.display.set_mode(
        (draw.screen_w, draw.screen_h)
    )
    pygame.display.set_caption("ice-hall")

    clock = pygame.time.Clock()
    millis = 1
    exit = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: exit = True
            else: inputs_record = collect.collect(inputs_record, event)

        if exit: break

        game = update.update(game, inputs_record, millis/1000)

        draw.draw(screen, game)

        pygame.display.flip()
        millis = clock.tick(60)

    pygame.quit()
Exemple #4
0
def main():
    #read instance
    #path=sys.argv[1]
    id,n,p,d,s,w,cxy,V,mytype,id = read('Instances/pmedcap1.dat')
    
    CVPMP.init(n,p,d,s,w,V)
    z, solution = CVPMP.Solver()

    #display solution
    data = Global.path()+'/out.dat'
    f = open(data,'w')
        
    for s in solution:
        i=s[0]
        for j in s[1]:
            if i == j:
                mytype = 1
            else:
                mytype = 0

            f.write('%d\t%d\t%d\t%d\t%d\n'%
                        (mytype, j, i, cxy[j][0], cxy[j][1]))

    f.close();
    draw.draw(data, mytype, id)
Exemple #5
0
def simulate(world, balls, edges, pockets, screen, clock, do_draw):
    background_color = (20, 130, 57) # Green felty color.
    world.Step(TIME_STEP, 10, 10)    # Kick things off.

    # Run simulation until balls stop moving.
    while is_moving(world):
        # Check for quit event
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()

        # Apply friction forces to balls
        for body in world.bodies:
            apply_friction(body)

        # Simulate the next step of the Box2D world and destroy balls in the destroy queue (i.e. balls that touched pockets)
        world.Step(TIME_STEP, 10, 10)
        world.contactListener.DestroyBalls(world)
        world.ClearForces()

        # Draw the world
        if do_draw:
            # Fill in the table background, draw the bodies, and update the display and clock.
            draw(world, screen, background_color)
            pygame.display.flip()
            clock.tick(FPS)

    # See if the cue ball went into a pocket.
    scratch = is_made(balls[0])
    if scratch:
        balls[0].body.position = (TABLE_WIDTH / 2.0 + TABLE_WIDTH / 4.0 + 0.4, TABLE_HEIGHT / 2.0)

    return scratch
Exemple #6
0
def add_attribute():
  try:
    current_concept = request.json["old_concept"]
    current_lattice = request.json["old_lattice"]
    attrM = request.json["attrM"]
    attrMI = request.json["attrMI"]

    a = core.Context(current_concept["G"],
        current_concept["M"],
        current_concept["I"])
    b = core.Lattice(
      list(map(lambda x: core.Node(set(x["G"]), set(x["M"])), current_lattice["C"])), 
      set(map(lambda x: (int(x[0]), int(x[1])), current_lattice["E"]))
    )
    start = datetime.now()
    (newCtx, L) = addAttribute.addAttr(a, b, attrM, attrMI)
    end = datetime.now()

    draw_start = datetime.now()
    draw.draw(L, OUT_FILE_NAME)
    draw_end = datetime.now()

    resp = dict({
      'latticeImg': encodedFile(OUT_FILE_NAME),
      'lattice': b.toJson(),
      'concept': a.toJson(),
      'drawTime': (draw_end - draw_start).total_seconds(),
      'addTime': (end - start).total_seconds(),
      'json': json.dumps(dict(G = newCtx.G, M = newCtx.M, I = newCtx.I)) 
    })
    return jsonify(resp)
  except:
    return "Wrong input", 400
def quickhull(points, start_time):
    '''
    Quickhll algorithm that takes in the array of
    points, and the start time of the timer.
    Returns the convex hull as an array.
    '''
    if points.size == 0:
        return []

    L, R = utils.lr_most_point(points)
    result = [L, R]
    if config.visual:
        x, y = np.vstack((L, R)).T
        config.lines = config.ax.plot(x,
                                      y,
                                      c=config.c_color,
                                      alpha=config.c_alpha,
                                      label=config.c_label)
    S1 = []
    S2 = []
    oldLine = L - R
    for point in points:
        newLine = L - point
        if np.cross(oldLine, newLine) > 0:
            S1.append(point)
        elif (point != L).all() and (point != R).all():
            S2.append(point)

    find_hull(S1, L, R, 1, result, start_time)
    find_hull(S2, R, L, len(result), result, start_time)
    if config.visual:
        draw(start_time)
        plt.savefig(config.image_path)

    return np.array(result)
def brute_force(points, start_time):
    '''
    Brute Force algorithm that takes in the array of
    points and start time of the timer.
    Returns the convex hull as an array.
    The results of this algorithm are out-of-order,
    unlike the other algorithms that have their results in-order.
    '''
    result = []
    lines = []
    if config.visual:
        lines.append(
            config.ax.plot((0, 0), (0, 0),
                           c=config.c_color,
                           alpha=config.c_alpha,
                           label=config.c_label))
    for i in points:
        for j in points:
            if (i == j).all():
                continue
            side = 0
            ItoJ = j - i
            for k in points:
                if (i == k).all() or (j == k).all():
                    continue
                ItoK = i - k
                newSide = np.cross(ItoJ, ItoK)
                if newSide != 0:  # Makes sure the three lines are not collinear
                    if side == 0:
                        side = newSide
                    elif (side < 0 and newSide > 0) or \
                         (side > 0 and newSide < 0):
                        side = False
                        break
            if side:
                i_is_new = all(i not in q for q in result)
                j_is_new = all(j not in q for q in result)
                if i_is_new or j_is_new:
                    if i_is_new:
                        result.append(i)
                    if j_is_new:
                        result.append(j)
                    if config.visual:
                        lines.append(
                            config.ax.plot((i[0], j[0]), (i[1], j[1]),
                                           color=config.c_color,
                                           alpha=config.c_alpha))
                        draw(start_time)
                elif config.visual:  # TODO: This happens too many times
                    lines.append(
                        config.ax.plot((i[0], j[0]), (i[1], j[1]),
                                       color=config.c_color,
                                       alpha=config.c_alpha))
                    draw(start_time)

    if config.visual:
        plt.savefig(config.image_path)
        for line in lines:
            line.pop(0).remove()
    return np.array(result)
Exemple #9
0
def random_draw(draw_input_dict,
                random_input_dict,
                folder_save,
                display=False,
                image_number=0,
                global_poly_number=None,
                global_color_palette_number=None):
    # draw_input_dict (doct) is dictionary with fixed parameters
    # random_input_dict (dict) is dictionary with random parameter distributions
    # folder_save (str) is path to folder where results should be saved
    # display (bool) indicates if plots should be prompted
    # image_number (int) is the starting number for the images to be saved (in their names)
    # global_poly_number (int) is - if not None - the number of polynomials to generate and to used in plots to be constructed thanks to all coefficient distributions without regard to cartesian product
    # global_color_palette_number (int) is - if not None - the number of color palette to generate and to used in plots to be constructed thanks to all coefficient distributions without regard to cartesian product

    # random_input_dict is used to generate input list to override fixed inputs
    ## If global_poly_number or global_color_palette_number are not None, polynomial or color palette lists are constructed explicitely
    new_input_dict = override(
        draw_input_dict,
        generate_random_inputs(random_input_dict, global_poly_number,
                               global_color_palette_number))

    # draw function is called with generated inputs
    draw(new_input_dict,
         folder_save,
         display,
         image_number,
         cartesian_poly=(global_poly_number is None),
         cartesian_color_palette=(global_color_palette_number is None))
Exemple #10
0
def main():
    #read instance
    #path=sys.argv[1]
    id, n, p, d, s, w, cxy, V, mytype, id = read('Instances/pmedcap1.dat')

    CVPMP.init(n, p, d, s, w, V)
    z, solution = CVPMP.Solver()

    #display solution
    data = Global.path() + '/out.dat'
    f = open(data, 'w')

    for s in solution:
        i = s[0]
        for j in s[1]:
            if i == j:
                mytype = 1
            else:
                mytype = 0

            f.write('%d\t%d\t%d\t%d\t%d\n' %
                    (mytype, j, i, cxy[j][0], cxy[j][1]))

    f.close()
    draw.draw(data, mytype, id)
Exemple #11
0
def main_loop():
    global speedup_factor
    global quit
    global players
    global camps
    global goals
    global world
    global animations
    global screen

    step = 0

    while not quit:
        handle_events()
        for _ in range(speedup_factor):
            call_ais()
            game_logic.tick(players, camps, goals, animations, world)
        draw.draw(players, camps, goals, animations, world, screen)
        clock.tick(50)  # 20ms relative to last tick

        step += 1
        if tournament_mode and step > 10000:
            best_player = sorted(players, key=lambda p: p.score,
                                 reverse=True)[0]
            print(best_player.ai.filename)
            quit = True
Exemple #12
0
def runGA(cities, initFunc, initSize, selectFunc, selectParams, coFunc, scoreFunc, mutateFunc, mutparams, killFunc, maxGen, targetScore):
	
	window = draw.makescreen()
	g = 0
	pop = initFunc(initSize, len(cities))
	pop = map(lambda tour: [cities[i] for i in tour], pop)
	best = min(pop, key=lambda p: scoreFunc(p, DIST)); bestsofar='',None
	print 'Best:', scoreFunc(best, DIST)	##
	draw.draw(best, g, window, DIST)
	
	while g <= maxGen and bestsofar[0] > targetScore:
		children = []
		for p in pop:
#			if not _%10: print _,	##
#			print 'sel',	##
			mate = selectFunc(p, pop, *selectParams)
#			print '/sel',	##
			children.append(mutateFunc(coFunc(p[:], mate[:]), *mutparams))
			children.append(mutateFunc(coFunc(mate[:], p[:]), *mutparams))
			
#		print set((scoreFunc(c) for c in children))	##
#		pop = killFunc(pop, children)
		pop = kill(pop+children, initSize, DIST)
		g += 1
#		best = max((scoreFunc(p) for p in pop))
		best = min(pop, key=lambda p: scoreFunc(p, DIST))
		if scoreFunc(best, DIST) < bestsofar[0]:
			bestsofar = scoreFunc(best, DIST), best
			window = draw.makescreen()
			pg.display.init(); draw.draw(bestsofar[1], g, window, DIST)
#		if not g%10: print g, scoreFunc(best), "|", bestsofar[0]	##
		print g, scoreFunc(best, DIST), "|", bestsofar[0], len(set((c.id for c in bestsofar[1])))	##
	
	raw_input("Hit <ENTER> to continue")
	return bestsofar[0]
Exemple #13
0
 def draw(self, surface=None):
     draw.draw_bg(self.rendertarget, self.bg_color)
     if surface is None:
         surface = self.rendertarget
     for go in self.gameobjects:
         draw.draw(go, surface)
     if self.actor:
         draw.draw(self.actor, surface)
Exemple #14
0
def move_and_draw(world):
    w = world
    while True:
        sleep(w.speed)
        if not world.paused:
            check_for_direction_change(w.pushedKeys, w.snakeElements)
            move(w.snakeElements)
            draw(w.screen, w.surfaceSize, w.mapSize, w.score, w.highScore, w.egg, w.snakeElementSize, w.snakeElements)
            take_action(w)
Exemple #15
0
def checkInput(input):
    global errorNumber
    outcome = [i for i, x in enumerate(answer) if x == input.upper()]
    if len(outcome) > 0:
        for x in range(0, len(outcome)):
            test[outcome[x]] = input.upper()
    else:
        errorNumber += 1
        draw(errorNumber)
Exemple #16
0
    def draw(self):
        """
		Draw the game state.
		"""
        #REMOVEME
        #print "drawing"
        #return

        camera_x = 0
        camera_y = 0
        if self._scroll_type == SCROLL_HORIZ:
            try:
                px = self.player_list[0].x
                camera_x = px / self._field_width * (self._field_width -
                                                     self._view_width)
            except IndexError:
                camera_x = 0
        if self._scroll_type == SCROLL_VERT:
            try:
                py = self.player_list[0].y
                camera_y = py / self._field_height * (self._field_height -
                                                      self._view_height)
            except IndexError:
                camera_y = 0
        gl.glPushMatrix()
        gl.glTranslatef(-camera_x, -camera_y, 0)
        for object in self.player_list + self.foe_list + self.shot_list + self.others_list:
            object.draw()
        #print ("nbr of normal/ml bullets : " + str(self.array_fill) + "/" + str(self.array_ml_fill))
        draw.draw(self.bullet_array, self.array_fill, self.bullet_array_ml,
                  self.array_ml_fill)
        #		gl.glAccum(gl.GL_MULT, 0.9)
        #		gl.glAccum(gl.GL_ACCUM, 1.0)
        #		gl.glAccum(gl.GL_RETURN, 1.0)
        gl.glDisable(gl.GL_TEXTURE_2D)
        gl.glLineWidth(3.)
        gl.glColor4f(1., 1., 1., 1.)
        gl.glBegin(gl.GL_LINE_LOOP)
        gl.glVertex2f(-0.45 * self._field_width, 0.45 * self._field_height)
        gl.glVertex2f(-0.45 * self._field_width, -0.45 * self._field_height)
        gl.glVertex2f(0.45 * self._field_width, -0.45 * self._field_height)
        gl.glVertex2f(0.45 * self._field_width, 0.45 * self._field_height)
        gl.glEnd()
        gl.glBegin(gl.GL_LINE_LOOP)
        gl.glVertex2f(-0.5 * self._field_width, 0.5 * self._field_height)
        gl.glVertex2f(-0.5 * self._field_width, -0.5 * self._field_height)
        gl.glVertex2f(0.5 * self._field_width, -0.5 * self._field_height)
        gl.glVertex2f(0.5 * self._field_width, 0.5 * self._field_height)
        gl.glEnd()
        gl.glEnable(gl.GL_TEXTURE_2D)
        gl.glLineWidth(1.)

        pygame.display.flip()
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        gl.glPopMatrix()
Exemple #17
0
def train(epoch = 100, batch_size = 100, input_size = 2):
    GEN = gen(input_size).to(device).double()
    DIS = dis().to(device).double()
    optimizer_g = torch.optim.RMSprop(GEN.parameters(), lr=0.0001)
    optimizer_d = torch.optim.RMSprop(DIS.parameters(), lr=0.0001)
    for ep in range(epoch):
        total_gen_loss = 0
        total_dis_loss = 0
        for j in range(int(len(train_set) / batch_size)):
            func = torch.from_numpy(train_set[j * batch_size: (j + 1) * batch_size]).double().to(device)
            input = torch.randn(batch_size, input_size).to(device).double()
            noise = GEN(input)

            GEN_loss = -torch.mean(DIS(noise)).to(device)
            optimizer_g.zero_grad()
            GEN_loss.backward()
            optimizer_g.step()

            DIS_loss = -torch.mean(DIS(func) - DIS(noise.detach())).to(device) + 0.001* gradient_penalty(DIS, func, noise)
            optimizer_d.zero_grad()

            DIS_loss.backward()
            optimizer_d.step()

            total_gen_loss += GEN_loss.item() * batch_size
            total_dis_loss += DIS_loss.item() * batch_size
        print("epoch %d \t G_LOSS: %.4f \t D_LOSS: %.4f" % (ep + 1, total_gen_loss / len(train_set) , total_dis_loss / len(train_set)))

        if ep % 10 == 9 :
            with torch.no_grad():
                input = torch.randn(1000, input_size).to(device).double()
                output = GEN(input)
                data = np.array(output.cpu().data)
                x_min = np.min(test_set[:, 0])
                x_max = np.max(test_set[:, 0])
                y_min = np.min(test_set[:, 1])
                y_max = np.max(test_set[:, 1])
                x_min = np.min(np.append(data[:, 0], x_min))
                x_max = np.max(np.append(data[:, 0], x_max))
                y_min = np.min(np.append(data[:, 1], y_min))
                y_max = np.max(np.append(data[:, 1], y_max))
                i = x_min
                background = []
                while i <= x_max:
                    j = y_min
                    while j <= y_max:
                        background.append([i,j])
                        j = j + 0.01
                    background.append([i, y_max])
                    i = i + 0.01
                print(x_min,x_max,y_min,y_max)
                background = np.array(background)
                background_color = DIS(torch.Tensor(background).to(device).double())
                draw.draw(ep, data,test_set, background , np.array(background_color.cpu().data), x_min, x_max, y_min, y_max, "wgan_gp")
                GEN.zero_grad()
                DIS.zero_grad()
Exemple #18
0
	def draw(self):
		"""
		Draw the game state.
		"""
		#REMOVEME
		#print "drawing"
		#return

		camera_x = 0
		camera_y = 0
		if self._scroll_type == SCROLL_HORIZ:
			try:
				px = self.player_list[0].x
				camera_x = px/self._field_width*(self._field_width - self._view_width)
			except IndexError:
				camera_x = 0
		if self._scroll_type == SCROLL_VERT:
			try:
				py = self.player_list[0].y
				camera_y = py/self._field_height*(self._field_height - self._view_height)
			except IndexError:
				camera_y = 0
		gl.glPushMatrix()
		gl.glTranslatef(-camera_x, -camera_y, 0)
		for object in self.player_list + self.foe_list + self.shot_list + self.others_list:
			object.draw()
		#print ("nbr of normal/ml bullets : " + str(self.array_fill) + "/" + str(self.array_ml_fill))
		draw.draw(self.bullet_array, self.array_fill,self.bullet_array_ml, self.array_ml_fill)
#		gl.glAccum(gl.GL_MULT, 0.9)
#		gl.glAccum(gl.GL_ACCUM, 1.0)
#		gl.glAccum(gl.GL_RETURN, 1.0)
		gl.glDisable(gl.GL_TEXTURE_2D)
		gl.glLineWidth(3.)
		gl.glColor4f(1.,1.,1.,1.)
		gl.glBegin(gl.GL_LINE_LOOP)
		gl.glVertex2f(-0.45*self._field_width, 0.45*self._field_height)
		gl.glVertex2f(-0.45*self._field_width,-0.45*self._field_height)
		gl.glVertex2f(0.45*self._field_width, -0.45*self._field_height)
		gl.glVertex2f(0.45*self._field_width,  0.45*self._field_height)
		gl.glEnd()
		gl.glBegin(gl.GL_LINE_LOOP)
		gl.glVertex2f(-0.5*self._field_width, 0.5*self._field_height)
		gl.glVertex2f(-0.5*self._field_width,-0.5*self._field_height)
		gl.glVertex2f(0.5*self._field_width, -0.5*self._field_height)
		gl.glVertex2f(0.5*self._field_width,  0.5*self._field_height)
		gl.glEnd()
		gl.glEnable(gl.GL_TEXTURE_2D)
		gl.glLineWidth(1.)
		

		pygame.display.flip()
		gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

		gl.glPopMatrix()
Exemple #19
0
def index(oid, idx):
    props = download.fetch_prop(oid)
    id = int(idx)
    if props.has_key(id):
        text, prod_id = props[id]
        config = eval(open('%d/config.json' %(prod_id)).read())
        bytes = io.BytesIO()
        draw.draw('%d/origin.jpg' % (prod_id), text, bytes, config)
        response.set_header('Content-Type', 'image/jpg')
        return bytes.getvalue()
    abort(404)
Exemple #20
0
def collision_stuff(tank, object):
    """Does the stuff once a tank has been hit with an object."""
    for flash in range(8):
        draw.draw("flash", object.origin)
        time.sleep(random.randint(0, 1) / 20)
        delete.delete()
        draw.draw()
        time.sleep(random.randint(0, 1) / 20)
        delete.delete()
    config.reset_scored()
    if tank != object.origin:
        object.origin.score += 1
Exemple #21
0
def main(game_counter, players):

    field = [list('   '), list('   '), list('   ')]

    current_player = 0

    pygame.init()

    window = pygame.display.set_mode((600, 600))

    color = (255, 255, 255)

    playing = True
    while playing:

        pygame.draw.line(window, color, (200, 0), (200, 600))
        pygame.draw.line(window, color, (400, 0), (400, 600))
        pygame.draw.line(window, color, (0, 200), (600, 200))
        pygame.draw.line(window, color, (0, 400), (600, 400))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                playing = False
                global loop
                loop = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                coordinateX = int(event.pos[0] / 200)
                coordinateY = int(event.pos[1] / 200)

                if field[coordinateY][coordinateX] == ' ':
                    draw(window, players[current_player].symbol, event.pos,
                         color)
                    field[coordinateY][coordinateX] = players[
                        current_player].symbol

                    if check_field(field):
                        output(field)
                        print('{0} wins\n'.format(
                            players[current_player].name))
                        playing = False

                    current_player = (current_player + 1) % 2

        if playing:
            playing = False
            for row in field:
                if ' ' in row:
                    playing = True

        pygame.display.update()
Exemple #22
0
    def change_sort(self):
        #rtsp://admin:[email protected]:554//Streaming/Channels/1

        cap = cv2.VideoCapture(camera2)
        while True:
            _, img = cap.read()
            if _:
                draw.draw(img)
                picture = Image.fromarray(img[..., ::-1])

                picture.save('frame2.jpg')
            break
        self.initface_reco.destroy()
        initface_sort(self.master)
def run():
    print 'date:%s step1 start error statistics' % TODAY
    error.save_error()
    print 'date:%s step2 start update statistics' % TODAY
    update.save_update()
    print 'date:%s step3 start db statistics' % TODAY
    db_data.save_db()
    print 'date:%s step4 start making tables' % TODAY
    mktables.mktables()
    print 'date:%s step5 start draw statistics picture' % TODAY
    draw.draw()
    print 'date:%s step6 start sending emails' % TODAY
    send_email.send_email()
    print 'date:%s finished' % TODAY
    def annotate_video(self, videopath, line_names, angle_names):
        lines_to_draw = [self.datastore[name] for name in line_names]
        angles_to_print = {
            "left": self.datastore[angle_names[0]],
            "right": self.datastore[angle_names[1]]
        }

        draw.draw(path=videopath,
                  startframe=self.startframe,
                  endframe=self.endframe,
                  lines=lines_to_draw,
                  segments=None,
                  angles=angles_to_print,
                  outfile=self.outpath)
Exemple #25
0
def main():
    random.seed(42)
    mint = gen_token()
    num_bidders = 300
    total_purchase_amount = 20 * 10**6
    median_valuation = 5 * 10**6

    std_deviation = 0.25 * median_valuation
    bids = gen_bids(num_bidders, total_purchase_amount, median_valuation,
                    std_deviation)

    sim = Simulation(mint, bids[:])

    print 'Running Auction'
    sim.run_auction(factor=10**12, const=10**3)

    print 'Running Trading'
    final_price = 1.2 * sim.mint.ask
    sim.run_trading(mint.auction.elapsed * 3,
                    stddev=0.005,
                    final_price=final_price)

    tstart = len(sim.ticker)

    if False:  # calc changes
        e = sim.ticker[-1]
        s = sim.ticker[tstart + 1]
        for i, t in enumerate(sim.ticker):
            for key in [
                    'CT_Supply', 'CT_Sale_Price', 'CT_Purchase_Price',
                    'CT_Spread', 'MktCap', 'Valuation', 'CT_Reserve',
                    'Market_Price'
            ]:
                n = 'Change_' + key
                if i > tstart:
                    t[n] = t[key] / s[key]
                else:
                    t[n] = 1
        print e

    print 'max valuation', max(i.valuation for i in bids)
    print 'min valuation', min(i.valuation for i in bids)
    print 'avg valuation', sum(i.valuation for i in bids) / len(bids)
    print 'max order value', max(i.value for i in bids)
    print 'min order value', min(i.value for i in bids)
    print 'not ordered', len(sim.bids)

    print 'visualizing {} ticks'.format(len(sim.ticker))
    draw(sim.ticker)
Exemple #26
0
def show(vertices, edges, faces) -> None:
    V = []
    for vertex in vertices.values():
        V.append([vertex.x, vertex.y, vertex.z])

    I = []
    for face in faces.values():
        points: Set[str] = set()
        for edge in [edges[i] for i in face.edges]:
            points.update(edge.vertices)

        for p in points:
            I.append(int(p.replace('v', '')))

    draw(V, I)
def main():
    # 训练数据
    X_train = np.array([[5, 4], [9, 6], [4, 7], [2, 3], [8, 1], [7, 2]])
    y_train = np.array([1, 1, 1, -1, -1, -1])
    # 测试数据
    X_new = np.array([[5, 3]])
    # 绘图
    draw(X_train, y_train, X_new)
    # 不同的k(取奇数)对分类结果的影响
    for k in range(1, 6, 2):
        #构建KNN实例
        clf = KNN(X_train, y_train, k=k)
        #对测试数据进行分类预测
        y_predict = clf.predict(X_new)
        print("k={},被分类为:{}".format(k, y_predict))
Exemple #28
0
    def change_reco(self):
        global camera1
        camera1 = str(self.ip1.get())
        global camera2
        camera2 = str(self.ip2.get())
        cap = cv2.VideoCapture(camera1)
        while True:
            _, img = cap.read()
            if _:
                draw.draw(img)
                picture = Image.fromarray(img[..., ::-1])

                picture.save('frame1.jpg')
            break
        self.interface_first.destroy()
        initface_reco(self.master)
Exemple #29
0
def main(args):
    """
    Gets all the information for the current rankings and tournament and then
    prints them in the correct format to be used in javascript.

    Example run:
        python generate_data.py -n 300 "Brisbane" "ATP 250" > ../static/data.js
    """
    tournament = args.tournament
    points_list = points(args.type)
    if not points_list:
        print("Not a valid tournament type")
        return
    matches, seeds, results = draw(tournament)
    if args.num_rankings:
        num_rankings = args.num_rankings
    else:
        num_rankings = 300
    current_rankings = get_current_rankings(num_rankings)
    new_rankings = subtract_tournament(current_rankings, tournament)
    seeds = extend_seeds(matches, seeds, current_rankings)
    print_players(matches)
    print_seeds(seeds)
    print_new_rankings(new_rankings)
    print_old_rankings(current_rankings)
    print_results(results)
    print_points([str(p) for p in points_list])
    print("var tournament = '{}';".format(tournament))
Exemple #30
0
    def __init__(self, name):
        self.buffers = []
        self.draws = []
        self.color = 0.0

        if name == 'cube':
            poses = cube_positions()
            norms = cube_normals()

            vao = gen_vao()
            self.__make_cube_vbo(0, poses, 3)
            self.__make_cube_vbo(1, norms, 3)
            self.draws.append(
                draw(vao, 36,
                     vec3(0.5, 0.15, 0.1) * 5, vec3(0.5, 0.15, 0.1), vec3(1)))
        else:
            scene = Wavefront(name)
            for mesh in scene.mesh_list:
                for mat in mesh.materials:
                    if mat.vertex_format == 'N3F_V3F':
                        self.__add_drawmat(mat)
                    else:
                        print("unhandled vertex format: ", mat.vertex_format)

        self.__create_shaders()
        self.position = vec3()
        self.angle = 0.0
        self.scale = vec3(1)
Exemple #31
0
async def handle(request):
    if not 'word2' in request.args or not 'word3' in request.args:
        return json({"message": "word2 and word3 must be provided!"})
    pattern = re.compile(r'^[A-Z0-9]{1}$')

    word1 = 'I'  # request.args['word1'][0]
    word2 = request.args['word2'][0]
    word3 = request.args['word3'][0]
    if not pattern.match(word2) or not pattern.match(word3):
        return json(
            {"message": "word must be an uppercase english character!"})

    file_path = os.path.join(static_path, word1 + word2 + word3 + '.jpg')
    if not os.path.isfile(file_path):
        draw(word1, word2, word3)
    return json({"message": "ok"})
Exemple #32
0
def process_image(oimg):
    uimg = undistort.undistort(oimg)
    _, _, _, timg = threshold.threshold(uimg)
    wimg = topview.warp(timg)
    left_fit, right_fit, roc, dfc, ly, lx, ry, rx = lane_finder.find(wimg)
    result = draw.draw(uimg, wimg, left_fit, right_fit, roc, dfc, 
            ly, lx, ry, rx, False)
    return result
def frame_creator(path, maxpeople):
    maxpeople = maxpeople
    import cv2
    img = cv2.imread(path)
    r, frame = draw.draw(img)
    #    img = img[0:349, 272:556]
    cv2.imwrite('Output/frame1.jpg', frame)
    get_image(frame, 3, maxpeople, 1, r)
Exemple #34
0
def oxygnize(grid, oxygen):
    t = 0
    grid[coordinate(oxygen)] = 'O'

    while any(v == '.' for v in grid.values()):
        draw(grid)
        # find all coordinates with oxygen
        o = [key for key, value in grid.items() if value == 'O']
        # spread
        for c in o:
            x, y = c
            for d in 'NSWE':
                cc = x + DX[d], y + DY[d]
                if grid[cc] == '.':
                    grid[cc] = 'O'
        t += 1
    print(t)
 def solveSudoku(image):
     isSudokuProblem = Sudoku.sudoku(image)
     if (isSudokuProblem):
         nonMatrixGrid = Sudoku.getNumberArray()
         grid = Sudoku.sudokuStringToQuestion(nonMatrixGrid)
         grid_string = ''
         if (len(grid) > 0):
             # print nonMatrixGrid
             SudokuSolution.solve(grid)
             # print grid
             grid_string = Sudoku.gridToString(grid)
             # print grid_string
         for file in os.listdir(os.path.dirname(
                 os.path.realpath(__file__))):
             if file.endswith('.jpg'):
                 os.remove(file)
         draw.draw(nonMatrixGrid, grid_string)
def test_draw():
    screen = draw()
    reference = pygame.image.load("image.png")

    pygame.image.save(screen, "image_test.png")

    np.testing.assert_almost_equal(pygame.surfarray.pixels3d(screen), pygame.surfarray.pixels3d(reference))

    print "test ok"
Exemple #37
0
 def play(*args):
     global WAIT
     initial_start_time = time()
     current_player = player1
     while not board.is_over():
         board.current_player = current_player.race
         start_time = time()
         actions = current_player.get_next_move(board)
         if time() - start_time > 2:
             print('player {} timeout and looses!'.format(current_player))
             # break # FIXME
         print('action of {} are {}'.format(board.current_player, actions))
         board.do_actions(actions, False)
         draw(board.grid)
         # sleep(0.2)
         current_player = player2 if current_player == player1 else player1
         if WAIT:
             input('waiting')
     print(board.is_over() + ' won!')
     print('lasted {:.2f}s'.format(time() - initial_start_time))
Exemple #38
0
def read(gesture):
    image = draw(gesture)
    gray_image = np.asarray([[sum(p) / 3 for p in line] for line in image])
    shape = image.shape[:2]
    larger = shape.index(max(shape))
    new_shape = [0, 0]
    new_shape[larger] = 20
    new_shape[int(not larger)] = 20 * min(shape) / max(shape)
    new_image = (imresize(gray_image, new_shape)>0).astype(float)
    big_image = np.zeros((28,28))
    left = 14 - new_image.shape[0] / 2
    top = 14 - new_image.shape[1] / 2
    right = left + new_image.shape[0]
    bottom = top + new_image.shape[1]
    big_image[left:right, top:bottom] = new_image
    return classify(big_image)
Exemple #39
0
green = (0, 255, 0)
yellow = (255, 255, 0)

""" @screen_info[0][0]: 屏幕像素宽
    @screen_info[0][1]: 屏幕像素高
    @screen_info[1][0]: 棋盘起始点x
    @screen_info[1][1]: 棋盘起始点y
    @screen_info[2]:    长方框之间的距离
    @screen_info[3]:    长方框的高度
    @screen_info[4]:    棋子的半径
    @screen_info[5]:    棋子列表如[1, 2, 3, 4, 5]
    @screen_info[6]:    标题
"""
screen_info = [(800, 560), (20, 20), 4, 100, 40, [1, 2, 3, 4, 5], "nim"]
pygame.init()
draw = draw.draw(screen_info)
core = core.core()


statusbar = [550, 400, 200, 40]
menu0 = [600, 80, 160, 40]
menu1 = [600, 130, 160, 40]
draw.drawtext(menu0, (605, 82), 30, "GAMECUBEN.ttf", green, "i first")
draw.drawtext(menu1, (605, 132), 30, "GAMECUBEN.ttf", green, "ai first")


def setstatusbar(text):
    draw.drawtext(statusbar, (555, 402), 30, "GAMECUBEN.ttf", yellow, text)


def clearstatusbar():
Exemple #40
0
    print "x", x.ident
    y = VarAtom("y")
    print "y", y.ident
    stmt = UnaryOpAtom("\\integral", BinOpAtom("+", x, y))
    print "stmt", stmt.ident
    
    b = stmt.render()
    draw.boxes = [b]

    t = Thread(target=console_thread)
    t.start()

    # Event loop
    running = True
    while running:
        draw.draw()
        running = draw.events()
        while not cmdq.empty():
            try:
                cmd = cmdq.get_nowait()
                running = alg.runCmd(stmt, cmd)
                print stmt
                # Rerender
                b = stmt.render()
                draw.boxes = [b]
            except Empty:
                break

    # Cleanup
    t.join()
Exemple #41
0
def index(pid, text):
    response.set_header('Content-Type', 'image/png')
    bytes = io.BytesIO()
    draw.draw('origin.png', text, bytes)
    return bytes.getvalue()
 def draw(self):
     draw.draw(self.faces, self.coordinates.tolist())
Exemple #43
0
 def _drawImagesInto(self, sheet):
     for im, rect in self.layout.placedImages:
         if not self.drawBackgrounds:
             im.background = None
         draw(sheet, im, rect)
Exemple #44
0
def main():
    name = sys.argv[1] if sys.argv[1:] else 'spheres'
    scene = __import__(name).Scene()
    scene.init()
    draw(scene.get_pixel, 'test', 640, 480)
Exemple #45
0
 def draw(self, screen, viewPoint):
   if not self.checkAvailable():
     return
   draw(screen, self.getImage(), self.getPosition(), self.getDirection(),
                                 viewPoint.getPosition(), viewPoint.getDirection())
   '''
Exemple #46
0
 def draw(self, screen, viewPoint):
   draw(screen, self.getImage(), self.getPosition(), self.getDirection(),
                                 viewPoint.getPosition(), viewPoint.getDirection())
   '''
import grabcut
import blacktowhite
import draw

output = grabcut.grabcut("/Users/anthony/opencv/orignal.jpg")
output = blacktowhite.blacktowhite()
output = draw.draw();
print "hello"
Exemple #48
0
# -*- coding: utf-8 -*-

import analyse_text, draw, text_segmentation, os, SimpleHTTPServer, SocketServer

if __name__ == '__main__':
    text_segmentation.text_seg()
    analyse_text.training()
    _ = analyse_text.cosine_all()
    _ = analyse_text.get_relationship(_)
    draw.draw(_)
    os.chdir('../tmp')
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", 8000), Handler)
    print 'serving at port 8000'
    httpd.serve_forever()
Exemple #49
0
 def get_chart_data(quiz_id, scores):
     norm = QService.get_norm(quiz_id)
     q = QService.get_questionnaire(quiz_id=quiz_id)
     return draw(quiz_id, q.caption, scores, norm=norm)