コード例 #1
0
def train(model, config, loss_fun, optim, target_idx):
    model.train()
    corpus = config.corpus
    all_loss = 0.0
    sample_len = 0
    for id_, (idx_tweets, idx_target, stances, target_idx) in enumerate(
            corpus.iter_epoch(target_idx, "Train", batch_size=16)):
        #for id_, (idx_tweets, idx_target, stances, sentiments, target_idx) in enumerate(corpus.iter_all_train_target(batch_size=30, is_random=False)):
        np_idx_tweets = fixed_length(idx_tweets, Config.fixed_len)
        np_idx_targets = fixed_length(idx_target, len(idx_target[0]))
        sample_len += len(idx_tweets)

        var_s1 = Variable(torch.from_numpy(stance2idx(stances)))
        output1, output2 = model(np_idx_tweets, np_idx_targets, target_idx)

        loss = loss_fun(output1, var_s1)
        all_loss += loss.data.sum()
        optim.zero_grad()
        loss.backward()
        optim.step()
    judge()
    print("-----------train mean loss: ", all_loss / sample_len)
    return model.state_dict()
コード例 #2
0
ファイル: server.py プロジェクト: quas1009/iot_JennyGo
def post_image_test():
    sensor = mongo.db.sensor
    response = mongo.db.response
    from test import test
    from utils import judge
    from train import rgb2gray
    # Get the name of the uploaded file
    for i in range(5):
        img_file = request.files['file%s' % str(i)]
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(img_file.filename)
        save_folder = os.path.join(app.config['UPLOAD_FOLDER'], 'test')
        img_path = os.path.join(save_folder, filename)
        img_file.save(img_path)
        image = mpimg.imread(img_path)
        if i == 0:
            images = image
            images = rgb2gray(images)
        else:
            image = rgb2gray(image)
            images = np.concatenate((images, image),axis=2)
        os.remove(img_path)
    judge(pred)
    return 'OK', 200
コード例 #3
0
ファイル: mqtt.py プロジェクト: nczitzk/maison
def parse_data(devEUI, data):
    """
    To fetch messages devices of interests
    and store info into caches for further reading.

    :param  devEUI:string -- devEUI of the device
    :param  data  :string -- data extracted from message json
    """
    # To decode data with Base64.
    data = base64.b64decode(data).decode("utf-8")

    # To deconstruct data into parts.
    parts = data.split("_")
    parts_len = len(parts)

    # More than one command are not allowed.
    if parts_len < 3 or parts_len > 4:
        issue_command(devEUI, "invalid message data: {}".format(data))
        return

    device, number, value = parts[0], int(parts[1]), parts[2]
    # "state" is ignored (see readme/command_code or readme/state_code)
    if parts_len is 3:
        key = "state"
    else:
        key, value = parts[2], parts[3]
    if not judge(device, number):
        issue_command(devEUI,
                      "\"{}_{}\" does not exist".format(device, number))
        return
    if key not in keys[device]:
        issue_command(devEUI,
                      "\"{}\" devices have no key \"{}\"".format(device, key))
        return
    if value not in keys[device][key]:
        issue_command(
            devEUI,
            "value \"{}\" is not included in key \"{}\" of \"{}\" devices:\n".
            format(value, key, device) + ", ".join(keys[device][key]))
        return
    # To print for debug
    print("RECEIVED : {}_{}".format(device, number), key, value)
    write_database(device, number, devEUI, key, value)
コード例 #4
0
ファイル: handlers.py プロジェクト: nczitzk/maison
def state_handler(device, number, form):
    """
    To fetch states of certain device with Structive Query Language SUPPORTED!

    :param  device:string -- device name (eg. light, fan...)
    :param  number:int    -- device number (eg. 1 for No.1...)
    :param  form  :json   -- argument form (see readme/state)
    :return json
    """
    if not judge(device, number):
        return "\"{}_{}\" does not exist".format(device, number)

    # To deconstruct <ResultSet> wrapper around database query result.
    info = []
    for resultset in query_database(device, number, form):
        info_generator = resultset.get_points()
        while True:
            try:
                info.append(next(info_generator))
            except StopIteration:
                break

    return json.dumps(info if len(info) > 1 else info[0])
コード例 #5
0
import utils
import random

print("じゃんけんをはじめます")
player_name = input("名前を入力してください:")
print('何を出しますか?(0: グー, 1: チョキ, 2: パー)')
player_hand = int(input("数字で入力してください:"))

