async def concede(self,
                      ctx: commands.Context,
                      game_id: int = None) -> None:
        logger.info("Got a !concede command")

        game = await get_game_ctx(ctx, ctx.author.id, game_id)
        if game is None:  # check the Game object for validity
            return

        if game.winner is not None:  # check that the game hasn't finished yet
            await ctx.send(f"{ctx.author.mention}, the game is over.")
            logger.error(
                f"Can't concede in game #{game.id} - the game is over")
            return

        user = await get_author_user_ctx(ctx)
        if user is None:  # check the User object for validity
            return

        if not is_player(
                game, user
        ):  # check that the message author is a player in this game
            logger.error(
                f"User #{user.discord_id} tried to illegally play game #{game.id}"
            )
            await ctx.send(f"{ctx.author.mention}, you can't play this game.")
            return

        update_game(game, concede_side=which_player(game, user))
        user.last_game = game
        database.add_to_database(user)
        await self.status_func(ctx, game=game)
Пример #2
0
def write_data():
    if request.method == 'POST':
        # message = request.form['userInput']
        data = request.get_json()
        res = make_response(data['message'])
        cookie = request.cookies
        user_id = cookie.get('user_id')
        print(user_id)
        if user_id == None:
            user_id_list = database.read_table(database_name,
                                               message_table_name, "user_id")

            for ids in user_id_list:
                new_id = rand.randint(1000001, 9999999)
                if not user_id_list.count(new_id):
                    user_id = new_id
                    break
            res.set_cookie('user_id', f'{user_id}', expires='never')
        # Determine time of input here instead of taking from client-side js##############################
        epoch = round(time.time())
        epoch = int(epoch) * 1000
        database.add_to_database(database_name, database_columns,
                                 message_table_name, user_id, data['message'],
                                 epoch)
        print(data)
        print(epoch)
    return res
Пример #3
0
def recalculate_elo(game: database.Game) -> None:
    if game is None:
        raise RuntimeError("Game is None")

    white = game.white
    black = game.black
    game_result = game.winner

    if game_result is None:
        raise RuntimeError("Game is not over yet")
    if white is None or black is None:
        raise RuntimeError("Either white or black is None")
    if white.elo is None or black.elo is None:
        raise RuntimeError("Either white or black does not have an elo rating")

    WEa = round(1 / (1 + 10 ** ((black.elo - white.elo) / 400)), 2)
    white_actual = constants.result_to_int(game_result)

    white_delta = white_actual - WEa

    white_diff = white_delta * constants.ELO_K
    black_diff = (-white_delta) * constants.ELO_K

    white.elo += white_diff
    black.elo += black_diff

    if white.elo < 0:
        white.elo = 0
    if black.elo < 0:
        black.elo = 0

    database.add_to_database(white)
    database.add_to_database(black)
Пример #4
0
    def OnSwitch(self, event):
        switch = [self.ListboxLocs.GetString(sel) for sel in self.selection]
        if not switch:
            dial = wx.MessageDialog(None, 'Er is geen locatie geselecteerd',
                                    '', wx.OK | wx.ICON_INFORMATION)
            dial.ShowModal()
        else:
            if self.id == 10:
                with open('data/Mypup_bus.pkl', 'rb') as f:
                    database = pickle.load(f)
                for loc in switch:
                    info_list = [
                        loc, database[loc]['Address'],
                        database[loc]['Loadtime'], database[loc]['Demands'],
                        database[loc]['Timewindow']
                    ]
                    db.remove_from_database(loc, 'data/Mypup_bus')
                    db.add_to_database(info_list, 'data/Mypup_bakfiets')
            elif self.id == 11:
                with open('data/Mypup_bakfiets.pkl', 'rb') as f:
                    database = pickle.load(f)
                for loc in switch:
                    info_list = [
                        loc, database[loc]['Address'],
                        database[loc]['Loadtime'], database[loc]['Demands'],
                        database[loc]['Timewindow']
                    ]
                    db.remove_from_database(loc, 'data/Mypup_bakfiets')
                    db.add_to_database(info_list, 'data/Mypup_bus')

            dial = wx.MessageDialog(
                None, 'De locaties zijn verplaatst naar de juiste planner!',
                'Succes', wx.OK | wx.ICON_INFORMATION)
            dial.ShowModal()
