示例#1
0
def commits(req_id, debugging):
    # GitHub API 사용
    # API 사양은 https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository 참조
    try:
        response = (
            urllib.request.urlopen(url="https://api.github.com/repos/hgyoseo/hdmeal/commits").read().decode('utf-8')
        )
        data = json.loads(response)
    except Exception as error:
        if debugging:
            print(error)
        log.err("[#%s] commits@modules/getData.py: Failed to Parse Commits" % req_id)
        return error

    # 마지막 커밋이 일어난 시간를 파싱함
    # 시간은 UTC 기준, datetime에서 인식할 수 있게 하기 위해 Z를 떼고 9시간을 더해 한국 표준시로 변환
    updated_at_datetime = (datetime.datetime.fromisoformat(data[0]["commit"]["committer"]["date"].replace("Z", ""))
                           + datetime.timedelta(hours=9))
    updated_at = "%s년 %s월 %s일 %s시 %s분" % (
        updated_at_datetime.year, updated_at_datetime.month, updated_at_datetime.day,
        updated_at_datetime.hour, updated_at_datetime.minute
    )
    # 최근 5개 커밋의 메시지 가져오기
    messages = list(map(lambda loc: data[loc]["commit"]["message"], range(5)))
    # 리스트의 0번에 마지막 커밋 시간 삽입
    messages.insert(0, updated_at)
    log.info("[#%s] commits@modules/getData.py: Succeeded" % req_id)
    return messages
示例#2
0
def manage_user(uid, user_grade, user_class, req_id, debugging):
    log.info("[#%s] manage_user@modules/user.py: Started Managing User Info" % req_id)
    try:
        with open(path, encoding="utf-8") as data_file:
            enc = hashlib.sha256()
            enc.update(uid.encode("utf-8"))
            enc_uid = enc.hexdigest()
            data = json.load(data_file)
        if debugging:
            print(data)
        if enc_uid in data:  # 사용자 정보 있을 때
            if data[enc_uid][0] == user_grade and data[enc_uid][1] == user_class:  # 사용자 정보 똑같을 때
                log.info("[#%s] manage_user@modules/user.py: Same" % req_id)
                return "Same"
            else:  # 사용자 정보 있고 같지도 않을 때 - 업데이트 (삭제 후 재생성)
                del data[enc_uid]
                if debugging:
                    print("DEL USER")
                log.info("[#%s] manage_user@modules/user.py: Updated" % req_id)
                return_msg = "Updated"
        else:  # 사용자 정보 없을 때 - 생성
            log.info("[#%s] manage_user@modules/user.py: Registered" % req_id)
            return_msg = "Registered"
        user_data = [int(user_grade), int(user_class)]
        data[enc_uid] = user_data
        with open(path, "w", encoding="utf-8") as write_file:
            json.dump(data, write_file, ensure_ascii=False, indent="\t")
            log.info("[#%s] manage_user@modules/user.py: Succeeded" % req_id)
            return return_msg
    except Exception:
        log.err("[#%s] manage_user@modules/user.py: Failed" % req_id)
        return Exception
示例#3
0
 def put(self, msg):
     '''
     客户端的PUT命令,即服务器端获取数据
     :param msg:
     :return:
     '''
     m = hashlib.md5()
     USE_DICT = json.load(open(setting.PATH_USE, 'r'))
     # 配额检查
     if msg["size"] + os.stat(self.path).st_size > USE_DICT[self.user_name]["user_size"]:
         self.request.send(b'400')   # 用户配额不足
         log.info("【{}】帐号:{}  用户配额不足".format(self.client_address[0], self.name))
     else:
         self.request.send(b'200')  # 用户配额足
         file_size = 0
         with open(os.path.join(self.path, msg["filename"]), 'wb') as f:
             while file_size < msg["size"]:
                 file = self.request.recv(1024)           # 接收文件
                 f.write(file)
                 m.update(file)
                 file_size += len(file)
         md5sum = m.hexdigest()
         f_size = os.path.getsize(os.path.join(self.path, msg["filename"]))
         if f_size == msg["size"]:    # 校验是否下载完成
             self.request.send('服务端接受完毕'.encode())
             data = self.request.recv(1024).decode()
             if data == md5sum:
                 self.request.send(b'200')
             else:
                 self.request.send(b'400')
             log.info("【{}】帐号:{}  接受{}文件完成".format(self.client_address[0], self.name, msg["filename"]))
示例#4
0
def meal(reqdata, req_id, debugging):
    log.info("[#%s] meal@modules/skill.py: New Request" % req_id)
    try:
        sys_date = json.loads(
            json.loads(reqdata)["action"]["params"]["sys_date"])[
                "date"]  # 날짜 가져오기
    except Exception:
        log.err("[#%s] meal@modules/skill.py: Error while Parsing Request" %
                req_id)
        return skill("오류가 발생했습니다.\n요청 ID: " + req_id)
    try:
        # 년월일 파싱
        year = datetime.datetime.strptime(sys_date, "%Y-%m-%d").timetuple()[0]
        month = datetime.datetime.strptime(sys_date, "%Y-%m-%d").timetuple()[1]
        date = datetime.datetime.strptime(sys_date, "%Y-%m-%d").timetuple()[2]
        wday = datetime.datetime.strptime(sys_date, "%Y-%m-%d").timetuple()[6]
    except ValueError:  # 파싱중 값오류 발생시
        log.err("[#%s] meal@modules/skill.py: ValueError while Parsing Date" %
                req_id)
        return skill("오류가 발생했습니다.\n요청 ID: " + req_id)
    if debugging:
        print(sys_date)
        print(year)
        print(month)
        print(date)
        print(wday)
    return skill(meal_core(year, month, date, wday, req_id, debugging))
示例#5
0
 def f_tt():
     global briefing_tt
     tt_grade = str()
     tt_class = str()
     try:
         uid = json.loads(reqdata)["userRequest"]["user"]["id"]
         user_data = user.get_user(uid, req_id, debugging)  # 사용자 정보 불러오기
         tt_grade = user_data[0]
         tt_class = user_data[1]
     except Exception:
         log.err(
             "[#%s] briefing@modules/skill.py: Failed to Fetch Timetable" %
             req_id)
         briefing_tt = "시간표 조회 중 오류가 발생했습니다."
     if tt_grade is not None or tt_class is not None:  # 사용자 정보 있을 때
         tt = getData.tt(tt_grade, tt_class, date.year, date.month,
                         date.day, req_id, debugging)
         if tt == "등록된 데이터가 없습니다.":
             briefing_tt = "등록된 시간표가 없습니다."
         else:
             briefing_tt = "%s 시간표:\n%s" % (date_ko, tt.split('):\n\n')[1]
                                            )  # 헤더부분 제거
     else:
         log.info("[#%s] briefing@modules/skill.py: Non-Registered User" %
                  req_id)
         briefing_tt = "등록된 사용자만 시간표를 볼 수 있습니다."
示例#6
0
def tt(reqdata, req_id, debugging):
    log.info("[#%s] tt@modules/skill.py: New Request" % req_id)
    try:
        tt_grade = json.loads(reqdata)["action"]["params"]["Grade"]  # 학년 파싱
    except Exception:
        log.err("[#%s] tt@modules/skill.py: Error while Parsing Grade" %
                req_id)
        return skill("오류가 발생했습니다.\n요청 ID: " + req_id)
    try:
        tt_class = json.loads(reqdata)["action"]["params"]["Class"]  # 반 파싱
    except Exception:
        log.err("[#%s] tt@modules/skill.py: Error while Parsing Class" %
                req_id)
        return skill("오류가 발생했습니다.\n요청 ID: " + req_id)
    try:
        sys_date = json.loads(
            json.loads(reqdata)["action"]["params"]["sys_date"])[
                "date"]  # 날짜 파싱
    except Exception:
        log.err("[#%s] tt@modules/skill.py: Error while Parsing Date" % req_id)
        return skill("오류가 발생했습니다.\n요청 ID: " + req_id)
    try:
        date = datetime.datetime.strptime(sys_date, "%Y-%m-%d")
    except ValueError:  # 값오류 발생시
        log.err("[#%s] tt@modules/skill.py: ValueError while Parsing Date" %
                req_id)
        return skill("오류가 발생했습니다.\n요청 ID: " + req_id)
    if debugging:
        print(tt_grade)
        print(tt_class)
    msg = getData.tt(tt_grade, tt_class, date.year, date.month, date.day,
                     req_id, debugging)
    return skill(msg)
