def convert_file(self): """ Handles converting of single file. It creates stamps signaling the file is being converted and that it was finished. Returns filepath of the input file if there is an error. """ if self.should_convert(): if has_start_stamp(self.filepath_in): if os.path.exists(self.filepath_out): os.remove(self.filepath_out) try: create_start_stamp(self.filepath_in) text('Converting: {}'.format(self.filepath_in)) with open('{}.convert'.format(self.path), 'w') as convert_out: cmd = [ self.binary, '-y', '-i', self.filepath_in, '-sn', '-x265-params', 'crf=28', '-c:v', 'libx265', self.filepath_out ] if self.convert: subprocess.check_call(cmd, stdout=convert_out, stderr=convert_out) create_end_stamp(self.filepath_in) if self.delete: self.remove_original() except subprocess.CalledProcessError: text('Failed. Check the "{}.convert" file for more details.'. format(self.path))
def checkForConnection(self): utils.text(self.game.screen, "Please turn knob to position 1.", 50, 170, 45) utils.text(self.game.screen, "And turn off all shields.", 65, 240, 45) for shield in self.game.interface.shieldOn: if shield != False: return if self.game.interface.radarPosition == 1: self.connectionSuccess = True
def __init__(self, director): escena.Escena.__init__(self, director) pygame.mixer.music.load("../musica/divano.mp3") pygame.mixer.music.play(-1, 0.0) self.menu = utils.loadImage('../graficos/menu/foto.png', True, (480, 400)) self.espadita = utils.loadImage("../graficos/menu/espadita.png", True) self.r_espadita = self.espadita.get_rect() self.r_espadita.centerx = 310 self.r_espadita.centery = 290 self.texto_comenzar, self.r_texto_comenzar = utils.text("Comenzar", 490, 290) self.texto_salir, self.r_texto_salir = utils.text("Salir", 490, 490) self.option = 1 # Opción del menú que está seleccionada.
def update(self): if self.lost: for o in self.game.gameObjects: o.enabled = False self.enabled = True self.game.interface.enabled = True utils.text(self.game.screen, "You Lost", 160, 160, 80, red) print("Your base was destroyed. :(") if self.won: for o in self.game.gameObjects: o.enabled = False self.enabled = True self.game.interface.enabled = True utils.text(self.game.screen, "You Won", 160, 160, 80, green) print("Your engineers fixed your power generator. :)")
def main(args): dir_path = os.path.abspath(args.path) files_failed = [] for root, dirs, files in os.walk(dir_path): for filename in sorted(files): filepath = os.path.abspath(os.path.join(root, filename)) f = ConvertedFile(BIN, VIDEO_FORMATS, filepath, args.delete) failed = f.convert_file() if failed: files_failed.append(filepath) for fail in files_failed: text('Failed: {}'.format(fail))
def encode(data,mime_type='',charset='utf-8',base64=True): if isinstance(data,six.text_type): data = data.encode(charset) else: charset = None if base64: data = utils.text(b64encode(data)) else: data = data # 这里有一个BUG,以后看看改怎么修改 # data = utils.text(quote(data)) result = ['data:',] if mime_type: result.append(mime_type) if charset: result.append(';charset=') result.append(charset) if base64: result.append(';base64') result.append(',') result.append(data) return ''.join(result)
async def edit_user(r: aiohttp.web.RequestHandler): if not await privilegehelper.logged_in( r) or not await privilegehelper.is_admin(r): return aiohttp.web.HTTPForbidden() acc = await Account.from_sql(r.rel_url.query["id"]) paramlist = [ "name", "id", "email", "country", "privileges", "pp", "stars", "coins", "u_coins", "demons" ] mydict = {} for i in paramlist: try: if i == "pp": mydict[i] = float(r.rel_url.query[i].rstrip("pp")) else: mydict[i] = int(r.rel_url.query[i]) except: mydict[i] = r.rel_url.query[i] if i in ["pp", "stars", "coins", "u_coins", "demons"]: setattr(acc.stats, i, mydict[i]) else: setattr(acc, i, mydict[i]) await acc.stats.save() await acc.save() return utils.text("a")
def execute(self, img, context): gray = utils.gray(utils.crop(img, self.NUM_RECT)) type = cv2.THRESH_BINARY | cv2.THRESH_OTSU ret, bin = cv2.threshold(gray, 60, 255, type) #cv2.imshow('tyoshi', bin) #cv2.waitKey(1) context.clear() context['tyoshi'] = utils.text(bin, "+0123456789")
def update(self): deltaT = self.game.deltatime self.timer += deltaT self.progTimer += deltaT if self.game.interface.radarOn: self.timer += 2 * deltaT for shield in self.game.interface.shieldOn: if shield: self.timer += deltaT self.energy -= self.timer / 5000 if self.timer >= 5000: self.timer = 0 if self.energy <= 0: self.energy = 0 self.energyAvailable = False utils.text(self.game.screen, "Energy {0}%".format(str(self.energy)), 510, 10, 25) self.progress = floor(self.progTimer / 25200) if self.progress >= 10: self.game.gameover.won = True utils.text(self.game.screen, "{0}/10".format(str(self.progress).split(".")[0]), 10, 10, 25) utils.text( self.game.screen, "{0}x anti-Missiles".format( str(self.game.antimissile.antiMissilesRemaining)), 500, 460, 20)
def update(self): self.connectTimer += self.game.deltatime if (not self.game.interface.keyboard) and ( not self.game.interface.controller): utils.text(self.game.screen, "Connecting to controller...", 90, 200, 45) self.game.interface.connectToController() elif self.connectTimer < 2000 and self.game.interface.keyboard: utils.text(self.game.screen, "Unable to connect to controller.", 30, 200, 45) utils.text(self.game.screen, "Using keyboard input.", 110, 250, 45) elif self.connectTimer < 2000 and self.game.interface.controller: utils.text(self.game.screen, "Successfuly connected to controller", 10, 200, 40) elif self.game.interface.controller and not self.connectionSuccess: self.checkForConnection() else: for o in self.game.gameObjects: o.enabled = True for i in range(self.game.numMissiles): self.game.missiles.append(Missile(self.game)) self.enabled = False utils.text(self.game.screen, "START!", 280, 240, 45)
def handle_error(self, type, url, task, start_time, error): result = { 'status_code': getattr(error, 'code', 599), 'error': utils.text(error), 'content': "", 'time': time.time() - start_time, 'orig_url': url, 'url': url, "save": task.get('fetch', {}).get('save') } logger.error("[%d] %s:%s %s, %r %.2fs", result['status_code'], task.get('project'), task.get('taskid'), url, error, result['time']) return result
async def login_post(r: aiohttp.web.RequestHandler): data = await r.post() username = data["username"] password = data["password"] user = await userhelper.get_user_by_name(username) if user.compare_pass(password): session = await get_session(r) session["logged_in"] = True session["user_id"] = user.id await user.update_last_active() user.ip = r.headers.get("CF-Connecting-IP", "0.0.0.0") user.country = await geohelper.get_country(user.ip) await user.save() return aiohttp.web.HTTPFound("/") return utils.text("Invalid username or password")
def handle(builds, environ, cmd=None): error = None try: settings = json.loads(query(environ, 'settings', '{}')) except: log.exception("Error in json parsing the settings variable") error = escape(make_trace()) settings = {} for e in sorted(settings_validator.iter_errors(settings)): if error is None: error = "" error += str(e) + "\n" if error is not None: log.error("Errors from schema: " + error) yield '<result>\n<error>' + error + '</error>\n</result>\n' else: incremental = query(environ, 'incremental', '') incremental = incremental.lower() == 'true' try: if cmd == "makefile": log.info("Returning makefile") yield makefile(settings) elif cmd == "join": log.info("Joining existing build") yield "<result>\n" hashnumber = query(environ, 'hash', '') for k in join_from_hash(builds, hashnumber, incremental): yield k else: log.info("Starting a new build") yield "<result>\n" for k in build(builds, text(environ), settings, incremental, "xml"): yield k except: trace = make_trace() log.exception("Error in handle") yield '<trace>' + escape(trace) + '</trace>\n' yield '</result>\n'
from utils import text AUTHORS = [ text('Lord Basta of the Iron Isles'), text('Chris Van Halen'), text('Ngo Way'), text('Huck Charmston'), text('Davor van der Beergulpen') ] CARRIERS = { 'america_movil': 'America Movil', 'kddi': 'Kddi', 'o2': 'O2', 'telefonica': 'Telefonica', 'deutsche_telekom': 'DT', } REGIONS = { 'de': 'Germany', 'es': 'Spain', 'mx': 'Mexico', 'jp': 'Japan', 'us': 'United States', } MESSAGES = [ ['be careful, cvan made it', 'loljk'], ["it's probably a game or something"], None
def http_fetch(self, url, task): '''HTTP fetcher''' start_time = time.time() handle_error = lambda x: self.handle_error('http', url, task, start_time, x) # setup request parameters fetch = self.pack_tornado_request_parameters(url, task) task_fetch = task.get('fetch', {}) session = cookies.RequestsCookieJar() # fix for tornado request obj if 'Cookie' in fetch['headers']: c = http_cookies.SimpleCookie() try: c.load(fetch['headers']['Cookie']) except AttributeError: c.load(utils.utf8(fetch['headers']['Cookie'])) for key in c: session.set(key, c[key]) del fetch['headers']['Cookie'] if 'cookies' in fetch: session.update(fetch['cookies']) del fetch['cookies'] max_redirects = task_fetch.get('max_redirects', 5) # we will handle redirects by hand to capture cookies fetch['follow_redirects'] = False # making requests while True: # robots.txt # if task_fetch.get('robots_txt', False): # can_fetch = yield self.can_fetch(fetch['headers']['User-Agent'], fetch['url']) # if not can_fetch: # error = tornado.httpclient.HTTPError(403, 'Disallowed by robots.txt') # raise gen.Return(handle_error(error)) try: request = tornado.httpclient.HTTPRequest(**fetch) # if cookie already in header, get_cookie_header wouldn't work old_cookie_header = request.headers.get('Cookie') if old_cookie_header: del request.headers['Cookie'] cookie_header = cookies.get_cookie_header(session, request) if cookie_header: request.headers['Cookie'] = cookie_header elif old_cookie_header: request.headers['Cookie'] = old_cookie_header except Exception as e: logger.exception(fetch) raise gen.Return(handle_error(e)) try: response = yield self.http_client.fetch(request) except tornado.httpclient.HTTPError as e: if e.response: response = e.response else: raise gen.Return(handle_error(e)) extract_cookies_to_jar(session, response.request, response.headers) if (response.code in (301, 302, 303, 307) and response.headers.get('Location') and task_fetch.get('allow_redirects', True)): if max_redirects <= 0: error = tornado.httpclient.HTTPError( 599, 'Maximum (%d) redirects followed' % task_fetch.get('max_redirects', 5), response) raise gen.Return(handle_error(error)) if response.code in (302, 303): fetch['method'] = 'GET' if 'body' in fetch: del fetch['body'] fetch['url'] = quote_chinese(urljoin(fetch['url'], response.headers['Location'])) fetch['request_timeout'] -= time.time() - start_time if fetch['request_timeout'] < 0: fetch['request_timeout'] = 0.1 max_redirects -= 1 continue result = {} result['orig_url'] = url result['content'] = response.body or '' result['headers'] = dict(response.headers) result['status_code'] = response.code result['url'] = response.effective_url or url result['time'] = time.time() - start_time result['cookies'] = session.get_dict() result['save'] = task_fetch.get('save') if response.error: result['error'] = utils.text(response.error) if 200 <= response.code < 300: logger.info("[%d] %s:%s %s %.2fs", response.code, task.get('project'), task.get('taskid'), url, result['time']) else: logger.warning("[%d] %s:%s %s %.2fs", response.code, task.get('project'), task.get('taskid'), url, result['time']) raise gen.Return(result)
failed = f.convert_file() if failed: files_failed.append(filepath) for fail in files_failed: text('Failed: {}'.format(fail)) def cleanup(): """ Removes temporary directory if present. """ global TMP_DIR if TMP_DIR: try: shutil.rmtree(TMP_DIR) except IOError: # We probably don't have access to our own tmp directory, well # nothing we can do about it. pass try: args = parser.parse_args() main(args) except KeyboardInterrupt: text('Exiting.') finally: cleanup()
def types_handler(message): if message.content_type == "text": utils.text(message) elif message.content_type == "photo" and (message.chat.id == utils.admin_id or message.chat.id == utils.kat): utils.papug_insert(message)
def _udemae(self, img): type = cv2.THRESH_BINARY | cv2.THRESH_OTSU ret, bin = cv2.threshold(utils.gray(img), 240, 255, type) img = self._erode(bin) return utils.text(img, "SABC+-")