Ejemplo n.º 1
0
    def test_after_food_collision(self):
        '''
        Verify that got_food is set to False after a food collision is done and
        player is in a tile space that does not contain anything.
        Verify that the y position changes and score remains the same.
        '''
        Keys.reset()
        food_row = 10
        food_col = 10
        world = World(food_row, food_col)
        player = Player(world)
        player_row = 9
        player_col = 10
        player_y = StationaryTile.DIMS[1] * player_row
        player_x = StationaryTile.DIMS[0] * player_col
        player.position = (player_x, player_y)
        player.got_food = True

        new_x = player.position[0]
        new_y = player.position[1] - MovingTile.VERT_SPEED
        new_dead = player.dead
        new_got_food = False
        new_score = player.score

        player.do_something()

        self.assertEqual(new_x, player.position[0])
        self.assertEqual(new_y, player.position[1])
        self.assertEqual(new_dead, player.dead)
        self.assertEqual(new_got_food, player.got_food)
        self.assertEqual(new_score, player.score)
Ejemplo n.º 2
0
    def test_during_food_collision(self):
        '''
        Verify score does not increment during collision when got_food is
        already True.  Verify that player's got_food remains True, y position
        changes, and score remains the same.
        '''
        Keys.reset()
        food_row = 10
        food_col = 10
        world = World(food_row, food_col)
        player = Player(world)
        player_row = 10
        player_col = 10
        player_y = StationaryTile.DIMS[1] * player_row
        player_x = StationaryTile.DIMS[0] * player_col
        player.position = (player_x, player_y)
        player.got_food = True

        new_x = player.position[0]
        new_y = player.position[1] - MovingTile.VERT_SPEED
        new_dead = player.dead
        new_got_food = player.got_food
        new_score = player.score

        player.do_something()

        self.assertEqual(new_x, player.position[0])
        self.assertEqual(new_y, player.position[1])
        self.assertEqual(new_dead, player.dead)
        self.assertEqual(new_got_food, player.got_food)
        self.assertEqual(new_score, player.score)
Ejemplo n.º 3
0
 def __init__(self, gui):
     Keys.__init__(self)
     Mouse.__init__(self)
     # tkinter
     self.root = gui
     # self.root.withdraw()
     # parser
     self.parser = ArgumentParser()
     self.configure_parser()
     self.args = self.parser.parse_args()
     # general stuff
     self.firefox = True
     self.msg = 'Nothing'
     self.__link_tabs = 0
     self.link_list = None
     self.wait_time = 1.5
     self.raid_wait = 0.45
     self.a = 0.1
     self.is_sitter = False
     # village
     self.villages = None
     self.read_all_str()
     self.n_villages = len(self.villages)
     self.add_stat_info()
     self.Production = self.init_production()
     # self.print_village_overview()
     # raids
     self.units = {0: 'Clubswinger', 1: 'Scout', 2: 'Ram', 3: 'Chief', 4: 'Spearman', 5: 'Paladin', 6: 'Catapult', 7: 'Settler', 8: 'Axeman', 9: 'Teutonic Knight', 10: 'Hero'}
     self.raid_info = self.get_raid_info()
     # go back to the terminal
     self.press_alt_tab()
Ejemplo n.º 4
0
def mapDecisionToOutput(decision, move):
    keys = Keys()
    keys.directMouse(buttons=keys.mouse_lb_release)
    if decision == UP:
        GTAMovement.moveUp(move)
    elif decision == DOWN:
        GTAMovement.moveDown(move)
    elif decision == LEFT:
        GTAMovement.moveLeft(move)
    elif decision == RIGHT:
        GTAMovement.moveRight(move)

    elif decision == UP_SP:
        GTAMovement.moveUpSprint(move)
    elif decision == DOWN_SP:
        GTAMovement.moveDownSprint(move)
    elif decision == LEFT_SP:
        GTAMovement.moveLeftSprint(move)
    elif decision == RIGHT_SP:
        GTAMovement.moveRightSprint(move)

    elif decision == NOTHING:
        GTAMovement.doNothing(move)

    elif decision == SHOOT:
        GTAMovement.shoot()
Ejemplo n.º 5
0
def main():
    # create training data specific dir
    milliseconds = int(round(time.time() * 1000))
    full_path = f"data/{milliseconds}"
    if not os.path.exists(full_path):
        os.makedirs(full_path)

    countdown("Starting in...", 5)

    keys = Keys()
    training_data = []
    file_num = 1
    for frame in record_screen(resize=(_WIDTH, _HEIGHT)):
        pressed_keys = keys.check()
        onehot = keys.keys_to_onehot(pressed_keys)
        training_data.append([frame, onehot])

        # save new array every 10,000 iterations
        if (len(training_data) % 10000) == 0:
            print("Saving array...")
            save_path = f"{full_path}/training_data{file_num}.npy"
            np.save(save_path, training_data)
            training_data = []
            file_num += 1
            countdown("Continuing in...", 5)

        # pressing Q will save array and normalize data
        if "Q" in pressed_keys:
            print("Saving array...")
            save_path = f"{full_path}/training_data{file_num}.npy"
            np.save(save_path, training_data)
            normalize(full_path)
            break
Ejemplo n.º 6
0
def stock_price_notification():
    result = ""
    try:
        now = timezone.now()
        iex_interface = IEXInterface(Keys())
        polygon = PolygonInterface(Keys())
        market_status = polygon.get_market_status_now()

        if market_status.exchanges["nyse"] == "closed":
            print("It's " + now + "Market closed....")
            return "It's " + now + "Market closed...."
        companies = CompanyModel.objects.filter(notification__isnull=False)
        result = (now + ": There are " + len(companies) +
                  " of companies to keep track of.\n")

        for company in companies:
            price = iex_interface.get_ticker_quote(ticker=company.ticker)
            notifications = Notification.objects.filter(price__gte=price,
                                                        company=company)
            result += (company.name + " : " + len(notifications) +
                       " number of notifications sent.")
            for notification in notifications:
                pass
    except:
        pass
    return result