Пример #5
0
def run_main_reddit_loop():
    global praw,database,upload_timer
    #Main loop the listens to new comments on some subreddit 
    for c in praw.helpers.comment_stream(r, subreddit):
        if check_condition(c):
            if not database.is_in_db(c.id):
                submission = r.get_submission(submission_id=c.permalink)
                flat_comments = praw.helpers.flatten_tree(submission.comments)
                already_commented = False
                for comment in flat_comments:
                    if str(comment.author) == secret_keys.reddit_username:
                        database.add_to_database(c.id)
                        database.save_database()
                        already_commented = True
                        break
                if not already_commented:
                    bot_action(c)
        if (time.time() - upload_timer)  > upload_timeout :
            upload_timer = time.time()
            print "Trying to send a comment"
            try:
                reddit_comment,msg = upload_queue[0]
                print reddit_comment.permalink,msg
                reddit_comment.reply(msg)
                upload_queue.pop()
            except:
                pass
Пример #6
0
	def OnAdjustAction(self, event):
		"""Handles the back end functionality for adjustments of company data. """
		Name = self.NameCtrl.GetValue()
		Address = self.AddressCtrl.GetValue()
		LoadTime = int(self.LoadTimeCtrl.GetValue())
		Demand = LoadTime if self.DemandCtrl.GetValue()	== "" else int(self.DemandCtrl.GetValue())
		TimeWindow = self.FormatTW(self.TimeCtrl.GetValue())
		if TimeWindow == 2:
			dial = wx.MessageDialog(None, 'De vroegste tijd moet vroeger zijn dan de uiterlijke tijd.', 'Time Window',
				wx.OK | wx.ICON_ERROR)
			dial.ShowModal()
		elif TimeWindow == 3:
			dial = wx.MessageDialog(None, 'De uiterlijke tijd kan niet groter zijn dan 4 uur.', 'Time Window',
				wx.OK | wx.ICON_ERROR)
			dial.ShowModal()
		else:
			info_list = [Name, Address, LoadTime, Demand, TimeWindow]
			if self.id == 8:
				db.remove_from_database(self.CompToAdjust, 'data/Mypup_bus')
				db.add_to_database(info_list, 'data/Mypup_bus')
			elif self.id == 9:
				db.remove_from_database(self.CompToAdjust, 'data/Mypup_bakfiets')
				db.add_to_database(info_list, 'data/Mypup_bakfiets')
			dial = wx.MessageDialog(None, 'De gegevens zijn gewijzigd', 'Succes',
			wx.OK | wx.ICON_INFORMATION)
			dial.ShowModal()
