예제 #1
0
def refresh_data(sport=None):
    if sport:        
        database.clear('roster', sport)
        
        url = urllib.request.urlopen(URL['ATHLETICS_URL']
                                   + URL['SCHEDULE_PATH'] + sport)
        content = url.read().decode('utf8')
        url.close()

        soup = BeautifulSoup(content)
        schedule = soup.find_all("div", "schedule_game")
        
        scheduled_games = []
        
        for game in schedule:
            scheduled_game = ScheduledGame()
            if (game.find("div", "schedule_game_opponent_name")):
                scheduled_game.setSport(sport)
                if game.find("div", "schedule_game_opponent_name").a.span:
                    scheduled_game.setTeam(game.find("div", "schedule_game_opponent_name").a.span.string)
                else:
                    scheduled_game.setTeam(game.find("div", "schedule_game_opponent_name").get_text())
                scheduled_game.setDate(game.find("div", "schedule_game_opponent_date").string)
                scheduled_game.setTime(game.find("div", "schedule_game_opponent_time").string)
                scheduled_game.setLocation(game.find("div", "schedule_game_middle").get_text())
                scheduled_game.setTeam(game.find("div", "schedule_game_opponent_name").get_text())
                scheduled_game.setImage(game.find("div", "schedule_game_opponent_logo").img['src'])
                
                if (game.find("div", "schedule_game_results")):
                    scheduled_game.setScore(game.find("div", "schedule_game_results").contents[1].get_text())
                
                database.save(scheduled_game)
예제 #2
0
파일: shooting.py 프로젝트: hiro220/ReK
 def exit(self):
     self.data["play_time"] += pygame.time.get_ticks()
     print('-' * 50)
     print(self.data)
     db.save(self.data, self.cheat)
     pygame.quit()
     sys.exit()
예제 #3
0
def predict(inference_date):
    """
    Loads one month of inference data from a GCP bucket and runs inference using
    the locally saved model. The predictions are uploaded to GCP.

    :param inference_date: datetime object, the first day of the month to perform inference on
    """

    inference_date = inference_date.split(' ')[0]
    # load inference data from a GCP bucket as a pandas dataframe
    inference_df = db.load(f'{data_key}-inference-{inference_date}')
    # drop non-feature columns
    x_inference = inference_df.drop(['cust_id', 'date'], axis=1)

    # insert DataContract validation code here #

    ############################################

    x_inference = x_inference.fillna(0)

    # load model from local directory
    model = pickle.load(open("fitted_objects/model.pkl", "rb"))

    # run inference, and create a dataframe to store the predicted probabilities
    probs = model.predict_proba(x_inference)[:, 1]
    probs_df = pd.DataFrame(probs, columns=["predicted_churn_probability"])

    # save predictions to a GCP bucket
    db.save(f'{data_key}-predictions-{inference_date}', probs_df)
def overthrow(player):
    maxy(
        "You are a very wise one, now follow me, and together we will overthrow the king!"
    )
    you(player, "Let's go...")
    time.sleep(2)
    king_battle_with_max(player)
    time.sleep(2)
    you(player, "Now I am king...")
    maxy("Wait just a minute, I am king, you are second in command")
    you(player, "I don't wanna be second in command")
    maxy("Wait a minute, we had a deal!")
    you(player, "Not any more...")
    maxy("What do you mean? Are you going to kill me!")
    you(player, "hmm...")
    print("[1] Kill Maximus and take the throne for yourself")
    print("[2] Let Maximus live")
    choice = input()
    if choice == '1':
        player['bad_points'] += 12
        max_battle()
    elif choice == '2':
        player['good_points'] += 6
        you(player, "I'll let you live... for now")
    database.save(player)
def max_talk(player):
    from ai_talk import maxy, choice, you
    maxy("Hello there, " + player['name'] + ". You've come far... freind\n")
    you(player, "I'm here-")
    maxy(
        "Yes yes, I know you are here to kill me\nBut is that really the best option?"
    )
    maxy('You and I would make quite a team, if you would join me')
    you(player, "What are you talking about?")
    maxy(
        "The king is old and weak, he wants me dead becuase I'm a threat, I know too much, I'm too dangerous"
    )
    maxy(
        "But you don't have to kill me, we could be allies, we could join together against the king, overthrow him!"
    )
    you(player, "Um... welll")
    maxy(
        "What makes him right anyways? Becuase he's incharge. \nReally " +
        player['name'] +
        ', you think that he got his throne fairly?\nHe did the same thing I would like to to do get it!'
    )
    maxy("Now... will you join me and fight against him?")
    print("[1] Listen to Maximus | [2] Fight him now!")
    choice = input()
    if choice == '1':
        player['bad_points'] += 10
        overthrow(player)
    elif choice == '2':
        player['good_points'] += 10
        you(player, "I'm here to kill you Maximus, not to join you")
        maxy("Very well then, it appears that we will have to fight it out!")
        you(player, "As you wish... YAAAAAAH!")
    database.save(player)
