Exemplo n.º 1
0
def post_fanxiao_temperature_record(sid):
    today_date = time.strftime("%Y-%m-%d", time.localtime())
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    url = "http://fanxiao.ujn.edu.cn/temperatureRecord/createTemperatureRecordCopy"
    headers = {
        "Host": "fanxiao.ujn.edu.cn",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "X-Requested-With": "XMLHttpRequest",
        "Accept-Language": "zh-cn",
        "Accept-Encoding": "gzip, deflate",
        "Origin": "http://fanxiao.ujn.edu.cn",
        "User-Agent":
        "Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.18(0x1700122e) NetType/WIFI Language/zh_CN",
        "Cookie": f"sid={sid}",
        "Content-Length": "104",
        "Content-Type": "application/x-www-form-urlencoded",
        "Connection": "keep-alive"
    }
    data = {
        "reportTime": today_date,
        "isOut": "2",
        "address": None,
        "travelMode": None,
        "temperatureAm": "36.5",
        "temperaturePm": "36.5",
        "reserveOne": "36.5"
    }

    try:
        result = requests.post(url=url, headers=headers, data=data).json()
        status = result.get("status", 0)
        message = result.get("msg", "未知错误发生")
        if status == 1:
            logger = get_logger("access")
            message = {
                "action": "通过 fanxiao 站点 API 写入温度记录",
                "status": "成功",
                "message": message
            }
            logger.info(msg=message)
            sys.exit(0)
        else:
            logger = get_logger("error")
            message = {
                "action": "通过 fanxiao 站点 API 写入温度记录",
                "status": "失败",
                "message": message
            }
            logger.error(msg=message)
            sys.exit(0)
    except Exception as e:
        logger = get_logger("error")
        message = {
            "action": "构造 fanxiao 站点写入温度记录的 API 请求",
            "status": "失败",
            "message": e
        }
        logger.error(msg=message)
        sys.exit(0)
Exemplo n.º 2
0
   def update(self, key, value, timeout=None):
      self._last_seen[key] = time.time()
      if not key in self._context or self._context[key] != value  \
         or (key in self._timeout and self._timeout[key] < time.time()):

         self._context[key] = value
         self._last_change[key] = time.time()

         if timeout:
            self._timeout[key] = time.time() + timeout

         get_logger().event("context", "{key} changed to {value}".format(key=key,
                                                                         value=value))
Exemplo n.º 3
0
    def update(self, key, value, timeout=None):
        self._last_seen[key] = time.time()
        if not key in self._context or self._context[key] != value  \
           or (key in self._timeout and self._timeout[key] < time.time()):

            self._context[key] = value
            self._last_change[key] = time.time()

            if timeout:
                self._timeout[key] = time.time() + timeout

            get_logger().event(
                "context", "{key} changed to {value}".format(key=key,
                                                             value=value))
Exemplo n.º 4
0
    def start(self):
        while True:
            if self.context.get("ai"):
                for rule in rules:
                    if rule.check():
                        if self.last_rule != rule:
                            rule.activate()
                            get_logger().event("rule", "rule '%s' activated" % rule.name)
                            self.context.update("auto-status", rule.name)
                            self.last_rule = rule
                        break

            for device in devices:
                device.run()

            time.sleep(3)
Exemplo n.º 5
0
def post_fanxiao_sid(s, url):
    try:
        headers = {
            "Host": "fanxiao.ujn.edu.cn",
            "Cache-Control": "max-age=0",
            "Upgrade-Insecure-Requests": "1",
            "DNT": "1",
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36",
            "Accept":
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Referer": "http://sso.ujn.edu.cn/",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection": "keep-alive"
        }

        s.headers.clear()
        result = s.get(url=url, headers=headers)

        sid = result.request._cookies["sid"]

        return sid
    except Exception as e:
        logger = get_logger("error")
        message = {
            "action": "通过待认证参数的 fanxiao 站点登录 URL 获取 sid",
            "status": "失败",
            "message": e
        }
        logger.error(msg=message)
        sys.exit(0)
Exemplo n.º 6
0
 def __init__(self, keyfile_path):
     self.log = get_logger('Google API')
     self.speech_client = speech.Client.from_service_account_json(
         keyfile_path)
     self.translate_client = translate.Client.from_service_account_json(
         keyfile_path)
     self.log.info('Init successful')
