示例#1
0
 def background(self):
     net.send(self.addr, self.uplevel, 'discover')
     while 1:
         src, dst, data = net.dev_recv(self.s, self.addr, self.uplevel)
         if dst == self.addr and '_on_packet' in dir(self):
             self._on_packet(src, data)
         elif dst == 0 and '_on_broadcast' in dir(self):
             self._on_broadcast(src, data)
示例#2
0
文件: testChat.py 项目: slnc/cs425cp
 def test_should_ignore_messages_from_someone_not_in_the_group(self):
     self.test_should_be_able_to_create_group_if_not_already_in_a_group()
     self.c2 = Chat((Chat.DEFAULT_LISTEN_IP, getUnusedListenPort()))
     
     # send a message from c2 to c
     c1msgs = len(self.c.messages)
     c2rcv = len(self.c2.receivedPackets())
     c2nick = GroupView.defaultNickFromAddress(self.c2.getListenAddress())
     net.send(Message('hi', c2nick, 'lobby'), self.c2.getListenAddress(), self.c.getListenAddress())
     time.sleep(0.1)
     self.assertEqual(c1msgs, len(self.c.messages))
     self.assertEqual(c2rcv, len(self.c2.receivedPackets()))
示例#3
0
文件: Chat.py 项目: slnc/cs425cp
 def _sendPacket(self, msg, target_address, handle_failures=True):
     '''Sends a command to a single target via unicast.
     
     If there is an error it will return target_address. It will return
     None otherwise.'''
     self.sentPackets.append((msg, target_address))
     return net.send(msg, self.address, target_address)
示例#4
0
    def handle_sms(cmd):
        global cond_on, alarm_on

        if cmd == 'roomlight on':
            net.send(addr, 8003, 1)
        elif cmd == 'roomlight off':
            net.send(addr, 8003, 0)
        elif cmd == 'conditioner on':
            cond_on = True
        elif cmd == 'conditioner off':
            cond_on = False
        elif cmd == 'alarm on':
            alarm_on = True
        elif cmd == 'alarm off':
            alarm_on = False
            net.send(addr, 8012, 0)
示例#5
0
def main():
    if len(sys.argv) != 3:
        print "Example: python %s HOST PORT" % sys.argv[0]
        exit(0)
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((sys.argv[1], int(sys.argv[2])))
    server.listen(1)
    con, addr = server.accept()
    server.close()
    #send N,e
    r = RSA(128)
    send(con, pack_num(r.N))
    send(con, pack_num(r.e))
    # recv des key,iv
    key = pack_num(r.decrypt(unpack_num(recv(con))))
    iv = pack_num(r.decrypt(unpack_num(recv(con))))
    des = DES(key, iv)

    socks = [con.fileno(), sys.stdin.fileno()]
    mark = True
    while mark:
        readable, _, error = select.select(socks, [], socks)
        for i in readable:
            if i == con.fileno():
                raw = recv(con)
                if not raw:
                    mark = False
                    break
                data = des.decrypt(raw)
                sys.stdout.write(data)
            elif i == sys.stdin.fileno():
                data = sys.stdin.readline()
                if not data:
                    mark = False
                    break
                send(con, des.encrypt(data))
    con.close()
示例#6
0
def main():
    if len(sys.argv) != 3:
        print "Example: python %s HOST PORT" % sys.argv[0]
        exit(0)

    con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    con.connect((sys.argv[1], int(sys.argv[2])))
    # recv N,e
    N = unpack_num(recv(con))
    e = unpack_num(recv(con))
    r = RSA(N=N, e=e)
    key = get_random_str(8)
    iv = get_random_str(8)
    des = DES(key, iv)
    # send key,iv
    send(con, pack_num(r.encrypt(unpack_num(key))))
    send(con, pack_num(r.encrypt(unpack_num(iv))))

    socks = [con.fileno(), sys.stdin.fileno()]
    mark = True
    while mark:
        readable, _, error = select.select(socks, [], socks)
        for i in readable:
            if i == con.fileno():
                raw = recv(con)
                if not raw:
                    mark = False
                    break
                data = des.decrypt(raw)
                sys.stdout.write(data)
            elif i == sys.stdin.fileno():
                data = sys.stdin.readline()
                if not data:
                    mark = False
                    break
                send(con, des.encrypt(data))
    con.close()