예제 #6
0
async def save(client, dbFileName, message):
    accounts = utilities.unpackAccounts(message["accounts"])
    packages = utilities.unpackPackages(message["packages"])

    database.save(dbFileName, accounts, packages)

    successful = [
        entity["entity"] for entity in packages
        if entity["status"] == "success"
    ]
    print("successful               ", successful)

    await messages.respond(
        client, message, {
            "packages": [{
                "entity":
                utilities.packPackages([entity["entity"]])[0],
                **(utilities.packEntities([entity])[0])
            } for entity in packages]
        })

    changedUsernames = set([package["username"] for package in successful])
    clients2usernames = connections.getClients(changedUsernames)
    for otherClient, usernames in clients2usernames.items():
        usernames = list(usernames)
        await messages.send(otherClient, 'packages changed',
                            {'usernames': usernames})
예제 #7
0
def richiesta_soccorso_intelligente():
    user_lat = request.form.get('lat')
    user_long = request.form.get('long')

    if not user_lat or not user_long:
        abort(400)

    user_d = current_user.to_dict()

    request_to_ga = {
        'user': {
            'name': user_d.get('name'),
            'surname': user_d.get('surname'),
            'location': {
                'lat': user_lat,
                'long': user_long
            }
        }
    }
    ga_response = es_ga.nuova_richiesta_soccorso(request_to_ga)

    r_d = {
        'user_id': current_user.get_id(),
        'gestione_ambulanze_richiesta_id': ga_response.get('request_id'),
        'ambulanza_associata': ga_response.get('ambulanza_associata'),
        'data': '06/06/2018',
        'stato': 'in corso'
    }
    new_request = db.RichiestaSoccorso(r_d)
    db.save(new_request)

    return jsonify(status='SUCCESS',
                   request_id=new_request.to_dict().get('id'),
                   message='Richiesta inoltrata con successo')
예제 #8
0
def main():
  init_database()
  analytics = initialize_analyticsreporting()
  data = get_events(analytics)

  if (data):
    save(data)
def hack(player):
    while True:
        print("Welcome " + player['name'])
        print("What would you like to hack: ")
        print("[1] Add all weapons")
        print("[2] Add all shields")
        print("[3] Add all armor")
        print("[4] Add custom health")
        print("[5] Add locations")
        print("[6] Add Gold")
        print("[7] Exit hacks")
        choice = input()
        if choice == '1':
            for item in all_swords:
                player['weapons'].append(item)
        elif choice == '2':
            for item in all_shields:
                player['shields'].append(item)
        elif choice == '3':
            for item in all_armor:
                player['armors'].append(item)
        elif choice == '4':
            new_health = int(input("How much health would you like: "))
            player['life'] = new_health
        elif choice == '5':
            location = input("Location: ")
            player['unlocked_locations'].append(location)
        elif choice == '6':
            new_gold = int(input("Gold: "))
            player['gold'] += new_gold
        elif choice == '7':
            break
        database.save(player)
예제 #10
0
def signal_handler(signal, frame):
   global server
   print("Shutting Down Server")
   server.close()
   for client in clients:
      clients[client].disconnect()
   database.save()
   sys.exit(0)
예제 #11
0
def photo_apply():
    name = request.args.get("name")
    brand = request.args.get("brand")
    description = request.args.get("description")
    notes = request.args.get("notes")

    database.save(name, brand, description, notes)
    return render_template("apply_photo.html")
예제 #12
0
def create_power_colours():
    '''
    Function to generate power spectral density based on RXTE lightcurves.
    '''

    # Let the user know what's going to happen
    purpose = 'Creating Power Colours'
    print len(purpose) * '=' + '\n' + purpose + '\n' + len(purpose) * '='

    import os
    import pandas as pd
    import glob
    from collections import defaultdict
    from math import isnan
    import paths
    import logs
    import execute_shell_commands as shell
    import database

    # Set log file
    filename = __file__.split('/')[-1].split('.')[0]
    logs.output(filename)

    # Get database
    os.chdir(paths.data)
    db = pd.read_csv(paths.database)

    d = defaultdict(list)
    for ps, group in db.groupby('power_spectra'):

        # Determine parameters
        obsid = group.obsids.values[0]
        path_obsid = group.paths_obsid.values[0]
        mode = group.modes.values[0]
        res = group.resolutions.values[0]

        print obsid, mode, res

        # Calculate power colour
        output = power_colour(ps)

        if output:
            pc1, pc1err, pc2, pc2err, constraint = output

            d['power_spectra'].append(ps)
            d['pc1'].append(pc1)
            d['pc1_err'].append(pc1err)
            d['pc2'].append(pc2)
            d['pc2_err'].append(pc2err)
            d['lt3sigma'].append(constraint)

    # Update database and save
    df = pd.DataFrame(d)
    db = database.merge(db, df,
                        ['pc1', 'pc1_err', 'pc2', 'pc2_err', 'lt3sigma'])
    print 'DBNUNIQUE\n', db.apply(pd.Series.nunique)
    database.save(db)
    logs.stop_logging()