Пример #7
0
def bot_action(c, verbose=True, respond=False):

    if verbose:
        img_url = c.link_url
        img_path = image_downloader.download_image(img_url)
        print 'link is : ', img_url, 'img_path is ',img_path

        #didn't mange to download photo
        if len(img_path) == 0:
            return

        img = cv2.imread(img_path)
        if img is not None:
            h,w = (img.shape[0],img.shape[1])
            if h > MAX_IMAGE_HEIGHT or w > MAX_IMAGE_WIDTH:
                print '-----Resizing image!!------'
                ratio = float(w)/float(h)
                if h > MAX_IMAGE_HEIGHT:
                    factor = float(h)/float(MAX_IMAGE_HEIGHT)
                else:
                    factor = float(w)/float(MAX_IMAGE_WIDTH)
                img = cv2.resize(img,None,fx=1/factor, fy=1/factor, interpolation = cv2.INTER_CUBIC)
                print '---- after resize image shape is  ----',img.shape
                cv2.imwrite(img_path,img,[cv2.IMWRITE_JPEG_QUALITY,40])
            #if h > 1080 or w > 1920:
            #    try:
            #        c.reply("Sorry image is too big! we currently only support images as big as 1920x1080")
            #        database.add_to_database(c.id)
            #        database.save_database()
            #    except:
            #        return
            #    return
            #1)Run DNN on the b&w image
            print 'Image downloaded and is ok'
            if useDNN:
                coloredImage = colorize.runDNN(img_path)
            else:
                coloredImage = img
            print 'after DNN'
            image_name = 'colorized_'+img_path
            cv2.imwrite(image_name,coloredImage)

            #2)Upload image
            print 'Uploading image'
            if args.replicate:
                uploaded_image_link = img_url
            else:
                uploaded_image_link = image_uploader.upload_image(image_name)

            #3)Reply to the one who summned the bot
            if uploaded_image_link is not None:
                msg = 'Hi I\'m colorizebot. I was trained to color b&w photos (not comics or rgb photos! Please do not abuse me :{}).\n\n This is my attempt to color your image, here you go : %s \n\n This is still a **beta-bot**. If you called the bot and didn\'t get a response, pm us and help us make it better. \n\n  [For full explanation about this bot\'s procedure](http://whatimade.today/our-frst-reddit-bot-coloring-b-2/) | [code](https://github.com/dannyvai/reddit_crawlers/tree/master/redditBotColorize)'%(uploaded_image_link)
                try:
                    res = c.reply(msg)
                    database.add_to_database(c.id)
                    database.save_database()
                except:
                    upload_queue.append((c,msg))
                    traceback.print_exc()
Пример #8
0
def handle_move(game: database.Game, san_move: str) -> None:
    board = load_from_pgn(game.pgn)

    try:
        move(board, san_move)
    except ValueError as err:
        raise err

    game.pgn = save_to_pgn(board)
    database.add_to_database(game)
def create_database_user(discord_user: discord.User) -> database.User:
    if (database.session.query(
            database.User).filter_by(discord_id=discord_user.id).first()
            is not None):
        raise RuntimeError(f"User #{discord_user.id} already exists")

    user = database.User(discord_id=discord_user.id,
                         username=get_full_username(discord_user))
    database.add_to_database(user)

    return user
    async def move(self,
                   ctx: commands.Context,
                   san_move: str,
                   game_id: int = None) -> None:
        logger.info("Got a !move command")

        game = await get_game_ctx(ctx, ctx.author.id, game_id)
        if game is None:  # check the Game object for validity
            return

        if game.winner is not None:  # check that the game hasn't finished yet
            await ctx.send(f"{ctx.author.mention}, the game is over.")
            logger.error(f"Can't move in game #{game.id} - the game is over")
            return

        user = await get_author_user_ctx(ctx)
        if user is None:  # check the User object for validity
            return

        if not is_player(
                game, user
        ):  # check that the message author is a player in this game
            logger.error(
                f"User #{user.discord_id} tried to illegally play game #{game.id}"
            )
            await ctx.send(f"{ctx.author.mention}, you can't play this game.")
            return

        try:
            handle_turn_check(user, game)
        except RuntimeError as err:
            logger.error(err)
            await ctx.send(f"{ctx.author.mention}, it is not your turn.")
            return

        try:
            handle_move(game, san_move)
        except ValueError as err:
            logger.error(err)
            await ctx.send(
                f"{ctx.author.mention}, {san_move} is not a valid SAN move in this game."
            )
            return

        update_game(game, recalculate_expiration_date=True, reset_action=True)
        user.last_game = game
        database.add_to_database(user)
        await self.status_func(ctx, game=game)