if utils.validate(player_hand):
    computer_hand = random.randint(0, 2)

    if player_name == "":
        utils.print_hand(player_hand)
    else:
        utils.print_hand(player_hand, player_name)

    utils.print_hand(computer_hand, "コンピューター")

    result = utils.judge(player_hand, computer_hand)
    print("結果は" + result + "でした")
else:
    print("正しい数値を入力してください")
コード例 #6
0
import utils
import random

print('じゃんけんをしよう!!')
player_name = input('名前はなに?')
select_hand = int(input('何を出すか数字で決めてね!(0:ぐー 1:チョキ 2:パー)'))

if utils.validate(select_hand):
    computer_hand = random.randint(0, 2)
    if player_name == '':
        utils.print_hand(select_hand)
    else:
        utils.print_hand(select_hand, player_name)
    utils.print_hand(computer_hand, 'コンピューター')
    result = utils.judge(select_hand, computer_hand)
    print('結果は' + result + 'でした')
else:
    print('正しい値を入力してください')
コード例 #7
0
ファイル: handlers.py プロジェクト: nczitzk/maison
def command_handler(device, number, form):
    """
    To tranlate raw command to command code (see readme/commands_code)
    and filter out invalid command.

    :param  device:string -- device name (eg. light, fan...)
    :param  number:int    -- device number (eg. 0 for all, 1 for No.1...)
    :param  form  :json   -- command form (see readme/commands)
    :return string
    """
    if not judge(device, number):
        return "\"{}_{}\" does not exist".format(device, number)

    # queue for sending commands through MQTT
    queue = {}
    # result list composed by successfully interpreted commands
    results = []
    # error list containing commands with invalid keys or values
    errors = []
    # If commands contain "_time", then make it a cron job
    cron = False
    time = ""

    for (key, value) in form.items():
        if key in keys[device]:
            if value not in keys[device][key]:
                errors.append("value \"{}\" is not included in key \"{}\" of \"{}\" devices:\n".format(
                    value, key, device) + ", ".join(keys[device][key]))
                continue

            # "state" is ignored (see readme/command_code or readme/state_code)
            # Some values need to be translated into number form.
            states_str = "" if key == "state" else key + "_"
            value_str = configs["value"][str(value)] if str(
                value) in configs["value"] else str(value)

            # If commands acting on all devices of same type,
            # then push them into queue.
            if number == 0:
                for device_num in configs["devices"][device]:
                    queue["#{}_{}_{}{}".format(
                        configs["id"][device], device_num, states_str, value_str)] = device_num
                    results.append("{}_{}::{} -> {}".format(
                        device, device_num, key, value_str))
            else:
                queue["#{}_{}_{}{}".format(
                    configs["id"][device], number, states_str, value_str)] = str(number)
                results.append("{}_{}::{} -> {}".format(
                    device, number, key, value_str))
        elif key == "_time":
            time = value
            cron = True
        else:
            errors.append(
                "\"{}\" devices have no key \"{}\"".format(device, key))

    # Let us free the queue :D
    if cron:
        for (command, device_num) in queue.items():
            add_cron(
                time, configs["devEUI"]["{}_{}".format(device, device_num)], command)
    else:
        for (command, device_num) in queue.items():
            issue_command(
                configs["devEUI"]["{}_{}".format(device, device_num)], command)

    # To generate the output for results
    output = (("the following commands {} issued{}:\n> {}".format(
        "will be" if cron else "have been",
        " at {}".format(time) if cron else "",
        "\n> ".join(results))) if results else "") + \
        ((("\n" if results else "") +
          "errors have occured when parsing commands below:\n> {}".format(
            "\n> ".join(errors))) if errors else "")
    return output
コード例 #8
0
    if utils.name_validate(player_name):
        print('Player name can\'t be empty.')
        player_name = utils.input_user_name_1(count)
        if utils.name_validate(player_name):
            print('You have use the maximum limit. Exiting the program.')
            sys.exit()

other_player_name = input('Enter the other player name (optional): ')
print('Pick a hand: (0: Rock, 1: Paper, 2: Scissors)')

try:
    player_choice = int(input('Enter your choice: '))
except ValueError:
    print('Input should be a number only.')
    sys.exit()
if utils.validate(player_choice):
    #print ('into the functions')

    computer_hand = random.randint(0, 2)
    #print(random.randint(0,2))
    utils.print_hands(player_choice, player_name)
    if utils.name_validate(other_player_name):
        utils.print_hands(computer_hand)
    else:
        utils.print_hands(computer_hand, other_player_name)

    #print (computer_hand)
    print(utils.judge(player_choice, computer_hand))
else:
    print('Enter a valid choice.')