예제 #13
0
def find_channels():
    '''
    Function to determine the channel range needed for input during extraction.
    Requires the file energy_conversion_table.txt to determine the initial
    channel selection.
    '''

    purpose = 'Finding the correct channels for later extraction'
    print len(purpose) * '=' + '\n' + purpose + '\n' + len(purpose) * '='

    import os
    import pandas as pd
    import glob
    from collections import defaultdict
    import paths
    import logs
    import execute_shell_commands as shell
    import database

    # Set log file
    filename = __file__.split('/')[-1].split('.')[0]
    logs.output(filename)

    os.chdir(paths.data)
    db = pd.read_csv(paths.database)

    d = defaultdict(list)
    for obsid, group in db.groupby(['obsids']):
        group = group.drop_duplicates('paths_data')

        print obsid
        for mode, path, time, bit in zip(group.modes, group.paths_data,
                                         group.times, group.bitsize):

            if mode == 'std1':
                d['paths_data'].append(path)
                d['energy_channels'].append('INDEF')
                continue

            # Determine channels according to epoch
            abs_channels = calculated_energy_range(time, MIN_E, MAX_E, bit)
            final_channels = abs_channels

            # Check in which fashion the channels are binned, and return these
            if mode == 'event' or mode == 'binned':
                bin_channels = get_channel_range(mode, abs_channels, path, bit)
                final_channels = bin_channels

            print '   ', mode, '-->', final_channels

            d['paths_data'].append(path)
            d['energy_channels'].append(final_channels)

    # Update database and save
    df = pd.DataFrame(d)
    db = database.merge(db, df, ['energy_channels'])
    database.save(db)
    logs.stop_logging()
예제 #14
0
def fetch(artist, song, album):
    try:
        lyrics = Wikia.fetch(artist, song, album)
        if lyrics or settings.save_not_found_lyrics:
            database.save(artist, song, album, lyrics)
    except ConnectionError as e:
        lyrics = 'Could not fetch lyrics. Connection failed.'
        debug.debug('Connection error: %r'% e)
    return lyrics
def grim_quacker(player):
    duck = the_quack(
        200, 1, 50, 1, 20, ['leaps', 'quacks', 'flaps', 'wiggles', 'waddles'],
        ['strikes', 'bites', 'hits', 'smacks'],
        ['chest', 'face', 'leg', 'arm', 'eye', 'nose', 'head', 'snozzle'])
    win = False
    while not win:
        util.clear()
        print('Your life: ' + str(player['life']) + ' | Grim Quacker Life: ' +
              str(duck.life))
        print("The Grim Quacker " + random.choice(duck.t1) + ' and ' +
              random.choice(duck.t2) + ' you in the ' + random.choice(duck.t3))
        damage_full = random.randint(duck.damage_min, duck.damage_max)
        absorbed = random.randint(player['armor_min'], player['armor_max'])
        t_percent = int((absorbed / damage_full) * 100)
        print("Your armor absorbs " + str(t_percent) + '% of the damage')
        blocked = 0
        if random.randint(1, 2) == 1:
            blocked = player['shield_defense']
            percent = int((blocked / damage_full) * 100)
            print("Your shield deflects " + str(percent) + '% of the damage')
        damage_full -= (absorbed + blocked)
        print("You take " + str(damage_full) + ' damage')
        player['life'] -= damage_full
        print("You vicously attack The Grim Quacker with your " +
              player['main_weapon'])
        damage = random.randint(player['main_weapon_min'],
                                player['main_weapon_max'])
        duck_blocked = random.randint(duck.defense_min, duck.defense_max)
        pp = (duck_blocked / damage) * 100
        print('The Grim Qackers feathers absorb ' + str(int(pp)) +
              '% of the damage')
        print("You inflict " + str(damage) + ' damage')
        damage -= duck_blocked
        duck.life -= damage
        # Check for kill
        if duck.life <= 0:
            print("You defeated The Grim Quacker!")
            player['kills'].append('The Grim Quacker')
            player['monster_parts'].append('Grim Qacker Skull')
            player['weapons'].append('Lightening Blade')
            player['unlocked_locations'].append("Beggar City")
            player['gold'] += 100
            player['mission6'] = True
            database.save(player)
            print("You got a Grim Quacker Skull!")
            print("You now have a new weapon: Lightening Blade")
            print("You earned 100 Gold")
            print("You unlocked a new location: Beggar City")
            input()
            win = True
        elif player['life'] <= 0:
            print("You have been defeated...")
            input()
            win = True
        else:
            input()
예제 #16
0
def photo_apply():
    location = request.args.get("location")
    cleaness = request.args.get("clean")
    built_in = request.args.get("built")
    if cleaness is None:
        cleaness = False
    else:
        cleaness = True
    database.save(location, cleaness, built_in)
    return render_template("apply_photo.html")
예제 #17
0
def cut_xray_flares():
    '''
    Function to find X-ray flares in a light curve by finding when the rate
    exceeds more than 7sigma, and then cut around it. Write output to a file
    in an obsid-folder with the name corrected_rate_minus_xray_flare_
    <timingresolution>.dat if an X-ray flare was detected
    '''

    # Let the user know what's going to happen
    purpose = 'Determining X-ray flares'
    print len(purpose) * '=' + '\n' + purpose + '\n' + len(purpose) * '='

    import os
    import pandas as pd
    import glob
    from collections import defaultdict
    from math import isnan
    import paths
    import logs
    import execute_shell_commands as shell
    import database

    # Set log file
    filename = __file__.split('/')[-1].split('.')[0]
    logs.output(filename)

    os.chdir(paths.data)
    db = pd.read_csv(paths.database)

    d = defaultdict(list)
    for path_lc, group in db.groupby('bkg_corrected_lc'):

        # Set parameters
        obsid = group.obsids.values[0]
        path_bkg = group.rebinned_bkg.values[0]
        res = group.resolutions.values[0]
        mode = group.modes.values[0]
        path_obsid = group.paths_obsid.values[0]
        print obsid, mode, res

        # Calculate whether flare present
        result = cut_flare(path_obsid, path_lc, path_bkg, res, mode)

        if result:
            print 'Flare between:', result[2]
            d['bkg_corrected_lc'].append(path_lc)
            d['lc_no_flare'].append(result[0])
            d['bkg_no_flare'].append(result[1])
            d['flare_times'].append(result[2])

    # Update database and save
    df = pd.DataFrame(d)
    db = database.merge(db, df, ['lc_no_flare', 'bkg_no_flare', 'flare_times'])
    database.save(db)
    logs.stop_logging()