示例#7
0
def play_as_client(server):
    if supports_ansi():
        print('\x1b[3F\x1b[J', end='')  # clear initial connection text
    else:
        print()

    # CREATE CHARACTER #

    client_element = pick_element()
    client_stats = pick_stats()
    # pick moveset from that elementalist's movelist of possible moves
    if client_element == 'earth':
        client_moveset = pick_moveset('earth')
    elif client_element == 'fire':
        client_moveset = pick_moveset('fire')
    elif client_element == 'water':
        client_moveset = pick_moveset('water')
    elif client_element == 'wind':
        client_moveset = pick_moveset('wind')

    client_info = {
        'element': client_element,
        'stats': client_stats,
        'moveset': client_moveset
    }
    send(server, client_info)

    # BATTLE STAGE #

    wait()
    print('Let the battle commence!')
    wait()

    while True:

        hp_info = receive(server)
        print('Your HP: {}    Opponent\'s HP: {}\n'.format(
            hp_info['client_hp'], hp_info['server_hp']))
        print('Your moves:\n')
        for move in client_moveset:
            print_move(move)
        # push client for move until valid move entered
        while True:
            client_move = input('Choose your move: ').lower()
            if client_move in client_moveset:
                break
        send(server, client_move)
        wait()  # wait before printing results for better user experience

        # faster player's attack results
        results = receive(server)
        if results['attacker'] == 'server':
            print_def_results(results)
        else:
            print_atk_results(results)

        # check if game over
        if knocked_out(results['client_hp'], results['server_hp']):
            break

        # slower player's attack results
        results = receive(server)
        if results['attacker'] == 'server':
            print_def_results(results)
        else:
            print_atk_results(results)

        # check if game over
        if knocked_out(results['client_hp'], results['server_hp']):
            break

        # receive status info
        status_info = receive(server)
        if status_info['server_status'] == 'burned':
            print('Your opponent loses 25 HP from burns.')
            wait()
        if status_info['client_status'] == 'burned':
            print('You lose 25 HP from your burn.')
            wait()
        if knocked_out(status_info['client_hp'], status_info['server_hp']):
            break
示例#8
0
def play_as_server(client):
    if supports_ansi():
        print('\x1b[3F\x1b[J', end='')  # clear initial connection text
    else:
        print()

    # CREATE CHARACTERS #

    server_element = pick_element()

    # given the number stat chosen, get the map for those stats
    server_stat_num = int(pick_stats()) - 1
    server_stats = STAT_OPTIONS[server_stat_num]

    # pick moveset from that elementalist's movelist of possible moves
    if server_element == 'earth':
        server_moveset = pick_moveset('earth')
    elif server_element == 'fire':
        server_moveset = pick_moveset('fire')
    elif server_element == 'water':
        server_moveset = pick_moveset('water')
    elif server_element == 'wind':
        server_moveset = pick_moveset('wind')

    server_elementalist = Elementalist(server_element, server_stats['hp'],
                                       server_stats['attack'],
                                       server_stats['speed'], server_moveset)

    client_info = receive(client)
    # don't trust client: check info before instantiating elementalist
    if client_info['element'] not in {'earth', 'fire', 'water', 'wind'}:
        raise SystemExit(
            'The client\'s element choice was invalid. Client may be tampering with'
            + ' the code. Exiting the program.')
    # check that client chose one of the five stats options
    if int(client_info['stats']) not in range(1, 6):
        raise SystemExit(
            'The client\'s stats choice was invalid. Client may be tampering with '
            + 'the code. Exiting the program.')
    # check that the moveset is valid
    for choice in client_info['moveset']:
        # check that choice is a valid type for that elementalist
        valid_choice = False
        if client_info['element'] == 'earth':
            if MOVES[choice]['type'] == 'earth':
                valid_choice = True
        elif client_info['element'] == 'fire':
            if MOVES[choice]['type'] == 'fire':
                valid_choice = True
        elif client_info['element'] == 'water':
            if MOVES[choice]['type'] == 'water':
                valid_choice = True
        elif client_info['element'] == 'wind':
            if MOVES[choice]['type'] == 'wind':
                valid_choice = True
        # normal type moves are valid for all elementalists
        if MOVES[choice]['type'] == 'normal':
            valid_choice = True
        # if one of the moves was not in the proper movelist
        if not valid_choice:
            raise SystemExit(
                'The client\'s move choice was invalid. Client may be ' +
                'tampering with the code. Exiting the program.')
    # finished checking client_info

    # Given the number stat chosen, get the map for those stats
    client_stat_num = int(client_info['stats']) - 1
    client_stats = STAT_OPTIONS[client_stat_num]

    client_elementalist = Elementalist(client_info['element'],
                                       client_stats['hp'],
                                       client_stats['attack'],
                                       client_stats['speed'],
                                       client_info['moveset'])

    # BATTLE STAGE #

    wait()
    print('Let the battle commence!')
    wait()

    while True:

        hp_info = {
            'server_hp': server_elementalist.hp,
            'client_hp': client_elementalist.hp
        }
        send(client, hp_info)
        print('Your HP: {}    Opponent\'s HP: {}\n'.format(
            server_elementalist.hp, client_elementalist.hp))
        # choose a move
        print('Your moves:\n')
        for move in server_elementalist.moveset:
            print_move(move)
        while True:
            server_move = input('Choose your move: ').lower()
            if server_move in server_elementalist.moveset:
                break
        # receive and validate client's move
        client_move = receive(client)
        if client_move not in client_elementalist.moveset:
            raise SystemExit(
                'The client\'s move choice was invalid. Client may be tampering with '
                + 'the code. Exiting the program.')
        wait()  # call wait before printing results for nicer user experience
        # evaluate speeds
        if server_first(server_elementalist, server_move, client_elementalist,
                        client_move):
            server_second = False
            # if server's first, server attacks client
            server_atk_results = attack(server_elementalist, server_move,
                                        client_elementalist)
            # let client know which results these are
            server_atk_results['attacker'] = 'server'
            # tell client the hp of each after the attack
            server_atk_results['server_hp'] = server_elementalist.hp
            server_atk_results['client_hp'] = client_elementalist.hp
            send(client, server_atk_results)
            print_atk_results(server_atk_results)
            if knocked_out(server_elementalist.hp, client_elementalist.hp):
                break
        else:
            server_second = True
        # client attacks server
        client_atk_results = attack(client_elementalist, client_move,
                                    server_elementalist)
        client_atk_results['attacker'] = 'client'
        client_atk_results['server_hp'] = server_elementalist.hp
        client_atk_results['client_hp'] = client_elementalist.hp
        send(client, client_atk_results)
        print_def_results(client_atk_results)
        if knocked_out(server_elementalist.hp, client_elementalist.hp):
            break
        # if server hadn't been first, server attacks client
        if server_second:
            server_atk_results = attack(server_elementalist, server_move,
                                        client_elementalist)
            server_atk_results['attacker'] = 'server'
            server_atk_results['server_hp'] = server_elementalist.hp
            server_atk_results['client_hp'] = client_elementalist.hp
            send(client, server_atk_results)
            print_atk_results(server_atk_results)
            if knocked_out(server_elementalist.hp, client_elementalist.hp):
                break

        # status conditions
        if server_elementalist.status == 'burned':
            print('You lose 25 HP from your burn.')
            wait()
            server_elementalist.hp -= 25
        if client_elementalist.status == 'burned':
            print('Your opponent loses 25 HP from burns.')
            wait()
            client_elementalist.hp -= 25

        # send status condition info to client
        status_info = {
            'server_status': server_elementalist.status,
            'client_status': client_elementalist.status,
            'server_hp': server_elementalist.hp,
            'client_hp': client_elementalist.hp
        }
        send(client, status_info)

        # check that the status condition didn't knock one out
        if knocked_out(server_elementalist.hp, client_elementalist.hp):
            break
