Exemple #1
0
def micro_server(server_address, handle_request):
    address_family = socket.AF_INET
    socket_type = socket.SOCK_STREAM
    request_queue_size = REQUEST_QUEUE_SIZE

    # Create a new socket
    listen_socket = socket.socket(address_family, socket_type)
    # Allow to reuse the same address
    listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Bind
    listen_socket.bind(server_address)
    # Activate
    listen_socket.listen(request_queue_size)
    log.debug("Parent PID (PPID): {pid}\n".format(pid=os.getpid()))

    signal.signal(signal.SIGCHLD, handle_signal)

    while True:
        # New client connection
        client_connection, client_address = listen_socket.accept()
        # Handle request
        log.info("Start connected %s" % client_address[0])
        pid = os.fork()
        if pid == 0:
            listen_socket.close()  # close child copy
            handle_request(client_connection)
            client_connection.close()
            os._exit(0)
        else:
            client_connection.close()
Exemple #2
0
def process_message(data):
    """Echo any Direct Messages (DMs) sent to the @eliza chatbot user on Slack"""
    log.debug('{} heard message: {}'.format(PLUGIN, data))
    channel = data.get('channel', '').upper()
    text = data.get('text', '').lower()
    if channel.startswith("D") or text.startswith('@eliza') or text.startswith('<@{}>'.format(SELF_USER_ID.lower())):
        outputs.append([data['channel'], "{} plugin received '{}' in channel '{}' at {}".format(
                        PLUGIN, data['text'], data['channel'], datetime.datetime.now())])
Exemple #3
0
def get_routes():
    log.debug(request.json)

    origin = (request.json['origin']['lat'], request.json['origin']['lng'])

    destination = (request.json['destination']['lat'],
                   request.json['destination']['lng'])

    return jsonify(find_routes(origin, destination, max_walk=3000))
Exemple #4
0
def process_message(data):
    """Echo any Direct Messages (DMs) sent to the @eliza chatbot user on Slack"""
    log.debug('{} heard message: {}'.format(PLUGIN, data))
    channel = data.get('channel', '').upper()
    text = data.get('text', '').lower()
    if channel.startswith("D") or text.startswith('@eliza') or text.startswith(
            '<@{}>'.format(SELF_USER_ID.lower())):
        outputs.append([
            data['channel'],
            "{} plugin received '{}' in channel '{}' at {}".format(
                PLUGIN, data['text'], data['channel'], datetime.datetime.now())
        ])
Exemple #5
0
def handle_signal(signum, frame):
    while True:
        try:
            pid, status = os.waitpid(-1, os.WNOHANG)
        except OSError:
            return
        if pid == 0:
            return
        else:
            log.debug(
                'Child PID: {pid} terminated with status {status}'.format(
                    pid=pid, status=status))
Exemple #6
0
def _stop_player_process():
    """Stop both Radio and Player processes.

    Does not remove current playing song from playlist. User assumes responsibility of managing playlist.
    Acts like pressing STOP on any media player.
    """
    if player and player.poll() is None:
        player.terminate()
        log.debug("Terminating player process :)")

    if source and source.poll() is None:
        source.terminate()
        log.debug("Terminating source process :)")
Exemple #7
0
def get_stops_between(
        origin_id: str,
        destination_id: str,
        line_id: str,
        bus_lines: Dict[str, List[str]] = LINES) -> List[Dict[str, Any]]:
    l = bus_lines[line_id]

    l = l[l.index(origin_id):l.index(destination_id) + 1]
    log.debug(l)
    return [{
        'id': stop_id,
        'lat': stop_coords(stop_id)[0],
        'lng': stop_coords(stop_id)[1]
    } for stop_id in l]
Exemple #8
0
def _start_player():
    """Play all items found on Playlist sequentially on Radio.

    Starts player and radio process. Waits for the processes to end.
    Returns if _stop_requested or playlist is empty
    """
    global source, player, _stop_requested

    _player_lock.acquire()
    while _playlist:
        try:
            log.info("Playing : %s" % _playlist[0])
            # avconv -i "$File" -f s16le -ar 44100 -ac 2 -loglevel panic -
            source = subprocess.Popen(
                    ["avconv", "-i", "Music/%s" % _playlist[0], "-f", "s16le", "-ar", "44100", "-ac", "2", "-loglevel",
                     "panic", "-"],
                    stdout=subprocess.PIPE)

            if _radio_out:
                # ./pifm - "$2" 44100 stereo "$Volume"
                player = subprocess.Popen(["./pifm", "-", "%.1f" % _freq, "44100", "stereo", str(_volume)],
                                          stdin=source.stdout)
            else:
                # aplay -c 2 -f cd -q
                player = subprocess.Popen(["aplay", "-c", "2", "-f", "cd", "-q"],
                                          stdin=source.stdout)

            source.stdout.close()
        except Exception as error:
            log.error("Error: %s" % error.message)

        api.inform_subscribers()
        ws.inform_subscribers()

        if player:
            log.debug("player.wait() :)")
            player.wait()
            log.debug("Player terminated :)")
        if source:
            log.debug("source.wait() :)")
            source.wait()
            log.debug("Source terminated :)")

        if _stop_requested:
            _stop_requested = False
            break

        _playlist.pop(0)

    source = None
    player = None
    api.inform_subscribers()
    ws.inform_subscribers()

    _player_lock.release()
    log.info("Thread terminated :)")