Ejemplo n.º 7
0
    def test_collide_enemy_from_top(self):
        '''
        Player collides with enemy from top, by moving down.
        Verify that player's dead changes to True and y position changes.

        Map before collision:
        wwwwwwwwwwwwwwwwwwww
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000f00000000w
        w000000000p00000000w
        w000000000e00000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        wwwwwwwwwwwwwwwwwwww
        '''
        Keys.reset()
        food_row = 8
        food_col = 10
        world = World(food_row, food_col)
        enemy_row = 10
        enemy_col = 10
        enemy = Enemy(world)
        enemy.position = (StationaryTile.DIMS[1] * enemy_row,
                          StationaryTile.DIMS[0] * enemy_col)
        player = Player(world)
        player_row = 9
        player_col = 10
        player_y = StationaryTile.DIMS[1] * (player_row + 1) - \
                MovingTile.DIMS[1]
        player_x = StationaryTile.DIMS[0] * player_col
        player.position = (player_x, player_y)
        Keys.set_down()

        new_x = player.position[0]
        new_y = player.position[1] + MovingTile.VERT_SPEED
        new_dead = True
        new_got_food = player.got_food
        new_score = player.score

        player.do_something()

        self.assertEqual(new_x, player.position[0])
        self.assertEqual(new_y, player.position[1])
        self.assertEqual(new_dead, player.dead)
        self.assertEqual(new_got_food, player.got_food)
        self.assertEqual(new_score, player.score)
Ejemplo n.º 8
0
 def __init__(self, file_dir):
     self.FileDir = file_dir
     self.Band = self.get_band()
     self.Album = self.get_album()
     self.ExcludeTypes = ['ini', 'jpg', 'txt']
     self.Exclude = [self.Band, self.Album, '(mp3co.biz)']
     self.Songs = self.load_songs()
     Keys.__init__(self)
     Mouse.__init__(self)
Ejemplo n.º 9
0
 def __init__(self,
              main_path="",
              write_path="",
              video="",
              audio="",
              malla="",
              actividad_compartida=False):
     if main_path == "":
         raise Exception(
             "Error!, engine necesita el path al directorio principal de la aplicacion para funcionar (Class Engine)"
         )
     if video == "" or audio == "" or malla == "":
         raise Exception(
             "Error!, engine necesita Audio, Video y Malla para funcionar (Class Engine)"
         )
     self.__main_path = main_path
     self.__write_path = write_path
     #Iniciliazo el Audio y Video
     self.__video = video
     self.__audio = audio
     self.__malla = malla
     self.__actividad_compartida = actividad_compartida
     self.__audio.on_channel()
     #Inicializo las teclas
     self.__keys = Keys(main_path)
     #Iniciliazo el club (habitaciones)
     self.__club = Club(main_path)
     #Inicializo el usuario
     if self.__actividad_compartida:
         self.__usuario = User(
             main_path,
             write_path,
             lugar_inicial=self.__club.get_shared_initial_room())
         self.__paso_introduccion = True
         self.change_context(PLAY)
     else:
         self.__usuario = User(
             main_path,
             write_path,
             lugar_inicial=self.__club.get_alone_initial_room())
         self.__paso_introduccion = False
     #Seteo la configuracion del club a los valores del estado actual del usuario
     self.__estado_actual = self.__usuario.get_state()
     self.__club.set_current_state(self.__estado_actual)
     self.__keys.enable_keys(self.__usuario.get_context())
     #Iniciliazo el administrador de navegacion
     self.__navegacion_manager = NavigationManager(self, write_path)
     #Iniciliazo el administrador de dialogos
     self.__dialogo_manager = DialogueManager(engine=self,
                                              main_path=main_path,
                                              write_path=write_path)
     self.__events = Events()
     self.__accion = {}
     self.__path_archivo_juegos = main_path + "/data/games.xml"
     self.__show_club_introduction()
     self.__juego_mesh = False
Ejemplo n.º 10
0
def setAPIKey(request):

    if all(k in request.GET for k in ('key_name', 'key_value')):

        # get user parameters
        keyName = request.GET.get('key_name')
        keyValue = request.GET.get('key_value')

    # set key
    Keys.setKey(keyName, keyValue)
Ejemplo n.º 11
0
    def test_collide_from_left(self):
        '''
        Player collides with food from left, by moving right.
        Verify that player's got_food changes to True, x position changes, and
        score increments.

        Map before collision:
        wwwwwwwwwwwwwwwwwwww
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w00000000pf00000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        wwwwwwwwwwwwwwwwwwww
        '''
        Keys.reset()
        food_row = 10
        food_col = 10
        world = World(food_row, food_col)
        player = Player(world)
        player_row = 10
        player_col = 9
        player_y = StationaryTile.DIMS[1] * player_row
        player_x = StationaryTile.DIMS[0] * (player_col + 1) - \
                MovingTile.DIMS[0]
        player.position = (player_x, player_y)
        Keys.set_right()

        new_x = player.position[0] + MovingTile.HORIZ_SPEED
        new_y = player.position[1]
        new_dead = player.dead
        new_got_food = True
        new_score = player.score + 1

        player.do_something()

        self.assertEqual(new_x, player.position[0])
        self.assertEqual(new_y, player.position[1])
        self.assertEqual(new_dead, player.dead)
        self.assertEqual(new_got_food, player.got_food)
        self.assertEqual(new_score, player.score)