示例#9
0
文件: dog.py 项目: jaketanwh/gp
def jj():
    global GP_JJ_CATCH_DIC,GP_ALL_STR_URL_LIST

    # TODO 待优化:
    # 1.多线程发送协议,运行策略与请求数据分别进行
    # 2.未开板新股去除判定
    for url in GP_ALL_STR_URL_LIST:
        res = net.send(url, 0, 0)
        if res != -1:
            first = 1
            gpArray = res.split(';')
            for gp in gpArray:
                if len(gp) < 20:
                    continue

                if first == 1:
                    o = gp[13:]
                    first = None
                else:
                    o = gp[14:]

                _id = o[:6]
                data = o[8:][:-1]
                _o = data.split(',')
                if len(_o) < 31:
                    continue

                _31 = _o[31]  # 时间
                tmplist = GP_JJ_CATCH_DIC[_id]['list']
                # 1)
                # 数据去重
                _len = len(tmplist)
                if _len > 0:
                    tmpdata = tmplist[-1]
                    if tmpdata[2] == _31 or (tmpdata[0] == _o[6] and tmpdata[1] == _o[10]): # and tmpdata[2] == _o[11]
                        continue

                # 停盘去除
                if float(_o[3]) == 0:
                    continue

                # 2)收集数据
                '''
                _0 = _o[0]  # 名字
                _1 = _o[1]  # 今日开盘价
                _2 = _o[2]  # 昨日收盘价
                _3 = _o[3]  # 当前价格
                _4 = _o[4]  # 今日最高价
                _5 = _o[5]  # 今日最低价
                _6 = _o[6]  # 竞买价,即“买一”报价
                _7 = _o[7]  # 竞卖价,即“卖一”报价
                _8 = _o[8]  # 成交的股票数,由于股票交易以一百股为基本单位,所以在使用时,通常把该值除以一百
                _9 = _o[9]  # 成交金额,单位为“元”,为了一目了然,通常以“万元”为成交金额的单位,所以通常把该值除以一万
                _10 = _o[10]  # “买一”申请4695股,即47手
                _11 = _o[11]  # “买一”报价
                _12 = _o[12]  # 买二 申请
                _13 = _o[13]  # 买二 报价
                _14 = _o[14]  # 买三 申请
                _15 = _o[15]  # 买三 报价
                _16 = _o[16]  # 买四 申请
                _17 = _o[17]  # 买四 报价
                _18 = _o[18]  # 买五 申请
                _19 = _o[19]  # 买五 报价
                _20 = _o[20]  # “卖一”申报3100股,即31手
                _21 = _o[21]  # “卖一”报价
                _22 = _o[22]  # 卖二
                _23 = _o[23]  # 卖二
                _24 = _o[24]  # 卖三
                _25 = _o[25]  # 卖三
                _26 = _o[26]  # 卖四
                _27 = _o[27]  # 卖四
                _28 = _o[28]  # 卖五
                _29 = _o[29]  # 卖五
                _30 = _o[30]  # 日期
                _31 = _o[31]  # 时间
                '''
                if _len == 0:
                    _oname = _o[0]
                    GP_JJ_CATCH_DIC[_id]['name'] = _oname
                    #GP_JJ_CATCH_DIC[_id]['date'] = _o[30]
                    #GP_JJ_CATCH_DIC[_id]['ed'] = _o[2]

                arr = []
                arr.append(_o[6])
                arr.append(_o[10])
                arr.append(_31)
                #arr[0] = _o[6]          # 竞买价,即“买一”报价
                #arr[1] = _o[10]         # “买一”申请4695股,即47手
                #arr[2] = _o[11]         # “买一”报价
                #arr[2] = _31            # 时间
                GP_JJ_CATCH_DIC[_id]['list'].append(arr)