def handle_action_offer(user: database.User, game: database.Game, action: int) -> None:
    if action not in [
        constants.ACTION_NONE,
        constants.ACTION_DRAW,
        constants.ACTION_UNDO,
    ]:
        raise RuntimeError("Impossible action")

    try:
        player = which_player(game, user)
    except RuntimeError as err:
        raise err

    if player == constants.WHITE:
        game.white_accepted_action, game.black_accepted_action = True, False
    else:
        game.white_accepted_action, game.black_accepted_action = False, True

    game.action_proposed = action
    database.add_to_database(game)
    async def chessplay(self, ctx: commands.Context,
                        user: discord.Member) -> None:
        white = await create_database_user_ctx(ctx, ctx.author)
        black = await create_database_user_ctx(ctx, user)

        if white is None or black is None:  # check the validity of User objects
            return

        if white == black:  # check that white and black are different users
            logger.error(
                f"User #{white.discord_id} tried to play against themselves")
            await ctx.send(
                f"{ctx.author.mention}, you can't play against yourself.")
            return

        game = database.Game(white=white, black=black)
        database.add_to_database(game)

        white.last_game = game
        database.add_to_database(white)

        black.last_game = game
        database.add_to_database(black)

        await self.status_func(ctx, game=game)
    async def accept(self, ctx: commands.Context, game_id: int = None) -> None:
        logger.info("Got an !accept command")

        game = await get_game_ctx(ctx, ctx.author.id, game_id)
        if game is None:  # check the Game object for validity
            return

        user = await get_author_user_ctx(ctx)
        if user is None:  # check the User object for validity
            return

        if not is_player(
                game, user
        ):  # check that the message author is a player in this game
            logger.error(
                f"User #{user.discord_id} tried to illegally !accept in game #{game.id}"
            )
            await ctx.send(
                f"{ctx.author.mention}, you can't use !accept in this game.")
            return

        if game.white_accepted_action != game.black_accepted_action:
            try:
                handle_action_accept(user, game)
            except RuntimeError as err:
                logger.error(err)
                await ctx.send(
                    f"{ctx.author.mention}, you can't accept your own actions."
                )
                return

            user.last_game = game
            database.add_to_database(user)
            await self.status_func(ctx, game=game)
        else:
            await ctx.send(
                f"{ctx.author.mention}, there is nothing to accept for this game."
            )
            logger.error(f"Nothing to accept for game #{game.id}")
Пример #14
0
    def process(self, client_tree):
        """Given the client information populate database.
        :param client_tree : Client information
        :return tuple of client info
        """
        username = client_tree.get('username')
        ip = client_tree.get('ip')
        port = client_tree.get('port')
        password = client_tree.get('password')
        email = client_tree.get('email')

        logger.info("processing information for username : {} ,"
                    " ip: {} , port: {}".format(username, ip, port))

        for alert in client_tree.findall("alert"):
            if "memory" in alert.get("type"):
                memory_threshold = alert.get("limit")
            else:
                cpu_threshold = alert.get("limit")

        memory_threshold = int(memory_threshold.split('%')[0])
        cpu_threshold = int(cpu_threshold.split('%')[0])

        clients = Session.query(Client).filter(
            Client.username == username
        ).filter(
            Client.ip == ip
        ).all()

        if len(clients) == 0:
            client = database.add_to_database(
                Client,
                username=username,
                ip=ip,
                email=email,
                port=port,
                memory_limit=memory_threshold,
                cpu_limit=cpu_threshold)
        else:
            try:
                clients[0].cpu_limit = cpu_threshold
                clients[0].memory_limit = memory_threshold
                Session.commit()
            except Exception as e:
                logger.exception(e)
                logger.error("An error occured while updating the information"
                             " of client having id = {}"
                             .format(clients[0].username))

        client_id = clients[0].id if len(clients) > 0 else client.id
        return client_id, ip, port, username, password