Ejemplo n.º 12
0
    def test_collide_from_right(self):
        '''
        Player collides with wall from right, by moving left.
        Verify that player's dead changes to True and x position changes.

        Map before collision:
        wwwwwwwwwwwwwwwwwwww
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000f00000000w
        w000000000000000000w
        w000000000wp0000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        wwwwwwwwwwwwwwwwwwww
        '''
        Keys.reset()
        food_row = 8
        food_col = 10
        world = World(food_row, food_col)
        world.grid[10][10] = Wall(10, 10)
        player = Player(world)
        player_row = 10
        player_col = 11
        player_y = StationaryTile.DIMS[1] * player_row
        player_x = StationaryTile.DIMS[0] * player_col
        player.position = (player_x, player_y)
        Keys.set_left()

        new_x = player.position[0] - MovingTile.HORIZ_SPEED
        new_y = player.position[1]
        new_dead = True
        new_got_food = player.got_food
        new_score = player.score

        player.do_something()

        self.assertEqual(new_x, player.position[0])
        self.assertEqual(new_y, player.position[1])
        self.assertEqual(new_dead, player.dead)
        self.assertEqual(new_got_food, player.got_food)
        self.assertEqual(new_score, player.score)
Ejemplo n.º 13
0
def copyAssetsToS3(s3conn):

    s3conn = S3Connection(Keys.getKey(S3_ACCESS_KEY), Keys.getKey(S3_SECRET_KEY), is_secure=False)

    # assets
    assetList = [

        # sprite
        'http://static.gamedex.net/images/sprites.png',

        # images
        'http://static.gamedex.net/images/bg_tile.png',
        'http://static.gamedex.net/images/bg_tile_light.png',
        'http://static.gamedex.net/images/bg_tile_light2.png',
        'http://static.gamedex.net/images/chosen-sprite.png',
        'http://static.gamedex.net/images/glyphicons-halflings-white.png',
        'http://static.gamedex.net/images/glyphicons-halflings.png',
        'http://static.gamedex.net/images/guide1.png',
        'http://static.gamedex.net/images/guide2.png',
        'http://static.gamedex.net/images/guide3.png',
        'http://static.gamedex.net/images/header_tile.png',
        'http://static.gamedex.net/images/jquery.ui.stars.gif',
        'http://static.gamedex.net/images/loading_bar.gif',
        'http://static.gamedex.net/images/logo.png',
        'http://static.gamedex.net/images/logo_small.png',
        'http://static.gamedex.net/images/no_selection_placeholder.png',
        'http://static.gamedex.net/images/select2.png',
        'http://static.gamedex.net/images/site_description.png',
        'http://static.gamedex.net/images/site_features.png',
        'http://static.gamedex.net/images/site_features_detail.png',
        'http://static.gamedex.net/images/title_bar_center.png',
        'http://static.gamedex.net/images/title_bar_dark_center.png',
        'http://static.gamedex.net/images/title_bar_dark_left.png',
        'http://static.gamedex.net/images/title_bar_dark_right.png',
        'http://static.gamedex.net/images/title_bar_left.png',
        'http://static.gamedex.net/images/title_bar_right.png',
        'http://static.gamedex.net/images/video-js.png',

        # css
        'http://static.gamedex.net/css/bootstrap.css',
        'http://static.gamedex.net/css/gamedex.css',

        # scripts
        'http://static.gamedex.net/dist/scripts.min.js',

    ]

    # iterate urls and copy to s3
    for url in assetList:
        copyUrlToS3(url, s3conn)

    return HttpResponse('done', mimetype='text/html')
Ejemplo n.º 14
0
    def test_collide_from_bot(self):
        '''
        Player collides with food from bottom, by moving up.
        Verify that player's got_food changes to True, y position changes, and
        score increments.

        Map before collision:
        wwwwwwwwwwwwwwwwwwww
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000f00000000w
        w000000000p00000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        wwwwwwwwwwwwwwwwwwww
        '''
        Keys.reset()
        food_row = 10
        food_col = 10
        world = World(food_row, food_col)
        player = Player(world)
        player_row = 11
        player_col = 10
        player_y = StationaryTile.DIMS[1] * player_row
        player_x = StationaryTile.DIMS[0] * player_col
        player.position = (player_x, player_y)

        new_x = player.position[0]
        new_y = player.position[1] - MovingTile.VERT_SPEED
        new_dead = player.dead
        new_got_food = True
        new_score = player.score + 1

        player.do_something()

        self.assertEqual(new_x, player.position[0])
        self.assertEqual(new_y, player.position[1])
        self.assertEqual(new_dead, player.dead)
        self.assertEqual(new_got_food, player.got_food)
        self.assertEqual(new_score, player.score)
Ejemplo n.º 15
0
    def __init__(self):  #Constructor

        keys = Keys()
        [consumer_key, consumer_secret, access_token,
         access_token_secret] = keys.get_keys()

        try:
            #Creating OAuth Handler Object
            self.auth = OAuthHandler(consumer_key, consumer_secret)
            self.auth.set_access_token(access_token, access_token_secret)
            self.api = tweepy.API(self.auth)
        except:
            print("Error : Authentication Failed")
Ejemplo n.º 16
0
def setAPIKey(request):

    if all(k in request.GET for k in ('name', 'value')):

        # get user parameters
        key_name = request.GET.get('name')
        key_value = request.GET.get('value')

        # set key
        Keys.set_key(key_name, key_value)

        return HttpResponse(json.dumps({'status': 'success'}), mimetype='application/json')
    else:
        return HttpResponse(json.dumps({'status': 'missing_param'}), mimetype='application/json', status='400')
Ejemplo n.º 17
0
def published(page, status, authtoken):
    url = 'http://api.buscape.com.br/product/search/?page='
    import ipdb
    ipdb.set_trace()
    keys = Keys()
    custom_header = {"auth-token": authtoken, "app-token": keys.app_token}

    file = codecs.open(status + ' - ' + custom_header['auth-token'] + '.txt',
                       'a+b', 'utf-8')
    request = requests.get(url + str(page), headers=custom_header)
    buscape = json.loads(str(request.content))

    for i in buscape['products']:
        if i['summary']['status'] == status:

            # import ipdb; ipdb.set_trace()
            file.write("SKU: " + i['productDataSent']['sku'] + '\n')
            file.write("Produto: " + i["productDataSent"]["title"] + '\n')
            file.write("Estoque: " + str(i["productDataSent"]["quantity"]) +
                       '\n')

            file.write("__________________________________________\n")
            print i['productDataSent']['title'] + '...'

            global COUNT
            COUNT += 1
    if (page < buscape["totalPages"]):
        published(page + 1, status, authtoken)
    else:
        #import ipdb; ipdb.set_trace()
        file.write('TOTAL: ' + str(COUNT))
        file.close()