示例#7
0
    def ls(self, msg):
        '''
        查询不同用户HOME目录下的文件
        :param msg:
        :return:
        '''
        osname = platform.system()
        cmd = ''
        de_code = ''
        if osname == 'Windows':
            cmd = 'dir'
            de_code = 'gbk'
        elif osname == 'Linux':
            cmd = 'ls -arlt'
            de_code = 'utf-8'
        res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, cwd=self.path)  # 查询当前目录下文件
        res_data = res.stdout.read()
        msg_dic = {
            "size": len(res_data),
            "de_code": de_code
        }
        self.request.send(json.dumps(msg_dic).encode())
        self.request.recv(1024)

        self.request.send(res_data)
        log.info("【{}】帐号:{} ls 查询".format(self.client_address[0], self.name))
示例#8
0
 def cd(self, msg):
     rec_path = msg["path"]
     send_code = 200
     if rec_path == 'HOME':
         self.path = self.home
         log.info("【{}】帐号:{}  执行cd命令,返回帐号目录".format(self.client_address[0], self.name))
         print(self.path)
     elif rec_path == '..':                  # 如果是'..' ,返回父目录
         self.path = os.path.dirname(os.path.abspath(self.path))
         log.info("【{}】帐号:{}  执行cd命令,返回父目录".format(self.client_address[0], self.name))
     else:
         print(os.path.join(self.path, rec_path))
         print(os.path.isabs(os.path.join(self.path, rec_path)))
         if os.path.isabs(os.path.join(self.path, rec_path)):    # 判断是否是正确目录
             self.path = os.path.join(self.path, rec_path)
             log.info("【{}】帐号:{}  执行cd命令,到{}目录".format(self.client_address[0], self.name, self.path))
         else:
             send_code = 400
             log.info("【{}】帐号:{}  执行cd命令,未找到目录".format(self.client_address[0], self.name))
     send_msg = {
         "run_code": send_code,
         "run_path": self.path,
     }
     self.request.send(json.dumps(send_msg).encode())
     log.info("【{}】帐号:{}  执行cd命令".format(self.client_address[0], self.name))
示例#9
0
 def f_cal():
     global briefing_schdl
     briefing_schdl = getData.schdl(date.year, date.month, date.day, req_id,
                                    debugging)
     if not briefing_schdl:
         log.info("[#%s] briefing@modules/skill.py: No Schedule" % req_id)
         briefing_schdl = "%s은 학사일정이 없습니다." % date_ko
     else:
         briefing_schdl = "%s 학사일정:\n%s" % (date_ko, briefing_schdl)
示例#10
0
 def f_header():
     global briefing_header, hd_err
     if date.weekday() >= 5:  # 주말이면
         log.info("[#%s] briefing@modules/skill.py: Weekend" % req_id)
         hd_err = "%s은 주말 입니다." % date_ko
     else:
         briefing_header = "%s은 %s(%s) 입니다." % (
             date_ko, date.date().isoformat(), wday(date))
         hd_err = None
示例#11
0
def add_user():
    '''
    增加用户
    :return:
    '''
    flag = True
    creat_name = ''
    creat_path = ''
    power_info = input('''请选择创建用户类型 【0】普通用户;【1】管理用户 ;\n>>''')
    if not (power_info == '1' or power_info == '0'):
        print('输入非法字符!')
    else:
        if power_info == '1':
            while flag:
                creat_name = input('请自定义需要添加的管理员帐号:').strip()
                rq = login_in.chack_dir_file(setting.PATH_ADMIN, creat_name)
                if rq:
                    print('输入的帐号已存在,请重新输入!')
                else:
                    flag = rq
            creat_path = os.path.join(setting.PATH_ADMIN, creat_name)
        elif power_info == '0':
            while flag:
                # 帐号重复性检查
                creat_name = creat_username()
                rq = login_in.chack_dir_file(setting.PATH_USER, creat_name)
                flag = rq
            print('系统生成帐号为:%s' % creat_name)
            creat_path = os.path.join(setting.PATH_CLIENT, creat_name)
        info = input('''设置用户信息:
        依次输入:密码/权限(0:普通用户;1:管理员用户)/信用卡最大透支额度/本月可用额度/还款日期/储蓄金额
        格式:\033[33;0m 123/0/10000/10000/15/0/\033[0m\n
        >>''').strip()
        info_list = info.split('/')
        pass_word = login_in.md5(info_list[0])   # 密码
        power = info_list[1]            # 权限
        credit = int(info_list[2])           # 最大透支额度
        balance = int(info_list[3])          # 本月可用额度
        repay_date = info_list[4]            # 还款日期
        saving = int(info_list[5])           # 储蓄金额

        base_info = {
            'username': creat_name,     # 用户
            'password': pass_word,      # 密码
            'power': power,             # 权限
            'credit': credit,           # 最大透支额度
            'balance': balance,         # 本月可用额度
            'saving': saving,           # 储蓄金额
            'repay_date': repay_date,   # 还款日期
            'type': 'Y',    # 用户有效 ,Y 有效;N 无效;
            'debt': {},     # 欠费记录
        }
        os.mkdir(creat_path)
        json.dump(base_info, open(os.path.join(creat_path, creat_name), 'w'))
        print('帐号为:%s 创建完毕!' % creat_name)
        log.info('【%s】-->帐号为:%s 创建完毕!' % (login_in.USER_STATUS['username'], creat_name))
示例#12
0
def get(req_id, debugging):
    filenames = os.listdir('data/cache/')
    return_data = str()
    for filename in filenames:
        ext = os.path.splitext(filename)[-1]
        # 시간표와 수온, 날씨 캐시 파일 숨김
        if ext == '.json' and filename != "TT.json" and filename != "wtemp.json" and filename != "weather.json":
            if debugging:
                print(filename)
            return_data = "%s\n%s" % (return_data, filename.replace(
                ".json", ""))
    # 시간표 캐시 만료기한 조회
    if "TT.json" in filenames:
        with open('data/cache/TT.json', encoding="utf-8") as data:  # 캐시 읽기
            timestamp = datetime.datetime.fromtimestamp(
                json.load(data)["Timestamp"])
            if (datetime.datetime.now() -
                    timestamp) < datetime.timedelta(hours=3):  # 캐시 만료됐는지 확인
                time_left = int(
                    (datetime.timedelta(hours=3) -
                     (datetime.datetime.now() - timestamp)).seconds / 60)
                return_data = "%s\n시간표 캐시 만료까지 %s분 남음" % (return_data,
                                                          time_left)
            else:
                return_data = "%s\n시간표 캐시 만료됨" % return_data
    # 한강 수온 캐시 만료기한 조회
    if "wtemp.json" in filenames:
        with open('data/cache/wtemp.json', encoding="utf-8") as data:  # 캐시 읽기
            timestamp = datetime.datetime.fromtimestamp(
                json.load(data)["timestamp"])
            if (datetime.datetime.now() -
                    timestamp) < datetime.timedelta(minutes=76):  # 캐시 만료됐는지 확인
                time_left = int(
                    (datetime.timedelta(minutes=76) -
                     (datetime.datetime.now() - timestamp)).seconds / 60)
                return_data = "%s\n한강 수온 캐시 만료까지 %s분 남음" % (return_data,
                                                            time_left)
            else:
                return_data = "%s\n한강 수온 캐시 만료됨" % return_data
    # 날씨 캐시 만료기한 조회
    if "weather.json" in filenames:
        with open('data/cache/weather.json',
                  encoding="utf-8") as data:  # 캐시 읽기
            timestamp = datetime.datetime.fromtimestamp(
                json.load(data)["Timestamp"])
            if (datetime.datetime.now() -
                    timestamp) < datetime.timedelta(hours=1):  # 캐시 만료됐는지 확인
                time_left = int(
                    (datetime.timedelta(hours=1) -
                     (datetime.datetime.now() - timestamp)).seconds / 60)
                return_data = "%s\n날씨 캐시 만료까지 %s분 남음" % (return_data,
                                                         time_left)
            else:
                return_data = "%s\n날씨 캐시 만료됨" % return_data
    log.info("[#%s] get@modules/cache.py: Succeeded" % req_id)
    return return_data