Пример #15
0
	def OnAdd(self, event):
		"""Handles the back end functionality for the addition of companies """
		Name = self.NameCtrl.GetValue()
		Address = self.AddressCtrl.GetValue()
		LoadTime = int(self.LoadTimeCtrl.GetValue())
		Demand = LoadTime if self.DemandCtrl.GetValue()	== "" else int(self.DemandCtrl.GetValue())
		TimeWindow = self.FormatTW(self.TimeCtrl.GetValue())
		if TimeWindow == 2:
			dial = wx.MessageDialog(None, 'De vroegste tijd moet vroeger zijn dan de uiterlijke tijd.', 'Time Window',
				wx.OK | wx.ICON_ERROR)
			dial.ShowModal()
		elif TimeWindow == 3:
			dial = wx.MessageDialog(None, 'De uiterlijke tijd kan niet groter zijn dan 4 uur.', 'Time Window',
				wx.OK | wx.ICON_ERROR)
			dial.ShowModal()
		else:
			info_list = [Name, Address, LoadTime, Demand, TimeWindow]
			if self.id == 3:
				db.add_to_database(info_list, 'data/Mypup_bus')
			else:
				db.add_to_database(info_list, 'data/Mypup_bakfiets')
			dial = wx.MessageDialog(None, 'De nieuwe locatie is toegevoegd aan de database!', 'Succes',
			wx.OK | wx.ICON_INFORMATION)
			dial.ShowModal()
Пример #16
0
def add_book():
    try:
        if len(entry_id.get()) != 0 and len(entry_title.get()) != 0 and len(entry_author.get()) != 0 and \
                len(entry_year.get()) != 0 and len(entry_count.get()) != 0:
            data = [
                entry_id.get(),
                entry_title.get(),
                entry_author.get(),
                entry_year.get(),
                entry_count.get()
            ]
            if data[0].isdigit():
                if not database.check_id(int(entry_id.get())):
                    messagebox.showerror("TypeError",
                                         "Введенный Id уже существует")
                    return
            else:
                messagebox.showerror("TypeError",
                                     "Id должен быть указан числом")
                return
            if not data[3].isdigit():
                messagebox.showerror("TypeError",
                                     "Год издания должен быть указан числом")
                return
            if not data[4].isdigit():
                messagebox.showerror(
                    "TypeError",
                    "Кол-во экземпляров должно быть указано числом")
                return
            frame.insert('', 'end', values=data)
            database.add_to_database(data)
        else:
            messagebox.showerror("InputError",
                                 "Все поля должны быть заполнены")
    except Exception as e:
        print(e)
Пример #17
0
def handle_response(client_id, output):
    """For give statistics of client populate database.
    :param client_id: id of the client inside database
    :param output: statistics of the client
    """
    cpu = float(output[0])
    memory = float(output[1])
    uptime = output[2]

    stats = database.add_to_database(Stats,
                                     client_id=client_id,
                                     cpu_usage=cpu,
                                     memory_usage=memory,
                                     uptime=uptime)

    client = Session.query(Client).filter(Client.id == client_id).one()

    return stats, client, cpu, memory
