def get(name): if Config._config is None: try: with open(Util.basedir() + '/config.json', 'r') as fp: Config._config = json.load(fp) except: Util.log('json error on config.json') return None if name in Config._config: return Config._config[name] else: return None
def test_time_to_readable(self): util = Util() self.assertEqual(util.time_to_readable(0), '0 secs') self.assertEqual(util.time_to_readable(1), '1 sec') self.assertEqual(util.time_to_readable(59), '59 secs') self.assertEqual(util.time_to_readable(60), '1 min') self.assertEqual(util.time_to_readable(3600), '1 hr') self.assertEqual(util.time_to_readable(604800), '7 days') self.assertEqual(util.time_to_readable(604800, max_unit="week"), '1 week') self.assertEqual(util.time_to_readable(604800, max_unit="hr"), '168 hrs') self.assertEqual(util.time_to_readable(86410), '1 day') self.assertEqual(util.time_to_readable(86410, max_levels=4), '1 day 10 secs')
def test_get_ability(self): util = Util() self.assertEqual("Agility", util.get_ability("Agility")) self.assertEqual("Agility", util.get_ability("Agil")) self.assertEqual("Agility", util.get_ability("A")) self.assertEqual("Agility", util.get_ability("a")) self.assertEqual("Agility", util.get_ability("agility")) self.assertEqual(None, util.get_ability("agilityy")) self.assertEqual(None, util.get_ability("agilb"))
def test_parse_time(self): util = Util() self.assertEqual(10, util.parse_time("10s")) self.assertEqual("hola", util.parse_time("10s sdfsd", "hola")) self.assertEqual(70, util.parse_time("1m10s")) self.assertEqual(70, util.parse_time("10s1m")) self.assertEqual(70, util.parse_time("10s1m")) self.assertEqual(183661, util.parse_time("1s3hr2d1m"))
def test_parse_time(self): util = Util() self.assertEqual(util.parse_time("10s"), 10) self.assertEqual(util.parse_time("10s sdfsd", "hola"), "hola") self.assertEqual(util.parse_time("1m10s"), 70) self.assertEqual(util.parse_time("10s1m"), 70) self.assertEqual(util.parse_time("10s1m"), 70) self.assertEqual(util.parse_time("1s3hr2d1m"), 183661)
def test_group_by(self): util = Util() data1 = [1, 2, 3, 4, 5, 6] result1 = util.group_by(data1, lambda x: x % 2) self.assertEqual({1: [1, 3, 5], 0: [2, 4, 6]}, result1) data2 = [{ "group": "one", "name": "1" }, { "group": "two", "name": "2" }, { "group": "one", "name": "3" }, { "group": "two", "name": "4" }] result2 = util.group_by(data2, lambda x: x["group"]) self.assertEqual( { 'one': [{ 'group': 'one', 'name': '1' }, { 'group': 'one', 'name': '3' }], 'two': [{ 'group': 'two', 'name': '2' }, { 'group': 'two', 'name': '4' }] }, result2)
def update_program(): # c_float_p = ctypes.POINTER(ctypes.c_float) if not Render.pause: Render.elapsed = Util.current_milli_time() - Render.time_start else: # Render.sample_count = 0 pass glUniform1i(getattr(Render.trace_program, 'stop_motion_loc'), 1 if Render.pause else 0) glUniform1i(getattr(Render.trace_program, 'refresh_loc'), 1 if Render.refresh else 0) glUniform1f(getattr(Render.trace_program, 'sample_count_loc'), Render.sample_count) glUniform1f(getattr(Render.trace_program, 'glob_time_loc'), Render.elapsed / 50) glUniform1f(getattr(Render.trace_program, 'cam_fov_loc'), math.tan(Util.radian(Camera.fov / 2))) glUniform2fv(getattr(Render.trace_program, 'cam_res_loc'), 1, np.array(Camera.res, 'f')) glUniform3fv(getattr(Render.trace_program, 'cam_pos_loc'), 1, np.array(Camera.pos, 'f')) glUniformMatrix3fv(getattr(Render.trace_program, 'cam_trans_loc'), 1, GL_FALSE, Util.flat(Camera.rtrans)) Render.refresh = False
def update_rtrans(): global trans f = Util.normalize(Camera.lookat) u = Camera.up r = Util.cross_product(u, f) u = Util.cross_product(f, r) u = Util.normalize(u) r = Util.normalize(r) trans = np.matrix([ [r[0], u[0], f[0]], [r[1], u[1], f[1]], [r[2], u[2], f[2]] ]) rot = Util.get_rot_x_mat(Camera.rotate[0]) * Util.get_rot_y_mat(Camera.rotate[1]) Camera.rtrans = trans * rot
class Render(object): ''' classdocs ''' image_texs = [] # image textures texs = [] water_norms = [] mtl_tex = None # material texture mtl_num = 0 trace_program = None # program for tracing draw_program = None # program to draw based on the result of trace_program fbo = None # frame buffer object sample_count = 0 time = -1 time_start = Util.current_milli_time() elapsed = 0 pause = False refresh = False def __init__(self, params): ''' Constructor ''' @staticmethod def get_shader(url, shader_type): file_content = open(url).read() shader = shaders.compileShader(file_content, shader_type) return shader @staticmethod def get_shader_program(vs_url, fs_url): '''Generate the GLSL program using vertex shader and fragment shader ''' vertex_shader = Render.get_shader(vs_url, GL_VERTEX_SHADER) fragment_shader = Render.get_shader(fs_url, GL_FRAGMENT_SHADER) program = shaders.compileProgram(vertex_shader, fragment_shader) return program @staticmethod def init_uniforms(loc_map): program = Render.trace_program for uniform, loc in loc_map.items(): uniform_loc = glGetUniformLocation(program, uniform) if uniform_loc in [-1, None]: # raise Exception("Error %s" % uniform) print ("Error %s" % uniform) pass else: print("%s : %s" % (uniform, uniform_loc)) setattr(program, loc, uniform_loc) @staticmethod def update_program(): # c_float_p = ctypes.POINTER(ctypes.c_float) if not Render.pause: Render.elapsed = Util.current_milli_time() - Render.time_start else: # Render.sample_count = 0 pass glUniform1i(getattr(Render.trace_program, 'stop_motion_loc'), 1 if Render.pause else 0) glUniform1i(getattr(Render.trace_program, 'refresh_loc'), 1 if Render.refresh else 0) glUniform1f(getattr(Render.trace_program, 'sample_count_loc'), Render.sample_count) glUniform1f(getattr(Render.trace_program, 'glob_time_loc'), Render.elapsed / 50) glUniform1f(getattr(Render.trace_program, 'cam_fov_loc'), math.tan(Util.radian(Camera.fov / 2))) glUniform2fv(getattr(Render.trace_program, 'cam_res_loc'), 1, np.array(Camera.res, 'f')) glUniform3fv(getattr(Render.trace_program, 'cam_pos_loc'), 1, np.array(Camera.pos, 'f')) glUniformMatrix3fv(getattr(Render.trace_program, 'cam_trans_loc'), 1, GL_FALSE, Util.flat(Camera.rtrans)) Render.refresh = False # Util.flat(mat) @staticmethod def make_texture(): tex_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, tex_id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, Camera.res[0], Camera.res[1], 0, GL_RGB, GL_UNSIGNED_BYTE, None) # glBindTexture(GL_TEXTURE_2D, None) return tex_id @staticmethod def make_texture_float(data): tex_id = glGenTextures(1) width = 4 height = len(data) // width // 3 # data_f = GLfloatArray(data) # data_f = array(data).tobytes() glBindTexture(GL_TEXTURE_2D, tex_id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, np.array(data, 'f')) # glBindTexture(GL_TEXTURE_2D, None) return (height - 1, tex_id) @staticmethod def get_texture(image_src): ix, iy, image = Render.load_image(image_src) tex_id = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, tex_id) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glGenerateMipmap(GL_TEXTURE_2D) # glBindTexture(GL_TEXTURE_2D, -1) return tex_id @staticmethod def load_image(imageName): im = pil_open(imageName) try: # # Note the conversion to RGB the crate bitmap is paletted! im = im.convert('RGB') ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1) except SystemError: ix, iy, image = im.size[0], im.size[1], im.tostring("raw", "RGBX", 0, -1) assert ix * iy * 4 == len(image), """Image size != expected array size""" return ix, iy, image
def test_interpolate_value(self): util = Util() # empty interpolation_ranges self.assertEqual(None, util.interpolate_value(1, {})) # ql outside of single interpolation_ranges self.assertEqual(None, util.interpolate_value(2, {1: 1})) # ql on interpolation_range lower boundary self.assertEqual(1, util.interpolate_value(1, {1: 1, 100: 100})) # ql on interpolation_range upper boundary self.assertEqual(100, util.interpolate_value(100, {1: 1, 100: 100})) # ql outside of multiple interpolation_ranges self.assertEqual(None, util.interpolate_value(101, {1: 1, 100: 100})) # ql within interpolation_range self.assertEqual(50, util.interpolate_value(50, {1: 1, 100: 100})) self.assertEqual( 50, util.interpolate_value(50, { 1: 1, 100: 100, 101: 101, 200: 400 })) self.assertEqual(653, util.interpolate_value(137, {1: 11, 200: 951})) self.assertEqual( 249, util.interpolate_value(150, { 1: 1, 100: 100, 101: 101, 200: 400 })) self.assertEqual( 55, util.interpolate_value(200, { 1: 5, 200: 55, 201: 55, 300: 73 })) # test reverse order self.assertEqual( 55, util.interpolate_value(200, { 300: 73, 201: 55, 200: 55, 1: 5 })) # test out of order self.assertEqual( 55, util.interpolate_value(200, { 201: 55, 300: 73, 1: 5, 200: 55 }))
def test_time_to_readable(self): util = Util() self.assertEqual('0 secs', util.time_to_readable(0)) self.assertEqual('1 sec', util.time_to_readable(1)) self.assertEqual('59 secs', util.time_to_readable(59)) self.assertEqual('1 min', util.time_to_readable(60)) self.assertEqual('1 min 1 sec', util.time_to_readable(61)) self.assertEqual('1 hr', util.time_to_readable(3600)) self.assertEqual('7 days', util.time_to_readable(604800)) self.assertEqual('1 week', util.time_to_readable(604800, max_unit="week")) self.assertEqual('168 hrs', util.time_to_readable(604800, max_unit="hr")) self.assertEqual('1 day', util.time_to_readable(86410)) self.assertEqual('1 day 10 secs', util.time_to_readable(86410, max_levels=4)) self.assertEqual('1 min 12 secs', util.time_to_readable(72))
def test_format_datetime(self): util = Util() self.assertEqual("2009-02-14 07:51:30 UTC", util.format_datetime(1234597890)) self.assertEqual("2018-08-10 04:05:22 UTC", util.format_datetime(1533873922))
def test_format_date(self): util = Util() self.assertEqual("2009-02-14", util.format_date(1234597890)) self.assertEqual("2018-08-10", util.format_date(1533873922))
def Register(username, password, email): #チェック if len(username) >= 32: return None if len(password) >= 32 or len(password) < 5: return None if len(email) >= 256: return None #データベース操作 connect = MySQLdb.connect(db=config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, user=config.DB_USER, passwd=config.DB_PASSWD) cur = connect.cursor() cur.execute('SELECT id FROM UserInfo WHERE username = %s;', (username,)) rows = cur.fetchall() if len(rows) != 0: cur.close() connect.close() return None d = datetime.datetime.today() cur.execute('INSERT INTO UserInfo (username,password,email,registration_date) VALUES(%s,%s,%s,%s);',(username, md5.new(password+'t').hexdigest(), Util.myencode(email), d.strftime("%Y-%m-%d"), )) connect.commit() d = datetime.datetime.today() key = md5.new(d.strftime('%s')).hexdigest() cur.execute('UPDATE UserInfo SET email_key=%s WHERE username=%s;', (key, username, )) connect.commit() from_addr = '*****@*****.**' to_addr = email link = 'http://game.clooca.com/confirm/%s' % (key) link2 = 'http://game.clooca.com/login' body = u''' %s さん!clooca game、ご登録ありがとうございます! 登録を完了するには %s にアクセスしてください。 また、グループにログインするには次のURLにアクセスしてください。 %s ''' % (username, link, link2) msg = Gmail.create_message(from_addr, to_addr, 'clooca game!', body) Gmail.send_via_gmail(from_addr, to_addr, msg) cur.close() connect.close() return True
class DownloadManager: """ Provides methods for interacting with Downloads, mainly finding files and moving them around """ def __init__(self): self.util = Util() def get_video_file_path(self, files): max_size = 0 file_id = None decompress = False for torrent_id in files: print strings.FINDING_VIDEO_FILE % torrent_id for f in files[torrent_id]: if "sample" not in files[torrent_id][f]['name'].lower() \ and "trailer" not in files[torrent_id][f]['name'].lower() \ and "bonus features" not in files[torrent_id][f]['name'].lower(): ext = files[torrent_id][f]['name'].rsplit('.', 1)[1].lower() if ext in config.FILETYPES['video'] and files[torrent_id][f]['size'] > max_size: decompress = False max_size = files[torrent_id][f]['size'] file_name = files[torrent_id][f]['name'] elif ext in config.FILETYPES['compressed'] and files[torrent_id][f]['size'] > max_size: if ext == 'zip': decompress = 'zip' max_size = files[torrent_id][f]['size'] file_name = files[torrent_id][f]['name'] elif ext == 'rar': decompress = 'rar' max_size = files[torrent_id][f]['size'] file_name = files[torrent_id][f]['name'] else: return None if decompress: if decompress == 'rar': file_name = self.unrar_file(file_name) if decompress == 'zip': file_name = self.unzip_file(file_name) file_dir = os.path.join(TransmissionManager().get_session().download_dir, file_name.rsplit('/*', 1)[0]) files_list = [f for f in os.listdir(file_dir) if (os.path.isfile(os.path.join(file_dir, f)) and f.lower().rsplit('.', 1)[1] in config.FILETYPES['video']) ] if not files_list: raise FakeDownloadException() elif file_name: if file_name.lower().rsplit('.', 1)[1] not in config.FILETYPES['video']: raise FakeDownloadException() else: return None return file_name def get_all_video_file_paths(self, files, kill_samples = True): videos = [] for torrent_id in files: print strings.FINDING_VIDEO_FILE % torrent_id for f in files[torrent_id]: ext = files[torrent_id][f]['name'].rsplit('.', 1)[1].lower() if ext in config.FILETYPES['video'] and (files[torrent_id][f]['selected']): videos.append(files[torrent_id][f]['name']) elif ext in config.FILETYPES['compressed'] and (files[torrent_id][f]['selected']): if ext == 'rar': done = self.unrar_file(files[torrent_id][f]['name']) videos.append(files[torrent_id][f]['name']) elif ext == 'zip': done = self.unzip_file(files[torrent_id][f]['name']) videos.append(files[torrent_id][f]['name']) else: raise Exception(strings.UNSUPPORTED_FILE_TYPE % files[torrent_id]) if kill_samples: videos = self.__filter_samples(videos) videos = self.__filter_video_only(videos) if len(videos) > 0: return videos else: raise FakeDownloadException() def __filter_samples(self, file_list): return [f for f in file_list if "sample" not in f.lower() and "trailer" not in f.lower()] def __filter_video_only(self, file_list): return [f for f in file_list if f.lower().rsplit('.', 1)[1] in config.FILETYPES['video']] def unrar_file(self, file_path): print strings.UNRAR guid = str(uuid.uuid4().hex) src_path = self.util.shellquote("%s/%s" % (TransmissionManager().get_session().download_dir, file_path)) dest_path = self.util.shellquote("%s/%s/" % (TransmissionManager().get_session().download_dir, guid)) try: if config.TVROBOT['completed_move_method'] == 'FABRIC': subprocess.check_call("fab unrar_file:rar_path='%s',save_path='%s'" % (src_path, dest_path), stdout=open("%s/log_fabfileOutput.txt" % (config.TVROBOT['log_path']), "a"), stderr=open("%s/log_fabfileError.txt" % (config.TVROBOT['log_path']), "a"), shell=True) elif config.TVROBOT['completed_move_method'] == 'LOCAL': subprocess.check_call("mkdir %s; unrar e %s %s" % (dest_path, src_path, dest_path), stdout=open("%s/log_localfileOutput.txt" % (config.TVROBOT['log_path']), "a"), stderr=open("%s/log_localfileError.txt" % (config.TVROBOT['log_path']), "a"), shell=True) else: print "FIX YER CONF. I ONLY KNOW FABRIC AND LOCAL." except Exception, e: print strings.CAUGHT_EXCEPTION raise e return "%s/*" % guid
def __init__(self): self.util = Util()
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys import os import time import shutil import smtplib from datetime import datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from core.util import Util from core.config import Config now = datetime.now().strftime('%s') pictureDir = Util.basedir() + '/' + Config.get('picture-dir') detectedPicrure = pictureDir + '/preview.jpg' lastmodified = 0 for i in range(0, 30): if os.path.exists(detectedPicrure): stat = os.stat(detectedPicrure) if int(stat.st_mtime) >= int(now): lastmodified = stat.st_mtime break time.sleep(1) if lastmodified == 0: Util.log('file not found') sys.exit()