示例#13
0
def build_ios (options):
    platform = 'ios'
    target = get_target(platform)

    if options.main and check_ignifuga_libraries(platform):
        return
    info('Building Ignifuga For iOS')
    env, pp = prepare_ios_env(target, None, options.openmp, options.applesdk, options.appletarget)
    prepare_ios_skeleton()
    build_generic(options, platform, pp, env)
示例#14
0
def build_arm_android (options):
    platform = 'arm_android'
    target = get_target(platform)
    if options.main != None and check_ignifuga_libraries(platform):
        return
    validate_android_api_level(options.androidtarget, ANDROID_SDK)
    info('Building Ignifuga For Android')
    env, pp = prepare_arm_android_env(target, openmp=options.openmp, api_level=options.androidtarget, gcc=options.androidgcc)
    prepare_arm_android_skeleton()
    build_generic(options, platform, pp, env)
示例#15
0
def run_cycle():
    # Read appropriate values from potentiometers and do appropriate writes

    if is_brake_on():
        log.info("Brake engaged")
        stop_throt()
    else:
        io.man_bmc_rfe.set(GPIO.HIGH)
        accel = get_accel()
        set_throt(accel, accel)
        log.info("Throttle value: %f" % accel)
示例#16
0
def commits(req_id, debugging):
    log.info("[#%s] commits@modules/skill.py: New Request" % req_id)
    commit_list = getData.commits(req_id, debugging)
    commits_msg = ("급식봇의 기능 개선과 속도 향상, 버그 수정을 위해 노력하고 있습니다.\n"
                   "마지막 서버 업데이트는 %s에 있었습니다.\n"
                   "흥덕중 급식봇의 최근 변경 내역입니다:\n"
                   "%s\n%s\n%s\n%s\n%s" %
                   (commit_list[0], commit_list[1], commit_list[2],
                    commit_list[3], commit_list[4], commit_list[5]))
    log.info("[#%s] commits@modules/skill.py: Started" % req_id)
    return skill(commits_msg)
示例#17
0
 def f_meal():
     global briefing_meal
     briefing_meal = meal_core(date.year, date.month, date.day,
                               date.weekday(), req_id, debugging)
     if "급식을 실시하지 않습니다." in briefing_meal:
         log.info("[#%s] briefing@modules/skill.py: No Meal" % req_id)
         briefing_meal = "%s은 %s" % (date_ko, briefing_meal)
     elif "열량" in briefing_meal:
         briefing_meal = "%s 급식:\n%s" % (
             date_ko, briefing_meal[16:].replace(
                 '\n\n', '\n'))  # 헤더부분 제거, 줄바꿈 2번 → 1번
示例#18
0
def build_ios(options):
    platform = 'ios'
    target = get_target(platform)

    if options.main and check_ignifuga_libraries(platform):
        return
    info('Building Ignifuga For iOS')
    env, pp = prepare_ios_env(target, None, options.openmp, options.applesdk,
                              options.appletarget)
    prepare_ios_skeleton()
    build_generic(options, platform, pp, env)
示例#19
0
def build_intel_mingw64(options):
    platform = 'intel_mingw64'
    target = get_target(platform)
    check_intel_mingw64_tools()
    if options.main and check_ignifuga_libraries(platform):
        return
    info('Building Ignifuga For Windows 64 bits')
    if not isdir(target.dist):
        os.makedirs(target.dist)
    env, pp = prepare_intel_mingw64_env(target, openmp=options.openmp)
    build_generic(options, platform, pp, env)
示例#20
0
def build_osx (options):
    platform = 'osx'
    target = get_target(platform)

    if options.main and check_ignifuga_libraries(platform):
        return
    info('Building Ignifuga For OS X')
    if not isdir(target.dist):
        os.makedirs(target.dist)
    env, pp = prepare_osx_env(target, openmp=options.openmp, sdk=options.applesdk, ostarget=options.appletarget)
    build_generic(options, platform, pp, env)
示例#21
0
def build_intel_linux32(options):
    platform = 'intel_linux32'
    target = get_target(platform)

    if options.main and check_ignifuga_libraries(platform):
        return
    info('Building Ignifuga For Linux 32 bits')
    if not isdir(target.dist):
        os.makedirs(target.dist)
    env, pp = prepare_intel_linux32_env(target, openmp=options.openmp)
    build_generic(options, platform, pp, env)
示例#22
0
def build_intel_mingw64 (options):
    platform = 'intel_mingw64'
    target = get_target(platform)
    check_intel_mingw64_tools()
    if options.main and check_ignifuga_libraries(platform):
        return
    info('Building Ignifuga For Windows 64 bits')
    if not isdir(target.dist):
        os.makedirs(target.dist)
    env, pp = prepare_intel_mingw64_env(target, openmp=options.openmp)
    build_generic(options, platform, pp, env)
示例#23
0
def build_intel_linux32 (options):
    platform = 'intel_linux32'
    target = get_target(platform)

    if options.main and check_ignifuga_libraries(platform):
        return
    info('Building Ignifuga For Linux 32 bits')
    if not isdir(target.dist):
        os.makedirs(target.dist)
    env, pp = prepare_intel_linux32_env(target, openmp=options.openmp)
    build_generic(options, platform, pp, env)
示例#24
0
def build_project_generic(options, platform, target, pp, env=None):
    package = options.project.split('.')[-1]
    if package == 'ignifuga':
        error('Name your project something else than ignifuga please')
        exit()

    if package +'.py' == basename(options.main).lower():
        error('Your main file can not have the same name as the project. If your project is com.mdqinc.test your main file can not be named test.py')
        exit()

    platform_build = join(target.project, platform)
    main_file = join(platform_build, basename(options.main))
    cython_src = join(target.project, platform, 'cython_src')
    info('Building %s for %s  (package: %s)' % (options.project, platform, package))
    if not isdir(target.project):
        os.makedirs(target.project)

    # Prepare and cythonize project sources
    prepare_project(target.project_root, platform_build)
    # Remove main file as it'll be cythonized differently
    if isfile(main_file):
        os.unlink(main_file)
    cfiles, glue_h, glue_c = cythonize(platform_build, package, options, [options.main,])

    # Cythonize main file
    main_file_ct = getctime(abspath(options.main))
    main_file_c = join(cython_src, splitext(basename(options.main))[0] + '.cpp')
    cfiles.append(main_file_c)

    if not isfile(main_file_c) or getctime(main_file_c) < main_file_ct:
        log('Cythonizing main file %s' % main_file)
        mfc = join(cython_src, splitext(basename(main_file))[0] + '.cpp')
        cmd = 'cython --embed --cplus --include-dir "%s/.." -o "%s" "%s" ' % (ROOT_DIR, mfc, abspath(options.main))
        Popen(shlex.split(cmd), cwd = cython_src).communicate()
        if not isfile(mfc):
            error ('Could not cythonize main file')
            exit()

        # Insert SDL.h into the cythonized file
        if not options.bare:
            with file(mfc, 'r') as original: mfc_data = original.read()
            mfc_data = mfc_data.replace('PyErr_Print();', 'PyErr_Print();fflush(stdout);fflush(stderr);')
            with file(mfc, 'w') as modified: modified.write("#include \"SDL.h\"\n"+mfc_data)
            shutil.move(mfc, main_file_c)

    # Build the executable
    sources = ''
    for cf in cfiles:
        sources += cf + ' '
    mod = __import__('modules.project.'+platform, fromlist=['make'])
    mod.make(options, env, target, sources, cython_src, cfiles)

    info('Project built successfully')