Ejemplo n.º 18
0
	def __init__(self):

		memcache_key = "secretsquirrel"
		data = memcache.get(memcache_key);

		if data is not None:
			conKey, conSec, cbURL, c2dmKey = data.split('|', 4)
			self.conKey   = conKey.encode('utf8')
			self.conSec   = conSec.encode('utf8')
			self.cbURL    = cbURL.encode('utf8')
			self.c2dmKey  = c2dmKey.encode('utf8')
			return
		
#		logging.info("secretsquirrel was not in memcache")

		# didn't find one
		keys = Keys.gql(""" LIMIT 1 """).get()

		if not keys:
			# still didn't fine one
			logging.error("Couldn't find the f*****g squirrel")
			raise Exception, "Couldn't find the f*****g squirrel"

		token = keys.conKey + "|" + keys.conSec + "|" + keys.cbURL + "|" + keys.c2dmKey
		memcache.set(memcache_key, token)

		self.conKey  = keys.conKey.encode('utf8')
		self.conSec  = keys.conSec.encode('utf8')
		self.cbURL   = keys.cbURL.encode('utf8')
		self.c2dmKey = keys.c2dmKey.encode('utf8')
Ejemplo n.º 19
0
 def __init__(self, owner=None, prevhash=None):
     self.blockNo = 0
     self.next = None
     self.hash = None
     self.difficulty = 0
     self.nonce = 0
     self.prevhash = prevhash
     self.timestamp = int(time.time())
     self.keys = None
     self.tx = []
     if not owner:
         # generate keys
         self.keys = Keys(False)
         self.keys.genkey()
         self.owner = self.keys.keys[0][1].x
         self.keys.saveToFile("blockkeys/")
Ejemplo n.º 20
0
    def do_GET(self):
        req = urllib.parse.urlparse('http://localhost:8080' + self.path)
        query = req.query

        if query:
            vals = urllib.parse.parse_qs(query)
            print('Access Token: {}\nAccess Token Secret: {}'.format(
                vals['oauth_token'][0], vals['oauth_verifier'][0]))
            exit()

        else:
            keys = Keys()
            auth = tweepy.OAuthHandler(keys.consumer_token,
                                       keys.consumer_secret,
                                       'http://127.0.0.1:8080')

            try:
                redirect_url = auth.get_authorization_url()

                self.send_response(307)
                self.send_header('Location', redirect_url)
                self.session_store(auth.request_token['oauth_token'])
                self.end_headers()
            except tweepy.TweepError as e:
                print(e)
Ejemplo n.º 21
0
def setAPIKey(request):

    if all(k in request.GET for k in ('name', 'value')):

        # get user parameters
        key_name = request.GET.get('name')
        key_value = request.GET.get('value')

        # set key
        Keys.set_key(key_name, key_value)

        return HttpResponse(json.dumps({'status': 'success'}),
                            mimetype='application/json')
    else:
        return HttpResponse(json.dumps({'status': 'missing_param'}),
                            mimetype='application/json',
                            status='400')
Ejemplo n.º 22
0
    def _keyAllowed(key):
        if isinstance(key, int):
            key = Keys.getKey(key)

        if not key in Keys:
            return False

        return Keyboard.Enabled
Ejemplo n.º 23
0
    def test_no_action(self):
        '''
        Player does not collide with any object and moves from default Keys.up.
        Verify that player variables are unchanged except y position.

        Map:
        wwwwwwwwwwwwwwwwwwww
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000f00000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        w0000p0000000000000w
        w000000000000000000w
        w000000000000000000w
        w000000000000000000w
        wwwwwwwwwwwwwwwwwwww
        '''
        Keys.reset()
        food_row = 10
        food_col = 10
        world = World(food_row, food_col)
        player = Player(world)

        new_x = player.position[0]
        new_y = player.position[1] - MovingTile.VERT_SPEED
        new_dead = player.dead
        new_got_food = player.got_food
        new_score = player.score

        player.do_something()

        self.assertEqual(new_x, player.position[0])
        self.assertEqual(new_y, player.position[1])
        self.assertEqual(new_dead, player.dead)
        self.assertEqual(new_got_food, player.got_food)
        self.assertEqual(new_score, player.score)
Ejemplo n.º 24
0
def testShoot():
    time.sleep(3)
    #    GTAMovement.shoot()
    keys = Keys()
    keys.directMouse(buttons=keys.mouse_lb_press)
    time.sleep(3)
    keys.directMouse(buttons=keys.mouse_lb_release)
Ejemplo n.º 25
0
    def main_loop (self):

        self.header = HeaderWidget()
        foot = help_bar()
        self.listbox = self.select_current_timeline().timeline
        self.main_frame = urwid.Frame(urwid.AttrWrap(self.listbox, 'body'), header=self.header, footer=foot)
        key_handle = Keys()
        urwid.connect_signal(key_handle, 'help_done', self.help_done)
        self.loop = urwid.MainLoop(self.main_frame, palette, unhandled_input=key_handle.keystroke)
        update = UpdateThread()
        update.start()
        self.loop.run()
        update._Thread__stop()
        update.stop()
Ejemplo n.º 26
0
def predict():
    keys = Keys()
    model = load_model(_MODEL_NAME)
    paused = False
    for frame in record_screen(resize=(_HEIGHT, _WIDTH)):
        if not paused:
            np_frame = np.array([frame])
            prediction = model.predict(np_frame)[0]

            if debug:
                print(prediction)

            move = [0, 1, 0]
            if prediction[1] > fwd_thresh:
                move = [0, 1, 0]
            elif prediction[0] > turn_thresh:
                move = [1, 0, 0]
            elif prediction[2] > turn_thresh:
                move = [0, 0, 1]

            execute_input(move)

        if "T" in keys.check():
            if paused:
                paused = False
                print("Resuming...")
                time.sleep(1)
            else:
                paused = True
                execute_input([0, 0, 0])
                print("Paused")
                time.sleep(1)
        elif "Q" in keys.check():
            execute_input([0, 0, 0])
            print("Exiting...")
            break