Пример #18
0
def update_game(
    game: database.Game,
    recalculate_expiration_date: bool = False,
    reset_action: bool = False,
    concede_side: int = None,
    only_check_expiration: bool = False,
) -> None:
    if game.winner is not None:
        return  # if the game has already finished, there is nothing to do

    board = load_from_pgn(game.pgn)
    turn = get_turn(board)

    if has_game_expired(game):
        game.win_reason = "Game expired"
        if turn == constants.WHITE:
            game.winner = constants.BLACK
        else:
            game.winner = constants.WHITE

        database.add_to_database(game)

        recalculate_elo(game)
        return

    if only_check_expiration:
        return

    if concede_side in [constants.WHITE, constants.BLACK]:
        if concede_side == constants.WHITE:
            game.winner = constants.BLACK
        else:
            game.winner = constants.WHITE

        concede_side_str = constants.turn_to_str(concede_side).capitalize()
        game.win_reason = f"{concede_side_str} conceded"
        game.expiration_date = None

        database.add_to_database(game)

        recalculate_elo(game)
        return

    if recalculate_expiration_date:
        game.expiration_date = datetime.datetime.now() + EXPIRATION_TIMEDELTA
        database.add_to_database(game)

    claim_draw = game.action_proposed == constants.ACTION_DRAW
    undo_last = game.action_proposed == constants.ACTION_UNDO
    both_agreed = game.white_accepted_action and game.black_accepted_action

    try:
        winner = get_winner(board,
                            claim_draw=claim_draw,
                            both_agreed=both_agreed)
        reason = get_game_over_reason(board,
                                      claim_draw=claim_draw,
                                      both_agreed=both_agreed)
    except RuntimeError as err:
        logger.info("The game has not ended yet:")
        logger.info(
            err
        )  # not actually an error, just the reasoning behind the game not being over

        if undo_last and both_agreed:
            undo(board)
            game.pgn = save_to_pgn(board)
            database.add_to_database(game)

        if reset_action:
            game.action_proposed = constants.ACTION_NONE
            game.white_accepted_action = False
            game.black_accepted_action = False

            database.add_to_database(game)

        return

    game.winner = winner
    game.win_reason = reason
    game.expiration_date = None
    database.add_to_database(game)

    recalculate_elo(game)
    if status == 'processed' or status == 'overtime':
        if raw_files_exist:
            answer = None
            while answer not in ("yes", "no"):
                print(f"{name} still contains the raw results files.")
                answer = input(f"Delete the arrays folder and slurm files? ")
                if answer == "yes":
                    #  prof_file = result_dir / 'array-1' / 'file.prof'
                    #  if prof_file.is_file():
                    #      run(['cp', prof_file, result_dir])
                    run('rm -r ' + str(result_dir / 'array-*'), shell=True)
                    run('rm ' + str(result_dir / 'slurm-*.out'), shell=True)
                    run(['rm', result_dir / 'job_script_slurm.sh'])
                    entry['raw_files_exist'] = False
                    add_to_database(entry)
                elif answer == "no":
                    pass
                else:
                    print("Please enter yes or no.")
        if status == 'processed':
            continue

    array_dirs = [
        d.name for d in result_dir.iterdir()
        if d.is_dir() and d.name[:6] == 'array-' and d.name[6:].isdigit()
    ]

    #  for d in array_dirs:
    #      if (status == 'to_be_processed' and
    #              not (result_dir / d / 'rewards.npy').is_file()):
    async def offer(self,
                    ctx: commands.Context,
                    action: str,
                    game_id: int = None) -> None:
        logger.info("Got an !offer command")

        game = await get_game_ctx(ctx, ctx.author.id, game_id)
        if game is None:  # check the Game object for validity
            return

        if game.winner is not None:  # check that the game hasn't finished yet
            await ctx.send(f"{ctx.author.mention}, the game is over.")
            logger.error(
                f"Can't offer an action in game #{game.id} - the game is over")
            return

        user = await get_author_user_ctx(ctx)
        if user is None:  # check the User object for validity
            return

        if not is_player(
                game, user
        ):  # check that the message author is a player in this game
            logger.error(
                f"User #{user.discord_id} tried to illegally offer an in game #{game.id}"
            )
            await ctx.send(
                f"{ctx.author.mention}, you can't offer an action in this game."
            )
            return

        action_type = constants.OFFERABLE_ACTIONS.get(action.upper())

        if action_type is None:  # check that this action is offerable
            logger.error(
                f'User #{user.discord_id} tried to offer an illegal action "{action}" in game #{game.id}'
            )
            await ctx.send(f"{ctx.author.mention}, this action does not exist."
                           )
            return

        if (game.action_proposed == action_type
            ):  # check that this action hasn't been offered yet
            logger.error(
                f'Action "{action}" has already been offered in game #{game.id}'
            )
            await ctx.send(
                f"{ctx.author.mention}, this action has already been offered in this game."
            )
            return

        try:
            handle_action_offer(user, game, action_type)
        except RuntimeError as err:
            logger.error(err)
            await ctx.send(
                f"{ctx.author.mention}, you can't offer an action in this game."
            )
            return

        update_game(game)
        user.last_game = game
        database.add_to_database(user)
        await self.status_func(ctx, game=game)