示例#25
0
def parse(year, month, req_id, debugging):

    log.info("[#%s] parse@modules/scheduleParser.py: Started Parsing Schedule(%s-%s)" % (req_id, year, month))

    # 학년도 기준, 다음해 2월까지 전년도로 조회
    if month < 3:
        school_year = year - 1
    else:
        school_year = year

    try:
        url = ("http://stu.goe.go.kr/sts_sci_sf01_001.do?"
               "schulCode=%s"
               "&schulCrseScCode=%s"
               "&schulKndScCode=%s"
               "&ay=%s&mm=%s"
               % (school_code, school_kind, str(school_kind).zfill(2), str(school_year).zfill(4), str(month).zfill(2)))
        req = urllib.request.urlopen(url)

    except Exception as error:
        if debugging:
            print(error)
        return error

    if debugging:
        print(url)

    data = BeautifulSoup(req, 'html.parser')
    data = data.find_all('div', class_='textL')

    calendar = dict()

    # 일정 후처리(잡정보들 삭제)
    def pstpr(cal):
        return cal.replace("토요휴업일", "").strip().replace('\n\n\n', '\n')

    for i in range(len(data)):
        string = data[i].get_text().strip()
        if string[2:].replace('\n', '') and pstpr(string[2:]):
            calendar[int(string[:2])] = pstpr(string[2:])

    if debugging:
        print(calendar)

    if calendar:
        with open('data/cache/Cal-%s-%s.json' % (year, month), 'w',
                  encoding="utf-8") as make_file:
            json.dump(calendar, make_file, ensure_ascii=False, indent="\t")
            print("File Created")

    log.info("[#%s] parse@modules/scheduleParser.py: Succeeded(%s-%s)" % (req_id, year, month))

    return 0
示例#26
0
def build_arm_android(options):
    platform = 'arm_android'
    target = get_target(platform)
    if options.main != None and check_ignifuga_libraries(platform):
        return
    validate_android_api_level(options.androidtarget, ANDROID_SDK)
    info('Building Ignifuga For Android')
    env, pp = prepare_arm_android_env(target,
                                      openmp=options.openmp,
                                      api_level=options.androidtarget,
                                      gcc=options.androidgcc)
    prepare_arm_android_skeleton()
    build_generic(options, platform, pp, env)
示例#27
0
def save_money():
    '''
    存款
    :return:
    '''
    user_dict = json.load(open(login_in.get_file_dir(setting.PATH_USER)[login_in.USER_STATUS['username']], 'r'))
    save_fee = input('请输入存款金额:').strip()
    user_dict['saving'] += int(save_fee)
    json.dump(user_dict, open(login_in.get_file_dir(setting.PATH_USER)[login_in.USER_STATUS['username']], 'w'))
    time.sleep(1)
    print('已存入【%s】元到帐户中...' % int(save_fee))
    log.info("【%s】-->帐期:存入【%s】元到帐户中" % (login_in.USER_STATUS['username'], int(save_fee)))
    input('按回车键继续\n')
示例#28
0
def spawn_shell(platform):
    target = get_target(platform)
    cmd = 'bash'
    env = os.environ
    if platform == 'arm_android':
        env, pp = prepare_arm_android_env(target)
    elif platform == 'intel_mingw32':
        env, pp = prepare_intel_mingw32_env(target)

    info('Entering %s shell environment' % (platform,))

    Popen(shlex.split(cmd), cwd = target.dist, env=env).communicate()
    info('Exited from %s shell environment' % (platform,))
示例#29
0
def spawn_shell(platform):
    target = get_target(platform)
    cmd = 'bash'
    env = os.environ
    if platform == 'arm_android':
        env, pp = prepare_arm_android_env(target)
    elif platform == 'intel_mingw32':
        env, pp = prepare_intel_mingw32_env(target)

    info('Entering %s shell environment' % (platform, ))

    Popen(shlex.split(cmd), cwd=target.dist, env=env).communicate()
    info('Exited from %s shell environment' % (platform, ))
示例#30
0
def lock_user(user_name):
    '''
    锁定帐号
    :param user_name:
    :return:
    '''
    file_dict = get_file_dir(setting.PATH_USER)
    user_dict = json.load(open(file_dict[user_name], 'r'))
    user_dict['type'] = 'N'
    json.dump(user_dict, open(file_dict[user_name], 'w'))
    print('帐号:%s已冻结!' % user_name)
    log.info('帐号:%s已冻结!' % user_name)
    return True
示例#31
0
def build_osx(options):
    platform = 'osx'
    target = get_target(platform)

    if options.main and check_ignifuga_libraries(platform):
        return
    info('Building Ignifuga For OS X')
    if not isdir(target.dist):
        os.makedirs(target.dist)
    env, pp = prepare_osx_env(target,
                              openmp=options.openmp,
                              sdk=options.applesdk,
                              ostarget=options.appletarget)
    build_generic(options, platform, pp, env)
示例#32
0
def get_user(uid, req_id, debugging):
    log.info("[#%s] get_user@modules/user.py: Started Fetching User Info" % req_id)
    try:
        with open(path, encoding="utf-8") as data_file:
            enc = hashlib.sha256()
            enc.update(uid.encode("utf-8"))
            enc_uid = enc.hexdigest()
            data = json.load(data_file)
        if debugging:
            print(data)
        if not enc_uid in data:  # 사용자 정보 없을 때
            return_data = [None, None]
            log.info("[#%s] get_user@modules/user.py: No User Info" % req_id)
            return return_data
        if debugging:
            print(data[enc_uid])
        if data[enc_uid][0] != "" or data[enc_uid][1] != "":  # 사용자 정보 있을 때
            return_data = [data[enc_uid][0], data[enc_uid][1]]
            log.info("[#%s] get_user@modules/user.py: Succeeded" % req_id)
        else:  # 사용자 정보 없을 때
            return_data = [None, None]
            log.info("[#%s] get_user@modules/user.py: No User Info" % req_id)
        return return_data
    except Exception:
        return Exception
示例#33
0
def meal(year, month, date, req_id, debugging):
    # 자료형 변환
    year = str(year).zfill(4)
    month = str(month).zfill(2)
    date = str(date).zfill(2)

    log.info("[#%s] meal@modules/getData.py: Started Fetching Meal Data(%s-%s-%s)" % (req_id, year, month, date))

    if not os.path.isfile('data/cache/' + year + '-' + month + '-' + date + '.json'):
        parser = mealParser.parse(year, month, date, req_id, debugging)
        if parser == "NoData" or parser == "":
            log.info("[#%s] meal@modules/getData.py: No Meal Data(%s-%s-%s)" % (req_id, year, month, date))
            return {"message": "등록된 데이터가 없습니다."}

    try:
        with open('data/cache/' + year + '-' + month + '-' + date + '.json',
                  encoding="utf-8") as data_file:
            data = json.load(data_file, object_pairs_hook=OrderedDict)
            json_data = data
    except FileNotFoundError:  # 파일 없을때
        if debugging:
            print("FileNotFound")
        log.info("[#%s] meal@modules/getData.py: No Meal Data(%s-%s-%s)" % (req_id, year, month, date))
        return {"message": "등록된 데이터가 없습니다."}
    log.info("[#%s] meal@modules/getData.py: Succeeded(%s-%s-%s)" % (req_id, year, month, date))
    return json_data