Ejemplo n.º 27
0
 def handle(self, *args, **options):
     start = options["start"]
     end = options["end"]
     self.polygon = PolygonInterface(Keys())
     for page_num in list(range(start, end)):
         tickers = self.polygon.get_polygon_company_list(page=page_num)
         for ticker in tickers:
             try:
                 company = CompanyModel(
                     ticker=ticker["ticker"],
                     name=ticker["name"],
                     market=ticker["market"],
                     locale=ticker["locale"],
                     active=ticker["active"],
                 )
                 company.save()
             except IntegrityError:
                 pass
Ejemplo n.º 28
0
def run_game():
    """ The main function"""
    # Initialize the game and create a screen object.
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption('Houtou Project')
    screen_sprite = Sprite()
    screen_sprite.rect = screen.get_rect()
    keys = Keys()

    # Create the player with her bullet group.
    player = Player(screen)
    # Create the list of enemies.
    enemies = []
    # Load the enemies.
    enemy_repo = EnemyRepo(screen)

    bullets_list = []

    # Initialize the clock.
    clock = Clock()
    ticks = 0

    # Start the main loop.
    while True:
        gf.check_events(player, keys)
        gf.check_ticks(ticks, enemies, enemy_repo)
        # Update the player and the enemies.
        player.update()
        for enemy in enemies.copy():
            if enemy.update(player):
                enemies.remove(enemy)
            enemy.check_ticks(player)
        # Update the bullets.
        bullets_list = gf.get_bullets_list(player, enemies)
        gf.update_bullets(screen_sprite, bullets_list)
        # Update the screen.
        gf.update_screen(screen, settings, player, enemies, bullets_list)
        clock.tick(settings.fps)
        ticks += 1
Ejemplo n.º 29
0
    def __init__(self, name, region, size, image, ssh_keys, backups=False, ipv6=False, private_networking=False, user_data=None):
        self.name = name
        self.region = region
        self.size = size
        self.image = image
        self.ssh_keys_name = ssh_keys
        self.backups = backups
        self.ipv6 = ipv6
        self.private_networking = private_networking
        self.user_data = user_data

        self.token = Token('token.json')
        self.token_write = self.token.get_token()

        self.keys = Keys(self.ssh_keys_name)
        self.key_id = self.keys.get_keys_id()

        self.url = "https://api.digitalocean.com/v2/droplets"
        self.headers = {'Content-Type': 'application/json',
                        'Authorization': 'Bearer %s' % self.token_write}
Ejemplo n.º 30
0
def download_tweets(handles, recover=False):
    keys = Keys()

    auth = tweepy.OAuthHandler(keys.consumer_token, keys.consumer_secret)
    auth.set_access_token(keys.access_token, keys.access_token_secret)

    api = tweepy.API(auth, wait_on_rate_limit=True)

    text = []

    if recover:
        text = pd.read_csv('tweets.csv', header=None,
                           squeeze=True).values.tolist()

    for handle in handles:
        print(f'Downloading tweets for {handle}...')
        try:
            tweets = tweepy.Cursor(api.user_timeline,
                                   id=handle,
                                   tweet_mode='extended').items()
        except TweepError as e:
            print(e)

        for tweet in tweets:
            if hasattr(tweet, 'retweeted_status'):
                try:
                    text.append(
                        clean(tweet.retweeted_status.
                              extended_tweet['full_text']))
                except AttributeError:
                    text.append(clean(tweet.retweeted_status.full_text))
            else:
                try:
                    text.append(clean(tweet.extended_tweet['full_text']))
                except AttributeError:
                    text.append(clean(tweet.full_text))

        print(f'Saving tweets for {handle}...')
        pd.DataFrame(text).to_csv('./tweets.csv', header=None, index=None)
Ejemplo n.º 31
0
 def __init__(self, main_path="", write_path="", video="", audio="", malla="", actividad_compartida=False):
     if main_path == "":
         raise Exception("Error!, engine necesita el path al directorio principal de la aplicacion para funcionar (Class Engine)")
     if video == "" or audio == "" or malla == "":
         raise Exception("Error!, engine necesita Audio, Video y Malla para funcionar (Class Engine)")
     self.__main_path = main_path
     self.__write_path = write_path
     #Iniciliazo el Audio y Video
     self.__video = video
     self.__audio = audio
     self.__malla = malla
     self.__actividad_compartida = actividad_compartida
     self.__audio.on_channel()
     #Inicializo las teclas
     self.__keys = Keys(main_path)
     #Iniciliazo el club (habitaciones)
     self.__club = Club(main_path)
     #Inicializo el usuario
     if self.__actividad_compartida:
         self.__usuario = User(main_path,write_path,lugar_inicial=self.__club.get_shared_initial_room())
         self.__paso_introduccion = True
         self.change_context(PLAY)
     else:
         self.__usuario = User(main_path,write_path,lugar_inicial=self.__club.get_alone_initial_room())
         self.__paso_introduccion = False
     #Seteo la configuracion del club a los valores del estado actual del usuario
     self.__estado_actual = self.__usuario.get_state()
     self.__club.set_current_state(self.__estado_actual)
     self.__keys.enable_keys(self.__usuario.get_context())
     #Iniciliazo el administrador de navegacion
     self.__navegacion_manager = NavigationManager(self, write_path)
     #Iniciliazo el administrador de dialogos
     self.__dialogo_manager = DialogueManager(engine=self,main_path=main_path,write_path=write_path)
     self.__events = Events()
     self.__accion = {}
     self.__path_archivo_juegos = main_path+"/data/games.xml"
     self.__show_club_introduction()
     self.__juego_mesh = False