예제 #18
0
def add_to_database(member: discord.Member):
    # save the database as members
    members = database.load("data.json")
    # get the member id (string)
    nameid = str(member.id)
    # if they already exist then return
    if nameid in members:
        return
    # otherwise add them to the database with default items and save it
    else:
        members[nameid] = database.load("items.json")
        database.save(members, "data.json")
예제 #19
0
def analyze(file_in):
    """
    Returns (bpm, Key) after analyzing the given audio file
    """
    data = load(file_in)
    if data is not None:
        bpm, key, scale = data
        return bpm, Key(key, scale)
    bpm = get_bpm(file_in)
    key = get_key(file_in)
    save(file_in, bpm, key)
    return bpm, key
예제 #20
0
async def useradd(client, msg: Message):
    user = "******".join(msg.command[1:])
    if not user:
        await msg.edit("دستور وارد شده اشتباه است! \n\n شما باید یک مقدار وارد کنید... \n\n `useradd 1346338819`")
        return
    data = DATA["list"]["user"]
    if int(user) in data:
        await msg.edit("این یوزر از قبل اضافه شده است!")
        return
    DATA["list"]["user"].append(int(user))
    save()
    await msg.edit(f"کاربر [{user}](tg://user?id={user}) به لیست اضافه شد")
예제 #21
0
    def commit(self, connection):

        # Try binary first
        iq_result = {}

        try:
            iq_result = self.buy_binary(connection)

        except Exception as ex:
            logger.error(ex)

        if not iq_result.get('success', False):
            # binary did not go through. Trying digital
            try:
                iq_result = self.buy_digital(connection)

            except Exception as ex:
                logger.error(ex)

        if iq_result.get('success', False):
            # if any succeed, waits for API get ready.
            print(f'waiting thread {threading.currentThread().getName()}')
            while not self.get_async_order_response(connection,
                                                    iq_result['id']):
                time.sleep(10)
                pass

            # waits for the order to close.
            logger.debug(
                f'started thread {threading.currentThread().getName()}')
            state = 'open'
            while state != 'closed':
                try:
                    response = self.get_async_order_response(
                        connection, iq_result['id']).get('position-changed')
                    state = response.get('msg').get('status')
                except Exception as ex:
                    log.error(f'raised exception {ex}')
                    state = 'open'
            logger.debut(
                f'ended order thread {threading.currentThread().getName()}')

            # saves data back to the self
            self.set_order_response(response.get('msg'))

            response = {'message': self.to_dict()}

            # save closed order data
            database.save(self.to_dict())  #connection.get_async_order(id))
        else:
            response = iq_result.get('id')
        return response
예제 #22
0
def newspost():
    body = request.form['comment']
    uname = session.get("USERNAME")
    tstamp = now()
    unique_key = uname + ":::" + tstamp
    hist[unique_key] = {
        'user': uname,
        'name': users[uname]['name'],
        'body': body,
        'timestamp': tstamp
    }
    database.save(hist, database.CHATHISTORY)
    return redirect(url_for('index'))
예제 #23
0
async def userrem(client, msg: Message):
    user = "******".join(msg.command[1:])
    if not user:
        await msg.edit("دستور وارد شده اشتباه است! \n\n شما باید یک مقدار وارد کنید... \n\n `userrem 1346338819`")
        return
    data = DATA["list"]["user"]
    if int(user) in data:
        data.remove(int(user))
        save()
        await msg.edit(f"کاربر [{user}](tg://user?id={user}) از لیست حذف شد")
    else:
        await msg.edit("چنین ایدی وجود ندارد!")
        return