示例#34
0
def schdl(year, month, date, req_id, debugging):

    log.info("[#%s] schdl@modules/getData.py: Started Fetching Schedule Data(%s-%s-%s)" % (req_id, year, month, date))

    # 파일 없으면 생성
    if not os.path.isfile('data/cache/Cal-%s-%s.json' % (year, month)):
        scheduleParser.parse(year, month, req_id, debugging)

    try:
        with open('data/cache/Cal-%s-%s.json' % (year, month),
                  encoding="utf-8") as data_file:
            data = json.load(data_file, object_pairs_hook=OrderedDict)
    except FileNotFoundError:  # 파일 없을때
        if debugging:
            print("FileNotFound")
        log.info("[#%s] schdl@modules/getData.py: No Schedule Data(%s-%s-%s)" % (req_id, year, month, date))
        return "일정이 없습니다."

    # 일정 있는지 확인
    if str(date) in data:
        log.info("[#%s] schdl@modules/getData.py: Succeeded(%s-%s-%s)" % (req_id, year, month, date))
        return data[str(date)]

    log.info("[#%s] schdl@modules/getData.py: No Schedule Data(%s-%s-%s)" % (req_id, year, month, date))
    return "일정이 없습니다."
示例#35
0
def check_cache(reqdata, req_id, debugging):
    log.info("[#%s] check_cache@modules/skill.py: New Request" % req_id)
    # 사용자 ID 가져오고 검증
    uid = json.loads(reqdata)["userRequest"]["user"]["id"]
    if user.auth_admin(uid, req_id, debugging):
        health = cache.health_check(req_id, debugging)
        msg = "시간표: %s\n한강 수온: %s\n날씨: %s" % (health["Timetable"],
                                              health["HanRiverTemperature"],
                                              health["Weather"])
    else:
        log.info("[#%s] check_cache@modules/skill.py: Non-Authorized User" %
                 req_id)
        msg = "사용자 인증에 실패하였습니다.\n당신의 UID는 %s 입니다." % uid
    return skill(msg)
示例#36
0
def auth_admin(uid, req_id, debugging):
    with open(admin_path, encoding="utf-8") as data_file:
        enc = hashlib.sha256()
        enc.update(uid.encode("utf-8"))
        enc_uid = enc.hexdigest()
        data = json.load(data_file)
    if debugging:
        print(enc_uid)
        print(data)
    if enc_uid in data:
        log.info("[#%s] auth_admin@modules/user.py: Match" % req_id)
        return True
    else:
        log.info("[#%s] auth_admin@modules/user.py: Not Match" % req_id)
        return False
示例#37
0
    def parse():
        global weather_data

        log.info("[#%s] weather@modules/getData.py: Started Parsing Weather Data" % req_id)

        weather_data = weatherParser.parse(req_id, debugging)

        # 지금의 날짜와 시간까지만 취함
        weather_data["Timestamp"] = int(datetime.datetime(now.year, now.month, now.day, now.hour).timestamp())

        with open('data/cache/weather.json', 'w',
                  encoding="utf-8") as make_file:  # 캐시 만들기
            json.dump(weather_data, make_file, ensure_ascii=False, indent="\t")
            print("File Created")

        log.info("[#%s] weather@modules/getData.py: Succeeded" % req_id)
示例#38
0
def chg_credit():
    '''
    调整用户最大透支额度
    :return: 成功为True, 失败为False
    '''
    user_name = input('请输入要调整额度的用户: ').strip()
    file_dict = login_in.get_file_dir(setting.PATH_USER)
    if user_name in file_dict.keys():
        user_dict = json.load(open(file_dict[user_name], 'r'))
        print('帐号:%s目前最大透支额度:%s' % (user_name, user_dict['credit']))
        inp_info = input('请输入要调整的最大透支额度:').strip()
        user_dict['credit'] = inp_info
        json.dump(user_dict, open(file_dict[user_name], 'w'))
        print('帐号:%s已调整最大透支额度!' % user_name)
        log.info('【%s】-->帐号:%s已调整最大透支额度!' % (login_in.USER_STATUS['username'], user_name))
    else:
        print('未查到%s帐号!' % user_name)
示例#39
0
 def parse():
     log.info("[#%s] wtemp@modules/getData.py: Started Parsing Water Temperature Data" % req_id)
     try:
         global date, temp
         parser = WTempParser.get(req_id, debugging)
         date = parser[0]
         temp = parser[1]
     except Exception:
         log.err("[#%s] wtemp@modules/getData.py: Failed to Fetch Water Temperature Data" % req_id)
         return "측정소 또는 서버 오류입니다."
     if not temp.isalpha():  # 무효값 걸러냄(값이 유효할 경우에만 캐싱)
         with open('data/cache/wtemp.json', 'w',
                   encoding="utf-8") as make_file:  # 캐시 만들기
             json.dump({"timestamp": int(date.timestamp()), "temp": temp}, make_file, ensure_ascii=False, indent="\t")
             print("File Created")
             temp = temp + "°C"
     log.info("[#%s] wtemp@modules/getData.py: Succeeded" % req_id)
示例#40
0
def purge_cache(reqdata, req_id, debugging):
    log.info("[#%s] purge_cache@modules/skill.py: New Request" % req_id)
    # 사용자 ID 가져오고 검증
    uid = json.loads(reqdata)["userRequest"]["user"]["id"]
    if user.auth_admin(uid, req_id, debugging):
        if cache.purge(req_id, debugging)["status"] == "OK":  # 삭제 실행, 결과 검증
            msg = "캐시를 비웠습니다."
        else:
            log.err(
                "[#%s] purge_cache@modules/skill.py: Failed to Purge Cache" %
                req_id)
            msg = "삭제에 실패하였습니다. 오류가 발생했습니다."
    else:
        log.info("[#%s] purge_cache@modules/skill.py: Non-Authorized User" %
                 req_id)
        msg = "사용자 인증에 실패하였습니다.\n당신의 UID는 %s 입니다." % uid
    return skill(msg)
示例#41
0
    def handle(self):
         while True:
            try:
                data = self.request.recv(1024).strip().decode()
                cmd_dic = json.loads(str(data))
                action = cmd_dic["action"]
                print("【{}】收到消息:{}".format(self.client_address[0], action))
                log.info("【{}】收到消息:{}".format(self.client_address[0], action))

                if hasattr(self, action):
                    function = getattr(self, action)
                    function(cmd_dic)
                    if action == 'quit': break
            except ConnectionResetError as e:
                print("error", e)
                log.info("【{}】error {}".format(self.client_address[0], e))
                break
示例#42
0
def purge(req_id, debugging):
    dict_data = OrderedDict()
    try:
        file_list = [
            file for file in os.listdir("data/cache/")
            if file.endswith(".json")
        ]
        for file in file_list:
            os.remove("data/cache/" + file)
    except Exception as error:
        log.err("[#%s] purge@modules/cache.py: Failed" % req_id)
        if debugging:
            dict_data["status"] = error
        dict_data["status"] = "Error"
        return dict_data
    dict_data["status"] = "OK"
    log.info("[#%s] purge@modules/cache.py: Succeeded" % req_id)
    return dict_data