Exemplo n.º 7
0
    def do_GET(self):

        parameters = {}

        try:
            (path, req_vars) = self.path.split("?", maxsplit=1)
            parameters = parse.parse_qs(req_vars)
        except ValueError:
            path = self.path

        if path == "/":
            with open("webui/index.html", "r") as index:
                self.send_text_response(index.read())
            return

        if path == "/devices":
            result = []
            for device in devices:
                result.append({
                    "name": device.name,
                    "type": device.__class__.__name__,
                    "status": device.get_status()
                })
            self.send_text_response(result)

        if path == "/context":
            self.send_text_response(request_context["context"].serialize())

        if path == "/event":
            if "page" in parameters:
                page = int(parameters["page"][0])
            else:
                page = 0
            self.send_text_response(get_logger().get_events(page=page,
                                                            count=60))
Exemplo n.º 8
0
    def execute(self, action, target=None):

        if action == "switch":
            device = get_device(target)
            device.switch(not device.get_status())
            get_logger().event("core", "manually switched '%s' to '%s'" % (device.name, ("on" if device.get_status() else "off")))

        if action == "dim":
            device = get_device(target)
            device.dim()

        if action == "undim":
            device = get_device(target)
            device.undim()

        if action == "toggle_ai":
            self.context.update("ai", not self.context.get("ai"))
Exemplo n.º 9
0
    def start(self):
        while True:
            if self.context.get("ai"):
                for rule in rules:
                    if rule.check():
                        if self.last_rule != rule:
                            rule.activate()
                            get_logger().event(
                                "rule", "rule '%s' activated" % rule.name)
                            self.context.update("auto-status", rule.name)
                            self.last_rule = rule
                        break

            for device in devices:
                device.run()

            time.sleep(3)
Exemplo n.º 10
0
    def execute(self, action, target=None):

        if action == "switch":
            device = get_device(target)
            device.switch(not device.get_status())
            get_logger().event(
                "core", "manually switched '%s' to '%s'" %
                (device.name, ("on" if device.get_status() else "off")))

        if action == "dim":
            device = get_device(target)
            device.dim()

        if action == "undim":
            device = get_device(target)
            device.undim()

        if action == "toggle_ai":
            self.context.update("ai", not self.context.get("ai"))
Exemplo n.º 11
0
def post_sso(s, cookies, username, password, lt, execution):
    try:
        ul = len(username)
        pl = len(password)
        rsa = make_sso_rsa(username, password, lt)
        url = "http://sso.ujn.edu.cn/tpass/login?service=http%3A%2F%2Ffanxiao.ujn.edu.cn%2Fcas%2Findex"
        headers = {
            "Host": "sso.ujn.edu.cn",
            "Content-Length": "401",
            "Cache-Control": "max-age=0",
            "Origin": "http://sso.ujn.edu.cn",
            "Upgrade-Insecure-Requests": "1",
            "DNT": "1",
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36",
            "Accept":
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Referer":
            "http://sso.ujn.edu.cn/tpass/login?service=http%3A%2F%2Ffanxiao.ujn.edu.cn%2Fcas%2Findex",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection": "keep-alive",
        }
        data = {
            "rsa": rsa,
            "ul": ul,
            "pl": pl,
            "lt": lt,
            "execution": execution,
            "_eventId": "submit"
        }

        s.headers.clear()
        result = s.post(url=url, headers=headers, cookies=cookies, data=data)

        fanxiao_token_url = result.request.url

        return fanxiao_token_url
    except Exception as e:
        logger = get_logger("error")
        message = {
            "action": "POST 请求 SSO 站点登录页,获取待认证参数的 fanxiao 站点登录 url",
            "status": "失败",
            "message": e
        }
        logger.error(msg=message)
        sys.exit(0)