예제 #24
0
async def search(ctx, location="None"):
    if location == "None":
        await ctx.send('''Please provide a location!
        Choose from: mine, dessert, ocean, forest''')
    else:
        members = database.load("data.json")
        nameid = str(ctx.author.id)
        amount = random.randint(0, 3)
        amount2 = random.randint(0, 3)
        if location.lower().startswith("m"):
            msg = await ctx.send("```Attempting to search the mine...```")
            await asyncio.sleep(3)
            await msg.edit(
                content=
                f'''```You found {amount} rocks.\nYou found {amount2} iron.```'''
            )
            members[nameid]["items"]["rocks"] += amount
            members[nameid]["items"]["iron"] += amount2
        elif location.lower().startswith("d"):
            msg = await ctx.send("```Attempting to search the dessert...```")
            await asyncio.sleep(3)
            await msg.edit(
                content=
                f'''```You found {amount} cactus.\nYou found {amount2} cups of sand.```'''
            )
            members[nameid]["items"]["cactus"] += amount
            members[nameid]["items"]["sand"] += amount2
        elif location.lower().startswith("o"):
            msg = await ctx.send("```Attempting to search the ocean...```")
            await asyncio.sleep(3)
            await msg.edit(
                content=
                f'''```You found {amount} fish.\nYou found {amount2} cups of water.```'''
            )
            members[nameid]["items"]["fish"] += amount
            members[nameid]["items"]["water"] += amount2
        elif location.lower().startswith("f"):
            msg = await ctx.send("```Attempting to search the forest...```")
            await asyncio.sleep(3)
            await msg.edit(
                content=
                f'''```You found {amount} apples.\nYou found {amount2} sticks.```'''
            )
            members[nameid]["items"]["apples"] += amount
            members[nameid]["items"]["sticks"] += amount
        else:
            await ctx.send(
                "```Please provide a valid location!```\nChoose from: mine, dessert, ocean, forest"
            )

    database.save(members, "data.json")
def new_helper(player, a, b, c, d, e, f, g, h, i):
    "function(player, name, life, min_damage, max_damage, min_defense, max_defense, block, level, defeated_list)"
    new = {
        'name': a,
        'life': b,
        'min_damage': c,
        'max_damage': d,
        'min_defense': e,
        'max_defense': f,
        'block': g,
        'level': h,
        'defeated': i,
    }
    player['team']['helpers'].append(new)
    database.save(player)
예제 #26
0
def king(player):
	util.clear()
	if player['bad_points'] > 5:
		k("Why have you come here? I know your evil deeds!")
		t = choice('Kill him', "Tell him you are sorry for the bad things you did")
		if t == '1':
			s_print("You draw your " + player['main_weapon'])
			k("So it is treason then?")
			battle.king_fight()
		else:
			k("If you truly wish to be pardoned, you can, but you will have to pay for your crimes!")
			k("Guards, lock him in the dungeon until he has paid for his crimes!")
			util.sentence(player['bad_points'] * 3)
	
	elif player['mission1'] == False and util.count_list(player['monster_parts'], 'Kraveb Head') >= 3:
		player['mission1'] = True
		player['weapons'].append("Ice Pick")
		k("You have completed your quest! Very good, here is an Ice Pick!")
		k("It is a deadly weapon at close range against enemies, weild it with skill and you will be very strong in battle")
		player['gold'] += 25
		k("Also, here is 25 gold coins for finishing the task so fast")
		k("And now I have another mission for you!")
		time.sleep(1)
		util.clear()
		k("A fiend roams my lands, his name is Maximus the III")
		k("He claims he is the heir to this throne, although he is not, and attemps to stir the commonfolk up")
		k("I would allow you to hunt him but you have not proven yourself yet")
		k("Find and kill a Thorg, and you will be strong enough to battle him!")
	elif player['mission1'] != True:
		k("You, warrior! You seem to be strong, I have a quest for you!")
		k("Monsters plague my lands, and if you bring me the head of three kraveb, I will grant you a special weapon!")
	elif player['mission1'] == True and player['mission2'] != True and 'Thorg' in player['kills']:
		k("You are a strong warrior, for you have defeated a thorg!")
		k("Now I know you are strong enough to battle Maximus himself!")
		k("For now he is banished to the realm of monsters, here is a key to that land, but beware, it is a very dangerous place to be!")
		player['unlocked_locations'].append("Monster Lands")
		s_print("You have unlocked a new location: Monster Lands")
		player['mission2'] = True
		database.save(player)
	elif player['mission3'] == False:
		k("Go to the monsterlands, and defeat Maximus the III")
	elif player['mission3'] == True:
		k("You have defeated Maximus the III? You are more powerful then I first thought")
		k("You are very powerful, powerful enough to travel to dangerous lands")
		s_print("You unlocked a new location: Far Place")
		player['unlocked_locations'].append('Far Place')
		database.save(player)
	input()
예제 #27
0
async def save(client, dbFileName, message):
    accounts = message["accounts"]
    packages = message["packages"]
    timestamp = message["timestamp"]
    
    changes = database.save(dbFileName, accounts, packages, timestamp) 
    print(changes)
    if changes != False and len(changes) != 0:
        client2changedAccountIds = {}
        for accountId in changes:
            otherClients = connections.getClients(accountId)

            for otherClient in otherClients:
                if otherClient != client:
                    try: 
                        accountIds = client2changedAccountIds[otherClient]
                    except:
                        accountIds = set()
                    accountIds.add(accountId)
                    client2changedAccountIds[otherClient] = accountIds

        for client, accountIds in client2changedAccountIds.items():
            accountIds = list(accountIds)
            await messages.send(otherClient, 'packages changed', {
                'accountIds': accountIds
            })
