コード例 #1
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def rsr(context):
    is_admin = check_admin(context.message)
    if not is_admin:
        await client.say("You do not have permissions to use this command.")
        return
    global SETTINGS_DATA
    server = context.message.server
    try:
        rolenames = parse_arguments(context.message)
        for rolename in rolenames:
            if not discord.utils.get(server.roles, name=rolename):
                await client.say("There is no such role" + ", " +
                                 context.message.author.mention + ".")
                continue
            if rolename not in SETTINGS_DATA[server.id]["assignable-roles"]:
                await client.say(
                    "The role " + rolename +
                    " is already not on the list of self-assignable roles.")
                continue
            SETTINGS_DATA[server.id]["assignable-roles"].remove(rolename)
            await client.say(
                "The role " + rolename +
                " was removed from the list of self-assignable roles.")
    except:
        await client.say("Error removing role.")

    save_data(SETTINGS_DATA)
コード例 #2
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
def checked_acquire_setting_dict(server_id, setting_category):
    if setting_category not in SETTINGS_DATA[server_id].keys(
    ) and setting_category in SETTINGS_CATEGORIES:
        SETTINGS_DATA[server_id][setting_category] = None
        save_data(SETTINGS_DATA)
        return SETTINGS_DATA[server_id][setting_category]
    return SETTINGS_DATA[server_id][setting_category]
コード例 #3
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
def settings_init():
    global SETTINGS_DATA
    for server in client.servers:
        if server.id not in SETTINGS_DATA.keys():
            SETTINGS_DATA[server.id] = {}
            for setting in SETTINGS_CATEGORIES:
                SETTINGS_DATA[server.id][setting] = []
            save_data(SETTINGS_DATA)
コード例 #4
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def welcomemsg(context):
    is_admin = check_admin(context.message)
    if not is_admin:
        await client.say("You do not have permissions to use this command.")
        return
    global SETTINGS_DATA
    member = context.message.author
    welcome_message = context.message.content.split(" ", 1)[1]
    SETTINGS_DATA[member.server.id]["welcome-message"] = welcome_message
    save_data(SETTINGS_DATA)
    await client.say("The welcome message has been changed to:\n" + "" +
                     welcome_message + "")
コード例 #5
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def setserverinfo(context):
    is_admin = check_admin(context.message)
    if not is_admin:
        await client.say("You do not have permissions to use this command.")
        return
    global SETTINGS_DATA
    member = context.message.author
    if not " " in context.message.content:
        return
    server_info = context.message.content.split(" ", 1)[1]
    SETTINGS_DATA[member.server.id]["server-info"] = server_info
    save_data(SETTINGS_DATA)
    await client.say("The server info message has been changed to:\n\n" +
                     "```" + server_info + "```")
コード例 #6
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def setchannelinfo(context):
    is_admin = check_admin(context.message)
    if not is_admin:
        await client.say("You do not have permissions to use this command.")
        return
    global SETTINGS_DATA
    member = context.message.author
    if not SETTINGS_DATA[member.server.id]["channel-info"]:
        SETTINGS_DATA[member.server.id]["channel-info"] = {}
        save_data(SETTINGS_DATA)
    channel_info = context.message.content.split(" ", 1)[1]
    SETTINGS_DATA[member.server.id]["channel-info"][
        context.message.channel.id] = channel_info
    save_data(SETTINGS_DATA)
    await client.say("The channel info message for" +
                     " has been changed to:\n\n" + "```" + channel_info +
                     "```")
コード例 #7
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def setnegreact(context):
    is_admin = check_admin(context.message)
    if not is_admin:
        await client.say("You do not have permissions to use this command.")
        return
    words = parse_arguments(context.message)
    checked_acquire_setting_dict(context.message.server.id, "pos-react")
    SETTINGS_DATA[context.message.server.id]["pos-react"] = []
    for word in words:
        for char in word:
            if char_is_emoji(char):
                if char in SETTINGS_DATA[
                        context.message.server.id]["pos-react"]:
                    continue
                SETTINGS_DATA[context.message.server.id]["pos-react"].append(
                    char)
                await client.add_reaction(context.message, word)
    save_data(SETTINGS_DATA)