Exemplo n.º 12
0
def get_sso(s):
    try:
        headers = {
            "Host": "sso.ujn.edu.cn",
            "Upgrade-Insecure-Requests": "1",
            "DNT": "1",
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36",
            "Accept":
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Referer": "http://fanxiao.ujn.edu.cn/",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection": "keep-alive"
        }
        url = "http://sso.ujn.edu.cn/tpass/login?service=http%3A%2F%2Ffanxiao.ujn.edu.cn%2Fcas%2Findex"

        s.headers.clear()
        result = s.get(url=url, headers=headers)

        cookies = result.cookies
        html = result.text
        lt_finder = re.search(r"id=\"lt\" name=\"lt\" value=\"(.*)\"",
                              html).groups()
        execution_finder = re.search(r"name=\"execution\" value=\"(.*)\"",
                                     html).groups()

        if len(lt_finder) > 0:
            lt = lt_finder[0]
        else:
            lt = None

        if len(execution_finder) > 0:
            execution = execution_finder[0]
        else:
            execution = None

        return cookies, lt, execution
    except Exception as e:
        logger = get_logger("error")
        message = {
            "action": "GET 请求 SSO 站点登录页,生成构造登录请求所需的关键变量",
            "status": "失败",
            "message": e
        }
        logger.error(msg=message)
        sys.exit(0)
Exemplo n.º 13
0
def make_sso_rsa(username, password, lt):
    try:
        f = open(des_js_path, "r", encoding="utf-8")
        line = f.readline()
        js_str = ""
        while line:
            js_str = js_str + line
            line = f.readline()
        ctx = execjs.compile(js_str)
        rsa = (ctx.call("strEnc", f"{username}{password}{lt}", "1", "2", "3"))
        return rsa
    except Exception as e:
        logger = get_logger("error")
        message = {
            "action": "生成 SSO 站点登录所需要的 rsa 变量",
            "status": "失败",
            "message": e
        }
        logger.error(msg=message)
        sys.exit(0)
Exemplo n.º 14
0
VERSION = "0.3"

import sys

try:
    import settings
except ImportError as e:
    print("Error: unable to load 'settings.py': %s" % e)
    sys.exit(1)

from lib.context import Context
from lib.core import Core
from lib.webserver import Webserver
from lib.log import get_logger

import logging

if __name__ == '__main__':

    get_logger().event("main", "started")
    logging.info(
        "Yelena, version {version} starting ...".format(version=VERSION))

    context = Context()
    core = Core(context=context)
    webserver = Webserver(core=core, context=context)
    webserver.start()

    core.start()
Exemplo n.º 15
0
VERSION = "0.3"

import sys

try:
    import settings
except ImportError as e:
    print("Error: unable to load 'settings.py': %s" % e)
    sys.exit(1)

from lib.context import Context
from lib.core import Core
from lib.webserver import Webserver
from lib.log import get_logger

import logging

if __name__ == '__main__':

    get_logger().event("main", "started")
    logging.info("Yelena, version {version} starting ...".format(version=VERSION))

    context = Context()
    core = Core(context=context)
    webserver = Webserver(core=core,
                          context=context)
    webserver.start()

    core.start()
Exemplo n.º 16
0
import schedule
import warnings

warnings.filterwarnings("ignore")

from adjuster.hero_adjuster import HeroAdjuster
from adjuster.updater import Updater
from l5.get_router import get_router
from transport.client import UDPClient
from busi.dao.base import BaseDao
from busi.dao.data import Video
from lib.log import get_logger
from lib.config import read_l5_info
from meta.games import GAME_MAP

logger = get_logger('main')
fetcher = get_logger('fetcher')
updater = get_logger('updater')
fixer = get_logger('fix')

modid, cmdid = read_l5_info()


def fetch_games_job():
    for k, v in GAME_MAP.items():
        fetch_job(game_id=k)


def update_games_job():
    for k, v in GAME_MAP.items():
        update_job(game_id=k)
Exemplo n.º 17
0
sys.path.append("..")
import lib.log as log

#======================================================================
# format of headers
#======================================================================
BACK_FLAG = 1
WHITE_FLAG = 2
WIN_COUNT = 5

LEFT = -1
RIGHT = 1
UP = -1
DOWN = 1

logger = log.get_logger('GomokuGame')
#======================================================================
# 服务端主类
#======================================================================
class GomokuGame(object):
	"""docstring for GomokuGame"""
	global logger
	def __init__(self):
		super(GomokuGame, self).__init__()

		self._init_attr()
		pass

    #----------------------------------------------------------------------
    # 类属性设置
    #----------------------------------------------------------------------
Exemplo n.º 18
0
import uuid
import os
import random
import commands
import traceback
from subprocess32 import STDOUT, check_output
import shlex