示例#43
0
def unlock():
    '''
    解锁用户
    :return: 成功返回True,否则为False
    '''
    file_dict = login_in.get_file_dir(setting.PATH_USER)
    user_name = input('请输入要解锁的用户: ').strip()
    if user_name in file_dict.keys():
        user_dict = json.load(open(file_dict[user_name], 'r'))
        if user_dict['type'] == 'Y':
            print('帐号:%s未冻结,不用处理!')
        else:
            user_dict['type'] = 'Y'
            json.dump(user_dict, open(file_dict[user_name], 'w'))
            print('帐号:%s已解锁!' % user_name)
            log.info('【%s】-->帐号:%s已解锁!' % (login_in.USER_STATUS['username'], user_name))
    else:
        print('未查到%s帐号!' % user_name)
示例#44
0
def tt(tt_grade, tt_class, year, month, date, req_id, debugging):
    tt_weekday = datetime.date(year, month, date).weekday()

    log.info("[#%s] tt@modules/getData.py: Started Fetching Timetable Data(%s-%s, %s-%s-%s)"
             % (req_id, tt_grade, tt_class, year, month, date))

    if tt_weekday >= 5:  # 토요일, 일요일 제외
        log.info("[#%s] tt@modules/getData.py: No Timetable Data(%s-%s, %s-%s-%s)"
                 % (req_id, tt_grade, tt_class, year, month, date))
        return "등록된 데이터가 없습니다."

    data = TTParser.parse(tt_grade, tt_class, year, month, date, req_id, debugging)

    if not data:
        log.info("[#%s] tt@modules/getData.py: No Timetable Data(%s-%s, %s-%s-%s)"
                 % (req_id, tt_grade, tt_class, year, month, date))
        return "등록된 데이터가 없습니다."

    def wday(tt_weekday):
        if tt_weekday == 0:
            return "월"
        elif tt_weekday == 1:
            return "화"
        elif tt_weekday == 2:
            return "수"
        elif tt_weekday == 3:
            return "목"
        elif tt_weekday == 4:
            return "금"
        elif tt_weekday == 5:
            return "토"
        elif tt_weekday == 6:
            return "일"
        else:
            return "오류"

    # 헤더 작성. n학년 n반, yyyy-mm-dd(요일): 형식
    header = ("%s학년 %s반,\n%s(%s):\n" % (
        tt_grade, tt_class, datetime.date(year, month, date), wday(tt_weekday)))
    if debugging:
        print(header)

    # 본문 작성
    body = str()
    for i in range(len(data)):
        if "[MSG]" in data[i]:  # 파서 메세지에는 아무것도 붙이지 않음
            body = body + "\n%s" % data[i].replace("[MSG]", "")
        else:
            body = body + "\n%s교시: %s" % (i+1, data[i])

    log.info("[#%s] tt@modules/getData.py: Succeeded(%s-%s, %s-%s-%s)"
             % (req_id, tt_grade, tt_class, year, month, date))

    return header + body
示例#45
0
def freeze_user():
    '''
    冻结用户
    :param:user_name 帐号
    :return:
    '''
    file_dict = login_in.get_file_dir(setting.PATH_USER)
    user_name = input('请输入要冻结的用户: ').strip()
    if user_name in file_dict.keys():
        user_dict = json.load(open(file_dict[user_name], 'r'))
        if user_dict['type'] == 'N':
            print('帐号:%s已冻结,不用处理!')
        else:
            user_dict['type'] = 'N'
            json.dump(user_dict, open(file_dict[user_name], 'w'))
            print('帐号:%s已冻结!' % user_name)
            log.info('【%s】-->帐号:%s已冻结!' % (login_in.USER_STATUS['username'], user_name))
    else:
        print('未查到%s帐号!' % user_name)
示例#46
0
def get(req_id, debugging):
    log.info("[#%s] get@modules/WTempParser.py: Started Parsing Water Temperature" % req_id)
    try:
        url = urllib.request.urlopen("http://koreawqi.go.kr/wQSCHomeLayout_D.wq?action_type=T")
    except Exception as error:
        if debugging:
            print(error)
        log.err("[#%s] get@modules/WTempParser.py: Failed" % req_id)
        return error
    data = BeautifulSoup(url, 'html.parser')
    # 측정일시 파싱
    date = data.find('span', class_='data').get_text().split('"')[1]
    date = int(date[0:4]), int(date[4:6]), int(date[6:8])
    time = int(data.find('span', class_='data').get_text().split('"')[3])
    measurement_date = datetime.datetime(date[0], date[1], date[2], time)
    # 수온 파싱
    wtemp = data.find('tr', class_='site_S01004').get_text()  # 구리측정소 사용
    wtemp = wtemp.replace("구리", "").strip()
    log.info("[#%s] get@modules/WTempParser.py: Succeeded" % req_id)
    return measurement_date, wtemp
示例#47
0
def get_home_timeline(api, limit=100, display=True):
    """Get home timeline."""
    log.success('Gathering home timeline')

    result = handle_request(tweepy.Cursor(api.home_timeline).items(limit))
    tweets = []

    if result:
        for tweet in result:
            tweets += [{'id_str': tweet.id_str, 'text': tweet.text}]

        count = len(tweets)
        log.bold('{count} tweet{s}'.format(count=count,
                                           s='' if count == 1 else 's'))

        if display:
            for tweet in tweets:
                log.info('{tweet}'.format(tweet=tweet['text']))

    sleep.sleep_interval()  # Sleep to prevent API rate limit
    return tweets
示例#48
0
def modify_password(user_name):
    '''
    修改密码
    :return:
    '''
    file_dict = get_file_dir(setting.PATH_USER)
    if user_name in file_dict.keys():
        user_dict = json.load(open(file_dict[user_name], 'r'))
        pas_word1 = input('请输入需要修改的密码:').strip()
        pas_word2 = input('请再次输入需要修改的密码:').strip()
        if pas_word1 == pas_word2:
            pasword_md5 = md5(pas_word2)
            user_dict['password'] = pasword_md5
            json.dump(user_dict, open(file_dict[user_name], 'w'))
            print('帐号:%s密码已修改!' % user_name)
            log.info('【%s】-->帐号:%s密码已修改!' % (USER_STATUS['username'], user_name))
        else:
            print('两次输入的密码不一致!')
    else:
        print('未查到%s帐号!' % user_name)
    input('按回车键继续\n')
示例#49
0
    def login_in(self, msg):
        '''
        用户登录
        :param user_name:
        :param pass_word:
        :return:
        '''
        user_name = msg["username"]
        pass_word = msg["pass_word"]
        self.user_name = user_name
        login_dict = json.load(open(setting.PATH_USE, 'r'))
        rs = ''
        if user_name in login_dict.keys():

            if login_dict[user_name]['password'] == pass_word:
                self.login_type = True
                self.name = user_name
                self.path = login_dict[user_name]['user_path']
                self.home = login_dict[user_name]['home_path']
                rs = '200'
                log.info("【{}】帐号:{} 登录成功!".format(self.client_address[0], user_name))
            else:
                rs = '400'
                log.info("【{}】帐号:{} 登录失败!".format(self.client_address[0], user_name))
        else:
            rs = '400'
            log.info("【{}】帐号:{} 登录失败!".format(self.client_address[0], user_name))
        self.request.send(rs.encode())