예제 #28
0
async def save(client, dbFileName, message):
    accounts = utilities.unpackAccounts(message["accounts"])
    packages = utilities.unpackPackages(message["packages"])

    print("packages before          ", message["packages"])
    print("packages after         ", packages)
    successList, failedList = database.save(dbFileName, accounts, packages)

    print("successList           ", successList)
    await messages.respond(
        client, message, {
            "successful": utilities.packPackages(successList, set(["data"])),
            "failed": utilities.packPackages(failedList, set(["data"]))
        })

    changedAccountIds = set([package["accountId"] for package in successList])
    print("changedAccountIds1       ", changedAccountIds)
    print("activeClients       ", connections.activeClients())
    clients2accountIds = connections.getClients(changedAccountIds)
    print("changedAccountIds2.5     ", clients2accountIds)
    clients2accountIds.pop(client, None)
    print("changedAccountIds2       ", clients2accountIds)
    for otherClient, accountIds in clients2accountIds.items():
        accountIds = list(accountIds)
        print("accountIds           ", accountIds)
        await messages.send(otherClient, 'packages changed',
                            {'accountIds': utilities.packBlobs(accountIds)})
예제 #29
0
def main():
    
    db.start("test.db", True)
    
    brass = Material(5, "brass")
    print brass.getNames()
    iron = Material(7, "iron", "irons", "iron")
    print iron.getNames()
    
    metals = MaterialSet("metal", "metals", "metallic", [brass, iron])
#    print metals.getNames()
#    for mat in metals.getMaterials():
#        print mat.getNames()
    
    print iron.materialSet.getNames()
    
    db.save(metals)
예제 #30
0
async def save(client, dbFileName, message):
    account = message["account"]
    packages = message["packages"]
    if database.save(client, account, packages):
        otherClients = connections.getClients(account["id"])

        for otherClient in otherClients:
            await messages.send(otherClient, 'packages changed')
예제 #31
0
def mega_rat(player):
	if player['mission7'] != True:
		m("I am mega rat! I own this town and extract payments from it's citizens")
		m("Gimmeh all your money or I'll kill you in the street!")
		print("[1] Give Mega Rat all you money | [2] Kill Mega Rat")
		i = input()
		if i == '1':
			you(player, "Fine, here's all my money")
			player['gold'] = 0
			database.save(player)
			m("Ah, now that you've given me all my money? Time to die!")
			boss_fight.mega_rat(player)
		else:
			m("So you want to kill me?")
			boss_fight.mega_rat(player)
	else:
		m("Mega rat is dead, I am the new leader, Ultra Rat, you may come here in peace")
예제 #32
0
	def start(self):
		def timeout_handler(signum, frame):
			raise TimeoutException()

		signal.signal(signal.SIGALRM,timeout_handler)
		signal.alarm(self.timeout)
		for i in range(self.times):
			try:
				lang = Crawler.random_language()
				wikipedia.set_lang(lang)
				p = wikipedia.page(wikipedia.random())
				if len(p.content) > self.tolerance:
					print "reading page: ", p.title
					print "in language: ", lang
					content = Crawler._clean(p.content)
					database.save({lang : langan.analyze(content)})
			except:
				pass
예제 #33
0
def prompt_new():
    db_data, prompted = check_database(verbose = False)
    if db_data:
        if prompted:
            print('')
        print('NEW ASSIGNMENT:')
        # Prompt title
        title = safe_input(INDENT + 'Title: ')

        # Prompt course
        course_set = set()
        for assignment in db_data['assignments']:
            course_set.add(assignment['course'])
        course_list = sorted(course_set)

        print(INDENT + 'Course', end='')
        for i, course in enumerate(course_list):
            if i == 0:
                print('')
            print('{}[{}] {}'.format(INDENT * 2, i+1, course))
        course = safe_input('{}: '.format(INDENT if course_list else ''))
        globbed = False
        try:
            index = int(course)
            assert 1 <= index <= len(course_list)
            course = course_list[index-1]
            globbed = True
        except (ValueError, AssertionError) as e:
            pass

        # Prompt due date
        due_date = safe_input(INDENT + 'Due Date: ')

        # Confirm
        if globbed and db_data['settings']['confirmOnGlob']:
            print('\nCONFIRM:\n{0}Title: {1}\n{0}Course: {2}\n{0}Due Date: {3}\n'
                  .format(INDENT, title, course, due_date))
            if safe_input('(y/n) ').lower() != 'y':
                return

        # Save
        db_data['assignments'].append(
            {'title': title, 'course': course, 'due_date': due_date})
        database.save(db_data)
예제 #34
0
def save2DB(_data):
    miss_list = _data.validateParam()
    valid_data = _data.toJSON()
    print(json.dumps(valid_data, indent=2))
    _id = database.save(valid_data)

    if len(miss_list) == 0:
        return (_id, [])
    else:
        return (_id, miss_list)
예제 #35
0
def refresh_data(sport=None):
    if sport:
        database.clear('roster', sport)
        
        url = urllib.request.urlopen(URL['ATHLETICS_URL']
                                   + URL['ROSTER_PATH'] + sport)
        content = url.read().decode('utf8')
        url.close()

        soup = BeautifulSoup(content)
        
        team_pic = TeamPic()
        team_pic.setSport(sport)
        if soup.find(id=ID['TEAM_PIC_ID']):
            team_pic.setUrl(soup.find(id=ID['TEAM_PIC_ID'])['src'])
            database.save(team_pic)
    
            return team_pic.getPic()
    return None