from lib.config import read_path_config
from lib.log import get_logger
from busi.dao.common import get_pic_by_gameid

TIMEOUT = 6000

ffmpeg_path = 'ffmpeg'
logger = get_logger('ffmpeg')

#image_to_video = "-loop 1 -i '%s' -c:v libx264 -t %s -pix_fmt yuv540p -vf scale=960:540 %s"
image_to_video = "-y -loop 1 -i '%s' -t %s -vf scale={0}:{1} %s"
#ffmpeg -loop 1 -i pic.png -c:v libx264 -t 3 -pix_fmt yuv420p -vf scale=1920:1080 pic.mp4
cutout_video_simple_arg = """-y -i '%s' -vcodec copy -acodec copy %s"""
cutout_video_long_time_arg = """-y -i '%s' -vf scale={0}:{1} -acodec copy %s"""
#cutout_video   = """-y -i '%s' -i '%s' -preset fast -filter_complex "[0:v][1:v] overlay=x=((main_w-overlay_w)/(main_w-overlay_w) + 10):y=(main_h-overlay_h - 40),drawtext=fontsize=20:fontfile=font/simsun.ttc:text='{0}':fontcolor='white':x=10:y=h-th-20,scale=1920:1080" -acodec copy %s"""
#ffmpeg -y -ss 00:00:00 -t 00:00:30 -i input.mp4 -vcodec copy -acodec copy output.mp4
merge_videos = "-y -f concat -safe 0 -protocol_whitelist 'file,http,https,tcp,tls' -i '%s' -c copy %s"
#eg: ffmpeg -f concat -safe 0 -protocol_whitelist "file,http,https,tcp,tls" -i videos.txt -c copy output.mp4
convert_ts = " -y -i '%s' -c copy -bsf:v h264_mp4toannexb -f mpegts %s"

merge_ts = "cat %s/*.ts > %s"
#ts_to_video    = " -y -i '%s' -acodec copy -vcodec copy %s"
ts_to_video = " -y -i '%s' -c copy -bsf:a aac_adtstoasc %s"
Exemplo n.º 19
0
import asyncio
import argparse

from concurrent.futures import ThreadPoolExecutor

from lib.audio import mp3_to_flack
from lib.doctor_watson import WatsonApi
from lib.google_api import GoogleApi
from lib.conf import Config
from lib.log import get_logger

pool = ThreadPoolExecutor()
log = get_logger(context='main')


def to_text(audio_chunck, google_client, chunk_number):
    return google_client.transcribe_sync(audio_chunck, 44100), chunk_number


async def main(loop):

    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('stream', help='File to stream to the API')
    parser.add_argument('watson_user', help='User for Watson API')
    parser.add_argument('watson_pass', help='Password for Watson API')
    parser.add_argument('google_key_path', help='Path to google key file')

    args = parser.parse_args()
    futures_to_text = list()
Exemplo n.º 20
0
Arquivo: data.py Projeto: miphreal/dsp
# coding=utf-8
import copy
import os
from collections import namedtuple
from struct import Struct, unpack

from lib.log import get_logger
from lib.i18n import gettext as _
from ui.frames.progress import progress_tick, progress_new, progress_release


logger = get_logger('dsp.data')

DATA_FILE_TYPE = '.bin'
DATA_GROUP_TYPE = '.txt'
SOURCE_DATA_TYPES = {
    '*.bin': _('Channel Data Source (*.bin)'),
    '*.txt': _('Channels Source Bundle (*.txt)'),
    }
SOURCE_DATA_TYPES_LINE = '|'.join('%s|%s' % (hint, ext) for ext, hint in SOURCE_DATA_TYPES.items())

