def handler(event, context): try: logger.info(event) if verify_supported_media_type(event['headers']) is False: return response_builder( 415, { 'error_message': "This API only support 'content-type: application/x-www-form-urlencoded' media type" }) token = parse_qs(event['body']).get('token', None) if token is None: return response_builder( 400, {'error_message': 'Missing token patameter'}) authlete = AuthleteSdk(api_key=os.environ['AUTHLETE_API_KEY'], api_secret=os.environ['AUTHLETE_API_SECRET']) result = authlete.verify_access_token(token=token[0]) except AuthleteApiError as e: if e.status_code != 400: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) return response_builder(e.status_code, {'error_message': e.message}) return response_builder(200, result)
def _responseData(): try: vendor = find_by_id(vid=args['VENDOR_ID']) if(not isNone(vendor)): vendor.MENU = None if isNone(args['MENU']) else args['MENU'] session = pg_session() try: session.add(vendor) except Exception as e: session.rollback() logger.error('_menu_update :' + str(e)) else: session.commit() response_data['data'] = models_to_list(vendor) except Exception as e: logger.error('_menu_update :' + str(e)) pass return response_data
def handle_unresolved_url(data, action): url = unquote(data) logger.info(u'Trying to resolve URL (%s): %s' % (action, url)) if xbmc.Player().isPlaying(): utils.show_info_notification(utils.translation(32007), 1000) else: utils.show_info_notification(utils.translation(32007)) if 'youtube.com' in url or 'youtu.be' in url: youtube_addon = xbmcaddon.Addon(id="plugin.video.youtube") if youtube_addon: if utils.get_setting('preferYoutubeAddon') == 'true' or youtube_addon.getSetting("kodion.video.quality.mpd") == "true": logger.info(u'Youtube addon have DASH enabled or is configured as preferred use it') clean_url = list(urlparse(url)) clean_url[4] = '&'.join( [x for x in clean_url[4].split('&') if not re.match(r'app=', x)]) url = urlunparse(clean_url) utils.play_url('plugin://plugin.video.youtube/uri2addon/?uri=%s' % url, action) return logger.info(u'Trying to resolve with YoutubeDL') result = resolve_with_youtube_dl(url, {'format': 'best', 'no_color': 'true', 'ignoreerrors': 'true'}, action) if result: return # Second pass with new params to fix site like reddit dash streams logger.info(u'Trying to resolve with YoutubeDL other options') result = resolve_with_youtube_dl(url, {'format': 'bestvideo+bestaudio/best', 'no_color': 'true', 'ignoreerrors': 'true'}, action) if result: return logger.error(u'Url not resolved by YoutubeDL') logger.info(u'Trying to play as basic url') utils.play_url(url, action) if url: utils.show_error_notification(utils.translation(32006))
def handlePackage_Activate(*args,**kwargs): event = kwargs["sender"] session = kwargs["session"] accountId = event.accountId try: account = session.query(Tenant).filter(Tenant.id == accountId).one() logger.error("<%s> account is in db , need to clean.") except NoResultFound: logger.info("<%s> is new accountid , create tenant id in db" % accountId) tenant = Tenant() tenant.id = accountId tenant.name = "TBD" tenant.state = Tenant_Sate.INIT session.add(tenant) packageName = event.packageName manager = ModelManager() svcs = manager.listsvcbypath(packageName) if svcs is None: logger.error("package(%s) has no corresponding service definition..." % pkg_path) return else: for model_svc in svcs: servcie = createRuntimeService(model_svc,tenant.id) session.add(servcie) tenant.getSM().trigger("package_activate",tenant = tenant,payload = event)
def handler(event, context): try: logger.info(event) authlete = AuthleteSdk(api_key=os.environ['AUTHLETE_API_KEY'], api_secret=os.environ['AUTHLETE_API_SECRET']) congito_user_pool = CognitoUserPool( user_pool_id=os.environ['COGNITO_USER_POOL_ID']) access_token = get_access_token_from_header(headers=event['headers']) response_content = authlete.get_user_info(access_token=access_token) sub = congito_user_pool.get_user_sub_value( username=response_content['sub']) except ValidationError as e: return response_builder(e.status_code, {'error_message': e.message}) except AuthleteApiError as e: if e.status_code != 401: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) return response_builder(e.status_code, {'error_message': e.message}) except ClientError as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) return response_builder(200, {'sub': sub, 'name': response_content['sub']})
def decorator(func): encode_rule = rule if (rule is not None and rule == '/'): '''routing by function name''' encode_rule = '/{0}'.format(func.__name__) elif (rule is None or len(str(rule)) == 0): '''routing by file name''' encode_rule = '' path = '' if (urlcheck.match(func.__module__) is None): logger.error('API Blueprint: invalid api path!') if (Config.DEBUG): raise Exception('API Blueprint: invalid api path!') else: path = '/{0}{1}'.format( '/'.join(re.split(r'\b\.\b', func.__module__)[1:]), encode_rule) options.update({'endpoint': path}) @bpt.route(path, **options) def route_wrapper(*args, **kwargs): try: if (not isNone(params)): kwargs['args'] = get_parameter(**params) return func(*args, **kwargs) except ValueError as e: rs = {'success': False, 'message': str(e), 'data': []} return api_response(**rs), 400 route_wrapper.__doc__ = func.__doc__ return route_wrapper
def handler(event, context): try: logger.info(event) data = json.loads(event['body']) user_id = event['pathParameters']['user_id'] if 'email' not in data: return response_builder(400, {'error_message': 'emailのパラメータが足りません'}) if users.exists_user(user_id=user_id): return response_builder(409, {'error_message': '既にそのユーザは存在しています'}) users.create( user_id=user_id, email=data['email'], ) except json.decoder.JSONDecodeError: return response_builder(400, {'error_message': 'JSONが不正です'}) except ClientError as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) return response_builder(201)
def listsvcbypath(self,pnames): ret = [] for package_name in pnames: if self.model_base.has_key(package_name): ret.extend(self.model_base.get(package_name)) else: logger.error("invalid package name: %s" % package_name) return ret
def connect(): try: ftp = ftplib.FTP(__const_host) ftp.login(__const_username, __const_pwd) return ftp except Exception as e: logger.error(str(e)) raise Exception( "FTP is unavailable,please check the host,username and password!")
def handler(event, context): try: logger.info(event) result = users.get_all() except ClientError as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) return response_builder(200, result['Items'])
def handler(event, context): try: logger.info(event) user_id = event['pathParameters']['user_id'] users.delete(user_id=user_id) except ClientError as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) return response_builder(204)
def exe_query_by_clz(clz, session, sql, **params): '''使用Data class 執行 SQL Command''' try: comment = text(sql) proxy = session.execute(comment, params) descrip = proxy._cursor_description() cur = proxy.fetchall() data = [] if len(cur) > 0: instance = clz() properties = [ dict((t.lower(), t) for t in instance.__dict__.keys() if not t.startswith('_')) ][0] oths = { p.lower(): p for p in dir(instance.__class__) if isinstance(getattr(instance.__class__, p), property) } properties = dict(properties, **oths) for row in cur: instance = clz() for i, value in enumerate(row): try: if descrip[i][0].lower() in properties: p = properties[descrip[i][0].lower()] setattr(instance, p, db_convert(value)) elif (re.sub(r"[\W_]+", "", descrip[i][0]).lower()) in properties: p = properties[re.sub(r"[\W_]+", "", descrip[i][0]).lower()] setattr(instance, p, db_convert(value)) else: continue #如果要把沒有定義在clz中欄位顯示出來,再把它打開 #setattr(instance, descrip[i][0], Convert(value)) except Exception as e: continue data.append(instance) else: data = None return data except sqlalchemy.exc.SQLAlchemyError as e: error, = e.args logger.error(error) raise e finally: session.close()
def handler(event, context): try: logger.info(event) authlete = AuthleteSdk(api_key=os.environ['AUTHLETE_API_KEY'], api_secret=os.environ['AUTHLETE_API_SECRET']) configuration = authlete.get_openid_configuration() except AuthleteApiError as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) return response_builder(200, configuration)
def _responseData(): try: vendor = find_by_id(vid=args['VENDOR_ID']) if (not isNone(vendor)): pass response_data['data'] = models_to_list(vendor) except Exception as e: logger.error('menu_release :' + str(e)) pass return response_data
def handler(event, context): try: logger.info(event) user_id = event['pathParameters']['user_id'] if not users.exists_user(user_id=user_id): return response_builder(404, {'error_message': 'そのユーザは存在しません'}) result = users.get(user_id=user_id) except ClientError as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) return response_builder(200, result['Item'])
def resolve_with_youtube_dl(url, parameters, action): youtube_dl_resolver = YoutubeDL(parameters) youtube_dl_resolver.add_default_info_extractors() try: result = youtube_dl_resolver.extract_info(url, download=False) if result is None: result = {} except Exception as e: logger.error(u'Error with YoutubeDL: %s' % e) result = {} logger.info(u'YoutubeDL full result: %s' % result) if 'entries' in result: logger.info(u'Playlist resolved by YoutubeDL: %s items' % len(result['entries'])) item_list = [] for entry in result['entries']: if entry is not None and 'url' in entry: item_list.append(entry) logger.info(u'Media found: %s' % entry['url']) if len(item_list) > 0: utils.play_items(item_list, action) return True else: logger.info(u'No playable urls in the playlist') if 'url' in result: logger.info(u'Url resolved by YoutubeDL: %s' % result['url']) utils.play_url(result['url'], action, result) return True if 'requested_formats' in result: if have_adaptive_plugin: logger.info(u'Adaptive plugin enabled looking for dash content') for entry in result['requested_formats']: if 'container' in entry and 'manifest_url' in entry: if 'dash' in entry['container']: logger.info(u'Url resolved by YoutubeDL: %s' % entry['manifest_url']) utils.play_url(entry['manifest_url'], action, result, True) return True for entry in result['requested_formats']: if 'protocol' in entry and 'manifest_url' in entry: if 'm3u8' in entry['protocol']: logger.info(u'Url resolved by YoutubeDL: %s' % entry['manifest_url']) utils.play_url(entry['manifest_url'], action, result) return True return False
def to_excel(dataset, filepath, filename): if (isNone(dataset)): return False writer = None try: # Note, Python 2 example. For Python 3 use: output = io.BytesIO(). output = io.BytesIO() # Use the StringIO object as the filehandle. writer = pd.ExcelWriter(output, engine='xlsxwriter') #writer = pd.ExcelWriter(filepath, engine='xlsxwriter') #title = DEFAULT_TOCC_TITLE.keys() for k, v in TOCC_IN_REASON.items(): subset = filter(v['filter'], dataset) xls_set = v['XLS_TITLE'] #title = xls_set.keys() title = [] index = xls_set.keys() datalist = [] for item in subset: d = [] for key in index: if (xls_set[key]['name'] not in title): title.append(xls_set[key]['name']) d.append(xls_set[key]['filter'](item)) datalist.append(d) df = pd.DataFrame(columns=title, data=datalist) df.to_excel(writer, sheet_name=k) writer.save() output.seek(0) return output #xlsx_data = output.getvalue() except Exception as e: logger.error('error travelhis to_excel :' + str(e)) return False finally: if (not isNone(writer)): writer.close()
def handle_unresolved_url(data, action): url = unquote(data) logger.info(u'Trying to resolve URL (%s): %s' % (action, url)) if xbmc.Player().isPlaying(): utils.show_info_notification(utils.translation(32007), 1000) else: utils.show_info_notification(utils.translation(32007)) if 'youtube.com' in url or 'youtu.be' in url: youtube_addon = xbmcaddon.Addon(id="plugin.video.youtube") if youtube_addon: if youtube_addon.getSetting("kodion.video.quality.mpd") == "true": logger.info(u'Youtube addon have DASH enabled use it') utils.play_url('plugin://plugin.video.youtube/uri2addon/?uri=%s' % url, action) return logger.info(u'Trying to resolve with YoutubeDL') result = resolve_with_youtube_dl(url, {'format': 'best', 'no_color': 'true', 'ignoreerrors': 'true'}, action) if result: return # Second pass with new params to fix site like reddit dash streams logger.info(u'Trying to resolve with YoutubeDL other options') result = resolve_with_youtube_dl(url, {'format': 'bestvideo+bestaudio/best', 'no_color': 'true', 'ignoreerrors': 'true'}, action) if result: return logger.error(u'Url not resolved by YoutubeDL') if utils.is_python_3(): logger.info(u'Skipping urlResolver as running on Python 3') else: logger.info(u'Trying to resolve with urlResolver') stream_url = urlresolver.HostedMediaFile(url=url).resolve() if stream_url: logger.info(u'Url resolved by urlResolver: %s' % stream_url) utils.play_url(stream_url, action) return logger.info(u'Trying to play as basic url') utils.play_url(url, action) if url: utils.show_error_notification(utils.translation(32006))
def o_to_d(obj, func=None): '''object to dictionary''' result = None dict1 = {} try: method = func if not isNone(func) else 'to_dict' if hasattr(obj, method): dict1 = getattr(obj, method)() else: dict1 = dict((t, getattr(obj, t)) for t in obj.__dict__.keys() if not t.startswith('_')) #dict1 = getattr(obj, method)() if hasattr(obj, method) else obj.__dict__ except Exception as identifier: logger.error(str(identifier)) else: oths = {} if isNone(func): oths = { p: getattr(obj, p) for p in dir(obj.__class__) if isinstance(getattr(obj.__class__, p), property) } result = dict(dict1, **oths) return result
def handleTenant_SAEnable(*args,**kwargs): event = kwargs["sender"] session = kwargs["session"] accountId = event.accountId if accountId == None: logger.error("accountId is None, ignore the invalid request") return try: account = session.query(Tenant).filter(Tenant.id == accountId).one() logger.error("<%s> account is in db , need to clean.") return except NoResultFound: tenant = Tenant() tenant.id = accountId tenant.name = "TBD" tenant.state = Tenant_Sate.PACKAGE_ACTIVATE session.add(tenant) session.flush() inventory = DMSInventoryManager() try: inventory.start() services = inventory.getservice(accountId) except: logger.error("get account <%s> service from zookeeper failed" % accountId) return mgr = ModelManager() for svc in services: model_svc = mgr.getsvfdefbyname(svc) servcie = createRuntimeService(model_svc,tenant.id) session.add(servcie) session.flush() for svc in services: nodes = inventory.getinstancebyservice(accountId,svc) for node in nodes: node["topic"] = "dms.event.rundeck" msg_event = EventFactory.getEvent("CREATE_VM",node) tenant.getSM().trigger("create_vm",tenant = tenant,payload=msg_event) session.commit() inventory.stop()
def handler(event, context): try: logger.info(event) if verify_supported_media_type(event['headers']) is False: return response_builder( 415, { 'error_message': "This API only support 'content-type: application/x-www-form-urlencoded' media type" }) # jwtの検証 jwt_token = get_access_token_from_header(event['headers']) if not verify_jwt_token(jwt_token): return response_builder(401, {"error_message": "invalid jwt token"}) # パラメーター設定 claims = jwt.get_unverified_claims(jwt_token) params = urllib.parse.parse_qs(event.get('body', '')) params['subject'] = [claims['cognito:username']] params['sub'] = [claims['sub']] params['scope'] = params.get('scope', ['']) # scopeが無い場合は空配列で初期化 params['scope'] = [params['scope'][0]] # scopeが複数来たら最初だけ使う # scopeの検証 if not verify_scope_parameter(params['scope'][0]): return response_builder( 400, { "error_message": "invalid scope parameter. scope parameter must be 'openid read' or 'openid read write'" }) # authrazition API new_params = urllib.parse.urlencode(params, doseq=True) if urllib.parse.parse_qs(new_params).get( 'code_challenge_method') is None: return response_builder( 400, { 'error_message': "The authorization request does not contain 'code_challenge_method' parameter." }) authlete = AuthleteSdk(api_key=os.environ['AUTHLETE_API_KEY'], api_secret=os.environ['AUTHLETE_API_SECRET']) authrazition_response = authlete.authorization_request(new_params) AUTHORIZATION_ERROR_CODES = [ AUTHLETE_AUTHORIZATION_ERROR_CLIENT_ID_IS_NOT_FOUND, AUTHLETE_AUTHORIZATION_ERROR_CODE_CHALLENGE_IS_INVALID, AUTHLETE_AUTHORIZATION_ERROR_CODE_CHALLENGE_METHOD_IS_NOT_SUPPORTED, AUTHLETE_AUTHORIZATION_ERROR_DOES_NOT_CONTAIN_CLIENT_ID, AUTHLETE_AUTHORIZATION_ERROR_DOES_NOT_CONTAIN_CODE_CHALLENGE_PARAMETER, AUTHLETE_AUTHORIZATION_ERROR_DOES_NOT_CONTAIN_REDIRECT_URI, AUTHLETE_AUTHORIZATION_ERROR_DOES_NOT_CONTAIN_RESPONSE_TYPE, AUTHLETE_AUTHORIZATION_ERROR_REDIRECT_URI_IS_NOT_REGISTERED, AUTHLETE_AUTHORIZATION_ERROR_RESPONSE_TYPE_IS_INVALID, AUTHLETE_AUTHORIZATION_SUCCESS_CODE ] if authrazition_response['resultCode'] in AUTHORIZATION_ERROR_CODES: return response_builder( 400, { 'error_message': strip_authlete_code(authrazition_response['resultMessage']) }) # authorization issue API authrazition_issue_response = authlete.authorization_issue_request({ "ticket": authrazition_response['ticket'], "subject": claims['cognito:username'], "sub": claims['sub'] }) if authrazition_issue_response[ 'resultCode'] == AUTHLETE_AUTHORIZATION_ISSUE_SUBJECT_DOES_NOT_CONTAIN: return response_builder( 400, { 'error_message': strip_authlete_code(authrazition_response['resultMessage']) }) if authrazition_issue_response[ 'resultCode'] != AUTHLETE_AUTHORIZATION_SUCCESS_CODE: return response_builder(500, {'error_message': 'Internal Server Error'}) except AuthleteApiError as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) except ValidationError as e: return response_builder(e.status_code, {'error_message': e.message}) return response_builder( 200, {'redirect_uri': authrazition_issue_response['responseContent']})
def TOOC_JSON2DICT(self): try: temp = {} data = None try: data = json.loads(self.CONTENT) except Exception as e: data = self.CONTENT #職業別 temp['occupation'] = data['occupation']['occupation'] temp['occupation_name'] = job_to_name( data['occupation']['occupation']) #同住家人是否居家隔離 temp['cluster_familyQuarantineIso'] = data['cluster'][ 'familyQuarantineIso'] #周遭朋友最近是否有發燒或呼吸道不適症狀 temp['cluster_friendSymptom'] = data['cluster']['friendSymptom'] #同住家人最近是否有發燒或呼吸道不適症 temp['cluster_familySymptom'] = data['cluster']['familySymptom'] #同住家人是否居家檢疫 temp['cluster_familyQuarantineCheck'] = data['cluster'][ 'familyQuarantineCheck'] #到期日 temp['cluster_dueDate'] = data['cluster']['dueDate'] #工作同事最近是否有發燒或呼吸道不適症狀 temp['cluster_colleagueSymptom'] = data['cluster'][ 'colleagueSymptom'] #身邊親友最近是否有接二連三發燒或呼吸道不適症狀 temp['cluster_rfFrequentSymptom'] = data['cluster'][ 'rfFrequentSymptom'] #同住家人是否自主健康管理 temp['cluster_familyHealthManage'] = data['cluster'][ 'familyHealthManage'] #您近期是否與確診者接觸 temp['cluster_confirmCaseTouch'] = data['cluster'][ 'confirmCaseTouch'] if ('confirmCaseTouch' in data['cluster']) else '' #接觸史 # 其他 temp['contactHistory_others'] = 'Y' if data['contactHistory'][ 'others'] else 'N' # 曾參與公眾集會 temp['contactHistory_PA'] = 'Y' if data['contactHistory'][ 'PA'] else 'N' # 無 temp['contactHistory_none'] = 'Y' if data['contactHistory'][ 'none'] else 'N' # 曾出入機場、觀光景點及其他頻繁接觸外國人場所 temp['contactHistory_ATF'] = 'Y' if data['contactHistory'][ 'ATF'] else 'N' # 曾參與開學/畢業典禮、婚喪喜慶、運動賽事等聚眾活動 temp['contactHistory_GMS'] = 'Y' if data['contactHistory'][ 'GMS'] else 'N' # 野生動物與禽鳥接觸 temp['contactHistory_WB'] = 'Y' if data['contactHistory'][ 'WB'] else 'N' # 曾至醫院、診所就醫 temp['contactHistory_HC'] = 'Y' if data['contactHistory'][ 'HC'] else 'N' # 曾參與宗教/政治/學術/藝文活動 temp['contactHistory_RPEC'] = 'Y' if data['contactHistory'][ 'RPEC'] else 'N' # 過去14日內是否出過國? temp['travelHistory_isSelfGoAbroad'] = data['travelHistory'][ 'isSelfGoAbroad'] # 過去14日內是否出過國?(國家) temp['travelHistory_countrySelf_Code'] = data['travelHistory'][ 'countrySelf'] temp['travelHistory_countrySelf_Name'] = country_to_name( data['travelHistory']['countrySelf']) # 同住家屬過去14天是否曾至國外旅遊? temp['travelHistory_isFamilyGoAbroad'] = data['travelHistory'][ 'isFamilyGoAbroad'] # 同住家屬過去14天是否曾至國外旅遊?(國家) temp['travelHistory_countryFamily_Code'] = data['travelHistory'][ 'countryFamily'] temp['travelHistory_countryFamily_Name'] = country_to_name( data['travelHistory']['countryFamily']) # 經常接觸之親友過去14天是否曾至國外旅遊? temp['travelHistory_isFriendGoAbroad'] = data['travelHistory'][ 'isFriendGoAbroad'] # 經常接觸之親友過去14天是否曾至國外旅遊?(國家) temp['travelHistory_countryFriend_Code'] = data['travelHistory'][ 'countryFriend'] temp['travelHistory_countryFriend_Name'] = country_to_name( data['travelHistory']['countryFriend']) # 健康史 #您自己是否有以下呼吸道不適或類流感症狀?例如:咳嗽、發燒、流鼻水、肌肉痠痛、頭痛 temp['healthHistory_selfSymptom'] = data['healthHistory'][ 'selfSymptom'] #陪探病證申請結果 temp['passport'] = ('N' if (isNone(self.PRN_CNT)) else ('Y' if self.PRN_CNT > 0 else 'N')) return temp except Exception as e: logger.error('_tocc_by_date :' + str(e)) return {}
def vsd(R_est, t_est, R_gt, t_gt, model, depth_test, K, delta, tau, cost_type="step", renderer=None): """Visible Surface Discrepancy. :param R_est, t_est: Estimated pose (3x3 rot. matrix and 3x1 trans. vector). :param R_gt, t_gt: GT pose (3x3 rot. matrix and 3x1 trans. vector). :param model: Object model given by a dictionary where item 'pts' is nx3 ndarray with 3D model points. :param depth_test: Depth image of the test scene. :param K: Camera matrix. :param delta: Tolerance used for estimation of the visibility masks. in mm, default 15 :param tau: Misalignment tolerance. in mm, default 20 :param cost_type: Pixel-wise matching cost: 'tlinear' - Used in the original definition of VSD in: Hodan et al., On Evaluation of 6D Object Pose Estimation, ECCVW 2016 'step' - Used for SIXD Challenge 2017. It is easier to interpret. :return: Error of pose_est w.r.t. pose_gt. typically err_vsd < 0.3, correct """ # im_size = (depth_test.shape[1], depth_test.shape[0]) height, width = depth_test.shape[:2] # Render depth images of the model in the estimated and the ground truth pose # depth_est = renderer.render(model, im_size, K, R_est, t_est, clip_near=100, # clip_far=10000, mode='depth') # depth_gt = renderer.render(model, im_size, K, R_gt, t_gt, clip_near=100, # clip_far=10000, mode='depth') _, depth_est = renderer.render(0, R_est, t_est, K=K, W=width, H=height, near=100, far=10000, to_255=True) _, depth_gt = renderer.render(0, R_gt, t_gt, K=K, W=width, H=height, near=100, far=10000, to_255=True) # Convert depth images to distance images dist_test = misc.depth_im_to_dist_im(depth_test, K) dist_gt = misc.depth_im_to_dist_im(depth_gt, K) dist_est = misc.depth_im_to_dist_im(depth_est, K) # Visibility mask of the model in the ground truth pose visib_gt = visibility.estimate_visib_mask_gt(dist_test, dist_gt, delta) # Visibility mask of the model in the estimated pose visib_est = visibility.estimate_visib_mask_est(dist_test, dist_est, visib_gt, delta) # Intersection and union of the visibility masks visib_inter = np.logical_and(visib_gt, visib_est) visib_union = np.logical_or(visib_gt, visib_est) # Pixel-wise matching cost costs = np.abs(dist_gt[visib_inter] - dist_est[visib_inter]) if cost_type == "step": costs = costs >= tau elif cost_type == "tlinear": # Truncated linear costs *= 1.0 / tau costs[costs > 1.0] = 1.0 else: logger.error("Error: Unknown pixel matching cost.") exit(-1) # costs_vis = np.ones(dist_gt.shape) # costs_vis[visib_inter] = costs # import matplotlib.pyplot as plt # plt.matshow(costs_vis) # plt.colorbar() # plt.show() # Visible Surface Discrepancy visib_union_count = visib_union.sum() visib_comp_count = visib_union_count - visib_inter.sum() if visib_union_count > 0: e = (costs.sum() + visib_comp_count) / float(visib_union_count) else: e = 1.0 return e
sys.argv.insert( 1, 0) # Stupid hack as calling scripts from JSON does not add script handle import xbmcgui import xbmcaddon from lib import share, stream, utils from lib.utils import logger, translation logger.info("Starting script version: %s", utils.ADDON_VERSION) argument = {} for arg in sys.argv[2:]: argInfo = arg.split('=') argument[argInfo[0]] = argInfo[1] logger.info("Parameters: %s" % argument) commands = {'share': share.run, 'stream': stream.run} if 'action' not in argument: xbmcaddon.Addon().openSettings() else: if argument['action'] in commands: commands[argument['action']](argument) else: logger.error("Command not supported: %s" % argument['action']) xbmcgui.Dialog().ok(utils.ADDON_NAME, translation(32004), translation(32005))
def handler(event, context): # 初期化処理 token = {} authlete = None try: if verify_supported_media_type(event['headers']) is False: return response_builder( 415, { 'error_message': "This API only support 'content-type: application/x-www-form-urlencoded' media type" }) authlete = AuthleteSdk(api_key=os.environ['AUTHLETE_API_KEY'], api_secret=os.environ['AUTHLETE_API_SECRET']) except Exception as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'}) # トークン取得処理 try: grant_type = authlete.get_grant_type(body=event['body']) data = authlete.get_clientid_and_clientsecret(headers=event['headers'], body=event['body']) if grant_type == 'authorization_code': if data.get('client_secret') is None: token = authlete.get_access_token_from_code( body=event['body'], client_id=data['client_id']) else: token = authlete.get_access_token_from_code( body=event['body'], client_id=data['client_id'], client_secret=data['client_secret']) elif grant_type == 'refresh_token': if data.get('client_secret') is None: token = authlete.get_access_token_from_refresh_token( body=event['body'], client_id=data['client_id']) else: token = authlete.get_access_token_from_refresh_token( body=event['body'], client_id=data['client_id'], client_secret=data['client_secret']) else: return response_builder(400, {'error_message': 'invalid grant_type'}) except ValidationError as e: logger.error(e) return response_builder(e.status_code, {'error_message': e.message}) except AuthleteApiError as e: logger.error(e) if e.status_code != 500: return response_builder(e.status_code, {'error_message': e.message}) return response_builder(500, {'error_message': 'Internal Server Error'}) try: congito_user_pool = CognitoUserPool( user_pool_id=os.environ['COGNITO_USER_POOL_ID']) access_token = token.get('access_token') response_content = authlete.get_user_info(access_token=access_token) attributes = congito_user_pool.get_user_attributes( username=response_content['sub']) phone_number_verified = 'false' for attribute in attributes: if attribute['Name'] == 'phone_number_verified': phone_number_verified = attribute['Value'] if phone_number_verified == 'true': return response_builder(200, token) else: return response_builder( 403, {'error_message': 'phone_number must be verified'}) except Exception as e: logger.error(e) return response_builder(500, {'error_message': 'Internal Server Error'})