Ejemplo n.º 32
0
class DropletCreate:

    def __init__(self, name, region, size, image, ssh_keys, backups=False, ipv6=False, private_networking=False, user_data=None):
        self.name = name
        self.region = region
        self.size = size
        self.image = image
        self.ssh_keys_name = ssh_keys
        self.backups = backups
        self.ipv6 = ipv6
        self.private_networking = private_networking
        self.user_data = user_data

        self.token = Token('token.json')
        self.token_write = self.token.get_token()

        self.keys = Keys(self.ssh_keys_name)
        self.key_id = self.keys.get_keys_id()

        self.url = "https://api.digitalocean.com/v2/droplets"
        self.headers = {'Content-Type': 'application/json',
                        'Authorization': 'Bearer %s' % self.token_write}

    def create(self):
        droplet = {}
        droplet["name"] = self.name
        droplet["region"] = self.region
        droplet["size"] = self.size
        droplet["image"] = self.image
        droplet["ssh_keys"] = self.key_id
        droplet["backups"] = self.backups
        droplet["ipv6"] = self.ipv6
        droplet["user_data"] = self.user_data
        droplet["private_networking"] = self.private_networking

        response = requests.post(self.url, data=json.dumps(droplet, ensure_ascii=False), headers=self.headers)
        return response.status_code, response.json()
Ejemplo n.º 33
0
which can be found here: https://botometer.iuni.iu.edu/#!/ and https://github.com/IUNetSci/botometer-python.

In order to use this tool, make sure that all of the dependencies listed in
requirements.txt have been installed, and then use it as so:

python bot_score.py handle