示例#50
0
def repay_money():
    '''还款'''
    chose = {}
    user_dict = json.load(open(login_in.get_file_dir(setting.PATH_USER)[login_in.USER_STATUS['username']], 'r'))

    if not user_dict['debt']:  # 如果无帐单信息
        print('帐号:%s无帐单数据!' % login_in.USER_STATUS['username'])
    else:

        flag = True
        while flag:  # 遍历并做输出展示
            print('选择仍需还款的帐期:')
            print('编码 \t 帐期 \t 需还款金额')
            for num, item in enumerate(user_dict['debt']):  # 遍历并做输出展示
                bill_value = user_dict['debt'][item][0]
                pay_value = user_dict['debt'][item][1]
                if bill_value + pay_value != 0:
                    print('【%d】\t 【%s】\t 【%s】' % (num, item, float(-bill_value) - float(pay_value)))
                    chose.setdefault(num, item)
            print('【q】 \t 退出')
            inp = input('请输入选择的帐期序列:').strip()

            if inp == 'q' or inp == 'Q':
                flag = False
                break

            chose_bill_date = chose.get(int(inp))
            repay_fee = input('还款金额:\n>>').strip()
            user_dict['debt'][chose_bill_date][1] += int(repay_fee)
            curr_date = bill_date()
            if chose_bill_date == curr_date:     # 当前帐期则增加可用额度
                user_dict['balance'] += int(repay_fee)

            print('帐期:【%s】已完成还款【%s】元' % (chose_bill_date, repay_fee))
            json.dump(user_dict, open(login_in.get_file_dir(setting.PATH_USER)[login_in.USER_STATUS['username']], 'w'))
            log.info("【%s】-->帐期:【%s】已完成还款【%s】元" % (login_in.USER_STATUS['username'], chose_bill_date, repay_fee))
            input('按回车键继续')
示例#51
0
def build_generic(options, platform, pp, env=None):
    target = get_target(platform)

    if options.release:
        pp.defines.append('RELEASE')
        pp.undefines.append('DEBUG')
    else:
        pp.undefines.append('RELEASE')
        pp.defines.append('DEBUG')

    if options.rocket:
        pp.defines.append('ROCKET')
    else:
        pp.undefines.append('ROCKET')

    if platform in ['intel_linux64', 'intel_linux32', 'mingw64', 'intel_mingw32', 'osx']:
        # Android/iOS has its own skeleton set up
        cmd = 'mkdir -p "%s"' % target.dist
        Popen(shlex.split(cmd), env=env).communicate()
        cmd = 'mkdir -p "%s"' % join(target.dist,'include')
        Popen(shlex.split(cmd), env=env).communicate()
        cmd = 'mkdir -p "%s"' % join(target.dist,'bin')
        Popen(shlex.split(cmd), env=env).communicate()
        cmd = 'mkdir -p "%s"' % join(target.dist,'lib')
        Popen(shlex.split(cmd), env=env).communicate()

    if not isdir(target.tmp):
        os.makedirs(target.tmp)
            
    # Compile SDL statically
    if 'sdl' in options.modules and not options.bare:
        info('Building SDL')
        prepare_sdl(platform, options, env)
        make_sdl(platform, options, env)

    if options.bare:
        # We need to build zlib
        target = get_target(platform)
        prepare_source('zlib', SOURCES['ZLIB'], target.builds.ZLIB)
        mod = __import__('modules.sdl.common', fromlist=['make_common'])
        mod.make_common(env, target, options, ['zlib',])

    # Compile Ignifuga then Python statically
    if 'ignifuga' in options.modules:
        info('Building Ignifuga')
        if options.bare:
            if options.baresrc:
                prepare_ignifuga(platform, pp, options, options.baresrc)
                ignifuga_src, glue_h, glue_c = make_ignifuga(target.builds.IGNIFUGA, options)
            else:
                ignifuga_src, glue_h, glue_c = [], '', ''
        else:
            prepare_ignifuga(platform, pp, options)
            ignifuga_src, glue_h, glue_c = make_ignifuga(target.builds.IGNIFUGA, options)
        info('Building Python')
        prepare_python(platform, ignifuga_src, target.builds.PYTHON, options, env)
        make_python(platform, ignifuga_src, options, env)
示例#52
0
def login_in():
    '''
    用户登录运行程序
    :return:username, flag, admin_type
    '''
    global USER_STATUS
    flag = False
    admin_type = False
    username = input("请输入登陆账号:")  # 打印登陆提示
    # password = getpass.getpass("请输入密码: ")      # 因getpass在pycharm 有BUG,为便于测试,用input替换
    password = input("请输入密码:")  # 测试时使用,替换getpass
    INPUT.setdefault(username, 0)
    if check_lock(username):  # 检查录入帐号是否锁定
        exit("该帐号已锁定!请联系管理员处理,谢谢!")
    else:
        user_pass, power = check_user(username, password)  # 如果未被锁,检查用户名和密码录入是否正确定
        if user_pass == 'Y':
            print("帐号:%s登陆成功!" % username)  # 用户名和密码录入正确,返回用户信息
            USER_STATUS['username'] = username
            USER_STATUS['power'] = power
            USER_STATUS['type'] = True
            if power == '1':
                admin_type = True
                flag = True
            else:
                flag = True
                admin_type = False
                log.info("【%s】-->帐号:%s登陆成功!" % (username, username))
            return username, flag, admin_type
        elif user_pass == 'N':
            check_error_count(username)
            INPUT[username] += 1
            print("帐号或密码输入错误,请重新输入!")
            log.info("【%s】-->帐号或密码输入错误,请重新输入!" % username)
            return username, flag, admin_type  # 密码录入不正确,校验尝试次数
        elif user_pass == 'q':
            return username, flag, admin_type
        elif user_pass == 'None':
            print('无此用户,请登录admin帐号添加!'.center(30, '*'))
            log.info("【%s】-->无此用户,请登录admin帐号添加!" % username)
            print("帐号未注册,Bye Bye !")  # ##用户名不正确,打印退出
            return username, flag, admin_type
示例#53
0
    def get(self, msg):
        '''
        客户端的get命令,即服务器端发送数据
        :param msg:
        :return:
        '''
        get_file = os.path.basename(msg["filename"])
        file_path = os.path.join(self.path, get_file)
        if not os.path.isfile(file_path):    # 参数不是文件

            msg_dic = {
                "filename": get_file,
                "is_file": False,
                "size": 0,
            }
            self.request.send(json.dumps(msg_dic).encode())
            log.info("【{}】帐号:{}  get {}不是文件".format(self.client_address[0], self.name, file_path))
        else:
            size = os.stat(file_path).st_size
            msg_dic = {
                "filename": get_file,
                "is_file": True,
                "size": size,
            }
            self.request.send(json.dumps(msg_dic).encode())  # 发送成功标示、文件大小
            data = self.request.recv(1024).decode()
            if data == '200':
                m = hashlib.md5()
                with open(file_path, 'rb') as f:
                    send_data = f.read()
                    m.update(send_data)
                    self.request.send(send_data)
                md5sum = m.hexdigest()
                self.request.recv(1024)  # 防止粘包
                self.request.send(md5sum.encode())
                log.info("【{}】帐号:{}  get {}文件发送完成".format(self.client_address[0], self.name, file_path))
            else:
                send_data = 0
                self.request.send(send_data)
                log.info("【{}】帐号:{}  get {}文件不存在".format(self.client_address[0], self.name, file_path))
示例#54
0
 def pwd(self, *args):
     pwd_path = self.path
     self.request.send(pwd_path.encode())
     log.info("【{}】帐号:{}  执行pwd命令".format(self.client_address[0], self.name))
示例#55
0
 def quit(self, *args):
     self.login_type = False
     log.info("【{}】帐号:{} 退出登录!".format(self.client_address[0], self.user_name))
示例#56
0
    env, pp = prepare_intel_mingw64_env(target, openmp=options.openmp)
    build_generic(options, platform, pp, env)

def build_project_intel_mingw64(options, project_root):
    platform = 'intel_mingw64'
    target = get_target(platform)
    env, pp = prepare_intel_mingw64_env(target, openmp=options.openmp)
    target = get_target(platform, project_root)
    build_project_generic(options, platform, target, pp, env)