예제 #36
0
def refresh_data(sport=None):
    if sport:
        database.clear('roster', sport)
        
        url = urllib.request.urlopen(URL['ATHLETICS_URL']
                                   + URL['ROSTER_PATH'] + sport)
        content = url.read().decode('utf8')
        url.close()

        soup = BeautifulSoup(content)
        player_table = soup.find(id=ID['ROSTER_TABLE_ID'])
        player_rows = player_table.find_all('tr')

        for row in player_rows:
            player = process_player_row(row.find_all('td'), sport)
            if player:
                database.save(player)

        return index(sport);
    return False
예제 #37
0
def savesnippet(ch, fileid):
    url = "https://slack.com/api/files.info?token=%s&file=%s&pretty=1" % (SLACK_TOKEN, fileid)
    response = requests.request("GET", url)
    resjson = response.json()
    if resjson and "file" in resjson and "url_private_download" in resjson["file"]:
        url = resjson['file']["url_private_download"]
        if url.endswith(".txt"):
            auth = "Bearer %s" % SLACK_TOKEN
            headers = {
                    'authorization': auth,
                        'cache-control': "no-cache",
                            }
            response = requests.request("GET", url, headers=headers)
            sniptxt = response.text
            if isstandup(sniptxt):
                # put in a database call to save the fileid here
                db.addToDB(ch, fid = fileid)
                db.save("/volume/slackdb.pickle")
                return True
    return False
예제 #38
0
def main_menu():
    """Run the main menu of the program"""

    repeat = False
    numberBase = "default"
    curDB  = "root"
    prompt = ("Repeat is %s.\nCurrent Default Database: %s.\n"
        "Enter a valid command, or help.")

    aliases, dbAliases = init_aliases()
    dbConfig, production = config.init_config_file()
    database = db.init(dbConfig)

    command = ""
    while command != "quit":
        entry = ui.get_input(
            prompt % (("on" if repeat else "off"), curDB), "lower")
        command, args = parse_entry(aliases, dbAliases, entry)

        if command == "help":
            print("\nI'm working on the help file!!")
        elif command == "repeat":
            repeat = not repeat
            print("\nRepeat is now %s." % ("on" if repeat else "off"))
        elif command == "run":
            tracker.produce(database, production)
        elif command in ("switch", "root", "global"):
            curDB = change_database(curDB, command)
        elif command == "database":
            db.basic_actions(database, curDB, *tuple(args))
        elif command == "load":
            db.load(database, *tuple(args))
        elif command == "save":
            db.save(database, dbConfig, *tuple(args))
        elif command == "wipe":
            wipePrompt = "Are you SURE you want to erase the database? Y/N"
            if ui.get_binary_choice(wipePrompt):
                database = db.init()
        elif command != "quit":
            print("\n\"%s\" is not a recognized command." % command)
예제 #39
0
파일: db_test.py 프로젝트: avaid96/standup
def testDB():
	# new store
	database.store = {}
	# add to database
	database.addToDB("sec", fid = "test")
	database.addToDB("sec", msg = "anotherone")
	# get from database
	assert len(database.get("sec", database.getDate())) == 2
	assert (database.get("sec", database.getDate()))[0]['fid'] == "test"
	assert (database.get("sec", database.getDate()))[1]['msg'] == "anotherone"
	assert (database.get("oth", database.getDate())) == []
	# save database to pickle
	database.save("temp.pickle")
	# remove from database
	database.remove(database.getDate())
	assert database.get("sec", database.getDate()) == []
	# load database from pickle
	database.store = database.load("temp.pickle")
	# get from database
	assert (database.get("sec", database.getDate()))[0]['fid'] == "test"
	assert (database.get("sec", database.getDate()))[1]['msg'] == "anotherone"
	os.remove("temp.pickle")
예제 #40
0
def save():
	
	hours = BuildingHours()
	
	hours._id = request.POST.get('id')
	hours._name = request.POST.get('name')
	
	hours._days[0] = False if request.POST.get('sunday') is None else True
	hours._days[1] = False if request.POST.get('monday') is None else True
	hours._days[2] = False if request.POST.get('tuesday') is None else True
	hours._days[3] = False if request.POST.get('wednesday') is None else True
	hours._days[4] = False if request.POST.get('thursday') is None else True
	hours._days[5] = False if request.POST.get('friday') is None else True
	hours._days[6] = False if request.POST.get('saturday') is None else True
	
	hours._opentime = int(request.POST.get('openhour'))
	hours._closetime = int(request.POST.get('closehour'))
	
	if (hours._id == 'None'):
		database.save(hours)
	else:
		database.updateHours(hours)
예제 #41
0
파일: feed.py 프로젝트: chengdujin/newsman
def add(feed_link=None, language=None, categories=None,
        transcoder_type="chengdujin"):
    """
    read rss/atom meta information from a given feed
    """
    if not feed_link or not language:
        logger.error("[feed.add] ERROR: Method not well formed!")
        return None
    if not isinstance(categories, dict):
        logger.error('categories should be a dictionary')
        return None

    try:
        d = feedparser.parse(feed_link)
        if d:
            # feed level
            feed = _read_source(d, feed_link, language, categories)
            if feed:
                feed_id = db_feeds.save(feed)
                if feed_id:
                    # add entries of this feed
                    # the FINAL return
                    return scraper.update(feed_link=feed_link, feed_id=feed_id,
                                          language=language,
                                          categories=categories,
                                          transcoder_type=transcoder_type)
                else:
                    logger.error('Cannot save feed in database')
                    return None
            else:
                logger.error('Cannot read source!')
                return None
        else:
            logger.error(
                "RSS source %s cannot be interpreted!" % feed_link)
            return None
    except Exception as k:
        logger.error(str(k))
        return None