コード例 #8
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def removewarnword(context):
    is_admin = check_admin(context.message)
    if not is_admin:
        await client.say("You do not have permissions to use this command.")
        return
    global SETTINGS_DATA
    server = context.message.server
    try:
        words = parse_arguments(context.message)
        for word in words:
            if word not in SETTINGS_DATA[server.id]["warn-words"]:
                await client.say(word +
                                 " is already not on the list of warn words.")
                continue
            await client.say(word + " was removed the list of warn words.")
            SETTINGS_DATA[server.id]["warn-words"].remove(word)
    except:
        await client.say("Error removing word.")

    save_data(SETTINGS_DATA)
コード例 #9
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def textunmute(context, *args):
    is_admin = check_admin(context.message)
    if not is_admin:
        await client.say("You do not have permissions to use this command.")
        return
    for target in args:
        user_id = re.sub('[<@>]', '', target)
        member = context.message.server.get_member(user_id)

        if checked_acquire_setting_dict(context.message.server.id,
                                        "textmuted-users") is None:
            SETTINGS_DATA[context.message.server.id]["textmuted-users"] = []
        if user_id in SETTINGS_DATA[
                context.message.server.id]["textmuted-users"]:
            SETTINGS_DATA[context.message.server.id]["textmuted-users"].remove(
                user_id)
            save_data(SETTINGS_DATA)
        else:
            await client.say('{} is not muted.'.format(member.mention))
            continue
        await client.say('{} has been text unmuted.'.format(member.mention))
コード例 #10
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def setwelcomechannel(context):
    is_admin = check_admin(context.message)
    if not is_admin:
        await client.say("You do not have permissions to use this command.")
        return
    if not context.message.channel_mentions:
        await client.say(
            "No channel was specified, mention a channel : #channelname.")
        return
    elif len(context.message.channel_mentions) > 1:
        await client.say(
            "Multiple channels specified, the first channel on the list, " +
            context.message.channel_mentions[0].mention +
            ", will be the one set as welcome channel.")
    else:
        await client.say("The channel " +
                         context.message.channel_mentions[0].mention +
                         " will be the one set as welcome channel.")

    SETTINGS_DATA[context.message.server.id][
        "welcome-channel"] = context.message.channel_mentions[0].id
    save_data(SETTINGS_DATA)
コード例 #11
0
ファイル: main.py プロジェクト: Zibski/Kaggle-insurance
X_train = data_concat[pd.notnull(data_concat['target'])][train_features]
y_train = data_concat[pd.notnull(data_concat['target'])]['target']
X_test = data_concat[pd.isnull(data_concat['target'])][train_features]
print('Test shape: {}'.format(X_test.shape))
print(X_train.shape, y_train.shape)

num_ensembles = 1
y_pred = 0.0

for i in tqdm(range(num_ensembles)):
    model = CatBoostClassifier(depth=12,
                               iterations=600,
                               l2_leaf_reg=2,
                               learning_rate=0.059)
    model.fit(X_train, y_train, cat_features=cat_feature_inds)
    y_pred += model.predict_proba(X_test)[:, 1]

y_pred /= num_ensembles

submission = pd.DataFrame(
    {'id': data_concat[pd.isnull(data_concat['target'])]['id']})
submission['target'] = y_pred

data_loader.save_data(
    submission, 'sub{}.csv'.format(datetime.now().strftime('%Y%m%d_%H%M%S')))
print("Done! Good luck with submission :)")