示例#10
0
文件: dog.py 项目: jaketanwh/gp
def sina(cnt):
    global SINA_RUL
    url = SINA_RUL % (str(cnt))
    res = net.send(url)
    if res == -1:
        return

    global GP_CATCH_DIC,SINA_BUY_TIP_LIST,SINA_SELL_TIP_LIST,FIRST_INIT
    res = res.replace('symbol', '"symbol"')
    res = res.replace('name', '"name"')
    res = res.replace('ticktime', '"ticktime"')
    res = res.replace(',price', ',"price"')
    res = res.replace('volume', '"volume"')
    res = res.replace('prev_price', '"prev_price"')
    res = res.replace('kind:', '"kind":')
    if res == 'null':
        return

    res = eval(res)
    for row in res:
        kind = row['kind']
        if kind == 'E':
            continue
        code = row['symbol'][2:]
        data = GP_CATCH_DIC.get(code,{})
        _ozsp = float(data.get('ed',0))   # 昨日收盘价格
        cur = float(row['price'])
        prev = float(row['prev_price'])
        volume = float(row['volume'])
        if cur > prev and kind == 'D':
            ctime = row['ticktime']
            sign = ctime + code
            if sign in SINA_BUY_TIP_LIST:
                continue

            SINA_BUY_TIP_LIST.append(sign)
            # 单笔拉升3%
            if _ozsp != 0 and ((cur / _ozsp) - (prev / _ozsp)) > 0.3:
                if FIRST_INIT != 1:
                    s = '[拉盘][' + row['ticktime'] + '] ' + row['name'] + ' ' + code + ' 单笔拉升超3%'
                    qq.senMsgToBuddy(s)
                    qq.sendMsgToGroup(s)

            money = int(volume * cur / 10000)
            #if money < 100:
            #    continue

            #大单主买
            if FIRST_INIT != 1:
                s = '[主买][' + ctime + '] ' + row['name'] + ' ' + code + ' ' + str(int(volume/100)) + '手超大单买盘,金额:' + str(money) + '万元'
                qq.senMsgToBuddy(s)
                qq.sendMsgToGroup(s)


        elif cur < prev and kind == 'D':
            ctime = row['ticktime']
            sign = ctime + code
            if sign in SINA_SELL_TIP_LIST:
                continue
            SINA_SELL_TIP_LIST.append(sign)

            # 单笔砸盘3%
            if _ozsp != 0 and ((prev / _ozsp) - (cur / _ozsp)) > 0.3:
                if FIRST_INIT != 1:
                    s = '[砸盘][' + row['ticktime'] + '] ' + row['name'] + ' ' + code + ' 单笔砸盘超3%'
                    qq.senMsgToBuddy(s)
                    qq.sendMsgToGroup(s)

            money = int(volume * cur / 10000)
            if money < 500:
                continue

            #大单主卖
            if FIRST_INIT != 1:
                s = '[主卖][' + row['ticktime'] + '] ' + row['name'] + ' ' + code + ' ' + str(int(volume/100)) + '手超大单抛盘,金额:' + str(money) + '万元'
                qq.senMsgToBuddy(s)
                qq.sendMsgToGroup(s)
示例#11
0
文件: Chat.py 项目: slnc/cs425cp
 def sendFinalOrdering(self, mid, mySeq):
     for addr in self.groupView.returnOnlineUsers():
         net.send(FinalOrdering(mid, mySeq), self.getListenAddress(), addr)