예제 #42
0
def save(ch, command):
    command = command[len(SAVE_COMMAND):]
    # db call to save the string here
    db.addToDB(ch, msg = command)
    db.save("/volume/slackdb.pickle")
예제 #43
0
def create_user(username, email, password):
	print('creating new user: '******' ' + email + ' ' + password)
	user = User(username, email, password)
	return db.save(user)
예제 #44
0
파일: run.py 프로젝트: Castronova/EMIT
def run_feed_forward(obj, ds=None):
    """
    executes a feed forward coupled model simulation
    Args:
        obj: engine coordinator object
        ds: dataSaveInfo object

    Returns: None

    """

    # set engine status
    obj.status.set(stdlib.Status.NOTREADY)

    # todo: determine unresolved exchange items (utilities)

    sim_st = time.time()

    # determine execution order
    elog.info("Determining execution order... ")
    sPrint("Determining execution order... ", MessageType.INFO)

    exec_order = obj.determine_execution_order()
    for i in range(0, len(exec_order)):
        elog.info("%d.) %s" % (i + 1, obj.get_model(model_id=exec_order[i]).name()))

    links = {}
    spatial_maps = {}

    # todo:  move this into function
    elog.info("Generating spatial maps... ")
    sPrint("Generating spatial maps... ")

    for modelid in exec_order:

        # get links
        l = obj.get_from_links_by_model(modelid)
        links[modelid] = l

        # build spatial maps
        for linkid, link in l.iteritems():
            source = link.source_exchange_item()
            target = link.target_exchange_item()
            key = generate_link_key(link)

            # set default spatial interpolation to ExactMatch
            if link.spatial_interpolation() is None:
                sPrint(
                    "Spatial interpolation not provided, using the default mapping approach:  'Spatial Index'",
                    MessageType.WARNING,
                )
                link.spatial_interpolation(spatial_index())

            spatial_interp = link.spatial_interpolation()
            source_geoms = source.getGeometries2()
            target_geoms = target.getGeometries2()

            if len(source_geoms) == 0:
                sPrint(
                    "Cannot continue simulation, %s -- %s contains 0 geometries" % link.source_component().name(),
                    source.name(),
                )
            if len(target_geoms) == 0:
                sPrint(
                    "Cannot continue simulation, %s -- %s contains 0 geometries" % link.target_component().name(),
                    target.name(),
                )

            # save the spatial mapping based on link key
            spatial_maps[key] = spatial_interp.transform(source_geoms, target_geoms)

    # prepare all models
    for modelid in exec_order:
        model_inst = obj.get_model_object(modelid).instance()
        model_inst.prepare()

        if model_inst.status() != stdlib.Status.READY:
            msg = (
                'Cannot continue with simulation because model "%s" has a status of "%s" after the preparation'
                ' phase.  Status must be "%s" in order to proceed with simulation '
                % (model_inst.name(), model_inst.status(), stdlib.Status.READY)
            )

            elog.critical(msg)
            sPrint(msg, MessageType.ERROR)
            return False

    # update engine status
    obj.status.set(stdlib.Status.READY)

    # loop through models and execute run
    for modelid in exec_order:

        # update engine status
        obj.status.set(stdlib.Status.RUNNING)

        st = time.time()

        # get the current model instance
        model_inst = obj.get_model_object(modelid).instance()
        sPrint("Executing module: %s \n" % model_inst.name(), MessageType.INFO)

        try:
            #  retrieve inputs from database
            sPrint("[1 of 3] Retrieving input data... ")
            input_data = model_inst.inputs()

            # pass these inputs ts to the models' run function
            sPrint("[2 of 3] Performing calculation... ")
            model_inst.run(input_data)

            # update links
            sPrint("[3 of 3] Updating links... ")
            oei = model_inst.outputs()
            update.update_links_feed_forward(links[modelid], oei, spatial_maps)

            model_inst.finish()
            elog.info("..module simulation completed in %3.2f seconds" % (time.time() - st))

        except Exception:
            # set the model status to failed
            model_inst.status(stdlib.Status.FAILED)
            return
            # raise Exception('Error during model execution')

        # set the model status to successful
        model_inst.status(stdlib.Status.SUCCESS)

    sPrint(
        "------------------------------------------\n"
        + "         Simulation Summary \n"
        + "------------------------------------------\n"
        + "Completed without error :)\n"
        + "Simulation duration: %3.2f seconds\n" % (time.time() - sim_st)
        + "------------------------------------------"
    )

    # update engine status
    obj.status.set(stdlib.Status.SUCCESS)

    # save simulation results
    model_ids = exec_order
    if ds is None:
        msg = "Simulation results will not be stored in database because database connection was not provided prior to simulation."
        elog.info(msg)
        sPrint(msg, messageType=MessageType.INFO)
    else:
        database.save(obj, ds, model_ids)