# ===============================================================================================================
# MAIN
# ===============================================================================================================
    
if __name__ == '__main__':
    info('Schafer - The Ignifuga Builder Utility')
    usage = "schafer.py -p platform [options]"
    parser = OptionParser(usage=usage, version="Ignifuga Build Utility 1.0")
    parser.add_option("-A","--available-platforms",
        action="store_true", dest="available_platforms", default=False,
        help="List the available target platforms on the system")
    parser.add_option("-P", "--platform", dest="platform", default=None,
                  help="Platform, see -A option for available platform names")
    parser.add_option("-M", "--module", dest="module", default="all",
                  help="Ignifuga module to build (all, ignifuga, sdl) Default: all")
    parser.add_option("-c", "--clean",
                  action="store_true", dest="clean", default=False,
                  help="Clean temporary files before building")
    parser.add_option("-C", "--forceclean",
                  action="store_true", dest="forceclean", default=False,
                  help="Clean everything before building")
示例#57
0
def show_bill():
    '''
    帐单展示
    :return:
    '''
    chose = {}
    struct_time = time.localtime()  # struct_time时间
    user_dict = json.load(open(login_in.get_file_dir(setting.PATH_USER)[login_in.USER_STATUS['username']], 'r'))
    balance = user_dict['balance']  # 可用额度
    credit = user_dict['credit']  # 最大额度额度
    repay_date = int(user_dict['repay_date'])  # 还款日期

    curr_time = bill_date()  # 取出账单日期
    if not user_dict['debt']:  # 如果无帐单信息
        print('帐号:%s无帐单数据!' % login_in.USER_STATUS['username'])

    else:
        flag = True
        while flag:  # 遍历并做输出展示
            print('编码 \t 帐期')
            for num, item in enumerate(user_dict['debt']):  # 遍历并做输出展示
                print('【%d】\t %s' % (num, item))
                chose.setdefault(num, item)
            print('【q】 \t 退出')

            inp = input('请输入选择的帐期序列:').strip()
            if inp == 'q' or inp == 'Q':
                flag = False
                break
            chose_bill_date = chose.get(int(inp))

            bill_value = user_dict['debt'][chose_bill_date][0]
            pay_value = user_dict['debt'][chose_bill_date][1]
            debt = float(-bill_value) - float(pay_value)  # 欠款金额
            # 计算延期手续费
            struct_bill_date = time.strptime(chose_bill_date, '%Y-%m-%d')
            repay_date1 = '%d-%d-%d' % (struct_bill_date.tm_year, struct_bill_date.tm_mon, repay_date)
            chose_bill = '%d-%d' % (struct_bill_date.tm_year, struct_bill_date.tm_mon)
            date1 = time.strftime('%j', time.strptime(repay_date1, '%Y-%m-%d'))  # 还款日
            date2 = time.strftime('%j', struct_time)  # 当前时间
            diff_days = int(date2) - int(date1)  # 差

            cost = (-bill_value) * 0.0005 * int(diff_days) if int(diff_days) > 0 else 0
            cost = ("%.2f" % cost)
            if struct_time.tm_mday >= repay_date and chose_bill_date == curr_time:
                print('\n 个人信用卡未出帐账单:\n{}'.format('*' * 60))
            else:
                print('\n 个人信用卡账单:\n{}'.format('*' * 60))
            print('''
                账号:\t\t【{}】
                账期:\t\t【{}】
                账单金额:\t\t【{}】
                已还金额:\t\t【{}】
                欠款金额:\t\t【{}】
                到期还款日:\t\t【{}】
                延期手续费:\t\t【{}】\n{}
            '''.format(login_in.USER_STATUS['username'],
                       chose_bill,
                       -bill_value,
                       pay_value,
                       debt,
                       repay_date1,
                       cost,
                       '*' * 60))
            log.info("【%s】-->查询%s帐期帐单" % (login_in.USER_STATUS['username'], chose_bill))
            input('按回车键继续')

        return flag
示例#58
0
def withdraw_money_base(flag):
    '''
    取款/转帐/消费基础函数
    :param flag: 处理类型
    :return: int(inp) 提取/转帐/消费的金额, succ_no 完成类型
    '''
    succ_no = False
    inp = '0'
    user_dict = json.load(open(login_in.get_file_dir(setting.PATH_USER)[login_in.USER_STATUS['username']], 'r'))
    balance = int(user_dict['balance'])  # 可取本月额度一半
    if balance > 0:
        if flag == '消费':
            inp = input('您的账户最高可%s【%.2f】元, 请输入你要%s的金额:' % (flag, int(balance) + user_dict['saving'], flag)).strip()
        else:
            inp = input('您的账户最高可%s【%.2f】元, 请输入你要%s的金额:' % (flag, int(balance / 2) + user_dict['saving'], flag)).strip()
        if inp.isdigit():
            if flag == '消费':
                a = int(inp) * 0  # 消费类型无手续费
            else:
                a = int(inp) * 0.05
            counter_fee = float("%.2f" % a)  # 手续费 5%
            if int(inp) <= balance / 2 + user_dict['saving'] and flag != '消费':  # 输入金额小于等于可取款金额的1/2,扣减可取金额

                if int(inp) <= user_dict['saving']:
                    user_dict['saving'] -= int(inp)
                    counter_fee = 0
                elif int(inp) > user_dict['saving']:
                    user_dict['balance'] = balance - int(inp) - counter_fee - user_dict['saving']
                    user_dict['saving'] = 0

                    # 写入当前帐期欠款数据
                    curr_time = bill_date()
                    # 有帐期数据
                    if user_dict['debt'].get(curr_time):
                        user_dict['debt'][curr_time][0] -= int(inp) + counter_fee   # 提现数据写入记录

                    # 无帐期数据
                    else:
                        user_dict['debt'].setdefault(curr_time, [-(int(inp)-counter_fee), 0])
                json.dump(user_dict, open(login_in.get_file_dir(setting.PATH_USER)[login_in.USER_STATUS['username']], 'w'))
                print('%s【%d】 元,手续费:【%.2f】元,正在处理,请稍后...' % (flag, int(inp), counter_fee))
                log.info("【%s】-->%s【%d】 元,手续费:【%.2f】元" % (login_in.USER_STATUS['username'], flag, int(inp), counter_fee))
                succ_no = True

            elif int(inp) <= balance + user_dict['saving'] and flag == '消费':

                if int(inp) <= user_dict['saving']:
                    user_dict['saving'] -= int(inp)
                    counter_fee = 0
                elif int(inp) > user_dict['saving']:
                    user_dict['balance'] = balance - int(inp) - counter_fee - user_dict['saving']
                    user_dict['saving'] = 0

                    # 写入当前帐期欠款数据
                    curr_time = bill_date()
                    # 有帐期数据
                    if user_dict['debt'].get(curr_time):
                        user_dict['debt'][curr_time][0] -= int(inp) - counter_fee   # 提现数据写入记录

                    # 无帐期数据
                    else:
                        user_dict['debt'].setdefault(curr_time, [-(int(inp)-counter_fee), 0])
                json.dump(user_dict, open(login_in.get_file_dir(setting.PATH_USER)[login_in.USER_STATUS['username']], 'w'))
                print('%s【%d】 元,手续费:【%.2f】元,正在处理,请稍后...' % (flag, int(inp), counter_fee))
                log.info("【%s】-->%s【%d】 元,手续费:【%.2f】元" % (login_in.USER_STATUS['username'], flag, int(inp), counter_fee))
                succ_no = True
            else:
                print('输入金额应该小于等于%.2f!' % (balance / 2))
        else:
            print('输入金额有误!')
    else:
        print('本月无可%s额度!' % flag)
        inp = 0
        succ_no = False
    return float(inp), succ_no