You don't need to (and shouldn't) include the `@` in the handle.
'''

import botometer
import argparse

from keys import Keys

keys = Keys()


def run(handle):
    rapidapi_key = keys.rapidapi_key
    twitter_app_auth = {
        'consumer_key': keys.consumer_token,
        'consumer_secret': keys.consumer_secret,
        'access_token': keys.access_token,
        'access_token_secret': keys.access_token_secret
    }

    bom = botometer.Botometer(wait_on_ratelimit=True,
                              rapidapi_key=rapidapi_key,
                              **twitter_app_auth)
Ejemplo n.º 34
0
 def test_list(self):
     con = Connection("http://127.0.0.1:9888")
     key_list = Keys.list(con)
     for key in key_list:
         print(key.alias, key.xpub, key.file)
     self.assertIsNotNone(key_list)
Ejemplo n.º 35
0
 def test_reset_password(self):
     con = Connection("http://127.0.0.1:9888")
     xpub = Keys.find_by_alias(con, "sheng").xpub
     print(xpub)
     status = Keys.reset_password(con, xpub, "567890", "123456")
     self.assertIs("true", status)
from keys import Keys
key = Keys()
AMQP_url = key.getAMQP_URL()

print(AMQP_url)
Ejemplo n.º 37
0
from api_token import Token
from keys import Keys
from droplet_create import DropletCreate

token = Token('token.json')
token_write = token.get_token()
token_read = token.get_token_read()

keys = Keys('bert')
key_dict = keys.get_keys_id()

droplet = DropletCreate("test", "ams2", "512mb", "ubuntu-14-04-x64", "bert")
vm = droplet.create()

print token_write
print token_read
print key_dict
print vm

Ejemplo n.º 38
0
 def __init__(self):
     self.polygon = PolygonInterface(Keys())
Ejemplo n.º 39
0
class Engine():
    def __init__(self, main_path="", write_path="", video="", audio="", malla="", actividad_compartida=False):
        if main_path == "":
            raise Exception("Error!, engine necesita el path al directorio principal de la aplicacion para funcionar (Class Engine)")
        if video == "" or audio == "" or malla == "":
            raise Exception("Error!, engine necesita Audio, Video y Malla para funcionar (Class Engine)")
        self.__main_path = main_path
        self.__write_path = write_path
        #Iniciliazo el Audio y Video
        self.__video = video
        self.__audio = audio
        self.__malla = malla
        self.__actividad_compartida = actividad_compartida
        self.__audio.on_channel()
        #Inicializo las teclas
        self.__keys = Keys(main_path)
        #Iniciliazo el club (habitaciones)
        self.__club = Club(main_path)
        #Inicializo el usuario
        if self.__actividad_compartida:
            self.__usuario = User(main_path,write_path,lugar_inicial=self.__club.get_shared_initial_room())
            self.__paso_introduccion = True
            self.change_context(PLAY)
        else:
            self.__usuario = User(main_path,write_path,lugar_inicial=self.__club.get_alone_initial_room())
            self.__paso_introduccion = False
        #Seteo la configuracion del club a los valores del estado actual del usuario
        self.__estado_actual = self.__usuario.get_state()
        self.__club.set_current_state(self.__estado_actual)
        self.__keys.enable_keys(self.__usuario.get_context())
        #Iniciliazo el administrador de navegacion
        self.__navegacion_manager = NavigationManager(self, write_path)
        #Iniciliazo el administrador de dialogos
        self.__dialogo_manager = DialogueManager(engine=self,main_path=main_path,write_path=write_path)
        self.__events = Events()
        self.__accion = {}
        self.__path_archivo_juegos = main_path+"/data/games.xml"
        self.__show_club_introduction()
        self.__juego_mesh = False

    def get_user(self):
        return self.__usuario

    def get_audio(self):
        return self.__audio

    def get_video(self):
        return self.__video

    def get_club(self):
        return self.__club

    def get_keys(self):
        return self.__keys

    def get_dialog_manager(self):
        return self.__dialogo_manager

    def get_navigation_manager(self):
        return self.__navegacion_manager

    def set_action(self, metodo, parametros=""):
        self.__accion = {"metodo":metodo,"parametros":parametros}

    def on_play_mesh_game(self):
        self.__juego_mesh = True

    def off_play_mesh_game(self):
        self.__juego_mesh = False

    def init_game(self, nombre, con_jugadas_posibles=True, nivel=Ai.FACIL):
        parser = Parser()
        archivo_juegos = open(os.path.abspath(self.__path_archivo_juegos))
        elementos = parser.find_child_element("game_"+str(nombre),archivo_juegos)
        fichas_iniciales = []
        if len(elementos) <= 0 :
            raise Exception("No se encontraron elementos para el juego: " + nombre + " en el archivo xml: " + self.__path_archivo_juegos)
        for e in elementos:
            if e.get_name() == 'features':
                board_dim = int(e.get_attribute('board'))
                if e.get_attribute('oponent') == "virtual":
                    #Es un juego de mesh contra Humano
                    jugador1 = Player(BLANCO,HUMANO)
                    jugador2 = Player(NEGRO,VIRTUAL)
                else:
                    #Es un juego contra la PC
                    if e.get_attribute('white') == "user":
                        jugador1 = Player(BLANCO,HUMANO)
                        jugador2 = Player(NEGRO,PC)
                    else:
                        jugador1 = Player(BLANCO,PC)
                        jugador2 = Player(NEGRO,HUMANO)
                if e.get_attribute('initiator') == "white":
                    comienza = BLANCO
                else:
                    comienza = NEGRO
            elif e.get_name() == 'piece':
                ficha = {}
                if e.get_attribute('color') == "black":
                    ficha["color"] = NEGRO
                else:
                    ficha["color"] = BLANCO
                ficha["posicion"] = (int(e.get_attribute('pos_f')),int(e.get_attribute('pos_c')))
                fichas_iniciales.append(ficha)
        tablero_logico = Board(board_dim)
        if nombre == "tutorial1":
            tablero_logico.save_initial_configuration(fichas_iniciales)
        else:
            tablero_logico.set_up(fichas_iniciales)
        self.__video.create_graphic_board(tablero_logico)
        self.juego = Game(self.__video.board,jugador1,jugador2,con_jugadas_posibles,nivel,write_path=self.__write_path)
        if comienza == BLANCO:
            self.juego.set_turn(jugador1)
        else:
            self.juego.set_turn(jugador2)
        self.juego.increase_turn_number()
        if nombre == "mesh":
            self.juego.set_mesh_game(True)
            self.__usuario.set_player(jugador1)
        parser.close()
        archivo_juegos.close()

    def setup_game(self, config, nombre=""):
        tablero_logico = Board(config["tablero"]["dimension"])
        tablero_logico.set_casillas(config["tablero"]["configuracion"])
        tablero_logico.update_pieces_counters()
        self.__video.create_graphic_board(tablero_logico)
        jugador1 = Player(config["jugadores"][0]["color"],VIRTUAL)
        jugador2 = Player(config["jugadores"][1]["color"],HUMANO)
        self.juego = Game(self.__video.board,jugador1,jugador2,write_path=self.__write_path)
        self.juego.set_turn(jugador1)
        self.juego.increase_turn_number()
        if nombre == "mesh":
            self.juego.set_mesh_game(True)
            self.__usuario.set_player(jugador2)

    def __show_club_introduction(self):
        self.__video.club.show_room(self.__usuario.get_current_room())
        if not self.__actividad_compartida:
            self.__audio.play_voice_sound("club","voz_inicio")

    def __join_the_club(self):
        self.__audio.play_fx_sound("club","pasos")
        nueva_hab = self.__usuario.get_current_room().get_up_room()
        self.__paso_introduccion = True
        self.__usuario.set_current_room(nueva_hab)
        if self.__usuario.get_state().is_initial_state():
            self.__video.club.move_to_another_floor(nueva_hab,ARRIBA,extra="introduccion")
            self.change_context(DIAL)
        else:
            self.__video.club.move_to_another_floor(nueva_hab,ARRIBA)
            self.change_context(NAVE)
        self.__begin_game()

    def change_context(self, nuevo_contexto):
        self.__usuario.set_context(nuevo_contexto)
        self.__keys.enable_keys(nuevo_contexto)

    def __begin_game(self):
        self.__run_state_events()

    def __run_state_events(self):
        #Verificar si existe algun evento para el estado actual y ejecutarlo
        eventos_iniciales = self.__estado_actual.get_state_events()
        for evento in eventos_iniciales:
            #thread.start_new_thread(self.__events.run_events,(self, eventos_iniciales))
            self.__events.run_event(self, evento)

    def change_state(self, nuevo_estado):
        self.__usuario.set_state(nuevo_estado)
        self.__estado_actual = self.__usuario.get_state()
        self.__club.set_current_state(self.__estado_actual)
        self.__run_state_events()


    def arrive_input(self, accion):
        if not self.__keys.is_enable(accion):
            self.__audio.play_disabled_key_sound()
        else:
            if accion == SALIR:
                if self.__actividad_compartida:
                    self.__actividad_compartida = False
                    self.__malla.remove_me()
                self.__navegacion_manager.exit_club()
            else:
                if self.__paso_introduccion:
                    if self.__usuario.get_context() == NAVE:
                        self.__audio.play_key_sound(accion)
                        self.__make_nav_action(accion)
                    elif self.__usuario.get_context() == DIAL:
                        if not self.__usuario.interrupt_dialogue():
                            if self.__audio.get_sound_name() == "more_text":
                                self.__audio.play_key_sound(accion)
                                self.__make_dialog_action(accion)
                            else:
                                self.__audio.play_disabled_key_sound()
                        else:
                            self.__audio.play_key_sound(accion)
                            self.__make_dialog_action(accion)
                    elif self.__usuario.get_context() == PLAY:
                        if not self.__usuario.interrupt_sounds() and self.__audio.get_sound_group_name() == "inicio_turno":
                            self.__audio.play_disabled_key_sound()
                        else:
                            self.__audio.play_key_sound(accion)
                            self.__make_play_action(accion)
                    elif self.__usuario.get_context() == LIST:
                        self.__audio.play_key_sound(accion)
                        self.__make_list_action(accion)
                else:
                    self.__audio.play_key_sound(accion)
                    if accion == CONTINUAR:
                        self.__join_the_club()

    def __make_nav_action(self, accion):
        if accion == CONTINUAR:
            hab_sel = self.__club.room_selected()["habitacion"]
            pos_hab_sel = self.__club.room_selected()["posicion"]
            if hab_sel != "":
                if hab_sel.is_available():
                    self.__navegacion_manager.enter_room(hab_sel, pos_hab_sel)
                    if not hab_sel.is_floor():
                    #Es una habitacion
                        if hab_sel.get_name() != "salon de encuentros" and hab_sel.get_name() != "secretaria":
                            self.change_context(DIAL)
                            per_duenho = hab_sel.get_owner()
                            per_duenho.init_room_action(self)
                            self.__accion = {"metodo":per_duenho.close_action,"parametros":(self)}
                        else:
                            if hab_sel.get_name() == "salon de encuentros":
                                try:
                                    ps = olpcgames.ACTIVITY._pservice
                                    self.__audio.play_voice_sound("club","ingresando a la red")
                                    ps.get_activities_async(reply_handler=self._share_join_activity_cb)
                                except Exception, e:
                                    log.debug('Error: ' + str(e) + '. Al intentar usar el presence service (Engine Class)')
                                    self.__audio.play_voice_sound("club","error de conexion")
                                    self.__audio.play_voice_sound("club","saliendo salon desafios")
                                    self.__navegacion_manager.leave_room()
                            elif hab_sel.get_name() == "secretaria":
                                self.change_context(LIST)
                                self.__video.create_selection_list(titulo="OPCIONES DE SECRETARIA",tipo="secretaria")
                                progreso = self.__usuario.get_game_progress()
                                hash_medallas = self.__usuario.get_medals()
                                total_medallas = hash_medallas["bronce"] + hash_medallas["plata"] + hash_medallas["oro"]
                                str_medallas = str(hash_medallas["bronce"])+" BR  "+str(hash_medallas["plata"])+" PL  "+str(hash_medallas["oro"])+" OR  "+str(total_medallas)+" TOT"
                                self.__video.selection_list.add_options([{"descripcion":"Progreso del Juego: "+str(progreso)+"%","id":"progreso_juego-"+str(progreso),"visible":True},{"descripcion":"Medallas: "+str_medallas, "id":"medallas_obtenidas-"+str(hash_medallas["bronce"])+"."+str(hash_medallas["plata"])+"."+str(hash_medallas["oro"]),"visible":True}])
                                self.__video.show_selection_list()
                                self.__audio.play_voice_sound("club","secretaria intro")
                                self.__audio.play_voice_sound("club","secretaria desc")
                                self.__audio.play_voice_sound("club","secretaria info")
                                self.__audio.play_fx_sound("otros","wait_input")
                                self.__video.selection_list.read_option(self.__audio)
                            else:
                                log.error("Nombre de habitacion desconocido! (Engine Class)")
                else:
                    if not hab_sel.is_floor():
                        if hab_sel.get_owner() != "":
                            self.__audio.play_voice_sound("club","bloqueo_acceso_pieza_vocal")
                        else:
                            if hab_sel.get_name() == "salon de encuentros":
                                self.__audio.play_voice_sound("club","bloqueo_acceso_salon_encuentros")
                            else:
                                self.__audio.play_voice_sound("club","bloqueo_acceso_pieza_gral")
                        self.__audio.wait_sound_end()
                        self.__video.club.end_door_animation()
                self.__club.select_room("","")
            elif self.__club.get_elevator()["seleccionado"]:
                if not self.__navegacion_manager.go_to_floor():
                    if self.__usuario.get_state().get_name() == "state1" and self.__usuario.get_current_room().get_name() == "segundo piso":
                        pm = self.__club.get_character_by_name("pedro madera")
                        self.change_context(DIAL)
                        pm.block_third_floor_access(self)
                        self.__accion = {"metodo":pm.close_action,"parametros":(self)}
                    elif self.__usuario.get_current_room().get_name() == "tercer piso":
                        hash_medallas = self.__usuario.get_medals()
                        total_medallas = hash_medallas["bronce"] + hash_medallas["plata"] + hash_medallas["oro"]
                        if int(total_medallas) >= 7 and int(hash_medallas["oro"]) > 0:
                            pass
                        else:
                            self.__audio.play_voice_sound("club","bloqueo_acceso_piso_4")
Ejemplo n.º 40
0
def size():
    return (ctypes.windll.user32.GetSystemMetrics(0),
            ctypes.windll.user32.GetSystemMetrics(1))


def _to_windows_coordinates(x=0, y=0):
    display_width, display_height = 1920, 1080
    # the +1 here prevents exactly mouse movements from sometimes ending up off by 1 pixel
    windows_x = (x * 65536) // display_width + 1
    windows_y = (y * 65536) // display_height + 1

    return windows_x, windows_y


ctr = Controller()
k = Keys()
HAS_PRESS = False
angle = 0
xx = 1050


def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(key.char))
    except AttributeError:
        print('special key {0} pressed'.format(key))


def on_release(key):
    try:
        print('{0} released'.format(key))
Ejemplo n.º 41
0
from tweeter import Tweeter
from freep import Freep
from keys import Keys


dalereedsay = Tweeter('dalereedsay',Keys.dalereedsay())
dalereed = Freep('dalereed', dalereedsay.mostRecent())
#print "dalereed comments:{0}".format(dalereed.newComments())
dalereedsay.postList(dalereed.newComments())
#dalereedsay.postList(dalereed.newMentions())

jimrobsay = Tweeter('jimrobsay', Keys.jimrobsay())
jimrob = Freep('jimrobinson', jimrobsay.mostRecent())
#print "jimrob comments:{0}".format(jimrob.newComments())
jimrobsay.postList(jimrob.newComments())
#jimrobsay.postList(jimrob.newMentions())