示例#12
0
文件: Chat.py 项目: slnc/cs425cp
 def sendOrderingSuggestion(self, mid, mySeq, sender):
     net.send(OrderingSuggestion(mid, mySeq), self.getListenAddress(), sender)
import cv2

# PC ip주소
# HOST = '172.30.1.39'
HOST = '192.168.0.4'
#HOST = '192.168.0.4' #태석pc

PORT = 5000

button = Button(20)

if __name__ == '__main__':
    save = 0
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        writer = s.makefile('wb')
        reader = s.makefile('rb')
        # device 번호
        with Video(device=0) as v:
            for image in v:
                image = Video.to_jpg(image, 60)

                if button.is_pressed:
                    save = 1
                else:
                    save = 0

                net.send(writer, image, save)

                # result = net.receive(reader)[0]
                # print(json.loads(result.decode()))
示例#14
0
def ai(data, writer):
    count_list = [0, 0, 0, 0, 0, 0]
    conn = pymysql.connect(host='yangjae-team08-database.ca8iiefanafw.eu-south-1.rds.amazonaws.com',
                         port=3306, user='******', password='******', db='mydb', charset='utf8')
    cur = conn.cursor()
    tm = time.localtime((time.time()))
    data_date = f'{tm.tm_year}_{tm.tm_mon}_{tm.tm_mday}_{tm.tm_min}_{tm.tm_sec}'
    faces_list = [] 
    faces_list = face_crop(data)
    model_age, model_gender = load_models()
    print('detected' + str(len(faces_list)))
    cam_location = 'Seoul'

    temp_age = []
    temp_gender = []
    temp_crop = []
    for i, face in enumerate(faces_list):
        buffer = BytesIO()
        age_result, gender_result = predict_models(model_age, model_gender, face)

        face = face.reshape(64, 64, 3)
        face_jpg = Image.fromarray((face * 255).astype(np.uint8))
        face_jpg.save(buffer, format = 'jpeg')
        face_byte = base64.b64encode(buffer.getvalue())

        if age_result == 'kids':
            count_list[0] += 1
        elif age_result == '2030' and gender_result == 'man':
            count_list[1] += 1
        elif age_result == '2030' and gender_result == 'woman':
            count_list[2] += 1
        elif age_result == '4050' and gender_result == 'man':
            count_list[3] += 1
        elif age_result == '4050' and gender_result == 'woman':
            count_list[4] += 1
        else:
            count_list[5] += 1

        temp_age.append(age_result)
        temp_gender.append(gender_result)
        temp_crop.append(face_byte)
    selected_id = select_AD(count_list)

    sql_select_AD = f'SELECT ad_id, ad_name, budget FROM advert WHERE ad_id = "{selected_id}"'
    cur.execute(sql_select_AD)
    ad_id, ad_name, budget = cur.fetchone()
    print('url')
    IoT_ad_url = f'https://yangjae-team08-bucket.s3.eu-south-1.amazonaws.com/{ad_name}.mp4'
    IoT_ad_url = IoT_ad_url.replace(' ', '+')
    IoT_ad_name = ad_name + '.mp4'
    IoT_ad_name = IoT_ad_name.replace(' ',  '_')

    result = json.dumps({'url': IoT_ad_url, 'ad_file': IoT_ad_name})
    net.send(writer, result.encode())

    for crop, age, gender in zip(temp_crop, temp_age, temp_gender):
        # INSERT face Table
        sql_face = '''INSERT INTO face(face_array, input_image, location)
                VALUES(%s, %s, %s)'''
        cur.execute(sql_face, [crop, data_date, cam_location])
        conn.commit()

        # MAX(face_id)
        sql_face_id = '''SELECT MAX(face_id) FROM face'''
        cur.execute(sql_face_id)
        face_id = cur.fetchone()

        # INSERT target Table SQL
        sql_target = '''INSERT INTO target(face_id, ad_id, age, gender)
                VALUES(%s, %s, %s, %s)'''
        cur.execute(sql_target, [face_id, ad_id, age, gender])
        conn.commit()