#plt.bar(range(len(model.feature_importances_)), model.feature_importances_)
#print(list(zip(X_test.columns, model.feature_importances_)))
コード例 #12
0
ファイル: batch_generator.py プロジェクト: dhn045/2048AI
def generate_sim(epochs, num, folder, nn=None, train=False):

    if nn:
        net = nn
    else:
        net = network.Network([16, 200, 100, 4])
        """
        data = data_loader.load_data("damngoodgame")
        net.stochastic_gradient_descent([data], [np.ndarray([1])], 10, 0.001)
        nn = net
        """
    end_arr = []

    for i in range(num):
        b = board.Board(4)
        data = []
        alive = True
        start = time.time()
        while alive:
            tmp = copy.deepcopy(b.get_array())

            # eliminate invalid moves given board config
            directions = ["up", "down", "left", "right"]
            choices = [0, 1, 2, 3]
            valid = [b.is_valid_move(direc) for direc in directions]

            if nn:
                output = net.feedforward(b.get_array().flatten())
                outMax = 0
                for node in range(len(output)):
                    if output[node] > output[outMax] and valid[node]:
                        outMax = node
                outMax = random.choices(choices, valid * output)
                outMax = outMax[0]
            else:
                outMax = np.random.randint(0, 4)

            direction = [0 for i in range(4)]
            direction[outMax] = 1
            if outMax == 0:
                b.move("up")
            if outMax == 1:
                b.move("down")
            elif outMax == 2:
                b.move("left")
            elif outMax == 3:
                b.move("right")

            # checks whether board changed at all
            different = False
            for row in range(4):
                for col in range(4):
                    if tmp[row][col] != b.get_array()[row][col]:
                        different = True
                        break
                if different:
                    break

            if different:
                start = time.time()
                # new number generator
                rand_x = np.random.randint(0, 4)
                rand_y = np.random.randint(0, 4)
                while b.get_array()[rand_x][rand_y] != 0:
                    rand_x = np.random.randint(0, 4)
                    rand_y = np.random.randint(0, 4)
                rand_two = random.random()
                if rand_two < 0.95:
                    b.get_array()[rand_x][rand_y] = 2
                else:
                    b.get_array()[rand_x][rand_y] = 4
                data.append([copy.deepcopy(b.get_array()), direction])
            else:
                end = time.time()
                if end - start > 1:
                    alive = False

            # check if you can make anymore moves
            if b.is_game_over():
                break

        data_loader.save_data(data, "{0}/file{1}".format(folder, i))

        if len(data):
            end_arr.append(data[-1][0])
    print("batch {0}: generated".format(10 - epochs))
    if train:
        end_score = []
        # for each file, calculate an end score and save them to a list
        # then standardize the scores so they have a mean of 1 and
        for arr in end_arr:
            end_score.append(arr.sum())

        end_score = (end_score - np.mean(end_score)) / np.std(end_score)

        # train net over newly made data
        training_data = []
        j = 0
        while os.path.exists("batches{0}/file{1}".format(10 - epochs, j)):
            training_data.append(
                data_loader.load_data("batches{0}/file{1}".format(
                    10 - epochs, j)))
            j += 1

        net.stochastic_gradient_descent(training_data, end_score, 5, 0.002)

        if not epochs:
            generate_sim(epochs - 1, num, "result", net, False)
        else:
            generate_sim(epochs - 1, num, "batches{0}".format(10 - epochs + 1),
                         net, True)
def random_dataset(dataset, char_dict):
    text = []
    out = []
    for ids, line in enumerate(dataset):
        line, label = random_word(line, char_dict)
        text.append(line)
        out.append(label)
    return text, out


if __name__ == '__main__':
    dataset = load_dataset('dataset/sentences.txt')
    char_dict = gen_char_dict(dataset)
    process_dataset, process_label = random_dataset(dataset, char_dict)
    save_data(process_dataset, 'dataset/sentences_noisy.txt')
    df = pd.DataFrame(columns=['original', 'noisy', 'label'])
    df['original'] = dataset
    df['noisy'] = process_dataset
    df['label'] = process_label
    # remove nan rows
    df.dropna(inplace=True)
    # df.to_csv('dataset/processed_data.csv', index=False)

    # df = pd.read_csv('dataset/processed_words.csv')
    dataset = df[['original', 'noisy', 'label']].values
    train, test = train_test_split(dataset, test_size=0.1)
    df = pd.DataFrame(columns=['original', 'noisy', 'label'], data=train)
    df.to_csv('dataset/processed_train.csv', index=False)
    df = pd.DataFrame(columns=['original', 'noisy', 'label'], data=test)
    df.to_csv('dataset/processed_test.csv', index=False)