Exemple #9
0
    async def get_data(self, symbol):
        log.debug("Success on creating TimeSeries")
        ts = TimeSeries(os.environ['API_KEY'])
        log.debug("Querying alpha vantage for data for {}".format(symbol))
        data, meta = await ts.get_daily_adjusted(symbol=symbol,
                                                 outputsize="compact")
        await ts.close()
        log.debug(meta)

        log.debug("Returned alpha vantage data for {}".format(symbol))
        return (data, meta)
Exemple #10
0
    def wait_for(self):
        log.debug("Started event Loop")
        loop = asyncio.get_event_loop()
        tasks = [self.get_data(symbol) for symbol in self.symbols]
        group = asyncio.gather(*tasks)
        results = loop.run_until_complete(group)
        log.debug("Returned all the results")
        loop.close()
        log.debug("Asyncronous loop finished")
        self.results = results
        info = []

        for result, meta in self.results:
            i = 0
            stockName = meta["2. Symbol"]
            tempResult = {}
            tempResult["name"] = stockName
            tempResult["date"] = {}
            for data in result:
                tempResult["date"][data] = {}
                for value in result[data]:
                    tempvalue = value.split(".")[1].strip()
                    tempResult["date"][data][tempvalue] = result[data][value]
                i += 1
                if i == 10:
                    info.append(tempResult)
                    break

        self.db.insert(info, "fp", "stocks")
Exemple #11
0
def process_presence_change(data=None):
    """Queues up a message with the time the bot joined the channel"""
    channel = data.get('channel', None)
    log.debug('Not responding on channel {} to data: {}'.format(channel, data))
Exemple #12
0
def process_presence_change(data=None):
    """Queues up a message with the time the bot joined the channel"""
    channel = data.get('channel', None)
    log.debug('Not responding on channel {} to data: {}'.format(channel, data))
Exemple #13
0
def judge_phase(content, Express_Company):
    guess = []

    if default_key.get(Express_Company):
        key_state = default_key.get(Express_Company)
        # print(key_state,Express_Company)
    else:
        key_state = {
            '打包': '途中',
            '发出': '途中',
            '收入': '途中',
            '发往': '途中',
            '到达': '途中',
            '到件扫描': '揽件',
            '称重扫描': '途中',
            '进行分拨': '途中',
            '【反馈】扫描': '途中',
            '离开': '途中',
            '卸车扫描': '途中',
            '【称重】扫描': '途中',
            '【到件】扫描': '途中',
            '【卸车】扫描': '途中',
            '【分发】扫描': '途中',
            '快件扫描': '途中',
            '已拆包': '途中',
            '签收': '签收',
            '代收': '签收',
            '为您服务': '签收',
            '派件': '派件',
            '【派送】扫描': '派件',
            '收件': '揽收',
            '揽收': '揽收',
            '揽件': '揽收',
            '揽件扫描': '揽收',
            '问题件': '异常',
            '开始配送': '派件',
            '等待配送': '途中',
            '正在投递': '派件',
            '已收寄': '揽收',
            '接收': '途中',
        }

    for k, v in key_state.items():
        if k in content:
            guess.append(v)

    result = set(guess)
    situation = len(result)

    if situation == 1:
        # log.debug('成功=>' + content + '=>' + guess[0])
        return (1, guess[0])

    if situation > 1:
        if '问题件' in guess:
            log.debug('歧义=>' + content + '=>' + '问题件')
            return (1, '异常')
        if '已揽件' in content or '已揽收' in content:
            log.debug('歧义=>' + content + '=>' + '揽收')
            return (1, '揽收')
        if '已签收' in content or '签收人' in content:
            log.debug('歧义=>' + content + '=>' + '签收')
            return (1, '签收')
        if '代收' in content and '取件' in content:
            log.debug('歧义=>' + content + '=>' + '签收')
            return (1, '签收')
        if '途中' in guess and '收件' in guess:
            log.debug('歧义=>' + content + '=>' + '途中')
            return (1, '途中')
        if '途中' in guess and '签收' in guess:
            log.debug('歧义=>' + content + '=>' + '签收')
            return (1, '签收')
        if '已被' in guess and '代签收' in content:
            log.debug('歧义=>' + content + '=>' + '签收')
            return (1, '签收')
        if '派件' in content and '代收' in content:
            log.debug('歧义=>' + content + '=>' + '签收')
            return (1, '签收')

        if '进行扫描' in content:
            log.debug('歧义=>' + content + '=>' + '途中')
            return (1, '途中')

        if '派件' in content:
            log.debug('歧义=>' + content + '=>' + '派件')
            return (1, '派件')

        log.debug('歧义=>分析失败=>' + content + '=>' + ','.join(result))

        # 关键字优先级
        key_sort = ['签收', '揽收', '派件', '异常', '途中']
        for i in key_sort:
            if i in guess:
                return (1, i)
        return (1, guess[0])
    if situation == 0:

        if '快件异常' in content:
            log.debug('歧义=>' + content + '=>' + '异常')
            return (1, '异常')

        log.debug('失败=>' + content)
        return (0, content)