示例#15
0
def main(argv):
    addr = int(argv[0])
    uplevel = int(argv[1])
    downlevel = set()
    immediate_downlevel = set()

    s = net.listen(addr)

    rediscover_tm = 0

    def log(s):
        print 'router[%d]: %s' % (addr, s)

    while 1:
        tm = time.time()
        if tm > rediscover_tm:
            log('rediscover initiated')
            net.send(addr, 0, 'discover')
            rediscover_tm = tm + REDISCOVER_DELAY

        src, dst, sendby, data = net.recv_all(s)
        log('packet captured: %s' % ((src, dst, sendby, data), ))

        if dst == addr and data == 'discover':
            if sendby == src:
                log('immediate downlevel device discovered: %d' % src)
                immediate_downlevel.add(src)
                downlevel.add(src)
            else:
                log('downlevel device discovered: %d' % src)
                downlevel.add(src)

            log('sending self discover to uplevel router')
            net.send(addr, uplevel, 'discover', sendby = addr)

            log('forwarding discover to uplevel router')
            net.send(src, uplevel, 'discover', sendby = addr)

        elif dst == 0 and src == uplevel and sendby == uplevel and data == 'discover':
            log('downlevel devices discover request recieved, forwarding...')
            net.send(addr, 0, 'discover')

        elif sendby == uplevel and dst in downlevel:
            log('forwarding packet sent by uplevel router to %d (%s)' % (dst, data))
            net.send(src, dst, data, sendby = addr)

        elif sendby in immediate_downlevel:
            log('forwarding packet sent by immediate downlevel router/device to %d (%s)' % (dst, data))
            net.send(src, dst, data, sendby = addr)

        else:
            log('packet dropped')
示例#16
0
文件: test.py 项目: LeeSungRyul/KD_AI
def ai(data, writer, location):
    count_list = [0, 0, 0, 0, 0, 0]
    conn = pymysql.connect(host='yangjae-team08-database.ca8iiefanafw.eu-south-1.rds.amazonaws.com',
                           port=3306, user='******', password='******', db='mydb', charset='utf8')
    cur = conn.cursor()
    tm = time.localtime((time.time()))
    data_date = f'{tm.tm_year}_{tm.tm_mon}_{tm.tm_mday}_{tm.tm_min}_{tm.tm_sec}'
    faces_list = []
    faces_list = face_crop(data)

    if len(faces_list) == 0:
        result = json.dumps({'url': '0', 'ad_file': '0'})
        net.send(writer, result.encode())
    else:
        model_age, model_gender = load_models()
        print('detected : ' + str(len(faces_list)))
        cam_location = location

        temp_age = []
        temp_gender = []
        temp_crop = []
        for i, face in enumerate(faces_list):
            buffer = BytesIO()
            age_result, gender_result = predict_models(model_age, model_gender, face)

            face = face.reshape(128, 128, 3)
            face_jpg = Image.fromarray((face * 255).astype(np.uint8))
            face_jpg.save(buffer, format='jpeg')
            face_byte = base64.b64encode(buffer.getvalue())

            if age_result == 'kids':
                count_list[0] += 1
            elif age_result == '2030' and gender_result == 'man':
                count_list[1] += 1
            elif age_result == '2030' and gender_result == 'woman':
                count_list[2] += 1
            elif age_result == '4050' and gender_result == 'man':
                count_list[3] += 1
            elif age_result == '4050' and gender_result == 'woman':
                count_list[4] += 1
            else:
                count_list[5] += 1

            temp_age.append(age_result)
            temp_gender.append(gender_result)
            temp_crop.append(face_byte)
        selected_id = select_AD(count_list)

        sql_select_AD = f'SELECT ad_id, ad_name FROM advert WHERE ad_id = "{selected_id}"'
        cur.execute(sql_select_AD)
        ad_id, ad_name = cur.fetchone()
        print('send url')
        IoT_ad_url = f'https://yangjae-team08-bucket.s3.eu-south-1.amazonaws.com/{ad_name}.mp4'
        IoT_ad_url = IoT_ad_url.replace(' ', '+')
        IoT_ad_name = ad_name + '.mp4'
        IoT_ad_name = IoT_ad_name.replace(' ', '_')

        result = json.dumps({'url': IoT_ad_url, 'ad_file': IoT_ad_name})
        print(f'전송된 URL : {IoT_ad_url}')
        print(f'전송된 파일 : {IoT_ad_name}')
        net.send(writer, result.encode())
示例#17
0
文件: ipv4.py 项目: yiopposite/pyip
def send(from_ip, to_ip, pdu, **extras):
    if to_ip == 0:
        log.error('target IP cannot be 0!')
        return 0

    if from_ip == 0:
        from_ip = net.ip_hint(to_ip)

    _stat.tx_count += 1

    pac = Pack(from_ip, to_ip, pdu, **extras)

    log.debug('SEND %s', pac)

    # TODO: obtain MTU from the sending interface
    mtu = 1500

    # Fast path - no fragmentation
    if len(pac) <= mtu:
        net.send(pac)
        return 1

    # fragmentation
    if pac.DF:
        # TODO: ICMP error
        log.warning('cannot send large packet with DF set')
        _stat.tx_dropped += 1
        return 0

    _stat.tx_fragmented += 1
    log.info('fragmenting large packet')

    hdr = pac.hdr
    nhdr = len(hdr)
    if hasattr(pdu, 'pack'):
        pdu = pdu.pack(None)
    npdu = len(pdu)

    ps = (mtu - nhdr) >> 3 << 3
    (n, r) = divmod(npdu, ps)
    if r == 0:
        n -= 1

    # send the last frag first
    net.send(Pack(from_ip, to_ip, pdu[n * ps:],
                  DSCP=pac.DSCP, ECN=pac.ECN,
                  proto=pac.proto, ttl=pac.ttl, ident=pac.ident,
                  MF=0, offset=n*ps>>3,
                  opts=tuple(opt for opt in pac.opts if opt.Copy)))

    # send remaining frags in reversed order
    while n > 0:
        n -= 1
        offset = n * ps
        net.send(Pack(from_ip, to_ip, pdu[offset:offset+ps],
                      DSCP=pac.DSCP, ECN=pac.ECN,
                      proto=pac.proto, ttl=pac.ttl, ident=pac.ident,
                      MF=1, offset=offset>>3,
                      opts=tuple(opt for opt in pac.opts if n==0 or opt.Copy)))

    return 1