コード例 #14
0
ファイル: main.py プロジェクト: Axmouth/smile_bot_discord
async def on_server_join(server):
    if server.id not in SETTINGS_DATA.keys():
        SETTINGS_DATA[server.id] = {}
        for setting in SETTINGS_CATEGORIES:
            SETTINGS_DATA[server.id][setting] = []
        save_data(SETTINGS_DATA)
コード例 #15
0
ファイル: game.py プロジェクト: dhn045/2048AI
def main(train=False):
    if train:
        data = data_loader.load_data()
    else:
        data = []
    net = network.Network([16, 10, 4])
    #return
    alive = True
    b = board.Board(SIZE)
    """
    for text based game
    
    for row in b.get_array():
        print(row)
    """

    win = GraphWin("2048", 500, 500, autoflush=False)
    p = Point(50, 50)
    for row in b.get_array():
        for cell in row:
            r = Rectangle(p, Point(p.getX() + 100, p.getY() + 100))
            r.draw(win)
            if cell != 0:
                t = Text(Point(p.getX() + 50, p.getY() + 50), cell)
                t.draw(win)
            p.move(100, 0)
        p.move(-400, 100)

    # draw the score
    score = Text(Point(250, 25), "Score: {0}".format(0))
    score.draw(win)

    while alive:
        # pauses to get key press
        key = win.getKey()

        # keep a variable that holds the array before it is changed
        tmp = np.copy(b.get_array())

        # move depending on key press
        if key == "Up":
            b.move("up")
        elif key == "Left":
            b.move("left")
        elif key == "Down":
            b.move("down")
        elif key == "Right":
            b.move("right")
        elif key == "Escape":
            alive = False
            win.close()
        else:
            continue

        data.append([tmp, key])

        # checks whether board changed at all
        different = False
        for row in range(SIZE):
            for col in range(SIZE):
                if tmp[row][col] != b.get_array()[row][col]:
                    different = True
                    break
            if different:
                break

        # only update if the board changed
        if different:
            # new number generator
            rand_x = random.randint(0, SIZE - 1)
            rand_y = random.randint(0, SIZE - 1)
            while b.get_array()[rand_x][rand_y] != 0:
                rand_x = random.randint(0, SIZE - 1)
                rand_y = random.randint(0, SIZE - 1)
            rand_two = random.random()
            if rand_two < 0.95:
                b.get_array()[rand_x][rand_y] = 2
            else:
                b.get_array()[rand_x][rand_y] = 4
            """
            for text based game
            
            print("\n")
            # print array
            for row in b.get_array():
                print(row)
            """

            # erase all items on window
            for item in win.items[:]:
                item.undraw()

            score.setText("Score : {0}".format(b.score))
            score.draw(win)

            # restart drawing from upper left corner
            p = Point(50, 50)
            # draw a rectangle for each element in the array
            # draw a number for each non zero element in the array
            for row in b.get_array():
                for cell in row:
                    r = Rectangle(p, Point(p.getX() + 100, p.getY() + 100))
                    r.draw(win)
                    if cell != 0:
                        t = Text(Point(p.getX() + 50, p.getY() + 50), cell)
                        t.draw(win)
                    # move over by a rectangle width
                    p.move(100, 0)
                # reset back four rectangles and down 1 to draw next row
                p.move(-400, 100)
            # update at 30 frames per sec if animation is used
            update(30)

        # pause so it doesn't overrun, unnecessary for gui since it pauses for
        # each keystroke
        #time.sleep(.2)
        else:
            # check if you can make anymore moves
            directions = ["up", "left", "down", "right"]
            for dir in directions:
                tmp_b = copy.deepcopy(b)
                tmp_b.move(dir)
                different = False
                for row in range(SIZE):
                    for col in range(SIZE):
                        if tmp[row][col] != tmp_b.get_array()[row][col]:
                            different = True
                            break
                    if different:
                        break
                if different:
                    break
            if not different:
                alive = False
    if not train:
        file_num = 0
        while os.path.exists("datafile{0}".format(file_num)):
            file_num += 1
        data_loader.save_data(data, 'datafile{0}'.format(file_num))