HEADER_DATA_FORMAT = (
    '4s'    # сигнатура файла TMB1
    'I'     # Количество каналов: 4 байта, целое (Количество каналов по которым принимался сигнал)
    'I'     # Размер выборки на один канал: 4 байта, целое (число дискретных точек на один временной интервал приема данных (блок даных) N)
    'I'     # Количество спектральных линий: 4 байта, целое (меньше или равно N/2)
    'I'     # Частота среза: 4 байта, целое  (заданная частота среза ФНЧ при приеме данных)
    'f'     # Частотное разрешение: 4 байта, вещественное (шаг по частоте между спектральными линиями при анализе, Гц )
    'f'     # Время приёма блока данных: 4 байта, вещественное (время за которое принимался  блок данных, величина обратная частотному разрешению)
    'I'     # Общее время приёма данных: 4 байта, целое  (время приема всей реализации в секундах)
    'I'     # Количество принятых блоков (задано пользователем): 4 байта, целое (то что было задано пользователем при приеме данных)
Exemplo n.º 21
0
 def __init__(self, username, password):
     self.log = get_logger(context='Doctor Watson')
     self.tts_api = TextToSpeechV1(username=username,
                                   password=password,
                                   x_watson_learning_opt_out=True)
     self.log.info('Init successful')
Exemplo n.º 22
0
# -*- coding: UTF-8 -*-
import time

from busi.dao.data import VideoInfo
from busi.dao.base import BaseDao
from busi.dao.data import Video
from l5.get_router import get_router
from transport.client import UDPClient
from lib.config import read_l5_info
from lib.config import read_appid
from lib.log import get_logger

logger = get_logger('uploader')


def get_second_c_by_gameid(game_id=0):
    b = BaseDao()
    video_dao = Video(b)
    name = video_dao.get_content_by_game_id(game_id)
    b.close()

    return name


def get_pic_by_gameid(game_id=0):
    pic_map = {
        1007058: 'http://beta.myapp.com/myapp/LRS/nb/role/chiji.jpg',
        1007039: 'http://beta.myapp.com/myapp/LRS/nb/role/libai.png',
        1007060: 'http://beta.myapp.com/myapp/LRS/nb/role/feiche.jpeg'
    }
    default = 'http://beta.myapp.com/myapp/LRS/nb/role/tgp.jpeg'
Exemplo n.º 23
0
import json
import traceback
import re
import urllib2
from urllib2 import urlopen
from lib.log import get_logger
#from urllib.request import urlopen

logger = get_logger('token')

def open_url_json(url='', data = None, timeout=10000):
    if data:
        data = json.dumps(data)
        request = urllib2.Request(url,data)
        request.add_header('Content-Type', 'application/json')

        f = urlopen(request,timeout = timeout)
        o=f.read().decode()
        return json.loads(o)

def open_url(url='', data = None, timeout=10000):
    if data:
        data = urllib.urlencode(data)
    f = urlopen(url, data = data , timeout = timeout)
    o=f.read().decode()

    try:
        #return o
        return json.loads(o)
    except:
        logger.error(traceback.format_exc())
Exemplo n.º 24
0
#!/usr/bin/python3

from lib import log
import json
import time
import requests

logger = log.get_logger("http_request.core")
default_headers = {
    'User-Agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
    "Chrome/74.0.3729.169 Safari/537.36"
}
ml_headers = {
    'accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
}


def html_get(url, headers=None):
    # if set none, use default headers
    if headers is None:
        headers = default_headers
    try:
        r = requests.get(url, headers=headers, timeout=30)
        if r.status_code == 200:
            return r.content
        else:
            print("Error response code: " + str(r.status_code))

    except requests.exceptions.HTTPError:
Exemplo n.º 25
0
import json
import os
import re
import traceback

from lib.log import get_logger
from busi.dao.base import BaseDao
from busi.dao.data import Video
from engines.engines import EngineFactory

logger = get_logger('resolver')

class Resolver(object):
    def __init__(self):
        self.rule_dir = 'cfg/rules'
        self.rules = []
        self.cmds  = []

    def valid_rule(self, rule):
        return rule.get('id') and rule.get('key') and rule.get('values')

    def valid_cmd(self, cmd):
        return cmd.get('cmd') and cmd.get('valid')

    def resolve_config(self):
        try:
            files= os.listdir(self.rule_dir)
            for f in files:
                if not os.path.isdir(f):
                    tmp_file = '%s/%s'%(self.rule_dir, f)
                    with open(tmp_file) as data_file:
Exemplo n.º 26
0
from flask import (
    Flask,
    request,
    jsonify,
    flash,
    redirect,
    url_for,
)

from lib.log import get_logger

logger = get_logger(__name__)

# Use hardcoded app name to ensure lib is not used for top-level directory
app = Flask('battlesnake')


def json_response(data={}, msg=None, status=200):
    return jsonify(
        data=data,
        message=msg,
    ), status, {
        'Content-Type': 'application/json'
    }


def json_error(msg=None, status=400, silent=False):
    if not silent:
        logger.exception('ROUTE ERROR: %s' % str(msg))
    return jsonify(message=str(msg)), status, {
        'Content-Type': 'application/json'
Exemplo n.º 27
0
from django.http import HttpResponse, Http404
from django.conf import settings

from lib.log import get_logger

# get the loggers we want to use here
ACCESS_LOG = get_logger('access')

def log_request(request, path):
    "We want to log all incoming requets, along with a few useful details"
    # first compose the log message. We want to know the path
    # as well as the request method
    msg = "%s request for %s" % (request.META['REQUEST_METHOD'], path)
    # if we have a query string we need to get that from the request
    # as it's not part of the path passed to the view
    if request.META['QUERY_STRING']:
        msg = "%s?%s" % (msg, request.META['QUERY_STRING'])
    # a Post or Put request will store data in the request
    # using the inbuilt urlencode method will give us 
    # a nice human readable version of this
    if request.POST:
        msg = "%s with data %s" % (msg, request.POST.urlencode())
    # we have a special list of things we don't care about in settings
    if path not in settings.REQUEST_EXCLUDES:
        # we have something we want, so lets log it
        ACCESS_LOG.info(msg)
        return HttpResponse("OK")
    else:
        # we hit something we don't care for, so ignore it
        raise Http404("NOT PRESENT")
Exemplo n.º 28
0
sys.path.append('/usr/local/app/nb')
import warnings
warnings.filterwarnings("ignore")

from hero.qt_herlper import QtHelper
import hero.proto.hero_time_recommend_pb2 as pb_hero_rec
import hero.proto.hero_time_pb2 as pb_hero
from lib.config import read_l5_info
from lib.log import get_logger
#from busi.dao.common import get_second_c_by_gameid
#from id_cvt import get_opedid_by_uid
from l5.get_router import get_router
from transport.client import UDPClient
from adjuster.adjuster_tool import *

fetcher = get_logger('main')
openid_logger = get_logger('main')
logger = get_logger('main')

class HeroAdjuster(object):
    def __init__(self, udp_client):
        self.udp_client = udp_client

    def build_multi_game_send_buf(self, game_ids=[],begin_sec=0,begin_usec=0, batch_num=10, v_type=0, uin=0, openid=''):
        #if not (game_ids and len(game_ids)):
        #    logger.error('build_multi_game_send_buf args error.')
        #    return None

        try:
            qt = QtHelper()
            sess = qt.createSessInfo(pb_hero.CMD_HEROTIMESVR,
Exemplo n.º 29
0
import lib.netstream as ns
import lib.datatag as dtag
import lib.log as log
from lib.dispatcher import dispatcher

from game import GomokuGame
from sqlitedb import SqliteDb
from roomservice import RoomService
from gameservice import GameService

#======================================================================
# 头定义数据
#======================================================================


logger = log.get_logger('MainServer')
#======================================================================
# 服务端主类
#======================================================================
class MainServer(object):
    """docstring for MainServer"""
    def __init__(self, **kwargs):
        super(MainServer, self).__init__()

        self.port = 8888
        self.header = 8
        self.shutdown = False

        if 'port' in kwargs:
            self.port = kwargs['port']
        if 'header' in kwargs:
Exemplo n.º 30
0
import lib.log as log
import lib.datatag as dtag

# import sys
# sys.path.append("..")
from lib.service import service

# ======================================================================
# 头定义数据
# ======================================================================
ROOM_NUM = 4
TABLE_NUM = 2
TABLE_PLAYER_NUM = 2


logger = log.get_logger("RoomService")


class RoomService(service):
    """docstring for room_service"""

    def __init__(self):
        service.__init__(self)

        self._init_attr()

    # ----------------------------------------------------------------------
    # 类属性设置
    # ----------------------------------------------------------------------
    def _init_attr(self):
        commands = {
Exemplo n.º 31
0
 def log(self, msg):
     get_logger().event("device", "{name}: {msg}".format(name=self.name,
                                                         msg=msg))
Exemplo n.º 32
0
import sys
sys.path.append('/Users/shawn/tencent/src/newbridge_proj/trunk/server/third_res')

from common.tool import sha_bin as func_sha_bin
from common.tool import sha_str as func_sha_str
from common.tool import md5_str as func_md5_str
from common.tool import tobytes
from lib.log import get_logger
from acloud.net.http_api import upload_file_to_http_svr
from acloud.net.http_api import fileUserApplyUpload
from acloud.m_struct.define import UPLOADFILE_SUCCESS

logger = get_logger('acloud')

class Uploader(object):
    def __init__(self, file_path):
        self.file_path = file_path
        self.block_size = 512*1024


    def upload(self, server='', port=0, hex_dirkey='', sha_bin='', fsize=0):
        if not (self.file_path and len(self.file_path) >= 0):
            logger.info('file path:%s invalid, return' % self.file_path)
            return False

        if not (server and port and hex_dirkey and sha_bin):
            logger.info('args invalid, return')
            return False

        fd = open(self.file_path, 'r')
        flag = 0
Exemplo n.º 33
0
import MySQLdb
import traceback
from lib.config import read_db_config
from lib.log import get_logger
logger = get_logger('db')


class BaseDao(object):
    def __init__(self, conf=read_db_config()):
        self.conn = MySQLdb.connect(**conf)
        self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)

    def exec_r(self, sql, *args):
        try:
            self.cursor.execute(sql, args)
            return self.cursor.fetchall()
        except:
            logger.error('fail|exception|base exec_r error|%s' %
                         traceback.format_exc())

    def exec_r_one(self, sql, *args):
        try:
            self.cursor.execute(sql, args)
            return self.cursor.fetchone()
        except:
            logger.error('fail|exception|base exec_r_one error|%s' %
                         traceback.format_exc())

    def exec_w(self, sql, *args):
        try:
            self.cursor.execute(sql, args)
Exemplo n.º 34
0
#-*-coding:utf-8-*-
import random
import math
import time
import sys
import traceback
#sys.path.append('/usr/local/app/nb')
from dao.video_tag import VideoTag
from dao.music_tag import MusicTag
from lib.log import get_logger
from lib.config import read_db_config
logger = get_logger('music')
#统计各类数量  
#def addValueToMat(theMat,key,value,incr):
#    if key not in theMat: #如果key没出先在theMat中  
#        theMat[key]=dict();
#        theMat[key][value]=incr;
#    else:
#        if value not in theMat[key]:
#            theMat[key][value]=incr;
#        else:
#            theMat[key][value]+=incr;#若有值,则递增  

tag_items = dict()
item_tags = dict()

def rec_music(base):
    vt = VideoTag(base)
    mt = MusicTag(base)
    try:
        for data in vt.get_maxweigth_items():
Exemplo n.º 35
0
import sys
from lib.httptool import open_url_json
from lib.log import get_logger

logger = get_logger('openid')


class OpenidService(object):
    def __init__(self, ip, port, appname):
        self.ip = ip
        self.port = port
        self.appname = appname

    def openid_to_commid(self, openid_list):
        url = 'http://%s:%s/innerapi/acctapi/transid/openid_to_commid?appname=%s' % (
            self.ip, self.port, self.appname)
        data = {}
        data['openid_list'] = openid_list

        tmp = open_url_json(url=url, data=data)
        if tmp and isinstance(tmp, dict) and tmp.has_key("commid_list"):
            logger.info('get commid_list success.')
            return tmp["commid_list"]
        else:
            logger.warn('[WARN]get commid_list failed.')
            return ''

    def commid_to_openid(self, commid_list, appid):
        url = 'http://%s:%s/innerapi/acctapi/transid/commid_to_openid?appname=%s' % (
            self.ip, self.port, self.appname)
        data = {}
Exemplo n.º 36
0
 def log(self, msg):
     get_logger().event("device", "{name}: {msg}".format(
         name=self.name,
         msg=msg
     ))
Exemplo n.º 37
0
 def __init__(self, base):
     self.base = base
     self.logger = get_logger('db')
Exemplo n.º 38
0
 def __init__(self, logger):
     self.logger = log.get_logger(logger)
Exemplo n.º 39
0
# limitations under the License.

import os
import sys
import argparse
import glob
from subprocess import run

from lib import util, aws
from lib.context import Context
from lib.log import get_logger
from lib.exceptions import UserException, CortexException

import requirements

logger = get_logger()

LOCAL_PACKAGE_PATH = "/packages"
WHEELHOUSE_PATH = "/wheelhouse"


def get_build_order(python_packages):
    build_order = []
    if "requirements.txt" in python_packages:
        build_order.append("requirements.txt")
    return build_order + sorted(
        [name for name in python_packages if name != "requirements.txt"])


def get_restricted_packages():
    cortex_packages = {"pyspark": "2.4.0", "tensorflow": "1.12.0"}
Exemplo n.º 40
0
from lib.log import get_logger
from config.context import CustomContext

LOG = get_logger(
    "engine.py",
    "'[%(levelname)s] [%(name)s] [%(asctime)s] [%(funcName)s::%(lineno)d] [%(message)s]'",
)


def run(event=None, context=None):
    '''
        Funtionality for lambda function.

        Parameters:
            - () :

        Returns:
            - () :
    '''
    LOG.info(f"Triggered from main.py lambda. Event --> {event}.")

    custom_context = CustomContext(event=event, aws_ctx=context)

    response = {}

    return response
Exemplo n.º 41
0
import traceback

from lib.log import get_logger
from dao.base import BaseDao
from dao.version import Version

logger = get_logger('busi')

class VersionService(object):
    def __init__(self):
        self.__base = None

    def get_update(self, version_code):
        self.__base = BaseDao()
        version     = Version(self.__base)
        versions    = version.get_version(version_code)

        max_version_code = version_code
        download_url     = ''
        force            = 0
        for ver in versions:
            if (ver.version_code > max_version_code):
                download_url     = ver.version_url
                max_version_code = ver.version_code
            if (ver.version_code == version_code and ver.use_flag == 0):
                force = 1
        return (download_url, force)

    def close(self):
        if (self.__base is not None):
            self.__base.close()
Exemplo n.º 42
0
# coding=utf-8
"""
Progress modal Frame
"""
import wx

from constants import events
from lib.config import app_config
from lib.event import trigger, on
from lib.i18n import gettext as _
from lib.log import get_logger


logger = get_logger('dsp.main_window')

DEFAULT_PROGRESS_CONFIG = {
    'main_progress_max': 100,
    'main_progress_position': 0,
    'main_progress_visible': False,
}
trigger(events.DO_UPDATE_CONFIG, DEFAULT_PROGRESS_CONFIG)


class ProgressWindow(wx.Frame):
    SIZE = (300, 20)
    def __init__(self, parent=None, conf=app_config):
        self.parent = parent
        self.conf = conf
        super(ProgressWindow, self).__init__(parent, -1, _('Progress'), size=self.SIZE,
            style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_NO_TASKBAR|wx.FRAME_NO_WINDOW_MENU|wx.BORDER_NONE)
        self.create_progress()
Exemplo n.º 43
0
# -*- coding: UTF-8 -*-
import traceback

from flask import Blueprint,request
from lib.log import get_logger
from lib.route_handler import handle_success,handle_param_error,handle_failure,handle_response,check_param
from service.video_service import VideoService

video_service = Blueprint('video_service', __name__)

logger = get_logger('main')


# 获取发现视频接口
@video_service.route('/video/discover/list', methods=['POST'])
def get_discover_video():
    res  = {'code' : 1000, 'msg' : '成功'}
    data = request.json
    command  = data.get("cmd") or ''
    data = data.get('data') if data else None
    if not data:
        return handle_param_error()

    page_num = data.get("page_num") or 1

    service = VideoService()
    try:
        result = service.get_discover_video(page_num)
        res    = handle_success(result, 1000, '成功')
    except:
        res = handle_failure()
Exemplo n.º 44
0
from game import GomokuGame

#======================================================================
# format of headers
#======================================================================
#游戏状态信息
GAME_REDEAY = 1
GAME_START = 2
GAME_HOLD_UP = 3
GAME_PLAYING = 4
GAME_WAITING = 5
GAME_STOP = 6
GAME_IN_TURN = 7
GAME_NOT_IN_TURN = 8

logger = log.get_logger('GameService')

class GameService(service):
    """docstring for game_service"""
    
    def __init__(self):
        service.__init__(self)

        self._init_attr()


    #----------------------------------------------------------------------
    # 类属性设置
    #----------------------------------------------------------------------
    def _init_attr(self):
        commands = {