示例#18
0
 def send(self, dst, data):
     net.send(self.addr, dst, data)
示例#19
0
import json
import net
import cv2
import numpy as np
from objdetect import ObjDetectApi, NumpyDecoder

PATH_TO_LABELS = 'data/mscoco_label_map.pbtxt'
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
api = ObjDetectApi(MODEL_NAME, PATH_TO_LABELS)

HOST = '127.0.0.1'
PORT = 5000

if __name__ == '__main__':
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        writer = s.makefile('wb')
        reader = s.makefile('rb')
        with Video(device=0) as v:
            for image in v:
                jpg = Video.to_jpg(image)
                net.send(writer, jpg)

                output_dict = net.receive(reader)[0].decode()
                output_dict = json.loads(output_dict, cls=NumpyDecoder)

                labeled_image = api.visualize(image, output_dict)
                cv2.imshow('frame', labeled_image)
                key = cv2.waitKey(1)
                if key == 27:
                    break
示例#20
0
文件: dog.py 项目: jaketanwh/gp
def gp():
    global GP_CATCH_DIC,GP_ALL_STR_URL_LIST
    #_clock = clock()
    #_clock.start()

    # TODO 待优化:
    # 1.多线程发送协议,运行策略与请求数据分别进行
    # 2.未开板新股去除判定
    for url in GP_ALL_STR_URL_LIST:
        res = net.send(url, 0, 0)
        if res != -1:
            first = 1
            gpArray = res.split(';')
            for gp in gpArray:
                if len(gp) < 20:
                    continue

                if first == 1:
                    o = gp[13:]
                    first = None
                else:
                    o = gp[14:]

                _id = o[:6]
                data = o[8:][:-1]
                _o = data.split(',')
                if len(_o) < 31:
                    continue

                _31 = _o[31]  # 时间
                tmplist = GP_CATCH_DIC[_id]['list']

                # 1)
                # 数据去重
                _len = len(tmplist)
                if _len > 0 and tmplist[31] == _31:
                    continue
                # 停盘去除
                if float(_o[3]) == 0:
                    continue

                # 2)收集数据
                '''
                _0 = _o[0]  # 名字
                _1 = _o[1]  # 今日开盘价
                _2 = _o[2]  # 昨日收盘价
                _3 = _o[3]  # 当前价格
                _4 = _o[4]  # 今日最高价
                _5 = _o[5]  # 今日最低价
                _6 = _o[6]  # 竞买价,即“买一”报价
                _7 = _o[7]  # 竞卖价,即“卖一”报价
                _8 = _o[8]  # 成交的股票数,由于股票交易以一百股为基本单位,所以在使用时,通常把该值除以一百
                _9 = _o[9]  # 成交金额,单位为“元”,为了一目了然,通常以“万元”为成交金额的单位,所以通常把该值除以一万
                _10 = _o[10]  # “买一”申请4695股,即47手
                _11 = _o[11]  # “买一”报价
                _12 = _o[12]  # 买二 申请
                _13 = _o[13]  # 买二 报价
                _14 = _o[14]  # 买三 申请
                _15 = _o[15]  # 买三 报价
                _16 = _o[16]  # 买四 申请
                _17 = _o[17]  # 买四 报价
                _18 = _o[18]  # 买五 申请
                _19 = _o[19]  # 买五 报价
                _20 = _o[20]  # “卖一”申报3100股,即31手
                _21 = _o[21]  # “卖一”报价
                _22 = _o[22]  # 卖二
                _23 = _o[23]  # 卖二
                _24 = _o[24]  # 卖三
                _25 = _o[25]  # 卖三
                _26 = _o[26]  # 卖四
                _27 = _o[27]  # 卖四
                _28 = _o[28]  # 卖五
                _29 = _o[29]  # 卖五
                _30 = _o[30]  # 日期
                _31 = _o[31]  # 时间
                '''
                if _len == 0:
                    _oname = _o[0]
                    GP_CATCH_DIC[_id]['name'] = _oname
                    GP_CATCH_DIC[_id]['s'] = _o[1]
                    GP_CATCH_DIC[_id]['ed'] = _o[2]
                    GP_CATCH_DIC[_id]['date'] = _o[30]
                    GP_CATCH_DIC[_id]['st'] = _oname.find('ST') >= 0
                    GP_CATCH_DIC[_id]['last'] = []
                    GP_CATCH_DIC[_id]['last'].append(float(_o[3]))


                #名字 开盘价 昨收价 日期只保存一份
                _o[0] = 0
                _o[1] = 0
                _o[2] = 0
                _o[30] = 0

                GP_CATCH_DIC[_id]['list'] = _o

                #以下开始每帧策略
                # 3)
                ks(_id)

                # 4)
                sc(_id)

                # 5)
                zd(_id)

                # 6)
                xg(_id)

                # 7)
                pt(_id)
示例#21
0
from video import Video
from time import sleep
import socket, json, net

HOST = '218.38.254.30'
PORT = 5000

if __name__ == '__main__':
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        writer = s.makefile('wb')
        reader = s.makefile('rb')
        with Video(device=0) as v:
            for image in v:
                image = Video.to_jpg(image, 80)
                print('video send ', len(image))
                net.send(writer, image)

                result = net.receive(reader)[0]
                print(json.loads(result.decode()))
示例#22
0
 def send_sms(text):
     net.send(addr, 8009, ('sms', '+79116661488', text))
示例#23
0
    with Video(device = 0) as v:    # 카메라 번호 지정
      middle_time = time.time()
      check = middle_time - start_time    # 사전 작업시간
    # with Video(file = 'test_people.jpg') as v:    # 카메라 번호 지정
      num_detections, image_data = 0, []
      for i in range(18):
        v.cap.read()
      for image in v:
        Video.show(image)                       # 영상 스트리밍
        num_detection = detect_face(image)      # 검출 인원 수 체크
        print(num_detection)
        if time.time() - middle_time > need_second:
          break         # 지정된 n초 후 break
        elif num_detection == 0:
          continue

        if num_detection > num_detections:
          num_detections = num_detection        # 최대로 인원 수 갱신
          image_data = Video.to_jpg(image)   # jpg파일 압축
      if len(image_data) == 0:                    # 이미지가 없으면
        print('no data')
      else:
        print("Number of faces detected: ", num_detections)
        net.send(writer, image_data)            # 서버로 데이터 전송
        print('video send ', len(image_data), '/', 'people :', num_detections)
        server_msg(reader)

  end_time = time.time()    # 끝나는 시간
  print('사전 작업시간 :', check)
  print('전체 시간 : ', end_time - start_time)
示例#24
0
def main(args):
    addr = int(args[0])
    s = net.listen(addr)

    immediate_downlevel = set()

    def log(s):
        print 'controller[%d]: %s' % (addr, s)

    cstate = 0

    def send_sms(text):
        net.send(addr, 8009, ('sms', '+79116661488', text))

    def handle_sms(cmd):
        global cond_on, alarm_on

        if cmd == 'roomlight on':
            net.send(addr, 8003, 1)
        elif cmd == 'roomlight off':
            net.send(addr, 8003, 0)
        elif cmd == 'conditioner on':
            cond_on = True
        elif cmd == 'conditioner off':
            cond_on = False
        elif cmd == 'alarm on':
            alarm_on = True
        elif cmd == 'alarm off':
            alarm_on = False
            net.send(addr, 8012, 0)

    while 1:
        src, dst, sendby, data = net.recv_all(s)

        #log('packet captured: %s' % ((src, dst, sendby, data), ))

        if dst == addr and sendby == src and data == 'discover':
            log('immediate downlevel device discovered: %d' % src)
            immediate_downlevel.add(src)
            continue

        if dst == addr and sendby != src and data == 'discover':
            log('downlevel device discovered: %d, ignored' % src)
            continue

        if dst != addr or sendby not in immediate_downlevel:
            continue

        log('packet recieved from %d: %s' % (src, data))

        if src == 8004:
            t = data
            if t > 25 and cond_on:
                net.send(addr, 8005, -1)
            elif t < 25 and cond_on:
                net.send(addr, 8005, 1)
            else:
                net.send(addr, 8005, 0)
        elif src == 8007 or src == 8008:
            cstate += 1 if data else -1
            net.send(addr, 8006, cstate % 2)
        elif src == 8009:
            handle_sms(data)
        elif src == 8010 and alarm_on:
            if data:
                send_sms('door is open')
                net.send(addr, 8012, 1)
        elif src == 8011 and alarm_on:
            if data:
                send_sms('window is open')
                net.send(addr, 8012, 1)

    s.close()
示例#25
0
文件: arp.py 项目: yiopposite/pyip
def _send(dst, src, pac):
    log.debug('SEND %s', pac)
    net.send(eth.Pack(dst, src, pac))