content
stringlengths
0
1.55M
<import_stmt>random<line_sep>l1=[]<line_sep>l2=[]<for_stmt>i range(20)<block_start>l1.append(random.uniform(-1E10 1E10))<line_sep>l2.append(random.uniform(-1E10 1E10))<block_end>print(l1)<line_sep>print(l2)<line_sep>l=[]<line_sep>l.extend(l1)<line_sep>l.extend(l2)<line_sep>print(sorted(l))<line_sep>''' [6015943293.071386, -3878285748.0708866, 8674121166.062424, -1528465047.6118088, 7584260716.494843, -373958476.80486107, -6367787695.054295, 6813992306.719868, 5986097626.907181, 9011134545.052086, 7123644338.268343, 2646164210.08445, 4407427446.995375, -888196668.2563229, 7973918726.985172, -6529216482.09644, 6079069259.51853, -8415952427.784341, -6859960084.757652, -502409126.89040375] [9241165993.258648, -9423768405.578083, 3280085607.6687145, -5253703037.682413, 3858507441.2785892, 9896256282.896187, -9439606732.236805, 3082628799.5320206, 9453124863.59945, 9928066165.458393, 1135071669.4712334, 6380353457.986282, 8329064041.853199, 2382910730.445751, -8478491750.445316, 9607469190.690144, 5417691217.440792, -9698248424.421888, -3933774735.280322, -5984555343.381466] [-9698248424.421888, -9439606732.236805, -9423768405.578083, -8478491750.445316, -8415952427.784341, -6859960084.757652, -6529216482.09644, -6367787695.054295, -5984555343.381466, -5253703037.682413, -3933774735.280322, -3878285748.0708866, -1528465047.6118088, -888196668.2563229, -502409126.89040375, -373958476.80486107, 1135071669.4712334, 2382910730.445751, 2646164210.08445, 3082628799.5320206, 3280085607.6687145, 3858507441.2785892, 4407427446.995375, 5417691217.440792, 5986097626.907181, 6015943293.071386, 6079069259.51853, 6380353457.986282, 6813992306.719868, 7123644338.268343, 7584260716.494843, 7973918726.985172, 8329064041.853199, 8674121166.062424, 9011134545.052086, 9241165993.258648, 9453124863.59945, 9607469190.690144, 9896256282.896187, 9928066165.458393] '''<line_sep>
# Copyright 2018 BLEMUNDSBURY AI LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. <import_from_stmt>cape_webservices.app.app_settings URL_BASE<import_from_stmt>cape_webservices.app.app_settings app_saved_reply_endpoints<import_from_stmt>cape_webservices.app.app_middleware respond_with_json requires_auth<import_from_stmt>cape_document_manager.annotation_store AnnotationStore<import_from_stmt>cape_api_helpers.output list_response<import_from_stmt>cape_api_helpers.input required_parameter optional_parameter list_saved_reply_ids<line_sep>_endpoint_route=<lambda>x:app_saved_reply_endpoints.route(URL_BASE+x methods=['GET' 'POST'])<line_sep>@_endpoint_route('/saved-replies/get-saved-replies')@respond_with_json@list_response@list_saved_reply_ids@requires_auth<def_stmt>_get_saved_replies request number_of_items=30 offset=0 saved_reply_ids=<none><block_start>user_token=request['user'].token<line_sep>search_term=optional_parameter(request 'searchTerm' <none>)<line_sep>saved_replies=AnnotationStore.get_annotations(user_token annotation_ids=saved_reply_ids search_term=search_term saved_replies=<true>)<line_sep><return>{'totalItems':len(saved_replies) 'items':saved_replies[offset:offset+number_of_items]}<block_end>@_endpoint_route('/saved-replies/add-saved-reply')@respond_with_json@requires_auth<def_stmt>_create_saved_reply request<block_start>user_token=request['user'].token<line_sep>question=required_parameter(request 'question')<line_sep>answer=required_parameter(request 'answer')<line_sep>response=AnnotationStore.create_annotation(user_token question answer)<line_sep><return>{'replyId':response['annotationId'] 'answerId':response['answerId']}<block_end>@_endpoint_route('/saved-replies/delete-saved-reply')@respond_with_json@requires_auth<def_stmt>_delete_saved_reply request<block_start>user_token=request['user'].token<line_sep>reply_id=required_parameter(request 'replyId')<line_sep>AnnotationStore.delete_annotation(user_token reply_id)<line_sep><return>{'replyId':reply_id}<block_end>@_endpoint_route('/saved-replies/edit-canonical-question')@respond_with_json@requires_auth<def_stmt>_edit_canonical_question request<block_start>user_token=request['user'].token<line_sep>reply_id=required_parameter(request 'replyId')<line_sep>question=required_parameter(request 'question')<line_sep>AnnotationStore.edit_canonical_question(user_token reply_id question)<line_sep><return>{'replyId':reply_id}<block_end>@_endpoint_route('/saved-replies/add-paraphrase-question')@respond_with_json@requires_auth<def_stmt>_add_paraphrase_question request<block_start>user_token=request['user'].token<line_sep>reply_id=required_parameter(request 'replyId')<line_sep>question=required_parameter(request 'question')<line_sep><return>AnnotationStore.add_paraphrase_question(user_token reply_id question)<block_end>@_endpoint_route('/saved-replies/edit-paraphrase-question')@respond_with_json@requires_auth<def_stmt>_edit_paraphrase_question request<block_start>user_token=request['user'].token<line_sep>question_id=required_parameter(request 'questionId')<line_sep>question=required_parameter(request 'question')<line_sep><return>AnnotationStore.edit_paraphrase_question(user_token question_id question)<block_end>@_endpoint_route('/saved-replies/delete-paraphrase-question')@respond_with_json@requires_auth<def_stmt>_delete_paraphrase_question request<block_start>user_token=request['user'].token<line_sep>question_id=required_parameter(request 'questionId')<line_sep><return>AnnotationStore.delete_paraphrase_question(user_token question_id)<block_end>@_endpoint_route('/saved-replies/add-answer')@respond_with_json@requires_auth<def_stmt>_add_answer request<block_start>user_token=request['user'].token<line_sep>reply_id=required_parameter(request 'replyId')<line_sep>answer=required_parameter(request 'answer')<line_sep><return>AnnotationStore.add_answer(user_token reply_id answer)<block_end>@_endpoint_route('/saved-replies/edit-answer')@respond_with_json@requires_auth<def_stmt>_edit_answer request<block_start>user_token=request['user'].token<line_sep>answer_id=required_parameter(request 'answerId')<line_sep>answer=required_parameter(request 'answer')<line_sep><return>AnnotationStore.edit_answer(user_token answer_id answer)<block_end>@_endpoint_route('/saved-replies/delete-answer')@respond_with_json@requires_auth<def_stmt>_delete_answer request<block_start>user_token=request['user'].token<line_sep>answer_id=required_parameter(request 'answerId')<line_sep><return>AnnotationStore.delete_answer(user_token answer_id)<block_end><if_stmt>__name__<eq>'__main__'# import sanic.response # # # Create a fake request # request = { # "user": { # "token": "test_user_token", # }, # "args": { # "token": '<KEY>', # "question": 'What is a potato?', # "answer": 'A potato is a vegetable', # } # } # response: sanic.response.HTTPResponse = _create_saved_reply(request) # print(response.body) <block_start><pass><block_end>
# Generated by Django 2.2.1 on 2019-08-01 16:34 <import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[('dojo' '0012_jira_finding_age') ]<line_sep>operations=[migrations.AddField(model_name='jira_conf' name='info_mapping_severity' field=models.CharField(help_text="Maps to the 'Priority' field in Jira. For example: Info" max_length=200) ) migrations.AlterField(model_name='system_settings' name='jira_minimum_severity' field=models.CharField(blank=<true> choices=[('Critical' 'Critical') ('High' 'High') ('Medium' 'Medium') ('Low' 'Low') ('Info' 'Info')] default='None' max_length=20 null=<true>) ) ]<block_end>
""" This is to keep Chinese doc update to English doc. Should be run regularly. There is no sane way to check the contents though. PR review should enforce contributors to update the corresponding translation. See https://github.com/microsoft/nni/issues/4298 for discussion. Under docs, run python tools/chineselink.py """<import_stmt>hashlib<import_stmt>shutil<import_stmt>sys<import_from_stmt>pathlib Path<def_stmt>iterate_dir path<block_start><for_stmt>p Path(path).iterdir()<block_start><if_stmt>p.is_dir()<block_start><yield><from>iterate_dir(p)<line_sep><continue><block_end><yield>p<block_end><block_end>suffix_list=['.html' '.md' '.rst' '.ipynb' ]<line_sep>pipeline_mode=len(sys.argv)<g>1<and>sys.argv[1]<eq>'check'<line_sep>failed_files=[]<line_sep># in case I need to change `_zh` to something else # files = list(filter(lambda d: d.name.endswith('zh_CN.rst'), iterate_dir('source'))) # for file in files: # os.rename(file, file.parent / (file.name[:-7] + file.name[-4:])) <def_stmt>need_to_translate source target<block_start><if_stmt><not>target.exists()<block_start>failed_files.append('(missing) '+target.as_posix())<if_stmt>pipeline_mode<block_start><return><block_end>shutil.copyfile(source target)<block_end><if_stmt>target.suffix<eq>'.html'<block_start><return># FIXME I don't know how to process html <block_end>target_checksum=hashlib.sha256(path.open('rb').read()).hexdigest()[:32]<line_sep>checksum=target.open('r').readline().strip()[3:]<if_stmt>checksum<ne>target_checksum<block_start>failed_files.append('(out-of-date) '+target.as_posix())<if_stmt>pipeline_mode<block_start><return><block_end><block_end>contents=target.open('r').readlines()<line_sep>firstline='.. '+target_checksum+'\n'<if_stmt>contents[0].startswith('.. ')<block_start>contents=[firstline]+contents[1:]<block_end><else_stmt><block_start>contents=[firstline '\n']+contents<block_end>target.open('w').writelines(contents)<block_end><for_stmt>path iterate_dir(Path('source'))<block_start>relative_path=path.relative_to('source')<if_stmt>relative_path.as_posix().startswith('_build')<block_start><continue><block_end><if_stmt>path.suffix<in>suffix_list<block_start><if_stmt>'_zh.'<not><in>path.name<block_start>target_path=path.parent/(path.stem+'_zh'+path.suffix)<if_stmt>target_path.exists()# whitelist files. should be translated <block_start>need_to_translate(path target_path)<line_sep>print(f'Skipped linking for {path} as it is in whitelist.')<block_end><block_end><else_stmt><block_start>source_path=path.parent/(path.stem[:-3]+path.suffix)<if_stmt><not>source_path.exists()# delete redundant files <block_start>failed_files.append('(redundant) '+source_path.as_posix())<if_stmt><not>pipeline_mode<block_start>print(f'Deleting {source_path}')<line_sep>path.unlink()<block_end><block_end><block_end><block_end><block_end><if_stmt>pipeline_mode<and>failed_files<block_start><raise>ValueError('The following files are not up-to-date. Please run "python3 tools/chineselink.py" under docs folder '<concat>'to refresh them and update their corresponding translation.\n'+'\n'.join([' '+line<for>line failed_files]))<block_end><if_stmt>failed_files<block_start>print('Updated files:' failed_files)<block_end>
<import_stmt>cv2<import_stmt>numpy<as>np<line_sep>VIDEO_PATH='data.mkv'<line_sep>kernel=np.ones((2 2) np.uint8)<line_sep>cap=cv2.VideoCapture(VIDEO_PATH)<line_sep>data=[]<line_sep>count=1<line_sep>limit=0<while_stmt>(cap.isOpened())<block_start>ret,image_np=cap.read()<if_stmt>ret<eq><false><block_start><break><block_end><if_stmt>limit<eq>3<block_start>limit=0<line_sep>#image_np = 255 - image_np image_np=cv2.resize(image_np (208 120))<line_sep>#ret,image_np = cv2.threshold(image_np,127,255,cv2.THRESH_BINARY) bg_index=np.where(np.greater(image_np 20))<line_sep>image_np[bg_index]=255<line_sep>image_np=cv2.cvtColor(image_np cv2.COLOR_BGR2GRAY)<line_sep>#(T, thresh) = cv2.threshold(image_np, 0, 255, cv2.THRESH_BINARY) cv2.imwrite("imgs/{}.jpg".format(count) image_np)<line_sep>print("{}.jpg".format(count))<line_sep>count<augadd>1<block_end>limit<augadd>1<block_end>
""" Classes from the 'CoreFollowUp' framework. """<try_stmt><block_start><import_from_stmt>rubicon.objc ObjCClass<block_end><except_stmt>ValueError<block_start><def_stmt>ObjCClass name<block_start><return><none><block_end><block_end><def_stmt>_Class name<block_start><try_stmt><block_start><return>ObjCClass(name)<block_end><except_stmt>NameError<block_start><return><none><block_end><block_end>FLApprovedItemsFilter=_Class("FLApprovedItemsFilter")<line_sep>FLHSA2PasswordResetNotification=_Class("FLHSA2PasswordResetNotification")<line_sep>FLItemChangeObserver=_Class("FLItemChangeObserver")<line_sep>FLApprovedItemsDecorator=_Class("FLApprovedItemsDecorator")<line_sep>FLHSA2LoginNotification=_Class("FLHSA2LoginNotification")<line_sep>FLDaemon=_Class("FLDaemon")<line_sep>FLGroupViewModelImpl=_Class("FLGroupViewModelImpl")<line_sep>FLTopLevelViewModel=_Class("FLTopLevelViewModel")<line_sep>FLHeadlessExtensionLoader=_Class("FLHeadlessExtensionLoader")<line_sep>FLItemDetailViewModel=_Class("FLItemDetailViewModel")<line_sep>FLFollowUpAction=_Class("FLFollowUpAction")<line_sep>FLFollowUpNotification=_Class("FLFollowUpNotification")<line_sep>FLEnvironment=_Class("FLEnvironment")<line_sep>FLHeadlessActionHandler=_Class("FLHeadlessActionHandler")<line_sep>FLTelemetryAggregateController=_Class("FLTelemetryAggregateController")<line_sep>FLFollowUpController=_Class("FLFollowUpController")<line_sep>FLUtilities=_Class("FLUtilities")<line_sep>FLTelemetryFactory=_Class("FLTelemetryFactory")<line_sep>FLFollowUpItem=_Class("FLFollowUpItem")<line_sep>FLConstants=_Class("FLConstants")<line_sep>FLTelemetryProcessor=_Class("FLTelemetryProcessor")<line_sep>FLExtensionHostContext=_Class("FLExtensionHostContext")<line_sep>
# # Contributed by <NAME> <<EMAIL>> # # ICRAR - International Centre for Radio Astronomy Research # (c) UWA - The University of Western Australia, 2016 # Copyright by UWA (in the framework of the ICRAR) # ''' Wrapper for _yajl2 C extension module '''<import_from_stmt>ijson common compat utils<import_from_stmt>. _yajl2<line_sep>_get_buf_size=<lambda>kwargs:kwargs.pop('buf_size' 64<times>1024)<line_sep>@utils.coroutine<def_stmt>basic_parse_basecoro target **kwargs<block_start><return>_yajl2.basic_parse_basecoro(target.send **kwargs)<block_end><def_stmt>basic_parse_gen file **kwargs<block_start>f=compat.bytes_reader(file)<line_sep>buf_size=_get_buf_size(kwargs)<line_sep><return>_yajl2.basic_parse(f buf_size **kwargs)<block_end><def_stmt>basic_parse_async file **kwargs<block_start>buf_size=_get_buf_size(kwargs)<line_sep><return>_yajl2.basic_parse_async(file buf_size **kwargs)<block_end>@utils.coroutine<def_stmt>parse_basecoro target **kwargs<block_start><return>_yajl2.parse_basecoro(target.send **kwargs)<block_end><def_stmt>parse_gen file **kwargs<block_start>f=compat.bytes_reader(file)<line_sep>buf_size=_get_buf_size(kwargs)<line_sep><return>_yajl2.parse(f buf_size **kwargs)<block_end><def_stmt>parse_async file **kwargs<block_start>buf_size=_get_buf_size(kwargs)<line_sep><return>_yajl2.parse_async(file buf_size **kwargs)<block_end>@utils.coroutine<def_stmt>kvitems_basecoro target prefix map_type=<none> **kwargs<block_start><return>_yajl2.kvitems_basecoro(target.send prefix map_type **kwargs)<block_end><def_stmt>kvitems_gen file prefix map_type=<none> **kwargs<block_start>f=compat.bytes_reader(file)<line_sep>buf_size=_get_buf_size(kwargs)<line_sep><return>_yajl2.kvitems(f buf_size prefix map_type **kwargs)<block_end><def_stmt>kvitems_async file prefix map_type=<none> **kwargs<block_start>buf_size=_get_buf_size(kwargs)<line_sep><return>_yajl2.kvitems_async(file buf_size prefix map_type **kwargs)<block_end>@utils.coroutine<def_stmt>items_basecoro target prefix map_type=<none> **kwargs<block_start><return>_yajl2.items_basecoro(target.send prefix map_type **kwargs)<block_end><def_stmt>items_gen file prefix map_type=<none> **kwargs<block_start>f=compat.bytes_reader(file)<line_sep>buf_size=_get_buf_size(kwargs)<line_sep><return>_yajl2.items(f buf_size prefix map_type **kwargs)<block_end><def_stmt>items_async file prefix map_type=<none> **kwargs<block_start>buf_size=_get_buf_size(kwargs)<line_sep><return>_yajl2.items_async(file buf_size prefix map_type **kwargs)<block_end>common.enrich_backend(globals())<line_sep>
<import_from_stmt>trading_ig IGService<import_from_stmt>trading_ig.config config<import_stmt>logging<line_sep>logger=logging.getLogger(__name__)<line_sep>logger.setLevel(logging.DEBUG)<line_sep># if you need to cache to DB your requests <import_from_stmt>datetime timedelta<import_stmt>requests_cache<class_stmt>Initialisation()<block_start><def_stmt>__init__ self<block_start>logging.basicConfig(level=logging.INFO)<line_sep>self.counter=-1<line_sep>self.initialise_connection()<block_end><def_stmt>initialise_connection self<block_start>key=self.increment_api_key()<line_sep># expire_after = timedelta(hours=1) # session = requests_cache.CachedSession( # cache_name='cache', backend='sqlite', expire_after=expire_after # ) # set expire_after=None if you don't want cache expiration # set expire_after=0 if you don't want to cache queries # no cache ig_service=IGService(config.username config.password key config.acc_type)<line_sep># if you want to globally cache queries # ig_service = IGService(config.username, config.password, config.api_key, config.acc_type, session) <return>ig_service<block_end># make sure once the object is received to the place were it is needed you createSession() to initialise the session <def_stmt>increment_api_key self<block_start>key=""<while_stmt>(<true>)<block_start><try_stmt><block_start>self.counter<augadd>1<line_sep># has 12000 api keys fp=open("D:\Stock_Analysis\ig-markets-api-python-library-master\generate_api_keys\IG_api_keys_raw.txt")<for_stmt>i,line enumerate(fp)<block_start><if_stmt>i<eq>self.counter<block_start>key=line.split("\n")[0]<line_sep>fp.close()<line_sep><return>key<block_end><block_end><raise>Exception("file has surpassed the last api key")<block_end><except_stmt><block_start>fp.close()<line_sep>self.counter=-1<block_end><block_end><block_end><block_end>
x="Okay"<line_sep>y=len(x)<line_sep>
<import_stmt>logging<import_stmt>pytest<import_from_stmt>ocs_ci.framework.testlib ignore_leftovers E2ETest tier3 skipif_openshift_dedicated skipif_external_mode <import_from_stmt>ocs_ci.helpers.sanity_helpers Sanity<import_from_stmt>ocs_ci.ocs constants defaults<import_from_stmt>ocs_ci.ocs.constants DEFAULT_NOOBAA_BUCKETCLASS DEFAULT_NOOBAA_BACKINGSTORE<import_from_stmt>ocs_ci.ocs.ocp OCP<import_from_stmt>ocs_ci.ocs.resources.pod get_noobaa_pods<import_from_stmt>ocs_ci.ocs.resources.pvc get_pvc_objs<line_sep>logger=logging.getLogger(__name__)<line_sep>@tier3@ignore_leftovers@pytest.mark.polarion_id("OCS-2653")@pytest.mark.bugzilla("1991361")@pytest.mark.bugzilla("2019577")@skipif_openshift_dedicated@skipif_external_mode<class_stmt>TestNoobaaRebuild(E2ETest)<block_start>""" Test to verify noobaa rebuild. """<line_sep>@pytest.fixture(autouse=<true>)<def_stmt>init_sanity self<block_start>""" Initialize Sanity instance """<line_sep>self.sanity_helpers=Sanity()<block_end>@pytest.fixture(autouse=<true>)<def_stmt>teardown_fixture self request<block_start>""" Teardown function """<def_stmt>finalizer # Get the deployment replica count <block_start>deploy_obj=OCP(kind=constants.DEPLOYMENT namespace=constants.OPENSHIFT_STORAGE_NAMESPACE )<line_sep>noobaa_deploy_obj=deploy_obj.get(resource_name=constants.NOOBAA_OPERATOR_DEPLOYMENT)<if_stmt>noobaa_deploy_obj["spec"]["replicas"]<ne>1<block_start>logger.info(f"Scaling back {constants.NOOBAA_OPERATOR_DEPLOYMENT} deployment to replica: 1")<line_sep>deploy_obj.exec_oc_cmd(f"scale deployment {constants.NOOBAA_OPERATOR_DEPLOYMENT} --replicas=1")<block_end><block_end>request.addfinalizer(finalizer)<block_end><def_stmt>test_noobaa_rebuild self bucket_factory<block_start>""" Test case to verify noobaa rebuild. Verifies KCS: https://access.redhat.com/solutions/5948631 1. Stop the noobaa-operator by setting the replicas of noobaa-operator deployment to 0. 2. Delete the noobaa deployments/statefulsets. 3. Delete the PVC db-noobaa-db-0. 4. Patch existing backingstores and bucketclasses to remove finalizer 5. Delete the backingstores/bucketclass. 6. Delete the noobaa secrets. 7. Restart noobaa-operator by setting the replicas back to 1. 8. Monitor the pods in openshift-storage for noobaa pods to be Running. """<line_sep>dep_ocp=OCP(kind=constants.DEPLOYMENT namespace=constants.OPENSHIFT_STORAGE_NAMESPACE)<line_sep>state_ocp=OCP(kind=constants.STATEFULSET namespace=constants.OPENSHIFT_STORAGE_NAMESPACE)<line_sep>noobaa_pvc_obj=get_pvc_objs(pvc_names=["db-noobaa-db-pg-0"])<line_sep># Scale down noobaa operator logger.info(f"Scaling down {constants.NOOBAA_OPERATOR_DEPLOYMENT} deployment to replica: 0")<line_sep>dep_ocp.exec_oc_cmd(f"scale deployment {constants.NOOBAA_OPERATOR_DEPLOYMENT} --replicas=0")<line_sep># Delete noobaa deployments and statefulsets logger.info("Deleting noobaa deployments and statefulsets")<line_sep>dep_ocp.delete(resource_name=constants.NOOBAA_ENDPOINT_DEPLOYMENT)<line_sep>state_ocp.delete(resource_name=constants.NOOBAA_DB_STATEFULSET)<line_sep>state_ocp.delete(resource_name=constants.NOOBAA_CORE_STATEFULSET)<line_sep># Delete noobaa-db pvc pvc_obj=OCP(kind=constants.PVC namespace=constants.OPENSHIFT_STORAGE_NAMESPACE)<line_sep>logger.info("Deleting noobaa-db pvc")<line_sep>pvc_obj.delete(resource_name=noobaa_pvc_obj[0].name wait=<true>)<line_sep>pvc_obj.wait_for_delete(resource_name=noobaa_pvc_obj[0].name timeout=300)<line_sep># Patch and delete existing backingstores params='{"metadata": {"finalizers":null}}'<line_sep>bs_obj=OCP(kind=constants.BACKINGSTORE namespace=constants.OPENSHIFT_STORAGE_NAMESPACE)<for_stmt>bs bs_obj.get()["items"]<block_start><assert_stmt>bs_obj.patch(resource_name=bs["metadata"]["name"] params=params format_type="merge" ) "Failed to change the parameter in backingstore"<line_sep>logger.info(f"Deleting backingstore: {bs['metadata']['name']}")<line_sep>bs_obj.delete(resource_name=bs["metadata"]["name"])<block_end># Patch and delete existing bucketclass bc_obj=OCP(kind=constants.BUCKETCLASS namespace=constants.OPENSHIFT_STORAGE_NAMESPACE)<for_stmt>bc bc_obj.get()["items"]<block_start><assert_stmt>bc_obj.patch(resource_name=bc["metadata"]["name"] params=params format_type="merge" ) "Failed to change the parameter in bucketclass"<line_sep>logger.info(f"Deleting bucketclass: {bc['metadata']['name']}")<line_sep>bc_obj.delete(resource_name=bc["metadata"]["name"])<block_end># Delete noobaa secrets logger.info("Deleting noobaa related secrets")<line_sep>dep_ocp.exec_oc_cmd("delete secrets noobaa-admin noobaa-endpoints noobaa-operator noobaa-server noobaa-root-master-key")<line_sep># Scale back noobaa-operator deployment logger.info(f"Scaling back {constants.NOOBAA_OPERATOR_DEPLOYMENT} deployment to replica: 1")<line_sep>dep_ocp.exec_oc_cmd(f"scale deployment {constants.NOOBAA_OPERATOR_DEPLOYMENT} --replicas=1")<line_sep># Wait and validate noobaa PVC is in bound state pvc_obj.wait_for_resource(condition=constants.STATUS_BOUND resource_name=noobaa_pvc_obj[0].name timeout=600 sleep=120 )<line_sep># Validate noobaa pods are up and running pod_obj=OCP(kind=constants.POD namespace=defaults.ROOK_CLUSTER_NAMESPACE)<line_sep>noobaa_pods=get_noobaa_pods()<line_sep>pod_obj.wait_for_resource(condition=constants.STATUS_RUNNING resource_count=len(noobaa_pods) selector=constants.NOOBAA_APP_LABEL timeout=900 )<line_sep># Verify everything running fine logger.info("Verifying all resources are Running and matches expected result")<line_sep>self.sanity_helpers.health_check(tries=120)<line_sep># Verify default backingstore/bucketclass default_bs=OCP(kind=constants.BACKINGSTORE namespace=constants.OPENSHIFT_STORAGE_NAMESPACE).get(resource_name=DEFAULT_NOOBAA_BACKINGSTORE)<line_sep>default_bc=OCP(kind=constants.BUCKETCLASS namespace=constants.OPENSHIFT_STORAGE_NAMESPACE).get(resource_name=DEFAULT_NOOBAA_BUCKETCLASS)<assert_stmt>(default_bs["status"]["phase"]<eq>default_bc["status"]["phase"]<eq>constants.STATUS_READY) "Failed: Default bs/bc are not in ready state"<line_sep># Create OBCs logger.info("Creating OBCs after noobaa rebuild")<line_sep>bucket_factory(amount=3 interface="OC" verify_health=<true>)<block_end><block_end>
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ Pytest-based testing ==================== This file performs automated tests with pytest. It does not generate charts or output to be reviewed. Run with: pytest-3 tests/test_new.py Run with: pytest-3 tests/test_new.py -s -vv --cov=ahrs for coverage + verbose Copyright 2021 <NAME> and <NAME> <<EMAIL>> Released under MIT License Formatted with Black References ---------- .. [Crassidis] <NAME> (2007) A Survey of Nonlinear Attitude Estimation Methods. .. [Teage] <NAME> (2016) Comparison of Attitude Estimation Techniques for Low-cost Unmanned Aerial Vehicles. https://arxiv.org/pdf/1602.07733.pdf http://ancs.eng.buffalo.edu/pdf/ancs_papers/2007/att_survey07.pdf .. [Cirillo] <NAME> et al. (2016) A comparison of multisensor attitude estimation algorithms. https://www.researchgate.net/profile/Pasquale_Cirillo/publication/303738116_A_comparison_of_multisensor_attitude_estimation_algorithms/links/5750181208aeb753e7b4a0c0/A-comparison-of-multisensor-attitude-estimation-algorithms.pdf """<import_stmt>numpy<as>np<import_stmt>pytest<import_stmt>scipy.io<as>sio<import_stmt>ahrs<import_stmt>ahrs.utils.io<line_sep>DEG2RAD=ahrs.common.DEG2RAD<class_stmt>Data<block_start>acc=<none><line_sep>gyr=<none><line_sep>mag=<none><block_end>@pytest.fixture()<def_stmt>data <block_start>fn="tests/ExampleData.mat"<line_sep>mat=sio.loadmat(fn)<line_sep>d=Data()<line_sep>d.acc=mat["Accelerometer"]<line_sep>d.gyr=mat["Gyroscope"]<line_sep>d.mag=mat["Magnetometer"]<line_sep>d.num_samples=len(d.acc)<assert_stmt>d.num_samples<assert_stmt>len(d.acc[0])<eq>3<assert_stmt>len(d.gyr[0])<eq>3<assert_stmt>len(d.mag[0])<eq>3<line_sep><return>d<block_end><def_stmt>check_integrity Q<block_start><assert_stmt>Q<is><not><none><line_sep>sz=Q.shape<line_sep>qts_ok=<not>np.allclose(np.sum(Q axis=0) sz[0]<times>np.array([1.0 0.0 0.0 0.0]))<line_sep>qnm_ok=np.allclose(np.linalg.norm(Q axis=1).mean() 1.0)<assert_stmt>qts_ok<and>qnm_ok<block_end>@pytest.fixture()<def_stmt>Q data<block_start>q=np.zeros((data.num_samples 4))<line_sep>q[: 0]=1.0<line_sep><return>q<block_end><def_stmt>test_fourati data Q<block_start>fourati=ahrs.filters.Fourati()<for_stmt>t range(1 data.num_samples)<block_start>Q[t]=fourati.update(Q[t-1] DEG2RAD<times>data.gyr[t] data.acc[t] data.mag[t])<block_end># check_integrity(Q) <assert_stmt>tuple(Q[0])<eq>(0.9999984512506995 -7.923098356158542e-05 -0.00010998618261451432 7.783371117384885e-05 )<assert_stmt>tuple(Q[-1])<eq>(0.8321632262796078 0.17064875423856807 -0.27862737470349475 0.44805150772046 )<block_end><def_stmt>test_ekf data Q<block_start>ekf=ahrs.filters.EKF()<for_stmt>t range(1 data.num_samples)<block_start>Q[t]=ekf.update(Q[t-1] DEG2RAD<times>data.gyr[t] data.acc[t] data.mag[t])<block_end>check_integrity(Q)<assert_stmt>tuple(Q[0])<eq>(1.0 0.0 0.0 0.0)<assert_stmt>tuple(Q[1])<eq>(0.9948152433072915 0.030997430898554206 -0.09666743395232329 0.006099030596487108 )<assert_stmt>tuple(Q[-1])<eq>(0.08996443890695231 0.23991941374716044 -0.958073763949303 -0.1282175396402196 )<block_end><def_stmt>test_mahony data Q<block_start>mahony=ahrs.filters.Mahony()<for_stmt>t range(1 data.num_samples)<block_start>Q[t]=mahony.updateMARG(Q[t-1] DEG2RAD<times>data.gyr[t] data.acc[t] data.mag[t])<block_end>check_integrity(Q)<assert_stmt>tuple(Q[0])<eq>(0.9999883099133865 -0.0007983637760660701 0.004762298093153807 0.00025133388483027455 )<assert_stmt>tuple(Q[-1])<eq>(-0.10375763267292282 -0.007875376758085736 -0.05233084545763538 0.9931937448034588 )<block_end><def_stmt>test_madgwick data Q<block_start>madgwick=ahrs.filters.Madgwick()<for_stmt>t range(1 data.num_samples)<block_start>Q[t]=madgwick.updateMARG(Q[t-1] DEG2RAD<times>data.gyr[t] data.acc[t] data.mag[t])<block_end>check_integrity(Q)<assert_stmt>tuple(Q[0])<eq>(0.999999906169997 -0.00039564882735884275 -0.00017641407301677547 -2.78332338967451e-07 )<assert_stmt>tuple(Q[-1])<eq>(0.9524138044137933 -0.10311931931141746 0.0038985200624795592 0.28680856453062387 )<block_end><def_stmt>test_distance <block_start>a=np.random.random((2 3))<line_sep>d=ahrs.utils.metrics.euclidean(a[0] a[1])<assert_stmt>np.allclose(d np.linalg.norm(a[0]-a[1]))<block_end>
<import_from_stmt>.session Session<import_from_stmt>.datamodel DataModel NonStrictDataModel schema_property StringEnum<import_from_stmt>.request Request BatchRequest CompoundRequest<import_from_stmt>.response Response<import_from_stmt>.token_manager TokenManager<import_from_stmt>.errors TimeoutExpiredError ResultNotReadyError<import_from_stmt>.callresult CallResult<line_sep>
<import_stmt>random<import_stmt>numpy<as>np<import_stmt>torch<import_stmt>torch.nn<as>nn<import_stmt>torch.nn.functional<as>F<import_from_stmt>graph4nlp.pytorch.modules.utils.tree_utils Tree to_cuda<import_from_stmt>.attention Attention<import_from_stmt>.base RNNTreeDecoderBase<class_stmt>StdTreeDecoder(RNNTreeDecoderBase)<block_start>r"""StdTreeDecoder: This is a tree decoder implementation, which is used for tree object decoding. Attributes ---------- attn_type : str, Describe which attention mechanism is used, can be ``uniform``, ``separate_on_encoder_type``, ``separate_on_node_type``. embeddings : torch.nn.Module, Embedding layer, input is tensor of word index, output is word embedding tensor. enc_hidden_size : int, Size of encoder hidden state. dec_emb_size : int, Size of decoder word embedding layer output size. dec_hidden_size : int, Size of decoder hidden state. (namely the ``lstm`` or ``gru`` hidden size when rnn unit has been specified) output_size : int, Size of output vocabulary size. teacher_force_ratio : float, The ratio of possibility to use teacher force training. use_sibling : boolean, Whether feed sibling state in each decoding step. use_copy : boolean, Whether use copy mechanism in decoding. fuse_strategy: str, option=[None, "average", "concatenate"], default=None The strategy to fuse attention results generated by separate attention. "None": If we do ``uniform`` attention, we will set it to None. "``average``": We will take an average on all results. "``concatenate``": We will concatenate all results to one. num_layers : int, optional, Layer number of decoder rnn unit. dropout_for_decoder: float, Dropout ratio for decoder(include both the dropout for word embedding and the dropout for attention layer) tgt_vocab : object, The vocab object used in decoder, including all the word<->id pairs appeared in the output sentences. graph_pooling_strategy : str, The graph pooling strategy used to generate the graph embedding with node embeddings rnn_type: str, optional, The rnn unit is used, option=["lstm", "gru"], default="lstm". max_dec_seq_length : int, optional, In decoding, the decoding steps upper limit. max_dec_tree_depth : int, optional, In decoding, the tree depth lower limit. """<def_stmt>__init__ self attn_type embeddings enc_hidden_size dec_emb_size dec_hidden_size output_size criterion teacher_force_ratio use_sibling=<true> use_attention=<true> use_copy=<false> fuse_strategy="average" num_layers=1 dropout_for_decoder=0.1 rnn_type="lstm" max_dec_seq_length=512 max_dec_tree_depth=256 tgt_vocab=<none> graph_pooling_strategy="max" <block_start>super(StdTreeDecoder self).__init__(use_attention=<true> use_copy=use_copy use_coverage=<false> attention_type="uniform" fuse_strategy="average" )<line_sep>self.num_layers=num_layers<line_sep>self.criterion=criterion<line_sep>self.rnn_size=dec_hidden_size<line_sep>self.enc_hidden_size=enc_hidden_size<line_sep>self.hidden_size=dec_hidden_size<line_sep>self.max_dec_seq_length=max_dec_seq_length<line_sep>self.max_dec_tree_depth=max_dec_tree_depth<line_sep>self.tgt_vocab=tgt_vocab<line_sep>self.teacher_force_ratio=teacher_force_ratio<line_sep>self.use_sibling=use_sibling<line_sep>self.dec_emb_size=dec_emb_size<line_sep>self.dropout_input=dropout_for_decoder<line_sep>self.embeddings=embeddings<line_sep>self.graph_pooling_strategy=graph_pooling_strategy<line_sep>self.attn_state={}<line_sep>self.use_copy=use_copy<line_sep>self.attention=Attention(query_size=dec_hidden_size memory_size=enc_hidden_size<times>2<if>(enc_hidden_size<times>2<eq>dec_hidden_size)<else>enc_hidden_size hidden_size=dec_hidden_size has_bias=<true> dropout=dropout_for_decoder attention_funtion="dot" )<line_sep>self.separate_attn=attn_type<ne>"uniform"<if_stmt>self.separate_attn<block_start>self.linear_att=nn.Linear(3<times>dec_hidden_size dec_hidden_size)<block_end><else_stmt><block_start>self.linear_att=nn.Linear(2<times>dec_hidden_size dec_hidden_size)<block_end>self.linear_out=nn.Linear(dec_hidden_size output_size)<line_sep>self.dropout_attn=nn.Dropout(dropout_for_decoder)<line_sep>self.logsoftmax=nn.LogSoftmax(dim=1)<if_stmt>self.use_copy<block_start>ptr_size=self.embeddings.embedding_dim<line_sep>ptr_size<augadd>4<times>self.rnn_size<line_sep>self.ptr=nn.Linear(ptr_size 1)<block_end>self.rnn=self._build_rnn(rnn_type=rnn_type input_size=output_size emb_size=dec_emb_size hidden_size=dec_hidden_size dropout_input=dropout_for_decoder use_sibling=use_sibling )<block_end><def_stmt>_run_forward_pass self graph_node_embedding graph_node_mask rnn_node_embedding graph_level_embedding graph_edge_embedding=<none> graph_edge_mask=<none> tgt_tree_batch=<none> enc_batch=<none> oov_dict=<none> <block_start>r""" The private calculation method for decoder. Parameters ---------- enc_batch : torch.Tensor, The input batch : (Batch_size * Source sentence word index tensor). tgt_tree_batch: The target tree to generate : consists of (Batch_size * Tree object), each node in a Tree object is either a word index or a children Tree object. graph_node_embedding: torch.Tensor, The graph node embedding matrix of shape :math:`(B, N, D_{in})` graph_node_mask: torch.Tensor, The graph node type mask matrix of shape :math`(B, N)` rnn_node_embedding: torch.Tensor, The rnn encoded embedding matrix of shape :math`(B, N, D_{in})` graph_level_embedding: torch.Tensor, graph level embedding of shape :math`(B, D_{in})` graph_edge_embedding: torch.Tensor, graph edge embedding of shape :math`(B, N, D_{in})` graph_edge_mask: torch.Tensor, graph edge type embedding oov_dict: dict, vocab dict used in copy mechanism to incorporate some new words which have never appeared in vocab for input sentences in training set. """<line_sep>tgt_batch_size=len(tgt_tree_batch)<line_sep>enc_outputs=graph_node_embedding<line_sep>device=graph_node_embedding.device<if_stmt>graph_level_embedding<is><none><block_start><if_stmt>self.graph_pooling_strategy<eq>"max"<block_start>graph_level_embedding=torch.max(graph_node_embedding 1)[0]<block_end><elif_stmt>self.graph_pooling_strategy<eq>"min"<block_start>graph_level_embedding=torch.min(graph_node_embedding 1)[0]<block_end><elif_stmt>self.graph_pooling_strategy<eq>"mean"<block_start>graph_level_embedding=torch.mean(graph_node_embedding 1)<block_end><else_stmt><block_start><raise>NotImplementedError()<block_end>graph_cell_state=graph_level_embedding<line_sep>graph_hidden_state=graph_level_embedding<block_end><else_stmt><block_start>graph_cell_state,graph_hidden_state=graph_level_embedding<block_end># rnn_node_embedding = torch.zeros_like(graph_node_embedding, # requires_grad=False).to(device) cur_index=1<line_sep>loss=0<line_sep>dec_batch,queue_tree,max_index=get_dec_batch(tgt_tree_batch tgt_batch_size device self.tgt_vocab)<line_sep>dec_state={}<for_stmt>i range(self.max_dec_tree_depth+1)<block_start>dec_state[i]={}<for_stmt>j range(self.max_dec_seq_length+1)<block_start>dec_state[i][j]={}<block_end><block_end><while_stmt>cur_index<le>max_index<block_start><if_stmt>cur_index<g>self.max_dec_tree_depth<block_start><break><block_end><for_stmt>j range(1 3)<block_start>dec_state[cur_index][0][j]=torch.zeros((tgt_batch_size self.rnn_size) dtype=torch.float requires_grad=<false>).to(device)<block_end>sibling_state=torch.zeros((tgt_batch_size self.rnn_size) dtype=torch.float requires_grad=<false>).to(device)<line_sep># with torch.no_grad(): <if_stmt>cur_index<eq>1<block_start><for_stmt>i range(tgt_batch_size)<block_start>dec_state[1][0][1][i :]=graph_cell_state[i]<line_sep>dec_state[1][0][2][i :]=graph_hidden_state[i]<block_end><block_end><else_stmt><block_start><for_stmt>i range(1 tgt_batch_size+1)<block_start><if_stmt>cur_index<le>len(queue_tree[i])<block_start>par_index=queue_tree[i][cur_index-1]["parent"]<line_sep>child_index=queue_tree[i][cur_index-1]["child_index"]<line_sep>dec_state[cur_index][0][1][i-1 :]=dec_state[par_index][child_index][1][i-1 :]<line_sep>dec_state[cur_index][0][2][i-1 :]=dec_state[par_index][child_index][2][i-1 :]<block_end>flag_sibling=<false><for_stmt>q_index range(len(queue_tree[i]))<block_start><if_stmt>((cur_index<le>len(queue_tree[i]))<and>(q_index<l>cur_index-1)<and>(queue_tree[i][q_index]["parent"]<eq>queue_tree[i][cur_index-1]["parent"])<and>(queue_tree[i][q_index]["child_index"]<l>queue_tree[i][cur_index-1]["child_index"]))<block_start>flag_sibling=<true><line_sep>sibling_index=q_index<block_end><block_end><if_stmt>flag_sibling<block_start>sibling_state[i-1 :]=dec_state[sibling_index][dec_batch[sibling_index].size(1)-1][2][i-1 :]<block_end><block_end><block_end>parent_h=dec_state[cur_index][0][2]<line_sep>pred=<none><for_stmt>i range(dec_batch[cur_index].size(1)-1)<block_start>teacher_force=random.random()<l>self.teacher_force_ratio<if_stmt>teacher_force<is><not><true><and>i<g>0<block_start>input_word=pred.argmax(1)<block_end><else_stmt><block_start>input_word=dec_batch[cur_index][: i]<block_end>pred,rnn_state_iter,attn_scores=self.decode_step(tgt_batch_size=tgt_batch_size dec_single_input=input_word dec_single_state=(dec_state[cur_index][i][1] dec_state[cur_index][i][2]) memory=enc_outputs parent_state=parent_h oov_dict=oov_dict enc_batch=enc_batch )<line_sep>dec_state[cur_index][i+1][1],dec_state[cur_index][i+1][2]=rnn_state_iter<line_sep>pred=torch.log(pred+1e-31)<line_sep>loss<augadd>self.criterion(pred dec_batch[cur_index][: i+1])<block_end>cur_index=cur_index+1<block_end>loss=loss/tgt_batch_size<line_sep><return>loss<block_end><def_stmt>_filter_oov self tokens vocab<block_start>r"""The function used to mask some oov word in word embedding layer."""<line_sep>ret=tokens.clone()<line_sep>ret[tokens<ge>vocab.vocab_size]=vocab.get_symbol_idx(vocab.unk_token)<line_sep><return>ret<block_end><def_stmt>decode_step self tgt_batch_size dec_single_input dec_single_state memory parent_state input_mask=<none> memory_mask=<none> memory_candidate=<none> sibling_state=<none> oov_dict=<none> enc_batch=<none> <block_start>"""The decoding function in tree decoder. Parameters ---------- tgt_batch_size : int, batch size. dec_single_input : torch.Tensor, word id matrix for decoder input: [B, N]. dec_single_state : torch.Tensor the rnn decoding hidden state: [B, N, D]. memory : torch.Tensor the encoder output node embedding. parent_state : torch.Tensor the parent embedding used in parent feeding mechanism. input_mask : torch.Tensor, optional input mask, by default None memory_mask : torch.Tensor, optional mask for encoder output, by default None memory_candidate : torch.Tensor, optional encoder output used for separate attention mechanism, by default None sibling_state : torch.Tensor, optional sibling state for sibling feeding mechanism, by default None oov_dict : object, optional out-of-vocabulary object for copy mechanism, by default None enc_batch : torch.Tensor, The input batch : (Batch_size * Source sentence word index tensor). """<line_sep>device=memory.device<line_sep>dec_single_input=self._filter_oov(dec_single_input self.tgt_vocab)<line_sep>rnn_state_c,rnn_state_h,dec_emb=self.rnn(dec_single_input dec_single_state[0] dec_single_state[1] parent_state sibling_state)<line_sep>attn_collect=[]<line_sep>score_collect=[]<if_stmt>self.separate_attn<block_start><pass><block_end><else_stmt><block_start>context_vector,attn_scores=self.attention(query=rnn_state_h memory=memory)<line_sep>attn_collect.append(context_vector)<line_sep>score_collect.append(attn_scores)<block_end>pred=F.tanh(self.linear_att(torch.cat((context_vector rnn_state_h) 1)))<line_sep>decoder_output=self.linear_out(self.dropout_attn(pred))<if_stmt>self.use_copy<block_start><assert_stmt>enc_batch<is><not><none><assert_stmt>oov_dict<is><not><none><line_sep>output=torch.zeros(tgt_batch_size oov_dict.vocab_size).to(device)<line_sep>attn_ptr=torch.cat(attn_collect dim=-1)<line_sep>pgen_collect=[dec_emb torch.cat((rnn_state_c rnn_state_h) -1) attn_ptr]<line_sep>prob_ptr=torch.sigmoid(self.ptr(torch.cat(pgen_collect -1)))<line_sep>prob_gen=1-prob_ptr<line_sep>gen_output=torch.softmax(decoder_output dim=-1)<line_sep>ret=prob_gen<times>gen_output<line_sep>need_pad_length=len(oov_dict)-len(self.tgt_vocab)<line_sep>output=torch.cat((ret ret.new_zeros((tgt_batch_size need_pad_length))) dim=1)<line_sep># output[:, :self.tgt_vocab.vocab_size] = ret ptr_output=attn_scores<line_sep>output.scatter_add_(1 enc_batch prob_ptr<times>ptr_output)<line_sep>decoder_output=output<line_sep># decoder_output = -F.threshold(-output, -1.0, -1.0) <block_end><else_stmt><block_start>decoder_output=torch.softmax(decoder_output dim=-1)<block_end><return>decoder_output (rnn_state_c rnn_state_h) attn_scores<block_end><def_stmt>_build_rnn self rnn_type input_size emb_size hidden_size dropout_input use_sibling<block_start>"""_build_rnn : how the rnn unit should be build."""<line_sep>rnn=TreeDecodingUnit(input_size emb_size hidden_size dropout_input use_sibling self.embeddings)<line_sep><return>rnn<block_end><def_stmt>forward self g tgt_tree_batch=<none> oov_dict=<none><block_start>params=self._extract_params(g)<line_sep>params["tgt_tree_batch"]=tgt_tree_batch<line_sep>params["oov_dict"]=oov_dict<line_sep><return>self._run_forward_pass(**params)<block_end><def_stmt>_extract_params self graph_list<block_start>""" Parameters ---------- g: GraphData Returns ------- params: dict """<line_sep>batch_data_dict=graph_list.batch_node_features<line_sep>graph_node_emb=batch_data_dict["node_emb"]<line_sep># [s_g.node_features["node_emb"] for s_g in graph_list] rnn_node_emb=batch_data_dict["rnn_emb"]<line_sep>graph_node_mask=(batch_data_dict["token_id"]<ne>0).squeeze(-1).float()-1<if_stmt>self.use_copy<block_start>src_seq_ret=graph_list.batch_node_features["token_id_oov"]<block_end><else_stmt><block_start>src_seq_ret=<none><block_end><return>{"graph_node_embedding":graph_node_emb "graph_node_mask":graph_node_mask "rnn_node_embedding":rnn_node_emb "graph_level_embedding":<none> "graph_edge_embedding":<none> "graph_edge_mask":<none> "enc_batch":src_seq_ret.long()<if>self.use_copy<else><none> }<block_end><block_end><def_stmt>create_mask x N device=<none><block_start>x=x.data<line_sep>mask=np.zeros((x.size(0) N))<for_stmt>i range(x.size(0))<block_start>mask[i :x[i]]=1<block_end><return>torch.Tensor(mask).to(device)<block_end><class_stmt>TreeDecodingUnit(nn.Module)<block_start><def_stmt>__init__ self input_size emb_size hidden_size dropout_input use_sibling dec_embeddings<block_start>super(TreeDecodingUnit self).__init__()<line_sep>self.hidden_size=hidden_size<line_sep>self.emb_size=emb_size<line_sep>self.embedding=dec_embeddings<line_sep>self.dropout=nn.Dropout(dropout_input)<line_sep>self.lstm=nn.LSTMCell(emb_size+hidden_size<times>(2<if>use_sibling<else>1) hidden_size)<line_sep>self.use_sibling=use_sibling<block_end><def_stmt>forward self input_src prev_c prev_h parent_h sibling_state<block_start>src_emb=self.embedding(input_src)<line_sep>src_emb=self.dropout(src_emb)<if_stmt>self.use_sibling<block_start>input_single_step=torch.cat((src_emb parent_h sibling_state) 1)<block_end><else_stmt><block_start>input_single_step=torch.cat((src_emb parent_h) 1)<block_end>prev_cy,prev_hy=self.lstm(input_single_step (prev_c prev_h))<line_sep><return>prev_cy prev_hy input_single_step<block_end><block_end><def_stmt>get_dec_batch dec_tree_batch batch_size device form_manager<block_start>queue_tree={}<for_stmt>i range(1 batch_size+1)<block_start>queue_tree[i]=[]<line_sep>queue_tree[i].append({"tree":dec_tree_batch[i-1] "parent":0 "child_index":1})<block_end>cur_index,max_index=1 1<line_sep>dec_batch={}<line_sep># max_index: the max number of sequence decoder in one batch <while_stmt>cur_index<le>max_index<block_start>max_w_len=-1<line_sep>batch_w_list=[]<for_stmt>i range(1 batch_size+1)<block_start>w_list=[]<if_stmt>cur_index<le>len(queue_tree[i])<block_start>t=queue_tree[i][cur_index-1]["tree"]<for_stmt>ic range(t.num_children)<block_start><if_stmt>isinstance(t.children[ic] Tree)<block_start>w_list.append(4)<line_sep>queue_tree[i].append({"tree":t.children[ic] "parent":cur_index "child_index":ic+1})<block_end><else_stmt><block_start>w_list.append(t.children[ic])<block_end><block_end><if_stmt>len(queue_tree[i])<g>max_index<block_start>max_index=len(queue_tree[i])<block_end><block_end><if_stmt>len(w_list)<g>max_w_len<block_start>max_w_len=len(w_list)<block_end>batch_w_list.append(w_list)<block_end>dec_batch[cur_index]=torch.zeros((batch_size max_w_len+2) dtype=torch.long)<for_stmt>i range(batch_size)<block_start>w_list=batch_w_list[i]<if_stmt>len(w_list)<g>0<block_start><for_stmt>j range(len(w_list))<block_start>dec_batch[cur_index][i][j+1]=w_list[j]<block_end># add <S>, <E> <if_stmt>cur_index<eq>1<block_start>dec_batch[cur_index][i][0]=1<block_end><else_stmt><block_start>dec_batch[cur_index][i][0]=form_manager.get_symbol_idx("(")<block_end>dec_batch[cur_index][i][len(w_list)+1]=2<block_end><block_end>dec_batch[cur_index]=to_cuda(dec_batch[cur_index] device)<line_sep>cur_index<augadd>1<block_end><return>dec_batch queue_tree max_index<block_end>
<import_from_future_stmt> unicode_literals<import_from_stmt>django.utils.translation ugettext_lazy<as>_<import_from_stmt>rest_framework.exceptions ValidationError<class_stmt>EqualityValidator(object)<block_start>message=_('The fields {field_names} must be equal.')<line_sep>missing_message=_('This field is required.')<def_stmt>__init__ self fields message=<none><block_start>self.fields=fields<line_sep>self.serializer_field=<none><line_sep>self.message=message<or>self.message<line_sep>self.instance=<none><line_sep>self.initial_data=<none><line_sep>self.validate_non_fields=<false><block_end><def_stmt>set_context self serializer<block_start>""" This hook is called by the serializer instance, prior to the validation call being made. """<line_sep>self.instance=getattr(serializer 'instance' <none>)<line_sep>self.initial_data=getattr(serializer 'initial_data' <none>)<line_sep>self.validate_non_fields=getattr(serializer 'validate_non_fields' <false>)<block_end><def_stmt>__call__ self *args **kwargs<block_start><if_stmt>self.validate_non_fields<block_start><if_stmt>self.fields[0]<not><in>self.initial_data<or>self.fields[1]<not><in>self.initial_data<block_start><raise>ValidationError("Both fields are required.")<block_end><if_stmt>self.initial_data.get(self.fields[0] 'Password1')<ne>self.initial_data.get(self.fields[1] 'Password2')<block_start>field_names=', '.join(self.fields)<line_sep><raise>ValidationError(self.message.format(field_names=field_names))<block_end><block_end><block_end><block_end><class_stmt>LengthValidator(object)<block_start>message=_('Field {field_name} must be at least {length} characters long.')<line_sep>missing_message=_('Field {field_name} is required.')<def_stmt>__init__ self field length message=<none><block_start>self.field=field<line_sep>self.length=length<line_sep>self.serializer_field=<none><line_sep>self.message=message<or>self.message<line_sep>self.initial_data=<none><line_sep>self.validate_non_fields=<false><block_end><def_stmt>set_context self serializer<block_start>self.initial_data=getattr(serializer 'initial_data' <none>)<line_sep>self.validate_non_fields=getattr(serializer 'validate_non_fields' <false>)<block_end><def_stmt>__call__ self *args **kwargs<block_start><if_stmt>self.validate_non_fields<block_start><if_stmt>self.field<not><in>self.initial_data<block_start><raise>ValidationError(self.missing_message.format(field_name=self.field))<block_end><if_stmt>len(self.initial_data[self.field])<l>self.length<block_start><raise>ValidationError(self.message.format(field_name=self.field length=self.length))<block_end><block_end><block_end><block_end><class_stmt>InequalityValidator(object)<block_start>message=_('Field {field_name} must be {field_operator} than {field_value}.')<def_stmt>__init__ self field value operator message=<none><block_start>self.field=field<line_sep>self.value=value<line_sep>self.operator='gt'<line_sep>self.message=message<or>self.message<line_sep>self.initial_data=<none><block_end><def_stmt>set_context self serializer<block_start>self.initial_data=getattr(serializer 'initial_data' <none>)<block_end><def_stmt>__call__ self *args **kwargs<block_start><if_stmt>self.initial_data[self.field]<ge>self.value<and>self.operator<eq>'lt'<block_start><raise>ValidationError(self.message.format(field_name=self.field field_operator='less' field_value=self.value))<block_end><elif_stmt>self.initial_data[self.field]<le>self.value<and>self.operator<eq>'gt'<block_start><raise>ValidationError(self.message.format(field_name=self.field field_operator='greater' field_value=self.value))<block_end><block_end><block_end><class_stmt>ConditionallyRequiredValidator(object)<block_start>message=_('Field {field2_name} is required because {field_name} is {type_value}.')<def_stmt>__init__ self field value field2 message=<none><block_start>self.field=field<line_sep>self.value=value<line_sep>self.field2=field2<line_sep>self.message=message<or>self.message<line_sep>self.initial_data=<none><block_end><def_stmt>set_context self serializer<block_start>self.initial_data=getattr(serializer 'initial_data' <none>)<block_end><def_stmt>__call__ self *args **kwargs<block_start><if_stmt>self.initial_data[self.field]<eq>self.value<and>self.field2<not><in>self.initial_data<block_start><raise>ValidationError(self.message.format(field_name=self.field field2_name=self.field2 type_value=self.value))<block_end><block_end><block_end>
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. ''' Created on May 17, 2011 '''<try_stmt><block_start><import_stmt>json<block_end><except_stmt>ImportError<block_start><import_stmt>simplejson<as>json<block_end><import_from_stmt>OvmObjectModule *<import_stmt>types<import_stmt>logging<import_stmt>popen2<import_stmt>subprocess<import_from_stmt>OvmFaultConstants toErrCode dispatchErrCode NoVmFoundException ShellExceutedFailedException<import_from_stmt>xmlrpclib Fault<as>XmlRpcFault<import_from_stmt>OVSCommons *<import_from_stmt>OvmLoggerModule OvmLogger<import_from_stmt>OVSXXenStore xen_get_vm_path<import_from_stmt>OVSSiteRMServer get_master_ip<line_sep>HEARTBEAT_TIMESTAMP_FORMAT='<timestamp>%s</timestamp>'<line_sep>HEARTBEAT_TIMESTAMP_PATTERN='(\<timestamp\>\d+.\d+<\/timestamp\>)'<line_sep>HEARTBEAT_DIR='heart_beat'<line_sep>ETC_HOSTS='/etc/hosts'<line_sep>HOSTNAME_FILE='/etc/sysconfig/network'<line_sep>OWNER_FILE_PREFIX='host_'<line_sep>OCFS2_CONF='/etc/ocfs2/cluster.conf'<line_sep>logger=OvmLogger('OvmCommon')<def_stmt>setAttrFromDict obj name refDict convertFunc=<none><block_start><if_stmt><not>convertFunc<block_start>setattr(obj name refDict[name])<block_end><else_stmt><block_start>setattr(obj name convertFunc(refDict[name]))<block_end><block_end><def_stmt>safeSetAttr obj name value<block_start><if_stmt><not>hasattr(obj name)<block_start><raise>Exception("%s doesn't have attribute %s"%(obj.__class__.__name__ name))<block_end>setattr(obj name value)<block_end><def_stmt>toAscii jstr<block_start><return>str(jstr).encode('ascii' 'ignore')<block_end><def_stmt>toAsciiHook dct<block_start><for_stmt>k dct<block_start>v=dct[k]<if_stmt>type(v)<is>types.UnicodeType<block_start>v=toAscii(v)<block_end><del_stmt>dct[k]<line_sep>k=toAscii(k)<line_sep>dct[k]=v<block_end><return>dct<block_end><def_stmt>asciiLoads jStr<block_start>jStr=str(jStr).replace("'" '"').replace('False' 'false').replace('True' 'true')<line_sep><return>json.loads(jStr object_hook=toAsciiHook)<block_end><def_stmt>exceptionIfNoSuccess str errMsg=<none><block_start><if_stmt><not>errMsg<block_start>errMsg=str<block_end><if_stmt><not>"success"<in>str<block_start><raise>Exception("%s (%s)"%(errMsg str))<block_end><block_end><def_stmt>successToMap str sep=';'<block_start><if_stmt><not>str.startswith("success")<block_start><raise>Exception(str)<block_end>str=str[len('success:'):]<line_sep>dct={}<for_stmt>pair str.split(sep)<block_start>(key value)=pair.split('=' 1)<line_sep>dct[key]=value<block_end><return>dct<block_end><def_stmt>jsonSuccessToMap str<block_start>dct=json.loads(str)<if_stmt>dct['status']<ne>'SUCC'<block_start><raise>Exception(str)<block_end><return>dct['value']<block_end><def_stmt>safeDictSet obj dct name<block_start><if_stmt><not>hasattr(obj name)<block_start><raise>Exception("%s has no attribute %s for encoding"%(obj.__class__.__name__ name))<block_end>dct[name]=getattr(obj name)<block_end><def_stmt>normalizeToGson str<block_start><return>str.replace('\\' '').strip('"').replace('"{' '{').replace('}"' '}')<line_sep><block_end><def_stmt>toGson obj<block_start><return>normalizeToGson(json.dumps(obj))<block_end><def_stmt>MtoBytes M<block_start><return>M<times>1024<times>1024<block_end><def_stmt>BytesToM bytes<block_start><return>bytes/(1024<times>1024)<block_end><def_stmt>BytesToG bytes<block_start><return>bytes/(1024<times>1024<times>1024)<block_end><def_stmt>runCmd cmds<block_start>process=subprocess.Popen(cmds shell=<true> stdout=subprocess.PIPE stderr=subprocess.PIPE)<line_sep>stdout,stderr=process.communicate()<if_stmt>process.returncode<ne>0<block_start><raise>ShellExceutedFailedException(stderr process.returncode)<block_end><return>stdout<block_end><def_stmt>doCmd lst<block_start>cmds=[str(i)<for>i lst]<line_sep>cmdStr=' '.join(cmds)<line_sep>logger.debug(doCmd cmdStr)<line_sep>res=runCmd(cmdStr)<line_sep>logger.debug(doCmd 'result:'+res)<line_sep><return>res<block_end><def_stmt>execute cmd<block_start>p=popen2.Popen3(cmd <true>)<if_stmt>(p.wait()<ne>0)<block_start><raise>Exception("Failed to execute command. Command: "+cmd+", Error: "+p.childerr.read())<block_end><return>p.fromchild.read()<block_end><def_stmt>getDomId vm_name<block_start><return>execute("xm list | grep "+vm_name+" | awk '{print $2}'").strip()<block_end><def_stmt>raiseExceptionIfFail res<block_start><if_stmt><not>"success"<in>res<and><not>"SUCC"<in>res<block_start><raise>Exception(res)<block_end><block_end><def_stmt>ipToHeartBeatFileName ip<block_start><return>ip.replace('.' '_')+"_HEARTBEAT"<block_end><def_stmt>getVmNameFromConfigureFile cfgPath<block_start>fd=open(cfgPath)<for_stmt>i fd.readlines()<block_start>i=i.strip()<if_stmt>i.startswith('name')<block_start>(key value)=i.split("=" 1)<line_sep>value=value.strip().strip("'")<line_sep>fd.close()<line_sep><return>value<block_end><block_end>fd.close()<line_sep><raise>Exception('Cannot find vm name in %s'%cfgPath)<block_end><def_stmt>makeOwnerFileName <block_start>hostIp=successToMap(get_master_ip())['ip']<line_sep>ownerFileName=OWNER_FILE_PREFIX+hostIp.replace('.' '_')<line_sep><return>ownerFileName<block_end>
""" This example is largely based on the question-answering example in the huggingface transformers library. The license for the transformer's library is reproduced below. ================================================================================================== Copyright 2020 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """<import_stmt>functools<import_stmt>logging<import_from_stmt>typing Dict Union<import_stmt>attrdict<import_stmt>data_beam_search<import_stmt>datasets<import_stmt>qa_utils<import_stmt>torch<import_stmt>transformers<import_stmt>determined.pytorch<as>det_torch<import_stmt>model_hub.huggingface<as>hf<class_stmt>QABeamSearchTrial(hf.BaseTransformerTrial)<block_start><def_stmt>__init__ self context:det_torch.PyTorchTrialContext<arrow><none><block_start>self.logger=logging.getLogger(__name__)<line_sep>self.hparams=attrdict.AttrDict(context.get_hparams())<line_sep>self.data_config=attrdict.AttrDict(context.get_data_config())<line_sep>self.context=context<line_sep># Check to make sure the dataset is configured correctly. <if_stmt>self.data_config.dataset_name<is><not><none><block_start>dataset_name=self.data_config.dataset_name<if_stmt>dataset_name<eq>"squad"<block_start><assert_stmt>(<not>self.data_config.version_2_with_negative) "version_2_with_negative should be false for squad"<block_end><elif_stmt>dataset_name<eq>"squad_v2"<block_start><assert_stmt>(self.data_config.version_2_with_negative) "version_2_with_negative should be true for squad_v2"<block_end><block_end>self.data_processors=data_beam_search<line_sep># Get the datasets: you can either provide your own CSV or JSON training and evaluation # files (see below) or just provide the name of one of the public datasets available on the # hub at https://huggingface.co/datasets/ (the dataset will be downloaded automatically # from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if # no column called 'text' is found. You can easily tweak this behavior (see below). # See more about loading any type of standard or custom dataset (from files, python dict, # pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. self.raw_datasets=hf.default_load_dataset(self.data_config)<line_sep>self.column_names=self.raw_datasets["train"].column_names<line_sep># For beam search, we need to use a different model from the default model returned by # AutoModelForQuestionAnswering. We will use a custom init in this case that is a slight # modification of the BaseTransformerTrial init method. self.exp_config=attrdict.AttrDict(context.get_experiment_config())<line_sep># Check to make sure all expected hyperparameters are set. self.check_hparams()<line_sep># Parse hparams and data_config. (self.config_kwargs self.tokenizer_kwargs self.model_kwargs )=hf.default_parse_config_tokenizer_model_kwargs(self.hparams)<line_sep>optimizer_kwargs,scheduler_kwargs=hf.default_parse_optimizer_lr_scheduler_kwargs(self.hparams)<line_sep>self.config=transformers.XLNetConfig.from_pretrained(**self.config_kwargs)<line_sep>self.tokenizer=transformers.XLNetTokenizerFast.from_pretrained(**self.tokenizer_kwargs)<line_sep># We need to use XLNetForQuestionAnswering instead of XLNetForQuestionAnsweringSimple # which is the default returned by AutoModelForQuestionAnswering. <if_stmt>self.hparams.use_pretrained_weights<block_start>self.model_kwargs["config"]=self.config<line_sep>self.model=transformers.XLNetForQuestionAnswering.from_pretrained(**self.model_kwargs)<block_end><else_stmt><block_start>self.model=transformers.XLNetForQuestionAnswering(self.config)<block_end>self.model=self.context.wrap_model(self.model)<line_sep># The rest is the same as the parent init method. self.optimizer=self.context.wrap_optimizer(hf.build_default_optimizer(self.model optimizer_kwargs))<if_stmt>self.hparams.use_apex_amp<block_start>self.model,self.optimizer=self.context.configure_apex_amp(models=self.model optimizers=self.optimizer )<block_end>self.lr_scheduler=self.context.wrap_lr_scheduler(hf.build_default_lr_scheduler(self.optimizer scheduler_kwargs) det_torch.LRScheduler.StepMode.STEP_EVERY_BATCH )<line_sep>self.grad_clip_fn=(<lambda>x:torch.nn.utils.clip_grad_norm_(x optimizer_kwargs.max_grad_norm)<if>optimizer_kwargs.max_grad_norm<g>0# type: ignore <else><none>)<line_sep>self.logger.info(self.config)<if_stmt><not>isinstance(self.tokenizer transformers.PreTrainedTokenizerFast)<block_start><raise>ValueError("This example script only works for models that have a fast tokenizer. Checkout "<concat>"the big table of models at "<concat>"https://huggingface.co/transformers/index.html#bigtable to find the model types "<concat>"that meet this requirement")<block_end># We need to create the tokenized dataset after init because we need to model and # tokenizer to be available. self.tokenized_datasets=self.build_datasets()<line_sep>train_length=len(self.tokenized_datasets["train"])<line_sep>self.logger.info("training records: {}".format(train_length))<if_stmt>("records_per_epoch"<in>self.exp_config<and>train_length<ne>self.exp_config["records_per_epoch"])<block_start>self.logger.warning("number of train records {} does not match records_per_epoch of {}".format(train_length self.exp_config["records_per_epoch"]))<block_end># Create metric reducer metric=datasets.load_metric("squad_v2"<if>self.data_config.version_2_with_negative<else>"squad")<line_sep>self.reducer=context.experimental.wrap_reducer(functools.partial(qa_utils.compute_metrics self.data_config self.column_names self.data_processors.post_processing_function self.raw_datasets self.tokenized_datasets self.model metric ) for_training=<false> )<block_end><def_stmt>build_datasets self<arrow>Dict[str Union[datasets.Dataset datasets.DatasetDict]]<block_start>tokenized_datasets={}<for_stmt>split ["train" "validation"]<block_start>tokenized_datasets[split]=self.raw_datasets[split].map(functools.partial(self.data_processors.prepare_features split self.data_config self.tokenizer self.column_names ) batched=<true> num_proc=self.data_config.preprocessing_num_workers remove_columns=self.column_names load_from_cache_file=<not>self.data_config.overwrite_cache )<line_sep>hf.remove_unused_columns(self.model tokenized_datasets[split])<block_end><if_stmt>self.data_config.pad_to_max_length<block_start>self.collator=transformers.default_data_collator<block_end><else_stmt><block_start>collator=transformers.DataCollatorWithPadding(self.tokenizer pad_to_multiple_of=8<if>self.hparams.use_apex_amp<else><none>)<line_sep>self.collator=<lambda>x:collator(x).data<block_end><return>tokenized_datasets<block_end><def_stmt>build_training_data_loader self<arrow>det_torch.DataLoader<block_start><return>det_torch.DataLoader(self.tokenized_datasets["train"] batch_size=self.context.get_per_slot_batch_size() collate_fn=self.collator )<block_end><def_stmt>build_validation_data_loader self<arrow>det_torch.DataLoader# Determined's distributed batch sampler interleaves shards on each GPU slot so # sample i goes to worker with rank i % world_size. Therefore, we need to re-sort # all the samples once we gather the predictions before computing the validation metric. <block_start><return>det_torch.DataLoader(qa_utils.DatasetWithIndex(self.tokenized_datasets["validation"]) batch_size=self.context.get_per_slot_batch_size() collate_fn=self.collator )<block_end><def_stmt>evaluate_batch self batch:det_torch.TorchData batch_idx:int<arrow>Dict<block_start>ind=batch.pop("ind")<line_sep>outputs=self.model(**batch)<if_stmt>isinstance(outputs dict)<block_start>predictions=tuple(v.detach().cpu().numpy()<for>k,v outputs.items()<if>k<not><in>("loss" "mems"))<block_end><else_stmt><block_start>predictions=outputs[1:].detach().cpu().numpy()<block_end>self.reducer.update((ind.detach().cpu().numpy() predictions))<line_sep># Although we are returning the empty dictionary below, we will still get the metrics from # custom reducer that we passed to the context during initialization. <return>{}<block_end><block_end>
<import_from_stmt>.utils *<line_sep>
<import_from_future_stmt> absolute_import<import_from_future_stmt> print_function<import_stmt>veriloggen<import_stmt>types_axi_slave_readwrite_lite_simultaneous<line_sep>expected_verilog=""" module test; reg CLK; reg RST; wire [32-1:0] sum; reg [32-1:0] myaxi_awaddr; reg [4-1:0] myaxi_awcache; reg [3-1:0] myaxi_awprot; reg myaxi_awvalid; wire myaxi_awready; reg [32-1:0] myaxi_wdata; reg [4-1:0] myaxi_wstrb; reg myaxi_wvalid; wire myaxi_wready; wire [2-1:0] myaxi_bresp; wire myaxi_bvalid; reg myaxi_bready; reg [32-1:0] myaxi_araddr; reg [4-1:0] myaxi_arcache; reg [3-1:0] myaxi_arprot; reg myaxi_arvalid; wire myaxi_arready; wire [32-1:0] myaxi_rdata; wire [2-1:0] myaxi_rresp; wire myaxi_rvalid; reg myaxi_rready; reg [32-1:0] _axi_awaddr; wire [4-1:0] _axi_awcache; wire [3-1:0] _axi_awprot; reg _axi_awvalid; wire _axi_awready; reg [32-1:0] _axi_wdata; reg [4-1:0] _axi_wstrb; reg _axi_wvalid; wire _axi_wready; wire [2-1:0] _axi_bresp; wire _axi_bvalid; wire _axi_bready; reg [32-1:0] _axi_araddr; wire [4-1:0] _axi_arcache; wire [3-1:0] _axi_arprot; reg _axi_arvalid; wire _axi_arready; wire [32-1:0] _axi_rdata; wire [2-1:0] _axi_rresp; wire _axi_rvalid; wire _axi_rready; assign _axi_awcache = 3; assign _axi_awprot = 0; assign _axi_bready = 1; assign _axi_arcache = 3; assign _axi_arprot = 0; reg [3-1:0] outstanding_wcount_0; wire [32-1:0] _tmp_1; assign _tmp_1 = _axi_awaddr; always @(*) begin myaxi_awaddr = _tmp_1; end wire [4-1:0] _tmp_2; assign _tmp_2 = _axi_awcache; always @(*) begin myaxi_awcache = _tmp_2; end wire [3-1:0] _tmp_3; assign _tmp_3 = _axi_awprot; always @(*) begin myaxi_awprot = _tmp_3; end wire _tmp_4; assign _tmp_4 = _axi_awvalid; always @(*) begin myaxi_awvalid = _tmp_4; end assign _axi_awready = myaxi_awready; wire [32-1:0] _tmp_5; assign _tmp_5 = _axi_wdata; always @(*) begin myaxi_wdata = _tmp_5; end wire [4-1:0] _tmp_6; assign _tmp_6 = _axi_wstrb; always @(*) begin myaxi_wstrb = _tmp_6; end wire _tmp_7; assign _tmp_7 = _axi_wvalid; always @(*) begin myaxi_wvalid = _tmp_7; end assign _axi_wready = myaxi_wready; assign _axi_bresp = myaxi_bresp; assign _axi_bvalid = myaxi_bvalid; wire _tmp_8; assign _tmp_8 = _axi_bready; always @(*) begin myaxi_bready = _tmp_8; end wire [32-1:0] _tmp_9; assign _tmp_9 = _axi_araddr; always @(*) begin myaxi_araddr = _tmp_9; end wire [4-1:0] _tmp_10; assign _tmp_10 = _axi_arcache; always @(*) begin myaxi_arcache = _tmp_10; end wire [3-1:0] _tmp_11; assign _tmp_11 = _axi_arprot; always @(*) begin myaxi_arprot = _tmp_11; end wire _tmp_12; assign _tmp_12 = _axi_arvalid; always @(*) begin myaxi_arvalid = _tmp_12; end assign _axi_arready = myaxi_arready; assign _axi_rdata = myaxi_rdata; assign _axi_rresp = myaxi_rresp; assign _axi_rvalid = myaxi_rvalid; wire _tmp_13; assign _tmp_13 = _axi_rready; always @(*) begin myaxi_rready = _tmp_13; end reg [32-1:0] read_fsm; localparam read_fsm_init = 0; reg [32-1:0] rsum; reg __axi_cond_0_1; reg __axi_cond_1_1; assign _axi_rready = (read_fsm == 1) || (read_fsm == 3); reg [32-1:0] write_fsm; localparam write_fsm_init = 0; reg __axi_cond_2_1; reg [32-1:0] wdata; reg __axi_cond_3_1; reg __axi_cond_4_1; reg __axi_cond_5_1; main uut ( .CLK(CLK), .RST(RST), .sum(sum), .myaxi_awaddr(myaxi_awaddr), .myaxi_awcache(myaxi_awcache), .myaxi_awprot(myaxi_awprot), .myaxi_awvalid(myaxi_awvalid), .myaxi_awready(myaxi_awready), .myaxi_wdata(myaxi_wdata), .myaxi_wstrb(myaxi_wstrb), .myaxi_wvalid(myaxi_wvalid), .myaxi_wready(myaxi_wready), .myaxi_bresp(myaxi_bresp), .myaxi_bvalid(myaxi_bvalid), .myaxi_bready(myaxi_bready), .myaxi_araddr(myaxi_araddr), .myaxi_arcache(myaxi_arcache), .myaxi_arprot(myaxi_arprot), .myaxi_arvalid(myaxi_arvalid), .myaxi_arready(myaxi_arready), .myaxi_rdata(myaxi_rdata), .myaxi_rresp(myaxi_rresp), .myaxi_rvalid(myaxi_rvalid), .myaxi_rready(myaxi_rready) ); initial begin CLK = 0; forever begin #5 CLK = !CLK; end end initial begin RST = 0; _axi_awaddr = 0; _axi_awvalid = 0; _axi_wdata = 0; _axi_wstrb = 0; _axi_wvalid = 0; _axi_araddr = 0; _axi_arvalid = 0; outstanding_wcount_0 = 0; read_fsm = read_fsm_init; rsum = 0; __axi_cond_0_1 = 0; __axi_cond_1_1 = 0; write_fsm = write_fsm_init; __axi_cond_2_1 = 0; wdata = 100; __axi_cond_3_1 = 0; __axi_cond_4_1 = 0; __axi_cond_5_1 = 0; #100; RST = 1; #100; RST = 0; #100000; $finish; end always @(posedge CLK) begin if(RST) begin outstanding_wcount_0 <= 0; _axi_araddr <= 0; _axi_arvalid <= 0; __axi_cond_0_1 <= 0; __axi_cond_1_1 <= 0; _axi_awaddr <= 0; _axi_awvalid <= 0; __axi_cond_2_1 <= 0; _axi_wdata <= 0; _axi_wvalid <= 0; _axi_wstrb <= 0; __axi_cond_3_1 <= 0; __axi_cond_4_1 <= 0; __axi_cond_5_1 <= 0; end else begin if(__axi_cond_0_1) begin _axi_arvalid <= 0; end if(__axi_cond_1_1) begin _axi_arvalid <= 0; end if(__axi_cond_2_1) begin _axi_awvalid <= 0; end if(__axi_cond_3_1) begin _axi_wvalid <= 0; end if(__axi_cond_4_1) begin _axi_awvalid <= 0; end if(__axi_cond_5_1) begin _axi_wvalid <= 0; end if(_axi_wvalid && _axi_wready && !(_axi_bvalid && _axi_bready) && (outstanding_wcount_0 < 7)) begin outstanding_wcount_0 <= outstanding_wcount_0 + 1; end if(!(_axi_wvalid && _axi_wready) && (_axi_bvalid && _axi_bready) && (outstanding_wcount_0 > 0)) begin outstanding_wcount_0 <= outstanding_wcount_0 - 1; end if((read_fsm == 0) && (_axi_arready || !_axi_arvalid)) begin _axi_araddr <= 1024; _axi_arvalid <= 1; end __axi_cond_0_1 <= 1; if(_axi_arvalid && !_axi_arready) begin _axi_arvalid <= _axi_arvalid; end if((read_fsm == 2) && (_axi_arready || !_axi_arvalid)) begin _axi_araddr <= 2048; _axi_arvalid <= 1; end __axi_cond_1_1 <= 1; if(_axi_arvalid && !_axi_arready) begin _axi_arvalid <= _axi_arvalid; end if((write_fsm == 0) && (_axi_awready || !_axi_awvalid)) begin _axi_awaddr <= 1024; _axi_awvalid <= 1; end __axi_cond_2_1 <= 1; if(_axi_awvalid && !_axi_awready) begin _axi_awvalid <= _axi_awvalid; end if((write_fsm == 1) && ((outstanding_wcount_0 < 6) && (_axi_wready || !_axi_wvalid))) begin _axi_wdata <= wdata; _axi_wvalid <= 1; _axi_wstrb <= { 4{ 1'd1 } }; end __axi_cond_3_1 <= 1; if(_axi_wvalid && !_axi_wready) begin _axi_wvalid <= _axi_wvalid; end if((write_fsm == 2) && (_axi_awready || !_axi_awvalid)) begin _axi_awaddr <= 1024; _axi_awvalid <= 1; end __axi_cond_4_1 <= 1; if(_axi_awvalid && !_axi_awready) begin _axi_awvalid <= _axi_awvalid; end if((write_fsm == 3) && ((outstanding_wcount_0 < 6) && (_axi_wready || !_axi_wvalid))) begin _axi_wdata <= wdata; _axi_wvalid <= 1; _axi_wstrb <= { 4{ 1'd1 } }; end __axi_cond_5_1 <= 1; if(_axi_wvalid && !_axi_wready) begin _axi_wvalid <= _axi_wvalid; end end end localparam read_fsm_1 = 1; localparam read_fsm_2 = 2; localparam read_fsm_3 = 3; localparam read_fsm_4 = 4; localparam read_fsm_5 = 5; always @(posedge CLK) begin if(RST) begin read_fsm <= read_fsm_init; rsum <= 0; end else begin case(read_fsm) read_fsm_init: begin if(_axi_arready || !_axi_arvalid) begin read_fsm <= read_fsm_1; end end read_fsm_1: begin if(_axi_rready && _axi_rvalid) begin rsum <= rsum + _axi_rdata; end if(_axi_rready && _axi_rvalid) begin read_fsm <= read_fsm_2; end end read_fsm_2: begin if(_axi_arready || !_axi_arvalid) begin read_fsm <= read_fsm_3; end end read_fsm_3: begin if(_axi_rready && _axi_rvalid) begin rsum <= rsum + _axi_rdata; end if(_axi_rready && _axi_rvalid) begin read_fsm <= read_fsm_4; end end read_fsm_4: begin $display("rsum=%d expected_rsum=%d", rsum, 768); read_fsm <= read_fsm_5; end endcase end end localparam write_fsm_1 = 1; localparam write_fsm_2 = 2; localparam write_fsm_3 = 3; localparam write_fsm_4 = 4; localparam write_fsm_5 = 5; localparam write_fsm_6 = 6; localparam write_fsm_7 = 7; localparam write_fsm_8 = 8; localparam write_fsm_9 = 9; localparam write_fsm_10 = 10; localparam write_fsm_11 = 11; localparam write_fsm_12 = 12; localparam write_fsm_13 = 13; localparam write_fsm_14 = 14; localparam write_fsm_15 = 15; always @(posedge CLK) begin if(RST) begin write_fsm <= write_fsm_init; wdata <= 100; end else begin case(write_fsm) write_fsm_init: begin wdata <= 100; if(_axi_awready || !_axi_awvalid) begin write_fsm <= write_fsm_1; end end write_fsm_1: begin if((outstanding_wcount_0 < 6) && (_axi_wready || !_axi_wvalid)) begin write_fsm <= write_fsm_2; end end write_fsm_2: begin wdata <= 200; if(_axi_awready || !_axi_awvalid) begin write_fsm <= write_fsm_3; end end write_fsm_3: begin if((outstanding_wcount_0 < 6) && (_axi_wready || !_axi_wvalid)) begin write_fsm <= write_fsm_4; end end write_fsm_4: begin write_fsm <= write_fsm_5; end write_fsm_5: begin write_fsm <= write_fsm_6; end write_fsm_6: begin write_fsm <= write_fsm_7; end write_fsm_7: begin write_fsm <= write_fsm_8; end write_fsm_8: begin write_fsm <= write_fsm_9; end write_fsm_9: begin write_fsm <= write_fsm_10; end write_fsm_10: begin write_fsm <= write_fsm_11; end write_fsm_11: begin write_fsm <= write_fsm_12; end write_fsm_12: begin write_fsm <= write_fsm_13; end write_fsm_13: begin write_fsm <= write_fsm_14; end write_fsm_14: begin $display("sum=%d expected_sum=%d", sum, 300); write_fsm <= write_fsm_15; end endcase end end endmodule module main ( input CLK, input RST, output reg [32-1:0] sum, input [32-1:0] myaxi_awaddr, input [4-1:0] myaxi_awcache, input [3-1:0] myaxi_awprot, input myaxi_awvalid, output myaxi_awready, input [32-1:0] myaxi_wdata, input [4-1:0] myaxi_wstrb, input myaxi_wvalid, output myaxi_wready, output [2-1:0] myaxi_bresp, output reg myaxi_bvalid, input myaxi_bready, input [32-1:0] myaxi_araddr, input [4-1:0] myaxi_arcache, input [3-1:0] myaxi_arprot, input myaxi_arvalid, output myaxi_arready, output reg [32-1:0] myaxi_rdata, output [2-1:0] myaxi_rresp, output reg myaxi_rvalid, input myaxi_rready ); assign myaxi_bresp = 0; assign myaxi_rresp = 0; reg [32-1:0] fsm; localparam fsm_init = 0; reg [32-1:0] addr_0; reg writevalid_1; reg readvalid_2; reg prev_awvalid_3; reg prev_arvalid_4; assign myaxi_awready = (fsm == 0) && (!writevalid_1 && !readvalid_2 && !myaxi_bvalid && prev_awvalid_3); assign myaxi_arready = (fsm == 0) && (!readvalid_2 && !writevalid_1 && prev_arvalid_4 && !prev_awvalid_3); reg [32-1:0] rdata; reg _myaxi_cond_0_1; assign myaxi_wready = fsm == 100; always @(posedge CLK) begin if(RST) begin myaxi_bvalid <= 0; prev_awvalid_3 <= 0; prev_arvalid_4 <= 0; writevalid_1 <= 0; readvalid_2 <= 0; addr_0 <= 0; myaxi_rdata <= 0; myaxi_rvalid <= 0; _myaxi_cond_0_1 <= 0; end else begin if(_myaxi_cond_0_1) begin myaxi_rvalid <= 0; end if(myaxi_bvalid && myaxi_bready) begin myaxi_bvalid <= 0; end if(myaxi_wvalid && myaxi_wready) begin myaxi_bvalid <= 1; end prev_awvalid_3 <= myaxi_awvalid; prev_arvalid_4 <= myaxi_arvalid; writevalid_1 <= 0; readvalid_2 <= 0; if(myaxi_awready && myaxi_awvalid && !myaxi_bvalid) begin addr_0 <= myaxi_awaddr; writevalid_1 <= 1; end else if(myaxi_arready && myaxi_arvalid) begin addr_0 <= myaxi_araddr; readvalid_2 <= 1; end if((fsm == 1) && (myaxi_rready || !myaxi_rvalid)) begin myaxi_rdata <= rdata; myaxi_rvalid <= 1; end _myaxi_cond_0_1 <= 1; if(myaxi_rvalid && !myaxi_rready) begin myaxi_rvalid <= myaxi_rvalid; end end end localparam fsm_1 = 1; localparam fsm_2 = 2; localparam fsm_100 = 100; localparam fsm_101 = 101; always @(posedge CLK) begin if(RST) begin fsm <= fsm_init; rdata <= 0; sum <= 0; end else begin case(fsm) fsm_init: begin if(readvalid_2) begin rdata <= addr_0 >> 2; end if(writevalid_1) begin fsm <= fsm_100; end if(readvalid_2) begin fsm <= fsm_1; end end fsm_1: begin if(myaxi_rready || !myaxi_rvalid) begin rdata <= rdata + 1; end if(myaxi_rready || !myaxi_rvalid) begin fsm <= fsm_2; end end fsm_2: begin fsm <= fsm_init; end fsm_100: begin if(myaxi_wready && myaxi_wvalid) begin sum <= sum + myaxi_wdata; end if(myaxi_wready && myaxi_wvalid) begin fsm <= fsm_101; end end fsm_101: begin fsm <= fsm_init; end endcase end end endmodule """<def_stmt>test <block_start>veriloggen.reset()<line_sep>test_module=types_axi_slave_readwrite_lite_simultaneous.mkTest()<line_sep>code=test_module.to_verilog()<import_from_stmt>pyverilog.vparser.parser VerilogParser<import_from_stmt>pyverilog.ast_code_generator.codegen ASTCodeGenerator<line_sep>parser=VerilogParser()<line_sep>expected_ast=parser.parse(expected_verilog)<line_sep>codegen=ASTCodeGenerator()<line_sep>expected_code=codegen.visit(expected_ast)<assert_stmt>(expected_code<eq>code)<block_end>
<import_from_stmt>PhysicsTools.SelectorUtils.centralIDRegistry central_id_registry<line_sep># Common functions and classes for ID definition are imported here: <import_from_stmt>RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_tools *<line_sep># # This is the first round of Spring15 25ns cuts, optimized on Spring15 25ns samples. # # The ID cuts below are optimized IDs for Spring15 Scenario with 25ns bunch spacing # The cut values are taken from the twiki: # https://twiki.cern.ch/twiki/bin/view/CMS/CutBasedElectronIdentificationRun2 # (where they may not stay, if a newer version of cuts becomes available for these # conditions) # See also the presentation explaining these working points (this will not change): # https://indico.cern.ch/event/370507/contribution/1/attachments/1140657/1633761/Rami_eleCB_ID_25ns.pdf # # First, define cut values # # Veto working point Barrel and Endcap idName="cutBasedElectronID-Spring15-25ns-V1-standalone-veto"<line_sep>WP_Veto_EB=EleWorkingPoint_V2(idName # idName 0.0152 # dEtaInCut 0.216 # dPhiInCut 0.0114 # full5x5_sigmaIEtaIEtaCut 0.181 # hOverECut 0.0564 # dxyCut 0.472 # dzCut 0.207 # absEInverseMinusPInverseCut 0.126 # relCombIsolationWithEALowPtCut 0.126 # relCombIsolationWithEAHighPtCut # conversion veto cut needs no parameters, so not mentioned 2# missingHitsCut )<line_sep>WP_Veto_EE=EleWorkingPoint_V2(idName # idName 0.0113 # dEtaInCut 0.237 # dPhiInCut 0.0352 # full5x5_sigmaIEtaIEtaCut 0.116 # hOverECut 0.222 # dxyCut 0.921 # dzCut 0.174 # absEInverseMinusPInverseCut 0.144 # relCombIsolationWithEALowPtCut 0.144 # relCombIsolationWithEAHighPtCut # conversion veto cut needs no parameters, so not mentioned 3# missingHitsCut )<line_sep># Loose working point Barrel and Endcap idName="cutBasedElectronID-Spring15-25ns-V1-standalone-loose"<line_sep>WP_Loose_EB=EleWorkingPoint_V2(idName # idName 0.0105 # dEtaInCut 0.115 # dPhiInCut 0.0103 # full5x5_sigmaIEtaIEtaCut 0.104 # hOverECut 0.0261 # dxyCut 0.41 # dzCut 0.102 # absEInverseMinusPInverseCut 0.0893 # relCombIsolationWithEALowPtCut 0.0893 # relCombIsolationWithEAHighPtCut # conversion veto cut needs no parameters, so not mentioned 2# missingHitsCut )<line_sep>WP_Loose_EE=EleWorkingPoint_V2(idName # idName 0.00814 # dEtaInCut 0.182 # dPhiInCut 0.0301 # full5x5_sigmaIEtaIEtaCut 0.0897 # hOverECut 0.118 # dxyCut 0.822 # dzCut 0.126 # absEInverseMinusPInverseCut 0.121 # relCombIsolationWithEALowPtCut 0.121 # relCombIsolationWithEAHighPtCut # conversion veto cut needs no parameters, so not mentioned 1# missingHitsCut )<line_sep># Medium working point Barrel and Endcap idName="cutBasedElectronID-Spring15-25ns-V1-standalone-medium"<line_sep>WP_Medium_EB=EleWorkingPoint_V2(idName # idName 0.0103 # dEtaInCut 0.0336 # dPhiInCut 0.0101 # full5x5_sigmaIEtaIEtaCut 0.0876 # hOverECut 0.0118 # dxyCut 0.373 # dzCut 0.0174 # absEInverseMinusPInverseCut 0.0766 # relCombIsolationWithEALowPtCut 0.0766 # relCombIsolationWithEAHighPtCut # conversion veto cut needs no parameters, so not mentioned 2# missingHitsCut )<line_sep>WP_Medium_EE=EleWorkingPoint_V2(idName # idName 0.00733 # dEtaInCut 0.114 # dPhiInCut 0.0283 # full5x5_sigmaIEtaIEtaCut 0.0678 # hOverECut 0.0739 # dxyCut 0.602 # dzCut 0.0898 # absEInverseMinusPInverseCut 0.0678 # relCombIsolationWithEALowPtCut 0.0678 # relCombIsolationWithEAHighPtCut # conversion veto cut needs no parameters, so not mentioned 1# missingHitsCut )<line_sep># Tight working point Barrel and Endcap idName="cutBasedElectronID-Spring15-25ns-V1-standalone-tight"<line_sep>WP_Tight_EB=EleWorkingPoint_V2(idName # idName 0.00926 # dEtaInCut 0.0336 # dPhiInCut 0.0101 # full5x5_sigmaIEtaIEtaCut 0.0597 # hOverECut 0.0111 # dxyCut 0.0466 # dzCut 0.012 # absEInverseMinusPInverseCut 0.0354 # relCombIsolationWithEALowPtCut 0.0354 # relCombIsolationWithEAHighPtCut # conversion veto cut needs no parameters, so not mentioned 2# missingHitsCut )<line_sep>WP_Tight_EE=EleWorkingPoint_V2(idName # idName 0.00724 # dEtaInCut 0.0918 # dPhiInCut 0.0279 # full5x5_sigmaIEtaIEtaCut 0.0615 # hOverECut 0.0351 # dxyCut 0.417 # dzCut 0.00999 # absEInverseMinusPInverseCut 0.0646 # relCombIsolationWithEALowPtCut 0.0646 # relCombIsolationWithEAHighPtCut # conversion veto cut needs no parameters, so not mentioned 1# missingHitsCut )<line_sep># Second, define what effective areas to use for pile-up correction isoEffAreas="RecoEgamma/ElectronIdentification/data/Spring15/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_25ns.txt"<line_sep># # Set up VID configuration for all cuts and working points # cutBasedElectronID_Spring15_25ns_V1_standalone_veto=configureVIDCutBasedEleID_V2(WP_Veto_EB WP_Veto_EE isoEffAreas)<line_sep>cutBasedElectronID_Spring15_25ns_V1_standalone_loose=configureVIDCutBasedEleID_V2(WP_Loose_EB WP_Loose_EE isoEffAreas)<line_sep>cutBasedElectronID_Spring15_25ns_V1_standalone_medium=configureVIDCutBasedEleID_V2(WP_Medium_EB WP_Medium_EE isoEffAreas)<line_sep>cutBasedElectronID_Spring15_25ns_V1_standalone_tight=configureVIDCutBasedEleID_V2(WP_Tight_EB WP_Tight_EE isoEffAreas)<line_sep># The MD5 sum numbers below reflect the exact set of cut variables # and values above. If anything changes, one has to # 1) comment out the lines below about the registry, # 2) run "calculateMD5 <this file name> <one of the VID config names just above> # 3) update the MD5 sum strings below and uncomment the lines again. # central_id_registry.register(cutBasedElectronID_Spring15_25ns_V1_standalone_veto.idName '202030579ee3eec90fdc2d236ba3de7e')<line_sep>central_id_registry.register(cutBasedElectronID_Spring15_25ns_V1_standalone_loose.idName '4fab9e4d09a2c1a36cbbd2279deb3627')<line_sep>central_id_registry.register(cutBasedElectronID_Spring15_25ns_V1_standalone_medium.idName 'aa291aba714c148fcba156544907c440')<line_sep>central_id_registry.register(cutBasedElectronID_Spring15_25ns_V1_standalone_tight.idName '4e13b87c0573d3c8ebf91d446fa1d90f')<line_sep>### for now until we have a database... cutBasedElectronID_Spring15_25ns_V1_standalone_veto.isPOGApproved=cms.untracked.bool(<true>)<line_sep>cutBasedElectronID_Spring15_25ns_V1_standalone_loose.isPOGApproved=cms.untracked.bool(<true>)<line_sep>cutBasedElectronID_Spring15_25ns_V1_standalone_medium.isPOGApproved=cms.untracked.bool(<true>)<line_sep>cutBasedElectronID_Spring15_25ns_V1_standalone_tight.isPOGApproved=cms.untracked.bool(<true>)<line_sep>
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. """ Implementation of the performance instrumentation report. """<import_stmt>json<import_stmt>numpy<as>np<import_stmt>re<class_stmt>InstrumentationReport(object)<block_start>@staticmethod<def_stmt>get_event_uuid event<block_start>uuid=(-1 -1 -1)<if_stmt>'args'<in>event<block_start>args=event['args']<if_stmt>'sdfg_id'<in>args<and>args['sdfg_id']<is><not><none><block_start>uuid=(args['sdfg_id'] -1 -1)<if_stmt>'state_id'<in>args<and>args['state_id']<is><not><none><block_start>uuid=(uuid[0] args['state_id'] -1)<if_stmt>'id'<in>args<and>args['id']<is><not><none><block_start>uuid=(uuid[0] uuid[1] args['id'])<block_end><block_end><block_end><block_end><return>uuid<block_end><def_stmt>__init__ self filename:str# Parse file <block_start>match=re.match(r'.*report-(\d+)\.json' filename)<line_sep>self.name=match.groups()[0]<if>match<is><not><none><else>'N/A'<line_sep>self.durations={}<line_sep>self.counters={}<line_sep>self._sortcat=<none><line_sep>self._sortdesc=<false><with_stmt>open(filename 'r')<as>fp<block_start>report=json.load(fp)<if_stmt>'traceEvents'<not><in>report<or>'sdfgHash'<not><in>report<block_start>print(filename 'is not a valid SDFG instrumentation report!')<line_sep><return><block_end>self.sdfg_hash=report['sdfgHash']<line_sep>events=report['traceEvents']<for_stmt>event events<block_start><if_stmt>'ph'<in>event<block_start>phase=event['ph']<line_sep>name=event['name']<if_stmt>phase<eq>'X'<block_start>uuid=self.get_event_uuid(event)<if_stmt>uuid<not><in>self.durations<block_start>self.durations[uuid]={}<block_end><if_stmt>name<not><in>self.durations[uuid]<block_start>self.durations[uuid][name]=[]<block_end>self.durations[uuid][name].append(event['dur']/1000)<block_end><if_stmt>phase<eq>'C'<block_start><if_stmt>name<not><in>self.counters<block_start>self.counters[name]=0<block_end>self.counters[name]<augadd>event['args'][name]<block_end><block_end><block_end><block_end><block_end><def_stmt>__repr__ self<block_start><return>'InstrumentationReport(name=%s)'%self.name<block_end><def_stmt>sortby self column:str ascending:bool=<false><block_start><if_stmt>(column<and>column.lower()<not><in>('counter' 'value' 'min' 'max' 'mean' 'median'))<block_start><raise>ValueError('Only Counter, Value, Min, Max, Mean, Median are '<concat>'supported')<block_end>self._sortcat=column<if>column<is><none><else>column.lower()<line_sep>self._sortdesc=<not>ascending<block_end><def_stmt>_get_runtimes_string self label runtimes element sdfg state string row_format colw with_element_heading=<true><block_start>indent=''<if_stmt>len(runtimes)<g>0<block_start>element_label=''<if_stmt>element[0]<g>-1<and>element[1]<g>-1<and>element[2]<g>-1# This element is a node. <block_start><if_stmt>sdfg<ne>element[0]# No parent SDFG row present yet, print it. <block_start>string<augadd>row_format.format('SDFG ('+str(element[0])+')' '' '' '' '' width=colw)<block_end>sdfg=element[0]<if_stmt>state<ne>element[1]# No parent state row present yet, print it. <block_start>string<augadd>row_format.format('|-State ('+str(element[1])+')' '' '' '' '' width=colw)<block_end>state=element[1]<line_sep>element_label='| |-Node ('+str(element[2])+')'<line_sep>indent='| | |'<block_end><elif_stmt>element[0]<g>-1<and>element[1]<g>-1# This element is a state. <block_start><if_stmt>sdfg<ne>element[0]# No parent SDFG row present yet, print it. <block_start>string<augadd>row_format.format('SDFG ('+str(element[0])+')' '' '' '' '' width=colw)<block_end>sdfg=element[0]<line_sep>state=element[1]<line_sep>element_label='|-State ('+str(element[1])+')'<line_sep>indent='| |'<block_end><elif_stmt>element[0]<g>-1# This element is an SDFG. <block_start>sdfg=element[0]<line_sep>state=-1<line_sep>element_label='SDFG ('+str(element[0])+')'<line_sep>indent='|'<block_end><else_stmt><block_start>element_label='N/A'<block_end><if_stmt>with_element_heading<block_start>string<augadd>row_format.format(element_label '' '' '' '' width=colw)<block_end>string<augadd>row_format.format(indent+label+':' '' '' '' '' width=colw)<line_sep>string<augadd>row_format.format(indent '%.3f'%np.min(runtimes) '%.3f'%np.mean(runtimes) '%.3f'%np.median(runtimes) '%.3f'%np.max(runtimes) width=colw)<block_end><return>string sdfg state<block_end><def_stmt>getkey self element<block_start>events=self.durations[element]<line_sep>result=[]<for_stmt>event events.keys()<block_start>runtimes=events[event]<line_sep>result.extend(runtimes)<block_end>result=np.array(result)<if_stmt>self._sortcat<eq>'min'<block_start><return>np.min(result)<block_end><elif_stmt>self._sortcat<eq>'max'<block_start><return>np.max(result)<block_end><elif_stmt>self._sortcat<eq>'mean'<block_start><return>np.mean(result)<block_end><else_stmt># if self._sortcat == 'median': <block_start><return>np.median(result)<block_end><block_end><def_stmt>__str__ self<block_start>COLW=15<line_sep>COUNTER_COLW=39<line_sep>element_list=list(self.durations.keys())<line_sep>element_list.sort()<line_sep>row_format=('{:<{width}}'<times>5)+'\n'<line_sep>counter_format=('{:<{width}}'<times>2)+'\n'<line_sep>string='Instrumentation report\n'<line_sep>string<augadd>'SDFG Hash: '+self.sdfg_hash+'\n'<if_stmt>len(self.durations)<g>0<block_start>string<augadd>('-'<times>(COLW<times>5))+'\n'<line_sep>string<augadd>('{:<{width}}'<times>2).format('Element' 'Runtime (ms)' width=COLW)+'\n'<line_sep>string<augadd>row_format.format('' 'Min' 'Mean' 'Median' 'Max' width=COLW)<line_sep>string<augadd>('-'<times>(COLW<times>5))+'\n'<line_sep>sdfg=-1<line_sep>state=-1<if_stmt>self._sortcat<in>('min' 'mean' 'median' 'max')<block_start>element_list=sorted(element_list key=self.getkey reverse=self._sortdesc)<block_end><for_stmt>element element_list<block_start>events=self.durations[element]<if_stmt>len(events)<g>0<block_start>with_element_heading=<true><for_stmt>event events.keys()<block_start>runtimes=events[event]<line_sep>string,sdfg,state=self._get_runtimes_string(event runtimes element sdfg state string row_format COLW with_element_heading)<line_sep>with_element_heading=<false><block_end><block_end><block_end>string<augadd>('-'<times>(COLW<times>5))+'\n'<block_end><if_stmt>len(self.counters)<g>0<block_start>string<augadd>('-'<times>(COUNTER_COLW<times>2))+'\n'<line_sep>string<augadd>('{:<{width}}'<times>2).format('Counter' 'Value' width=COUNTER_COLW)+'\n'<line_sep>string<augadd>('-'<times>(COUNTER_COLW<times>2))+'\n'<if_stmt>self._sortcat<eq>'value'<block_start>counter_list=sorted(self.counters key=<lambda>k:self.counters[k] reverse=self._sortdesc)<block_end><elif_stmt>self._sortcat<eq>'counter'<block_start>counter_list=sorted(self.counters.keys() reverse=self._sortdesc)<block_end><else_stmt><block_start>counter_list=self.counters.keys()<block_end><for_stmt>counter counter_list<block_start>string<augadd>counter_format.format(counter self.counters[counter] width=COUNTER_COLW)<block_end>string<augadd>('-'<times>(COUNTER_COLW<times>2))+'\n'<block_end><return>string<block_end><block_end>
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # # Copyright 2021 The NiPreps Developers <<EMAIL>> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # We support and encourage derived works from this project, please read # about our expectations at # # https://www.nipreps.org/community/licensing/ # """Utilities: Jinja2 templates."""<import_from_stmt>io open# pylint: disable=W0622 <import_stmt>jinja2<import_from_stmt>pkg_resources resource_filename<as>pkgrf<class_stmt>Template(object)<block_start>""" Utility class for generating a config file from a jinja template. https://github.com/oesteban/endofday/blob/f2e79c625d648ef45b08cc1f11fd0bd84342d604/endofday/core/template.py """<def_stmt>__init__ self template_str<block_start>self.template_str=template_str<line_sep>self.env=jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="/") trim_blocks=<true> lstrip_blocks=<true> )<block_end><def_stmt>compile self configs<block_start>"""Generates a string with the replacements"""<line_sep>template=self.env.get_template(self.template_str)<line_sep><return>template.render(configs)<block_end><def_stmt>generate_conf self configs path<block_start>"""Saves the oucome after replacement on the template to file"""<line_sep>output=self.compile(configs)<with_stmt>open(path "w+")<as>output_file<block_start>output_file.write(output)<block_end><block_end><block_end><class_stmt>IndividualTemplate(Template)<block_start>"""Specific template for the individual report"""<def_stmt>__init__ self<block_start>super(IndividualTemplate self).__init__(pkgrf("mriqc" "data/reports/individual.html"))<block_end><block_end><class_stmt>GroupTemplate(Template)<block_start>"""Specific template for the individual report"""<def_stmt>__init__ self<block_start>super(GroupTemplate self).__init__(pkgrf("mriqc" "data/reports/group.html"))<block_end><block_end>
# Common Segmentation Operator implemented by Pytorch # XiangtaiLi(<EMAIL>) <import_stmt>torch<import_stmt>torch.nn<as>nn<import_stmt>torch.nn.functional<as>F<import_from_stmt>torch.nn BatchNorm2d<line_sep>upsample=<lambda>x size:F.interpolate(x size mode='bilinear' align_corners=<true>)<def_stmt>conv3x3 in_planes out_planes stride=1<block_start>"""3x3 convolution with padding"""<line_sep><return>nn.Conv2d(in_planes out_planes kernel_size=3 stride=stride padding=1 bias=<false>)<block_end><class_stmt>GlobalAvgPool2d(nn.Module)<block_start><def_stmt>__init__ self<block_start>"""Global average pooling over the input's spatial dimensions"""<line_sep>super(GlobalAvgPool2d self).__init__()<block_end><def_stmt>forward self inputs<block_start>in_size=inputs.size()<line_sep>inputs=inputs.view((in_size[0] in_size[1] -1)).mean(dim=2)<line_sep>inputs=inputs.view(in_size[0] in_size[1] 1 1)<line_sep><return>inputs<block_end><block_end><class_stmt>SELayer(nn.Module)<block_start><def_stmt>__init__ self in_planes out_planes reduction=16<block_start>super(SELayer self).__init__()<line_sep>self.avg_pool=nn.AdaptiveAvgPool2d(1)<line_sep>self.fc=nn.Sequential(nn.Linear(in_planes out_planes<floordiv>reduction) nn.ReLU(inplace=<true>) nn.Linear(out_planes<floordiv>reduction out_planes) nn.Sigmoid())<line_sep>self.out_planes=out_planes<block_end><def_stmt>forward self x<block_start>b,c,_,_=x.size()<line_sep>y=self.avg_pool(x).view(b c)<line_sep>y=self.fc(y).view(b self.out_planes 1 1)<line_sep><return>y<block_end><block_end><class_stmt>ConvBnRelu(nn.Module)<block_start><def_stmt>__init__ self in_planes out_planes ksize stride=1 pad=0 dilation=1 groups=1 has_bn=<true> norm_layer=nn.BatchNorm2d bn_eps=1e-5 has_relu=<true> inplace=<true> has_bias=<false><block_start>super(ConvBnRelu self).__init__()<line_sep>self.conv=nn.Conv2d(in_planes out_planes kernel_size=ksize stride=stride padding=pad dilation=dilation groups=groups bias=has_bias)<line_sep>self.has_bn=has_bn<if_stmt>self.has_bn<block_start>self.bn=norm_layer(out_planes eps=bn_eps)<block_end>self.has_relu=has_relu<if_stmt>self.has_relu<block_start>self.relu=nn.ReLU(inplace=inplace)<block_end><block_end><def_stmt>forward self x<block_start>x=self.conv(x)<if_stmt>self.has_bn<block_start>x=self.bn(x)<block_end><if_stmt>self.has_relu<block_start>x=self.relu(x)<block_end><return>x<block_end><block_end><def_stmt>dsn in_channels nclass norm_layer=nn.BatchNorm2d<block_start><return>nn.Sequential(nn.Conv2d(in_channels in_channels kernel_size=3 stride=1 padding=1) norm_layer(in_channels) nn.ReLU() nn.Dropout2d(0.1) nn.Conv2d(in_channels nclass kernel_size=1 stride=1 padding=0 bias=<true>))<block_end><class_stmt>SeparableConv2d(nn.Module)<block_start><def_stmt>__init__ self in_channels out_channels kernel_size=3 stride=1 dilation=1 bias=<false> norm_layer=<none><block_start>super(SeparableConv2d self).__init__()<line_sep>self.kernel_size=kernel_size<line_sep>self.dilation=dilation<line_sep>self.conv1=nn.Conv2d(in_channels in_channels kernel_size stride 0 dilation groups=in_channels bias=bias)<line_sep>self.bn=norm_layer(in_channels)<line_sep>self.pointwise=nn.Conv2d(in_channels out_channels 1 bias=bias)<block_end><def_stmt>forward self x<block_start>x=self.fix_padding(x self.kernel_size self.dilation)<line_sep>x=self.conv1(x)<line_sep>x=self.bn(x)<line_sep>x=self.pointwise(x)<line_sep><return>x<block_end><def_stmt>fix_padding self x kernel_size dilation<block_start>kernel_size_effective=kernel_size+(kernel_size-1)<times>(dilation-1)<line_sep>pad_total=kernel_size_effective-1<line_sep>pad_beg=pad_total<floordiv>2<line_sep>pad_end=pad_total-pad_beg<line_sep>padded_inputs=F.pad(x (pad_beg pad_end pad_beg pad_end))<line_sep><return>padded_inputs<block_end><block_end><class_stmt>ASPPModule(nn.Module)<block_start>""" Reference: Chen, Liang-Chieh, et al. *"Rethinking Atrous Convolution for Semantic Image Segmentation."* """<def_stmt>__init__ self features inner_features=256 out_features=512 dilations=(12 24 36) norm_layer=nn.BatchNorm2d<block_start>super(ASPPModule self).__init__()<line_sep>self.conv1=nn.Sequential(nn.AdaptiveAvgPool2d((1 1)) nn.Conv2d(features inner_features kernel_size=1 padding=0 dilation=1 bias=<false>) norm_layer(inner_features) nn.ReLU())<line_sep>self.conv2=nn.Sequential(nn.Conv2d(features inner_features kernel_size=1 padding=0 dilation=1 bias=<false>) norm_layer(inner_features) nn.ReLU())<line_sep>self.conv3=nn.Sequential(nn.Conv2d(features inner_features kernel_size=3 padding=dilations[0] dilation=dilations[0] bias=<false>) norm_layer(inner_features) nn.ReLU())<line_sep>self.conv4=nn.Sequential(nn.Conv2d(features inner_features kernel_size=3 padding=dilations[1] dilation=dilations[1] bias=<false>) norm_layer(inner_features) nn.ReLU())<line_sep>self.conv5=nn.Sequential(nn.Conv2d(features inner_features kernel_size=3 padding=dilations[2] dilation=dilations[2] bias=<false>) norm_layer(inner_features) nn.ReLU())<line_sep>self.bottleneck=nn.Sequential(nn.Conv2d(inner_features<times>5 out_features kernel_size=1 padding=0 dilation=1 bias=<false>) norm_layer(out_features) nn.ReLU() nn.Dropout2d(0.1))<block_end><def_stmt>forward self x<block_start>_,_,h,w=x.size()<line_sep>feat1=F.upsample(self.conv1(x) size=(h w) mode='bilinear' align_corners=<true>)<line_sep>feat2=self.conv2(x)<line_sep>feat3=self.conv3(x)<line_sep>feat4=self.conv4(x)<line_sep>feat5=self.conv5(x)<line_sep>out=torch.cat((feat1 feat2 feat3 feat4 feat5) 1)<line_sep>bottle=self.bottleneck(out)<line_sep><return>bottle<block_end><block_end><class_stmt>A2Block(nn.Module)<block_start>""" Implementation of A2Block(NIPS 2018) """<def_stmt>__init__ self inplane plane<block_start>super(A2Block self).__init__()<line_sep>self.down=nn.Conv2d(inplane plane 1)<line_sep>self.up=nn.Conv2d(plane inplane 1)<line_sep>self.gather_down=nn.Conv2d(inplane plane 1)<line_sep>self.distribue_down=nn.Conv2d(inplane plane 1)<line_sep>self.softmax=nn.Softmax(dim=-1)<block_end><def_stmt>forward self x<block_start>res=x<line_sep>A=self.down(res)<line_sep>B=self.gather_down(res)<line_sep>b,c,h,w=A.size()<line_sep>A=A.view(b c -1)# (b, c, h*w) B=B.view(b c -1)# (b, c, h*w) B=self.softmax(B)<line_sep>B=B.permute(0 2 1)# (b, h*w, c) G=torch.bmm(A B)# (b,c,c) C=self.distribue_down(res)<line_sep>C=C.view(b c -1)# (b, c, h*w) C=self.softmax(C)<line_sep>C=C.permute(0 2 1)# (b, h*w, c) atten=torch.bmm(C G)# (b, h*w, c) atten=atten.permute(0 2 1).view(b c h -1)<line_sep>atten=self.up(atten)<line_sep>out=res+atten<line_sep><return>out<block_end><block_end><class_stmt>PSPModule(nn.Module)<block_start>""" Reference: Zhao, Hengshuang, et al. *"Pyramid scene parsing network."* """<def_stmt>__init__ self features out_features=512 sizes=(1 2 3 6) norm_layer=BatchNorm2d<block_start>super(PSPModule self).__init__()<line_sep>self.stages=[]<line_sep>self.stages=nn.ModuleList([self._make_stage(features out_features size norm_layer)<for>size sizes])<line_sep>self.bottleneck=nn.Sequential(nn.Conv2d(features+len(sizes)<times>out_features out_features kernel_size=1 padding=1 dilation=1 bias=<false>) norm_layer(out_features) nn.ReLU() nn.Dropout2d(0.1))<block_end><def_stmt>_make_stage self features out_features size norm_layer<block_start>prior=nn.AdaptiveAvgPool2d(output_size=(size size))<line_sep>conv=nn.Conv2d(features out_features kernel_size=1 bias=<false>)<line_sep>bn=norm_layer(out_features)<line_sep><return>nn.Sequential(prior conv bn)<block_end><def_stmt>forward self feats<block_start>h,w=feats.size(2) feats.size(3)<line_sep>priors=[F.upsample(input=stage(feats) size=(h w) mode='bilinear' align_corners=<true>)<for>stage self.stages]+[feats]<line_sep>bottle=self.bottleneck(torch.cat(priors 1))<line_sep><return>bottle<block_end><block_end># For BiSeNet <class_stmt>AttentionRefinement(nn.Module)<block_start><def_stmt>__init__ self in_planes out_planes norm_layer=nn.BatchNorm2d<block_start>super(AttentionRefinement self).__init__()<line_sep>self.conv_3x3=ConvBnRelu(in_planes out_planes 3 1 1 has_bn=<true> norm_layer=norm_layer has_relu=<true> has_bias=<false>)<line_sep>self.channel_attention=nn.Sequential(nn.AdaptiveAvgPool2d(1) ConvBnRelu(out_planes out_planes 1 1 0 has_bn=<true> norm_layer=norm_layer has_relu=<false> has_bias=<false>) nn.Sigmoid())<block_end><def_stmt>forward self x<block_start>fm=self.conv_3x3(x)<line_sep>fm_se=self.channel_attention(fm)<line_sep>fm=fm<times>fm_se<line_sep><return>fm<block_end><block_end># For BiSeNet <class_stmt>FeatureFusion(nn.Module)<block_start><def_stmt>__init__ self in_planes out_planes reduction=1 norm_layer=nn.BatchNorm2d<block_start>super(FeatureFusion self).__init__()<line_sep>self.conv_1x1=ConvBnRelu(in_planes out_planes 1 1 0 has_bn=<true> norm_layer=norm_layer has_relu=<true> has_bias=<false>)<line_sep>self.channel_attention=nn.Sequential(nn.AdaptiveAvgPool2d(1) ConvBnRelu(out_planes out_planes<floordiv>reduction 1 1 0 has_bn=<false> norm_layer=norm_layer has_relu=<true> has_bias=<false>) ConvBnRelu(out_planes<floordiv>reduction out_planes 1 1 0 has_bn=<false> norm_layer=norm_layer has_relu=<false> has_bias=<false>) nn.Sigmoid())<block_end><def_stmt>forward self x1 x2<block_start>fm=torch.cat([x1 x2] dim=1)<line_sep>fm=self.conv_1x1(fm)<line_sep>fm_se=self.channel_attention(fm)<line_sep>output=fm+fm<times>fm_se<line_sep><return>output<block_end><block_end>
<import_from_stmt>matplotlib.image imread<import_stmt>matplotlib.pyplot<as>plt<import_from_stmt>math sqrt<import_stmt>math<import_stmt>random<import_stmt>numpy<import_stmt>operator<import_from_stmt>scipy.spatial.distance cdist<import_from_stmt>scipy.linalg norm<import_stmt>datetime<def_stmt>Histogram path<block_start>image=imread(path)<if_stmt>len(image.shape)<ne>2<block_start><def_stmt>gray rgb<block_start><return>numpy.dot(rgb[<ellipsis> :3] [0.2989 0.5870 0.1140])<block_end>gray=gray(image)<line_sep>image=gray<block_end>hist,bins=numpy.histogram(image.ravel() 256 [0 256])<line_sep><return>adapt(hist)<block_end>
"""Codesign."""<import_stmt>re<import_stmt>subprocess<import_from_stmt>os remove<import_from_stmt>pathlib Path PurePath<import_from_stmt>tempfile gettempdir<def_stmt>_xxd blob<block_start>"""XXD"""<line_sep>result=<none><line_sep># Note, this requires input passed in via 'stdin', so include 'stdin' for piping input. _cmd=['/usr/bin/xxd' '-r' '-p']<line_sep>_p=subprocess.Popen(_cmd stdin=subprocess.PIPE stdout=subprocess.PIPE stderr=subprocess.PIPE)<line_sep>_p.stdin.write(blob)<line_sep>_r,_e=_p.communicate()<if_stmt>_p.returncode<eq>0<and>_r<block_start>result=_r<block_end><elif_stmt>_p.returncode<ne>0<and>_e<block_start>result=_e<block_end><return>result<block_end><def_stmt>csreq blob<block_start>"""csreq"""<line_sep>result=<none><line_sep># Note, this requires input passed in via 'stdin', so include 'stdin' for piping input. _cmd=['/usr/bin/csreq' '-vvv' '-r' '-' '-t']<line_sep>_p=subprocess.Popen(_cmd stdin=subprocess.PIPE stdout=subprocess.PIPE stderr=subprocess.PIPE)<line_sep>_p.stdin.write(_xxd(blob))<line_sep>_r,_e=_p.communicate()<if_stmt>_r<and>isinstance(_r bytes)<block_start>_r=_r.decode('utf-8').strip()<block_end><if_stmt>_e<and>isinstance(_e bytes)<block_start>_e=_e.decode('utf-8').strip()<block_end><if_stmt>_p.returncode<eq>0<and>_r<block_start>result=_r<block_end><elif_stmt>_p.returncode<ne>0<and>_e<block_start>result=_e<block_end><return>result<block_end><def_stmt>detached_signature path<block_start>"""Codesign using a detached signature."""<line_sep>result=<none><line_sep>_tmp=gettempdir()<line_sep>_path_sig='{}.sig'.format(PurePath(path).name)<line_sep>_sig_file=Path(_tmp)/_path_sig<line_sep>_cmd=['/usr/bin/codesign' '--detached' str(_sig_file) '-s' '-' path]<line_sep>_p=subprocess.Popen(_cmd stdout=subprocess.PIPE stderr=subprocess.PIPE)<line_sep>_r,_e=_p.communicate()<if_stmt>_r<and>isinstance(_r bytes)<block_start>_r=_r.decode('utf-8')<block_end><if_stmt>_e<and>isinstance(_e bytes)<block_start>_e=_e.decode('utf-8')<block_end><if_stmt>_p.returncode<eq>0<block_start>result=requirements(path detached_sig=_sig_file)<if_stmt>result<block_start>remove(str(_sig_file))<block_end><block_end><return>result<block_end><def_stmt>requirements path detached_sig=<none> apple_event=<false><block_start>"""Codesign."""<line_sep>result=dict()<line_sep># Change the dict keys if this is an AppleEvent style requirement <if_stmt>apple_event<block_start>_id_key='apple_events_identifier'<line_sep>_id_type_key='apple_events_identifier_type'<line_sep>_csreq_key='apple_events_csreq'<block_end><else_stmt><block_start>_id_key='identifier'<line_sep>_id_type_key='identifier_type'<line_sep>_csreq_key='csreq'<block_end># Lines with useful output start with these strings _dsgn_prefix='designated => '<line_sep>_idnt_prefix='Identifier='<line_sep># Bundle ID regex test string _bnid_regex=re.compile(r'^\w+\.')<if_stmt><not>detached_sig<block_start>_cmd=['/usr/bin/codesign' '-v' '-dr' '-' path]<block_end><elif_stmt>detached_sig<block_start>_cmd=['/usr/bin/codesign' '-vvv' '-d' '-r' '-' '--detached' detached_sig path]<block_end>_p=subprocess.Popen(_cmd stdout=subprocess.PIPE stderr=subprocess.PIPE)<line_sep>_r,_e=_p.communicate()<if_stmt>_r<and>isinstance(_r bytes)<block_start>_r=_r.decode('utf-8')<block_end><if_stmt>_e<and>isinstance(_e bytes)<block_start>_e=_e.decode('utf-8')<block_end><if_stmt>_p.returncode<eq>0# Extract the code signature from the result. Handle circumstances # where the output may not explicitly start with 'designated => ' # and where the code signature is split across multiple lines. <block_start><for_stmt>_line _r.splitlines()<block_start><if_stmt>_dsgn_prefix<in>_line<block_start>_res=_line.partition(_dsgn_prefix)<line_sep>_res=_res[_res.index(_dsgn_prefix)+1:][0]<line_sep>result[_csreq_key]=_res<block_end><block_end><for_stmt>_line _e.splitlines()<block_start><if_stmt>_line.startswith(_idnt_prefix)<block_start><if_stmt>_idnt_prefix<in>_line<block_start>result[_id_key]=_line.replace(_idnt_prefix '')<line_sep>result[_id_type_key]='bundleID'<line_sep># Test to make sure that the bundle ID matches # expected style of 'org.example.foo'. This is # not a terribly strict test, but it is aimed to # avoid scenarios like the 'python3' binary # deep in the framework has an identifier value # of 'python3'. <if_stmt><not>re.match(_bnid_regex result[_id_key])<block_start>result[_id_key]=path<line_sep>result[_id_type_key]='path'<block_end><block_end><block_end><block_end><block_end><elif_stmt>_p.returncode<eq>1<and>'not signed'<in>_e<block_start>result[_csreq_key]=<none><line_sep>result[_id_key]=<none><line_sep>result[_id_type_key]=<none><block_end>result['is_signed']=result.get('csreq' <none>)<is><not><none><line_sep><return>result<block_end>
""" top-level interface methods so user doesn't need to directly construct a dbsession """<import_stmt>debug_session<line_sep># default session _dbsession=<none><def_stmt>debug evals feed_dict=<none> breakpoints=<none> break_immediately=<false> session=<none><block_start>""" spawns a new debug session """<line_sep><global>_dbsession<line_sep>_dbsession=debug_session.DebugSession(session)<line_sep><return>_dbsession.run(evals feed_dict breakpoints break_immediately)<block_end><def_stmt>s <block_start>""" step to the next node in the execution order """<line_sep><global>_dbsession<line_sep><return>_dbsession.s()<block_end><def_stmt>c <block_start>""" continue """<line_sep><global>_dbsession<line_sep><return>_dbsession.c()<block_end><def_stmt>get_exe_queue <block_start><global>_dbsession<line_sep><return>_dbsession.get_exe_queue()<block_end><def_stmt>get_value node<block_start><global>_dbsession<line_sep><return>_dbsession.get_value(node)<block_end>
<import_from_stmt>.generic_wrappers *# NOQA <import_from_stmt>.lambda_wrappers action_lambda_v1 observation_lambda_v0 reward_lambda_v0# NOQA <import_from_stmt>.multiagent_wrappers agent_indicator_v0 black_death_v2 pad_action_space_v0 pad_observations_v0<line_sep># NOQA <import_from_stmt>supersuit.generic_wrappers frame_skip_v0 color_reduction_v0 resize_v0 dtype_v0 flatten_v0 reshape_v0 normalize_obs_v0 clip_actions_v0 clip_reward_v0 delay_observations_v0 frame_stack_v1 max_observation_v0 sticky_actions_v0<line_sep># NOQA <import_from_stmt>.vector.vector_constructors gym_vec_env_v0 stable_baselines_vec_env_v0 stable_baselines3_vec_env_v0 concat_vec_envs_v1 pettingzoo_env_to_vec_env_v1<line_sep># NOQA <import_from_stmt>.aec_vector vectorize_aec_env_v0# NOQA <class_stmt>DeprecatedWrapper(ImportError)<block_start><pass><block_end><def_stmt>__getattr__ wrapper_name<block_start>""" Gives error that looks like this when trying to import old version of wrapper: File "./supersuit/__init__.py", line 38, in __getattr__ raise DeprecatedWrapper(f"{base}{version_num} is now deprecated, use {base}{act_version_num} instead") supersuit.DeprecatedWrapper: concat_vec_envs_v0 is now deprecated, use concat_vec_envs_v1 instead """<line_sep>start_v=wrapper_name.rfind("_v")+2<line_sep>version=wrapper_name[start_v:]<line_sep>base=wrapper_name[:start_v]<try_stmt><block_start>version_num=int(version)<line_sep>is_valid_version=<true><block_end><except_stmt>ValueError<block_start>is_valid_version=<false><block_end>globs=globals()<if_stmt>is_valid_version<block_start><for_stmt>act_version_num range(1000)<block_start><if_stmt>f"{base}{act_version_num}"<in>globs<block_start><if_stmt>version_num<l>act_version_num<block_start><raise>DeprecatedWrapper(f"{base}{version_num} is now deprecated, use {base}{act_version_num} instead")<block_end><block_end><block_end><block_end><raise>ImportError(f"cannot import name '{wrapper_name}' from 'supersuit'")<block_end>__version__="3.3.2"<line_sep>
# (c) 2012-2019, Ansible by Red Hat # # This file is part of Ansible Galaxy # # Ansible Galaxy is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by # the Apache Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Ansible Galaxy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # Apache License for more details. # # You should have received a copy of the Apache License # along with Galaxy. If not, see <http://www.apache.org/licenses/>. <import_stmt>rq.job<import_from_stmt>django.db models<import_from_stmt>django.contrib.postgres fields<as>psql_fields<import_from_stmt>pulpcore.app models<as>pulp_models<class_stmt>Task(models.Model)<block_start>""" Generic table for handing tasks. :var params: Task parameters json dictionary :var result: Task result json dictionary """<line_sep>params=psql_fields.JSONField(null=<true>)<line_sep>result=psql_fields.JSONField(null=<true>)<line_sep>pulp_task=models.OneToOneField(pulp_models.Task on_delete=models.CASCADE related_name='galaxy_task')<line_sep>@property<def_stmt>job_id self<block_start><return>self.pulp_task.job_id<block_end>@property<def_stmt>state self<block_start><return>self.pulp_task.state<block_end>@property<def_stmt>started_at self<block_start><return>self.pulp_task.started_at<block_end>@property<def_stmt>finished_at self<block_start><return>self.pulp_task.finished_at<block_end>@property<def_stmt>warnings self<block_start><return>self.pulp_task.non_fatal_errors<block_end>@property<def_stmt>error self<block_start><return>self.pulp_task.error<block_end>@classmethod<def_stmt>current cls<block_start>job=rq.job.get_current_job()<if_stmt>job<is><none><block_start><raise>RuntimeError('This function is called outside of task context.')<block_end><return>cls.objects.get(pulp_task__job_id=job.id)<block_end><block_end>
<import_from_stmt>._version __version__# noqa: F401, E402 <import_from_stmt>.lazy LazyGraph LazyNode node# noqa: F401, E402 <import_from_stmt>.streaming *# noqa: F401, F403, E402 <import_from_stmt>.utils LazyToStreaming# noqa: F401, E402
<import_stmt>os<try_stmt><block_start>basestring<block_end><except_stmt>NameError<block_start>basestring=str<block_end><class_stmt>ListenImports<block_start>ROBOT_LISTENER_API_VERSION=2<def_stmt>__init__ self imports<block_start>self.imports=open(imports 'w')<block_end><def_stmt>library_import self name attrs<block_start>self._imported("Library" name attrs)<block_end><def_stmt>resource_import self name attrs<block_start>self._imported("Resource" name attrs)<block_end><def_stmt>variables_import self name attrs<block_start>self._imported("Variables" name attrs)<block_end><def_stmt>_imported self import_type name attrs<block_start>self.imports.write("Imported %s\n\tname: %s\n"%(import_type name))<for_stmt>name sorted(attrs)<block_start>self.imports.write("\t%s: %s\n"%(name self._pretty(attrs[name])))<block_end><block_end><def_stmt>_pretty self entry<block_start><if_stmt>isinstance(entry list)<block_start><return>'[%s]'%', '.join(entry)<block_end><if_stmt>isinstance(entry basestring)<and>os.path.isabs(entry)<block_start>entry=entry.replace('$py.class' '.py').replace('.pyc' '.py')<line_sep>tokens=entry.split(os.sep)<line_sep>index=-1<if>tokens[-1]<ne>'__init__.py'<else>-2<line_sep><return>'//'+'/'.join(tokens[index:])<block_end><return>entry<block_end><def_stmt>close self<block_start>self.imports.close()<block_end><block_end>
<import_stmt>sys<import_stmt>l_bp<import_from_stmt>exceptions MissingProbabilitiesException<class_stmt>BreakpointInterval(object)<block_start>''' Class for storing the range and probability distribution of a breakpoint '''<line_sep># Constant value for slop padding SLOP_PROB=1e-100<def_stmt>__init__ self chrom start end p<block_start>self.chrom=chrom<line_sep>self.start=start<line_sep>self.end=end<line_sep>self.p=p<block_end><def_stmt>pad_slop self percent_slop fixed_slop<block_start>''' Add slop to the interval '''<line_sep>slop=int(max(percent_slop<times>(self.end-self.start+1) fixed_slop))<line_sep>self.start<augsub>slop<line_sep>self.end<augadd>slop<line_sep>self.p=[BreakpointInterval.SLOP_PROB]<times>slop+self.p+[BreakpointInterval.SLOP_PROB]<times>slop<line_sep>self._trim()<line_sep>self._normalize()<block_end><def_stmt>_trim self<block_start>''' Trim any part of range past the beginning of the chromosome '''<if_stmt>self.start<l>0<block_start>self.p=self.p[-self.start:]<line_sep>self.start=0<block_end><block_end><def_stmt>_normalize self<block_start>''' Normalize interval's probability to sum to 1 '''<line_sep>sum_p=sum(self.p)<line_sep>self.p=[float(x)/sum_p<for>x self.p]<block_end><def_stmt>common_range self other<block_start><return>max(self.start other.start) min(self.end other.end)<block_end><def_stmt>overlap_prob self other c_start c_len<block_start>start_off=c_start-self.start<line_sep>other_start_off=c_start-other.start<line_sep>ovl=0<for_stmt>i range(c_len)<block_start>ovl<augadd>min(self.p[i+start_off] other.p[i+other_start_off])<block_end><return>ovl<block_end><block_end><class_stmt>Breakpoint(object)<block_start>''' Class for storing information about Breakpoints for merging '''<def_stmt>__init__ self line percent_slop=0 fixed_slop=0<block_start>''' Initialize with slop for probabilities '''<line_sep>self.l=line<line_sep>(self.sv_type chr_l chr_r self.strands start_l end_l start_r end_r m)=l_bp.split_v(line)<try_stmt><block_start>self.left=BreakpointInterval(chr_l start_l end_l self.floats_from_tag(m 'PRPOS'))<line_sep>self.right=BreakpointInterval(chr_r start_r end_r self.floats_from_tag(m 'PREND'))<block_end><except_stmt>RuntimeError<as>e<block_start><raise>MissingProbabilitiesException(str(e))<block_end><if_stmt>((percent_slop<g>0)<or>(fixed_slop<g>0))<block_start>self.left.pad_slop(percent_slop fixed_slop)<line_sep>self.right.pad_slop(percent_slop fixed_slop)<block_end><block_end><def_stmt>__str__ self<block_start>''' Convert back to a string '''<line_sep><return>'\t'.join([str(x)<for>x [self.left.chrom self.left.start self.left.end self.right.chrom self.right.start self.right.end self.sv_type self.strands self.left.p self.right.p]])<block_end><def_stmt>ovl self b<block_start>''' Calculate overlapping cumulative probability value as weight? 0 if not overlapping. '''<if_stmt>((self.left.chrom<ne>b.left.chrom)<or>(self.right.chrom<ne>b.right.chrom)<or>(self.sv_type<ne>b.sv_type))<block_start><return>0<block_end>#get common intervals c_start_l,c_end_l=self.left.common_range(b.left)<line_sep>c_start_r,c_end_r=self.right.common_range(b.right)<line_sep>c_l_len=c_end_l-c_start_l+1<line_sep>c_r_len=c_end_r-c_start_r+1<if_stmt>(c_l_len<l>1)<or>(c_r_len<l>1)<block_start><return>0<block_end>ovl_l=self.left.overlap_prob(b.left c_start_l c_l_len)<line_sep>ovl_r=self.right.overlap_prob(b.right c_start_r c_r_len)<line_sep><return>ovl_l<times>ovl_r<block_end>@staticmethod<def_stmt>floats_from_tag info_dict tag<block_start><if_stmt>tag<in>info_dict<block_start><return>[float(x)<for>x info_dict[tag].split(',')]<block_end><else_stmt><block_start><raise>RuntimeError('Required tag {0} not found.'.format(tag))<block_end><block_end><block_end>
<import_from_stmt>pybrain.structure.connections.full FullConnection<import_from_stmt>pybrain.structure.connections.identity IdentityConnection<import_from_stmt>pybrain.structure.connections.shared SharedFullConnection MotherConnection SharedConnection<import_from_stmt>pybrain.structure.connections.linear LinearConnection<import_from_stmt>pybrain.structure.connections.fullnotself FullNotSelfConnection<line_sep>
<import_from_stmt>dataclasses dataclass field<import_from_stmt>apischema alias deserialize serialize<import_from_stmt>apischema.json_schema deserialization_schema<line_sep>@dataclass<class_stmt>Foo<block_start>class_:str=field(metadata=alias("class"))<block_end><assert_stmt>deserialization_schema(Foo)<eq>{"$schema":"http://json-schema.org/draft/2020-12/schema#" "additionalProperties":<false> "properties":{"class":{"type":"string"}} "required":["class"] "type":"object" }<assert_stmt>deserialize(Foo {"class":"bar"})<eq>Foo("bar")<assert_stmt>serialize(Foo Foo("bar"))<eq>{"class":"bar"}<line_sep>
# model.py <import_stmt>torch<import_from_stmt>torch nn<import_from_stmt>torch Tensor<import_from_stmt>torch.autograd Variable<import_stmt>numpy<as>np<import_from_stmt>sklearn.metrics accuracy_score<class_stmt>CNNText(nn.Module)<block_start><def_stmt>__init__ self config<block_start>super(CNNText self).__init__()<line_sep>self.config=config<line_sep># Convolutional Layer # We use 3 kernels as in original paper # Size of kernels: (3,300),(4,300),(5,300) self.conv1=nn.Conv2d(in_channels=self.config.in_channels out_channels=self.config.num_channels kernel_size=(self.config.kernel_size[0] self.config.embed_size) stride=1 padding=0)<line_sep>self.activation1=nn.ReLU()<line_sep>self.max_out1=nn.MaxPool1d(self.config.max_sen_len-self.config.kernel_size[0]+1)<line_sep>self.conv2=nn.Conv2d(in_channels=self.config.in_channels out_channels=self.config.num_channels kernel_size=(self.config.kernel_size[1] self.config.embed_size) stride=1 padding=0)<line_sep>self.activation2=nn.ReLU()<line_sep>self.max_out2=nn.MaxPool1d(self.config.max_sen_len-self.config.kernel_size[1]+1)<line_sep>self.conv3=nn.Conv2d(in_channels=self.config.in_channels out_channels=self.config.num_channels kernel_size=(self.config.kernel_size[2] self.config.embed_size) stride=1 padding=0)<line_sep>self.activation3=nn.ReLU()<line_sep>self.max_out3=nn.MaxPool1d(self.config.max_sen_len-self.config.kernel_size[2]+1)<line_sep>self.dropout=nn.Dropout(self.config.dropout_keep)<line_sep># Fully-Connected Layer self.fc=nn.Linear(self.config.num_channels<times>len(self.config.kernel_size) self.config.output_size)<line_sep># Softmax non-linearity self.softmax=nn.Softmax()<block_end><def_stmt>forward self x<block_start>x=x.unsqueeze(1)# (batch_size,max_seq_len,embed_size) => (batch_size,1,max_seq_len,embed_size) conv_out1=self.conv1(x).squeeze(3)<line_sep>activation_out1=self.activation1(conv_out1)<line_sep>max_out1=self.max_out1(activation_out1).squeeze(2)<line_sep>conv_out2=self.conv2(x).squeeze(3)<line_sep>activation_out2=self.activation2(conv_out2)<line_sep>max_out2=self.max_out2(activation_out2).squeeze(2)<line_sep>conv_out3=self.conv3(x).squeeze(3)<line_sep>activation_out3=self.activation3(conv_out3)<line_sep>max_out3=self.max_out3(activation_out3).squeeze(2)<line_sep>all_out=torch.cat((max_out1 max_out2 max_out3) 1)<line_sep>final_feature_map=self.dropout(all_out)<line_sep>final_out=self.fc(final_feature_map)<line_sep><return>self.softmax(final_out)<block_end><def_stmt>add_optimizer self optimizer<block_start>self.optimizer=optimizer<block_end><def_stmt>add_loss_op self loss_op<block_start>self.loss_op=loss_op<block_end><def_stmt>run_epoch self train_data val_data<block_start>train_x,train_y=train_data[0] train_data[1]<line_sep>val_x,val_y=val_data[0] val_data[1]<line_sep>iterator=data_iterator(train_x train_y self.config.batch_size)<line_sep>train_losses=[]<line_sep>val_accuracies=[]<line_sep>losses=[]<for_stmt>i,(x y) enumerate(iterator)<block_start>self.optimizer.zero_grad()<line_sep>x=Tensor(x).cuda()<line_sep>y_pred=self.__call__(x)<line_sep>loss=self.loss_op(y_pred torch.cuda.LongTensor(y-1))<line_sep>loss.backward()<line_sep>losses.append(loss.data.cpu().numpy())<line_sep>self.optimizer.step()<if_stmt>(i+1)%50<eq>0<block_start>print("Iter: {}".format(i+1))<line_sep>avg_train_loss=np.mean(losses)<line_sep>train_losses.append(avg_train_loss)<line_sep>print("\tAverage training loss: {:.5f}".format(avg_train_loss))<line_sep>losses=[]<line_sep># Evalute Accuracy on validation set self.eval()<line_sep>all_preds=[]<line_sep>val_iterator=data_iterator(val_x val_y self.config.batch_size)<for_stmt>j,(x y) enumerate(val_iterator)<block_start>x=Variable(Tensor(x))<line_sep>y_pred=self.__call__(x.cuda())<line_sep>predicted=torch.max(y_pred.cpu().data 1)[1]+1<line_sep>all_preds.extend(predicted.numpy())<block_end>score=accuracy_score(val_y np.array(all_preds).flatten())<line_sep>val_accuracies.append(score)<line_sep>print("\tVal Accuracy: {:.4f}".format(score))<line_sep>self.train()<block_end><block_end><return>train_losses val_accuracies<block_end><block_end>
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. <import_stmt>unittest<import_from_stmt>pathlib Path<import_stmt>sys<import_stmt>numpy<as>np<import_stmt>tensorflow<as>tf<import_from_stmt>tensorflow keras<import_from_stmt>tensorflow.python ipu<line_sep>sys.path.append(str(Path(__file__).absolute().parent.parent))<import_from_stmt>model.model_factory ModelFactory<import_from_stmt>model.toy_model ToyModel<import_from_stmt>model.resnet_models ResNet50<import_from_stmt>custom_exceptions DimensionError<class_stmt>ResNetVersionTest(unittest.TestCase)<block_start>@staticmethod<def_stmt>get_num_of_trainable_weights model<block_start><return>np.sum([np.prod(layer.numpy().shape)<for>layer model.trainable_weights])<block_end><def_stmt>test_resnet50_num_learnable_parameters self<block_start>'''A test of whether ResNet50 implementations in TF1 and TF2 are alike.'''<line_sep>NUM_OF_LEARNABLE_PARAMETERS_TF1=25557032<line_sep>num_trainable_weights_tf2=self.get_num_of_trainable_weights(model=ResNet50())<assert_stmt>num_trainable_weights_tf2<eq>NUM_OF_LEARNABLE_PARAMETERS_TF1<block_end><block_end><class_stmt>UnsupportedModelTest(unittest.TestCase)<block_start><def_stmt>test_unsupported_model self<block_start><with_stmt>self.assertRaises(NameError)<block_start>ModelFactory.create_model(model_name='foo' input_shape=(32 32 3) classes=2)<block_end><block_end><block_end><class_stmt>InvalidStageNameTest(unittest.TestCase)<block_start><def_stmt>test_invalid_layer_name self<block_start>train_strategy=ipu.ipu_strategy.IPUStrategy()<with_stmt>train_strategy.scope()<block_start>model=ModelFactory.create_model(model_name='toy_model' weights=<none> input_shape=(28 28 1) classes=10)<block_end><with_stmt>self.assertRaises(NameError)<block_start>model=ModelFactory.configure_model(model=model gradient_accumulation_count=1 pipeline_splits=['foo'] device_mapping=[] pipeline_schedule='Grouped' available_memory_proportion=[])<block_end><block_end><def_stmt>test_invalid_layer_order self<block_start>train_strategy=ipu.ipu_strategy.IPUStrategy()<with_stmt>train_strategy.scope()<block_start>model=ModelFactory.create_model(model_name='toy_model' weights=<none> input_shape=(28 28 1) classes=10)<block_end><with_stmt>self.assertRaises(NameError)<block_start>model=ModelFactory.configure_model(model=model gradient_accumulation_count=1 pipeline_splits=['conv2d_1' 'conv2d'] device_mapping=[] pipeline_schedule='Grouped' available_memory_proportion=[])<block_end><block_end><block_end><class_stmt>InvalidDeviceMappingTest(unittest.TestCase)<block_start><def_stmt>test_invalid_number_of_device_mapping self<block_start>train_strategy=ipu.ipu_strategy.IPUStrategy()<with_stmt>train_strategy.scope()<block_start>model=ModelFactory.create_model(model_name='toy_model' weights=<none> input_shape=(28 28 1) classes=10)<block_end><with_stmt>self.assertRaises(DimensionError)<block_start>model=ModelFactory.configure_model(model=model gradient_accumulation_count=1 pipeline_splits=['conv2d_1' 'flatten'] device_mapping=[0 1] pipeline_schedule='Grouped' available_memory_proportion=[])<block_end><block_end><def_stmt>test_invalid_id_of_device_mapping self<block_start>train_strategy=ipu.ipu_strategy.IPUStrategy()<with_stmt>train_strategy.scope()<block_start>model=ModelFactory.create_model(model_name='toy_model' weights=<none> input_shape=(28 28 1) classes=10)<block_end><with_stmt>self.assertRaises(DimensionError)<block_start>model=ModelFactory.configure_model(model=model gradient_accumulation_count=1 pipeline_splits=['conv2d_1' 'flatten'] device_mapping=[1 2 3] pipeline_schedule='Grouped' available_memory_proportion=[])<block_end><block_end><block_end><class_stmt>CreateModelTest(unittest.TestCase)<block_start><def_stmt>get_predictions_for_model self model_name:str<block_start>tf.random.set_seed(1)<line_sep>np.random.seed(0)<line_sep>image0=np.zeros((1 32 32 3))<line_sep>image1=np.ones((1 32 32 3))<times>10<line_sep>model=ModelFactory.create_model(model_name=model_name input_shape=(32 32 3) classes=2)<line_sep>image0_preds=model.predict(image0)[0]<line_sep>image1_preds=model.predict(image1)[0]<line_sep>tf.random.set_seed(<none>)<line_sep>np.random.seed(<none>)<line_sep><return>(image0_preds image1_preds)<block_end><def_stmt>test_resnet50_output self<block_start>image0_preds,image1_preds=self.get_predictions_for_model(model_name='resnet50')<assert_stmt>(np.array_equal(image0_preds [0.5 0.5]))<assert_stmt>(np.allclose(image1_preds [0.40129033 0.5987097]))<block_end><def_stmt>test_resnet34_output self<block_start>image0_preds,image1_preds=self.get_predictions_for_model(model_name='resnet34')<assert_stmt>(np.array_equal(image0_preds [0.5 0.5]))<assert_stmt>(np.allclose(image1_preds [0.53946716 0.46053284]))<block_end><def_stmt>test_resnet18_output self<block_start>image0_preds,image1_preds=self.get_predictions_for_model(model_name='resnet18')<assert_stmt>(np.array_equal(image0_preds [0.5 0.5]))<assert_stmt>(np.allclose(image1_preds [0.44021496 0.55978507]))<block_end><block_end><class_stmt>CreateToyModelTest(unittest.TestCase)<block_start><def_stmt>test_toy_model_prediction self<block_start>tf.random.set_seed(1)<line_sep>model=ToyModel(input_shape=(32 32 3) classes=10)<line_sep>image_1=np.ones((1 32 32 3))<times>10<assert_stmt>(np.allclose(model.predict(image_1)[0] [0.08292384 0.05735856 0.27028584 0.2666999 0.02177826 0.01853362 0.06498592 0.04272136 0.15957771 0.015135]))<line_sep>tf.random.set_seed(<none>)<block_end><block_end><class_stmt>CreateToyModelInFactory(unittest.TestCase)<block_start><def_stmt>test_toy_model_factory_prediction self<block_start>tf.random.set_seed(1)<line_sep>model=ModelFactory.create_model(model_name='toy_model' weights=<none> input_shape=(32 32 3) classes=10)<line_sep>image_1=np.ones((1 32 32 3))<times>10<assert_stmt>(np.allclose(model.predict(image_1)[0] [0.08292384 0.05735856 0.27028584 0.2666999 0.02177826 0.01853362 0.06498592 0.04272136 0.15957771 0.015135]))<line_sep>tf.random.set_seed(<none>)<block_end><block_end><class_stmt>ConfigurePipelineTest(unittest.TestCase)<block_start><def_stmt>test_pipeline_split self<block_start><def_stmt>initial_model_1 <block_start>model_input=keras.Input(shape=(32 32 3))<line_sep>model_output=keras.layers.MaxPooling2D(name='test_pipeline_split_layer1')(model_input)<line_sep>model_output_1=keras.layers.Conv2D(filters=32 kernel_size=3 name='test_pipeline_split_layer2')(model_output)<line_sep>model_output_2=keras.layers.Conv2D(filters=32 kernel_size=3 name='test_pipeline_split_layer3')(model_output)<line_sep>model_output=keras.layers.Add(name='test_pipeline_split_layer4')([model_output_1 model_output_2])<line_sep>model_output=keras.layers.Flatten(name='test_pipeline_split_layer5')(model_output)<line_sep><return>keras.Model(model_input model_output)<block_end><def_stmt>expected_model_1 <block_start>model_input=keras.Input(shape=(32 32 3))<with_stmt>ipu.keras.PipelineStage(0)<block_start>model_output=keras.layers.MaxPooling2D()(model_input)<line_sep>model_output_1=keras.layers.Conv2D(filters=32 kernel_size=3)(model_output)<block_end><with_stmt>ipu.keras.PipelineStage(1)<block_start>model_output_2=keras.layers.Conv2D(filters=32 kernel_size=3)(model_output)<line_sep>model_output=keras.layers.Add()([model_output_1 model_output_2])<block_end><with_stmt>ipu.keras.PipelineStage(2)<block_start>model_output=keras.layers.Flatten()(model_output)<block_end><return>keras.Model(model_input model_output)<block_end>train_strategy=ipu.ipu_strategy.IPUStrategy()<with_stmt>train_strategy.scope()<block_start>model=initial_model_1()<line_sep>pipelined_model=ModelFactory.configure_model(model=model gradient_accumulation_count=1 pipeline_splits=['test_pipeline_split_layer3' 'test_pipeline_split_layer5'] device_mapping=[] pipeline_schedule='Grouped' available_memory_proportion=[])<line_sep>expected_assignments=expected_model_1().get_pipeline_stage_assignment()<line_sep>pipelined_assignments=pipelined_model.get_pipeline_stage_assignment()<for_stmt>expected_assignment,pipelined_assignment zip(expected_assignments pipelined_assignments)<block_start><assert_stmt>(expected_assignment.layer.__class__.name<eq>pipelined_assignment.layer.__class__.name)<assert_stmt>(expected_assignment.pipeline_stage<eq>pipelined_assignment.pipeline_stage)<block_end><block_end><block_end><block_end>
<import_from_stmt>mock AsyncMock<import_stmt>pytest<import_from_stmt>opentrons.drivers.smoothie_drivers SmoothieDriver<import_from_stmt>opentrons.tools write_pipette_memory<line_sep>@pytest.fixture<def_stmt>mock_driver <arrow>AsyncMock<block_start><return>AsyncMock(spec=SmoothieDriver)<block_end><async_keyword><def_stmt>test_write_identifiers mock_driver:AsyncMock<arrow><none><block_start>"""It should call driver to write a new id and model."""<line_sep>mount="left"<line_sep>new_id="some id"<line_sep>new_model="some model"<line_sep>mock_driver.read_pipette_id.return_value=new_id<line_sep>mock_driver.read_pipette_model.return_value=new_model<line_sep><await>write_pipette_memory.write_identifiers(mount=mount new_id=new_id new_model=new_model driver=mock_driver)<line_sep>mock_driver.write_pipette_id.assert_called_once_with(mount new_id)<line_sep>mock_driver.read_pipette_id.assert_called_once_with(mount)<line_sep>mock_driver.write_pipette_model.assert_called_once_with(mount new_model)<line_sep>mock_driver.read_pipette_model.assert_called_once_with(mount)<block_end><async_keyword><def_stmt>test_write_identifiers_id_mismatch mock_driver:AsyncMock<arrow><none><block_start>"""It should fail when written id doesn't match read id."""<line_sep>mount="left"<line_sep>new_id="some id"<line_sep>new_model="some model"<line_sep>mock_driver.read_pipette_id.return_value=new_id+"_wrong"<with_stmt>pytest.raises(Exception)<block_start><await>write_pipette_memory.write_identifiers(mount=mount new_id=new_id new_model=new_model driver=mock_driver)<block_end><block_end><async_keyword><def_stmt>test_write_identifiers_model_mismatch mock_driver:AsyncMock<arrow><none><block_start>"""It should fail when written model doesn't match read model."""<line_sep>mount="left"<line_sep>new_id="some id"<line_sep>new_model="some model"<line_sep>mock_driver.read_pipette_id.return_value=new_id<line_sep>mock_driver.read_pipette_model.return_value=new_model+"_wrong"<with_stmt>pytest.raises(Exception)<block_start><await>write_pipette_memory.write_identifiers(mount=mount new_id=new_id new_model=new_model driver=mock_driver)<block_end><block_end><async_keyword><def_stmt>test_check_previous_data mock_driver:AsyncMock<arrow><none><block_start>"""It should read the pipette id and model"""<line_sep>mount="left"<line_sep><await>write_pipette_memory.check_previous_data(mount mock_driver)<line_sep>mock_driver.read_pipette_id.assert_called_once_with(mount)<line_sep>mock_driver.read_pipette_model.assert_called_once_with(mount)<block_end>pipette_barcode_to_model={"P10S20180101A01":"p10_single_v1" "P10M20180101A01":"p10_multi_v1" "P50S180101A01":"p50_single_v1" "P50M20180101B01":"p50_multi_v1" "P300S20180101A01":"p300_single_v1" "P300M20180101A01":"p300_multi_v1" "P1000S20180101A01":"p1000_single_v1" "P10SV1318010101":"p10_single_v1.3" "P10MV1318010102":"p10_multi_v1.3" "P50SV1318010103":"p50_single_v1.3" "P50MV1318010104":"p50_multi_v1.3" "P3HSV1318010105":"p300_single_v1.3" "P3HMV1318010106":"p300_multi_v1.3" "P1KSV1318010107":"p1000_single_v1.3" "P10SV1418010101":"p10_single_v1.4" "P10MV1418010102":"p10_multi_v1.4" "P50SV1418010103":"p50_single_v1.4" "P50MV1418010104":"p50_multi_v1.4" "P3HSV1418010105":"p300_single_v1.4" "P3HMV1418010106":"p300_multi_v1.4" "P1KSV1418010107":"p1000_single_v1.4" "P20MV2120120204":"p20_multi_v2.1" "P1KSV2218010107":"p1000_single_v2.2" "P20SV2220020501":"p20_single_v2.2" }<def_stmt>test_parse_model_from_barcode <arrow><none><block_start><for_stmt>barcode,model pipette_barcode_to_model.items()<block_start><assert_stmt>write_pipette_memory._parse_model_from_barcode(barcode)<eq>model<block_end><with_stmt>pytest.raises(Exception)<block_start>write_pipette_memory._parse_model_from_barcode("P1HSV1318010101")<block_end><with_stmt>pytest.raises(Exception)<block_start>write_pipette_memory._parse_model_from_barcode("P1KSV1218010101")<block_end><with_stmt>pytest.raises(Exception)<block_start>write_pipette_memory._parse_model_from_barcode("aP300S20180101A01")<block_end><block_end>
<import_from_stmt>xweb App Model RESTController<class_stmt>UserModel(Model)<block_start>schema={"type":"object" "properties":{"username":{"type":"string"} "password":{"type":"string"} } "required":['username']}<block_end><class_stmt>EventController(RESTController)<block_start><async_keyword><def_stmt>get self<block_start>Model.validate(self.ctx.json)<line_sep>self.ctx.body={"Hello":"World"}<block_end><block_end>app=App()<line_sep>app.routes={'/':EventController}<line_sep>app.listen()<line_sep>
<import_from_stmt>allennlp.nn.parallel.sharded_module_mixin ShardedModuleMixin<import_from_stmt>allennlp.nn.parallel.ddp_accelerator DdpAccelerator DdpWrappedModel TorchDdpAccelerator <import_from_stmt>allennlp.nn.parallel.fairscale_fsdp_accelerator FairScaleFsdpAccelerator FairScaleFsdpWrappedModel <line_sep>
''' Longest Increasing Subarray Find the longest increasing subarray (subarray is when all elements are neighboring in the original array). Input: [10, 1, 3, 8, 2, 0, 5, 7, 12, 3] Output: 4 ========================================= Only in one iteration, check if the current element is bigger than the previous and increase the counter if true. Time Complexity: O(N) Space Complexity: O(1) '''<line_sep>############ # Solution # ############ <def_stmt>longest_increasing_subarray arr<block_start>n=len(arr)<line_sep>longest=0<line_sep>current=1<line_sep>i=1<while_stmt>i<l>n<block_start><if_stmt>arr[i]<l>arr[i-1]<block_start>longest=max(longest current)<line_sep>current=1<block_end><else_stmt><block_start>current<augadd>1<block_end>i<augadd>1<block_end># check again for max, maybe the last element is a part of the longest subarray <return>max(longest current)<block_end>########### # Testing # ########### # Test 1 # Correct result => 4 print(longest_increasing_subarray([10 1 3 8 2 0 5 7 12 3]))<line_sep>
<import_stmt>unittest<import_from_stmt>asq.queryables Queryable<line_sep>__author__="<NAME>"<class_stmt>TestToSet(unittest.TestCase)<block_start><def_stmt>test_to_set self<block_start>a=[1 2 4 8 16 32]<line_sep>b=Queryable(a).to_set()<line_sep>c=set([1 2 4 8 16 32])<line_sep>self.assertEqual(b c)<block_end><def_stmt>test_to_set_closed self<block_start>a=[1 2 4 8 16 32]<line_sep>b=Queryable(a)<line_sep>b.close()<line_sep>self.assertRaises(ValueError <lambda>:b.to_set())<block_end><def_stmt>test_to_set_duplicates self<block_start>a=[1 2 4 8 8 16 32]<line_sep>b=Queryable(a)<line_sep>self.assertRaises(ValueError <lambda>:b.to_set())<block_end><block_end>
<import_stmt>time<import_stmt>requests<import_from_stmt>urllib.parse urljoin<import_from_stmt>urllib3.util.retry Retry<import_from_stmt>requests.adapters HTTPAdapter<import_stmt>pytest<line_sep>pytest_plugins=["docker_compose"]<line_sep>@pytest.fixture(scope="module")<def_stmt>wait_for_api module_scoped_container_getter<block_start>"""Wait for the api from my_api_service to become responsive"""<line_sep>request_session=requests.Session()<line_sep>retries=Retry(total=5 backoff_factor=0.1 status_forcelist=[500 502 503 504])<line_sep>request_session.mount('http://' HTTPAdapter(max_retries=retries))<line_sep>service=module_scoped_container_getter.get("my_api_service").network_info[0]<line_sep>api_url="http://%s:%s/"%(service.hostname service.host_port)<assert_stmt>request_session.get(api_url)<line_sep>start=time.time()<while_stmt>'Exit'<not><in>module_scoped_container_getter.get("my_short_lived_service").human_readable_state<block_start><if_stmt>time.time()-start<ge>5<block_start><raise>RuntimeError('my_short_lived_service should spin up, echo "Echoing" and '<concat>'then shut down, since it still running something went wrong')<block_end>time.sleep(.5)<block_end><return>request_session api_url<block_end>@pytest.fixture<def_stmt>do_an_insert wait_for_api<block_start>"""Insert data to the database in the container my_db"""<line_sep>request_session,api_url=wait_for_api<line_sep>item_url='items/1'<line_sep>data_string='some_data'<line_sep>request_session.put('%s%s?data_string=%s'%(api_url item_url data_string))<line_sep><yield>item_url data_string<line_sep>request_session.delete(urljoin(api_url item_url)).json()<block_end><def_stmt>test_read_an_item wait_for_api do_an_insert<block_start>request_session,api_url=wait_for_api<line_sep>item_url,data_string=do_an_insert<line_sep>item=request_session.get(api_url+item_url).json()<assert_stmt>item['data']<eq>data_string<block_end><def_stmt>test_read_and_write wait_for_api<block_start>request_session,api_url=wait_for_api<line_sep>data_string='some_other_data'<line_sep>request_session.put('%sitems/2?data_string=%s'%(api_url data_string))<line_sep>item=request_session.get(urljoin(api_url 'items/2')).json()<assert_stmt>item['data']<eq>data_string<line_sep>request_session.delete(urljoin(api_url 'items/2'))<block_end><def_stmt>test_read_all wait_for_api<block_start>request_session,api_url=wait_for_api<assert_stmt>len(request_session.get(urljoin(api_url 'items/all')).json())<eq>0<block_end><if_stmt>__name__<eq>'__main__'<block_start>pytest.main(['--docker-compose' './my_network' '--docker-compose-no-build'])<block_end>
<def_stmt>esc_kw kw<block_start>""" Take a keyword and escape all the Solr parts we want to escape!"""<line_sep>kw=kw.replace('\\' '\\\\')# be sure to do this first, as we inject \! kw=kw.replace('(' '\(')<line_sep>kw=kw.replace(')' '\)')<line_sep>kw=kw.replace('+' '\+')<line_sep>kw=kw.replace('-' '\-')<line_sep>kw=kw.replace(':' '\:')<line_sep>kw=kw.replace('/' '\/')<line_sep>kw=kw.replace(']' '\]')<line_sep>kw=kw.replace('[' '\[')<line_sep>kw=kw.replace('*' '\*')<line_sep>kw=kw.replace('?' '\?')<line_sep>kw=kw.replace('{' '\{')<line_sep>kw=kw.replace('}' '\}')<line_sep>kw=kw.replace('~' '\~')<line_sep><return>kw<block_end>
<import_stmt>rope.base.builtins<import_stmt>rope.base.codeanalyze<import_stmt>rope.base.pynames<import_from_stmt>rope.base ast exceptions utils<class_stmt>Scope(object)<block_start><def_stmt>__init__ self pycore pyobject parent_scope<block_start>self.pycore=pycore<line_sep>self.pyobject=pyobject<line_sep>self.parent=parent_scope<block_end><def_stmt>get_names self<block_start>"""Return the names defined or imported in this scope"""<line_sep><return>self.pyobject.get_attributes()<block_end><def_stmt>get_defined_names self<block_start>"""Return the names defined in this scope"""<line_sep><return>self.pyobject._get_structural_attributes()<block_end><def_stmt>get_name self name<block_start>"""Return name `PyName` defined in this scope"""<if_stmt>name<not><in>self.get_names()<block_start><raise>exceptions.NameNotFoundError('name %s not found'%name)<block_end><return>self.get_names()[name]<block_end><def_stmt>__getitem__ self key<block_start>"""The same as ``get_name(key)``"""<line_sep><return>self.get_name(key)<block_end><def_stmt>__contains__ self key<block_start>"""The same as ``key in self.get_names()``"""<line_sep><return>key<in>self.get_names()<block_end>@utils.saveit<def_stmt>get_scopes self<block_start>"""Return the subscopes of this scope The returned scopes should be sorted by the order they appear. """<line_sep><return>self._create_scopes()<block_end><def_stmt>lookup self name<block_start><if_stmt>name<in>self.get_names()<block_start><return>self.get_names()[name]<block_end><if_stmt>self.parent<is><not><none><block_start><return>self.parent._propagated_lookup(name)<block_end><return><none><block_end><def_stmt>get_propagated_names self<block_start>"""Return the visible names of this scope Return the names defined in this scope that are visible from scopes containing this scope. This method returns the same dictionary returned by `get_names()` except for `ClassScope` which returns an empty dict. """<line_sep><return>self.get_names()<block_end><def_stmt>_propagated_lookup self name<block_start><if_stmt>name<in>self.get_propagated_names()<block_start><return>self.get_propagated_names()[name]<block_end><if_stmt>self.parent<is><not><none><block_start><return>self.parent._propagated_lookup(name)<block_end><return><none><block_end><def_stmt>_create_scopes self<block_start><return>[pydefined.get_scope()<for>pydefined self.pyobject._get_defined_objects()]<block_end><def_stmt>_get_global_scope self<block_start>current=self<while_stmt>current.parent<is><not><none><block_start>current=current.parent<block_end><return>current<block_end><def_stmt>get_start self<block_start><return>self.pyobject.get_ast().lineno<block_end><def_stmt>get_body_start self<block_start>body=self.pyobject.get_ast().body<if_stmt>body<block_start><return>body[0].lineno<block_end><return>self.get_start()<block_end><def_stmt>get_end self<block_start>pymodule=self._get_global_scope().pyobject<line_sep><return>pymodule.logical_lines.logical_line_in(self.logical_end)[1]<block_end>@utils.saveit<def_stmt>get_logical_end self<block_start>global_scope=self._get_global_scope()<line_sep><return>global_scope._scope_finder.find_scope_end(self)<block_end>start=property(get_start)<line_sep>end=property(get_end)<line_sep>logical_end=property(get_logical_end)<def_stmt>get_kind self<block_start><pass><block_end><block_end><class_stmt>GlobalScope(Scope)<block_start><def_stmt>__init__ self pycore module<block_start>super(GlobalScope self).__init__(pycore module <none>)<line_sep>self.names=module._get_concluded_data()<block_end><def_stmt>get_start self<block_start><return>1<block_end><def_stmt>get_kind self<block_start><return>'Module'<block_end><def_stmt>get_name self name<block_start><try_stmt><block_start><return>self.pyobject[name]<block_end><except_stmt>exceptions.AttributeNotFoundError<block_start><if_stmt>name<in>self.builtin_names<block_start><return>self.builtin_names[name]<block_end><raise>exceptions.NameNotFoundError('name %s not found'%name)<block_end><block_end><def_stmt>get_names self<block_start><if_stmt>self.names.get()<is><none><block_start>result=dict(self.builtin_names)<line_sep>result.update(super(GlobalScope self).get_names())<line_sep>self.names.set(result)<block_end><return>self.names.get()<block_end><def_stmt>get_inner_scope_for_line self lineno indents=<none><block_start><return>self._scope_finder.get_holding_scope(self lineno indents)<block_end><def_stmt>get_inner_scope_for_offset self offset<block_start><return>self._scope_finder.get_holding_scope_for_offset(self offset)<block_end>@property@utils.saveit<def_stmt>_scope_finder self<block_start><return>_HoldingScopeFinder(self.pyobject)<block_end>@property<def_stmt>builtin_names self<block_start><return>rope.base.builtins.builtins.get_attributes()<block_end><block_end><class_stmt>FunctionScope(Scope)<block_start><def_stmt>__init__ self pycore pyobject visitor<block_start>super(FunctionScope self).__init__(pycore pyobject pyobject.parent.get_scope())<line_sep>self.names=<none><line_sep>self.returned_asts=<none><line_sep>self.is_generator=<none><line_sep>self.defineds=<none><line_sep>self.visitor=visitor<block_end><def_stmt>_get_names self<block_start><if_stmt>self.names<is><none><block_start>self._visit_function()<block_end><return>self.names<block_end><def_stmt>_visit_function self<block_start><if_stmt>self.names<is><none><block_start>new_visitor=self.visitor(self.pycore self.pyobject)<for_stmt>n ast.get_child_nodes(self.pyobject.get_ast())<block_start>ast.walk(n new_visitor)<block_end>self.names=new_visitor.names<line_sep>self.names.update(self.pyobject.get_parameters())<line_sep>self.returned_asts=new_visitor.returned_asts<line_sep>self.is_generator=new_visitor.generator<line_sep>self.defineds=new_visitor.defineds<block_end><block_end><def_stmt>_get_returned_asts self<block_start><if_stmt>self.names<is><none><block_start>self._visit_function()<block_end><return>self.returned_asts<block_end><def_stmt>_is_generator self<block_start><if_stmt>self.is_generator<is><none><block_start>self._get_returned_asts()<block_end><return>self.is_generator<block_end><def_stmt>get_names self<block_start><return>self._get_names()<block_end><def_stmt>_create_scopes self<block_start><if_stmt>self.defineds<is><none><block_start>self._visit_function()<block_end><return>[pydefined.get_scope()<for>pydefined self.defineds]<block_end><def_stmt>get_kind self<block_start><return>'Function'<block_end><def_stmt>invalidate_data self<block_start><for_stmt>pyname self.get_names().values()<block_start><if_stmt>isinstance(pyname (rope.base.pynames.AssignedName rope.base.pynames.EvaluatedName))<block_start>pyname.invalidate()<block_end><block_end><block_end><block_end><class_stmt>ClassScope(Scope)<block_start><def_stmt>__init__ self pycore pyobject<block_start>super(ClassScope self).__init__(pycore pyobject pyobject.parent.get_scope())<block_end><def_stmt>get_kind self<block_start><return>'Class'<block_end><def_stmt>get_propagated_names self<block_start><return>{}<block_end><block_end><class_stmt>_HoldingScopeFinder(object)<block_start><def_stmt>__init__ self pymodule<block_start>self.pymodule=pymodule<block_end><def_stmt>get_indents self lineno<block_start><return>rope.base.codeanalyze.count_line_indents(self.lines.get_line(lineno))<block_end><def_stmt>_get_scope_indents self scope<block_start><return>self.get_indents(scope.get_start())<block_end><def_stmt>get_holding_scope self module_scope lineno line_indents=<none><block_start><if_stmt>line_indents<is><none><block_start>line_indents=self.get_indents(lineno)<block_end>current_scope=module_scope<line_sep>new_scope=current_scope<while_stmt>new_scope<is><not><none><and>(new_scope.get_kind()<eq>'Module'<or>self._get_scope_indents(new_scope)<le>line_indents)<block_start>current_scope=new_scope<if_stmt>current_scope.get_start()<eq>lineno<and>current_scope.get_kind()<ne>'Module'<block_start><return>current_scope<block_end>new_scope=<none><for_stmt>scope current_scope.get_scopes()<block_start><if_stmt>scope.get_start()<le>lineno<block_start><if_stmt>lineno<le>scope.get_end()<block_start>new_scope=scope<line_sep><break><block_end><block_end><else_stmt><block_start><break><block_end><block_end><block_end><return>current_scope<block_end><def_stmt>_is_empty_line self lineno<block_start>line=self.lines.get_line(lineno)<line_sep><return>line.strip()<eq>''<or>line.lstrip().startswith('#')<block_end><def_stmt>_get_body_indents self scope<block_start><return>self.get_indents(scope.get_body_start())<block_end><def_stmt>get_holding_scope_for_offset self scope offset<block_start><return>self.get_holding_scope(scope self.lines.get_line_number(offset))<block_end><def_stmt>find_scope_end self scope<block_start><if_stmt><not>scope.parent<block_start><return>self.lines.length()<block_end>end=scope.pyobject.get_ast().body[-1].lineno<line_sep>scope_start=self.pymodule.logical_lines.logical_line_in(scope.start)<if_stmt>scope_start[1]<ge>end# handling one-liners <block_start>body_indents=self._get_scope_indents(scope)+4<block_end><else_stmt><block_start>body_indents=self._get_body_indents(scope)<block_end><for_stmt>l self.logical_lines.generate_starts(min(end+1 self.lines.length()) self.lines.length()+1)<block_start><if_stmt><not>self._is_empty_line(l)<block_start><if_stmt>self.get_indents(l)<l>body_indents<block_start><return>end<block_end><else_stmt><block_start>end=l<block_end><block_end><block_end><return>end<block_end>@property<def_stmt>lines self<block_start><return>self.pymodule.lines<block_end>@property<def_stmt>code self<block_start><return>self.pymodule.source_code<block_end>@property<def_stmt>logical_lines self<block_start><return>self.pymodule.logical_lines<block_end><block_end><class_stmt>TemporaryScope(Scope)<block_start>"""Currently used for list comprehensions and generator expressions These scopes do not appear in the `get_scopes()` method of their parent scopes. """<def_stmt>__init__ self pycore parent_scope names<block_start>super(TemporaryScope self).__init__(pycore parent_scope.pyobject parent_scope)<line_sep>self.names=names<block_end><def_stmt>get_names self<block_start><return>self.names<block_end><def_stmt>get_defined_names self<block_start><return>self.names<block_end><def_stmt>_create_scopes self<block_start><return>[]<block_end><def_stmt>get_kind self<block_start><return>'Temporary'<block_end><block_end>
<import_from_stmt>.misc.utils sqlalchemy_to_pydantic<import_from_stmt>.crud_router crud_router_builder<import_from_stmt>.misc.type CrudMethods<line_sep>
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. <import_from_stmt>oci.util formatted_flat_dict NONE_SENTINEL value_allowed_none_or_none_sentinel# noqa: F401 <import_from_stmt>oci.decorators init_model_state_from_kwargs<line_sep>@init_model_state_from_kwargs<class_stmt>CreateLogAnalyticsObjectCollectionRuleDetails(object)<block_start>""" The configuration details of collection rule to enable automatic log collection from an object storage bucket. """<line_sep>#: A constant which can be used with the collection_type property of a CreateLogAnalyticsObjectCollectionRuleDetails. #: This constant has a value of "LIVE" COLLECTION_TYPE_LIVE="LIVE"<line_sep>#: A constant which can be used with the collection_type property of a CreateLogAnalyticsObjectCollectionRuleDetails. #: This constant has a value of "HISTORIC" COLLECTION_TYPE_HISTORIC="HISTORIC"<line_sep>#: A constant which can be used with the collection_type property of a CreateLogAnalyticsObjectCollectionRuleDetails. #: This constant has a value of "HISTORIC_LIVE" COLLECTION_TYPE_HISTORIC_LIVE="HISTORIC_LIVE"<def_stmt>__init__ self **kwargs<block_start>""" Initializes a new CreateLogAnalyticsObjectCollectionRuleDetails object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param name: The value to assign to the name property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type name: str :param description: The value to assign to the description property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type description: str :param compartment_id: The value to assign to the compartment_id property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type compartment_id: str :param os_namespace: The value to assign to the os_namespace property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type os_namespace: str :param os_bucket_name: The value to assign to the os_bucket_name property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type os_bucket_name: str :param collection_type: The value to assign to the collection_type property of this CreateLogAnalyticsObjectCollectionRuleDetails. Allowed values for this property are: "LIVE", "HISTORIC", "HISTORIC_LIVE" :type collection_type: str :param poll_since: The value to assign to the poll_since property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type poll_since: str :param poll_till: The value to assign to the poll_till property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type poll_till: str :param log_group_id: The value to assign to the log_group_id property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type log_group_id: str :param log_source_name: The value to assign to the log_source_name property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type log_source_name: str :param entity_id: The value to assign to the entity_id property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type entity_id: str :param char_encoding: The value to assign to the char_encoding property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type char_encoding: str :param is_enabled: The value to assign to the is_enabled property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type is_enabled: bool :param overrides: The value to assign to the overrides property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type overrides: dict(str, list[PropertyOverride]) :param object_name_filters: The value to assign to the object_name_filters property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type object_name_filters: list[str] :param defined_tags: The value to assign to the defined_tags property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type defined_tags: dict(str, dict(str, object)) :param freeform_tags: The value to assign to the freeform_tags property of this CreateLogAnalyticsObjectCollectionRuleDetails. :type freeform_tags: dict(str, str) """<line_sep>self.swagger_types={'name':'str' 'description':'str' 'compartment_id':'str' 'os_namespace':'str' 'os_bucket_name':'str' 'collection_type':'str' 'poll_since':'str' 'poll_till':'str' 'log_group_id':'str' 'log_source_name':'str' 'entity_id':'str' 'char_encoding':'str' 'is_enabled':'bool' 'overrides':'dict(str, list[PropertyOverride])' 'object_name_filters':'list[str]' 'defined_tags':'dict(str, dict(str, object))' 'freeform_tags':'dict(str, str)'}<line_sep>self.attribute_map={'name':'name' 'description':'description' 'compartment_id':'compartmentId' 'os_namespace':'osNamespace' 'os_bucket_name':'osBucketName' 'collection_type':'collectionType' 'poll_since':'pollSince' 'poll_till':'pollTill' 'log_group_id':'logGroupId' 'log_source_name':'logSourceName' 'entity_id':'entityId' 'char_encoding':'charEncoding' 'is_enabled':'isEnabled' 'overrides':'overrides' 'object_name_filters':'objectNameFilters' 'defined_tags':'definedTags' 'freeform_tags':'freeformTags'}<line_sep>self._name=<none><line_sep>self._description=<none><line_sep>self._compartment_id=<none><line_sep>self._os_namespace=<none><line_sep>self._os_bucket_name=<none><line_sep>self._collection_type=<none><line_sep>self._poll_since=<none><line_sep>self._poll_till=<none><line_sep>self._log_group_id=<none><line_sep>self._log_source_name=<none><line_sep>self._entity_id=<none><line_sep>self._char_encoding=<none><line_sep>self._is_enabled=<none><line_sep>self._overrides=<none><line_sep>self._object_name_filters=<none><line_sep>self._defined_tags=<none><line_sep>self._freeform_tags=<none><block_end>@property<def_stmt>name self<block_start>""" **[Required]** Gets the name of this CreateLogAnalyticsObjectCollectionRuleDetails. A unique name given to the rule. The name must be unique within the tenancy, and cannot be modified. :return: The name of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._name<block_end>@name.setter<def_stmt>name self name<block_start>""" Sets the name of this CreateLogAnalyticsObjectCollectionRuleDetails. A unique name given to the rule. The name must be unique within the tenancy, and cannot be modified. :param name: The name of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._name=name<block_end>@property<def_stmt>description self<block_start>""" Gets the description of this CreateLogAnalyticsObjectCollectionRuleDetails. A string that describes the details of the rule. It does not have to be unique, and can be changed. Avoid entering confidential information. :return: The description of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._description<block_end>@description.setter<def_stmt>description self description<block_start>""" Sets the description of this CreateLogAnalyticsObjectCollectionRuleDetails. A string that describes the details of the rule. It does not have to be unique, and can be changed. Avoid entering confidential information. :param description: The description of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._description=description<block_end>@property<def_stmt>compartment_id self<block_start>""" **[Required]** Gets the compartment_id of this CreateLogAnalyticsObjectCollectionRuleDetails. The `OCID`__ of the compartment to which this rule belongs. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :return: The compartment_id of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._compartment_id<block_end>@compartment_id.setter<def_stmt>compartment_id self compartment_id<block_start>""" Sets the compartment_id of this CreateLogAnalyticsObjectCollectionRuleDetails. The `OCID`__ of the compartment to which this rule belongs. __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm :param compartment_id: The compartment_id of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._compartment_id=compartment_id<block_end>@property<def_stmt>os_namespace self<block_start>""" **[Required]** Gets the os_namespace of this CreateLogAnalyticsObjectCollectionRuleDetails. Object Storage namespace. :return: The os_namespace of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._os_namespace<block_end>@os_namespace.setter<def_stmt>os_namespace self os_namespace<block_start>""" Sets the os_namespace of this CreateLogAnalyticsObjectCollectionRuleDetails. Object Storage namespace. :param os_namespace: The os_namespace of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._os_namespace=os_namespace<block_end>@property<def_stmt>os_bucket_name self<block_start>""" **[Required]** Gets the os_bucket_name of this CreateLogAnalyticsObjectCollectionRuleDetails. Name of the Object Storage bucket. :return: The os_bucket_name of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._os_bucket_name<block_end>@os_bucket_name.setter<def_stmt>os_bucket_name self os_bucket_name<block_start>""" Sets the os_bucket_name of this CreateLogAnalyticsObjectCollectionRuleDetails. Name of the Object Storage bucket. :param os_bucket_name: The os_bucket_name of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._os_bucket_name=os_bucket_name<block_end>@property<def_stmt>collection_type self<block_start>""" Gets the collection_type of this CreateLogAnalyticsObjectCollectionRuleDetails. The type of collection. Allowed values for this property are: "LIVE", "HISTORIC", "HISTORIC_LIVE" :return: The collection_type of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._collection_type<block_end>@collection_type.setter<def_stmt>collection_type self collection_type<block_start>""" Sets the collection_type of this CreateLogAnalyticsObjectCollectionRuleDetails. The type of collection. :param collection_type: The collection_type of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>allowed_values=["LIVE" "HISTORIC" "HISTORIC_LIVE"]<if_stmt><not>value_allowed_none_or_none_sentinel(collection_type allowed_values)<block_start><raise>ValueError("Invalid value for `collection_type`, must be None or one of {0}".format(allowed_values))<block_end>self._collection_type=collection_type<block_end>@property<def_stmt>poll_since self<block_start>""" Gets the poll_since of this CreateLogAnalyticsObjectCollectionRuleDetails. The oldest time of the file in the bucket to consider for collection. Accepted values are: BEGINNING or CURRENT_TIME or RFC3339 formatted datetime string. Use this for HISTORIC or HISTORIC_LIVE collection types. When collectionType is LIVE, specifying pollSince value other than CURRENT_TIME will result in error. :return: The poll_since of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._poll_since<block_end>@poll_since.setter<def_stmt>poll_since self poll_since<block_start>""" Sets the poll_since of this CreateLogAnalyticsObjectCollectionRuleDetails. The oldest time of the file in the bucket to consider for collection. Accepted values are: BEGINNING or CURRENT_TIME or RFC3339 formatted datetime string. Use this for HISTORIC or HISTORIC_LIVE collection types. When collectionType is LIVE, specifying pollSince value other than CURRENT_TIME will result in error. :param poll_since: The poll_since of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._poll_since=poll_since<block_end>@property<def_stmt>poll_till self<block_start>""" Gets the poll_till of this CreateLogAnalyticsObjectCollectionRuleDetails. The newest time of the file in the bucket to consider for collection. Accepted values are: CURRENT_TIME or RFC3339 formatted datetime string. Use this for HISTORIC collection type. When collectionType is LIVE or HISTORIC_LIVE, specifying pollTill will result in error. :return: The poll_till of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._poll_till<block_end>@poll_till.setter<def_stmt>poll_till self poll_till<block_start>""" Sets the poll_till of this CreateLogAnalyticsObjectCollectionRuleDetails. The newest time of the file in the bucket to consider for collection. Accepted values are: CURRENT_TIME or RFC3339 formatted datetime string. Use this for HISTORIC collection type. When collectionType is LIVE or HISTORIC_LIVE, specifying pollTill will result in error. :param poll_till: The poll_till of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._poll_till=poll_till<block_end>@property<def_stmt>log_group_id self<block_start>""" **[Required]** Gets the log_group_id of this CreateLogAnalyticsObjectCollectionRuleDetails. Logging Analytics Log group OCID to associate the processed logs with. :return: The log_group_id of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._log_group_id<block_end>@log_group_id.setter<def_stmt>log_group_id self log_group_id<block_start>""" Sets the log_group_id of this CreateLogAnalyticsObjectCollectionRuleDetails. Logging Analytics Log group OCID to associate the processed logs with. :param log_group_id: The log_group_id of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._log_group_id=log_group_id<block_end>@property<def_stmt>log_source_name self<block_start>""" **[Required]** Gets the log_source_name of this CreateLogAnalyticsObjectCollectionRuleDetails. Name of the Logging Analytics Source to use for the processing. :return: The log_source_name of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._log_source_name<block_end>@log_source_name.setter<def_stmt>log_source_name self log_source_name<block_start>""" Sets the log_source_name of this CreateLogAnalyticsObjectCollectionRuleDetails. Name of the Logging Analytics Source to use for the processing. :param log_source_name: The log_source_name of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._log_source_name=log_source_name<block_end>@property<def_stmt>entity_id self<block_start>""" Gets the entity_id of this CreateLogAnalyticsObjectCollectionRuleDetails. Logging Analytics entity OCID. Associates the processed logs with the given entity (optional). :return: The entity_id of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._entity_id<block_end>@entity_id.setter<def_stmt>entity_id self entity_id<block_start>""" Sets the entity_id of this CreateLogAnalyticsObjectCollectionRuleDetails. Logging Analytics entity OCID. Associates the processed logs with the given entity (optional). :param entity_id: The entity_id of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._entity_id=entity_id<block_end>@property<def_stmt>char_encoding self<block_start>""" Gets the char_encoding of this CreateLogAnalyticsObjectCollectionRuleDetails. An optional character encoding to aid in detecting the character encoding of the contents of the objects while processing. It is recommended to set this value as ISO_8859_1 when configuring content of the objects having more numeric characters, and very few alphabets. For e.g. this applies when configuring VCN Flow Logs. :return: The char_encoding of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: str """<line_sep><return>self._char_encoding<block_end>@char_encoding.setter<def_stmt>char_encoding self char_encoding<block_start>""" Sets the char_encoding of this CreateLogAnalyticsObjectCollectionRuleDetails. An optional character encoding to aid in detecting the character encoding of the contents of the objects while processing. It is recommended to set this value as ISO_8859_1 when configuring content of the objects having more numeric characters, and very few alphabets. For e.g. this applies when configuring VCN Flow Logs. :param char_encoding: The char_encoding of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: str """<line_sep>self._char_encoding=char_encoding<block_end>@property<def_stmt>is_enabled self<block_start>""" Gets the is_enabled of this CreateLogAnalyticsObjectCollectionRuleDetails. Whether or not this rule is currently enabled. :return: The is_enabled of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: bool """<line_sep><return>self._is_enabled<block_end>@is_enabled.setter<def_stmt>is_enabled self is_enabled<block_start>""" Sets the is_enabled of this CreateLogAnalyticsObjectCollectionRuleDetails. Whether or not this rule is currently enabled. :param is_enabled: The is_enabled of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: bool """<line_sep>self._is_enabled=is_enabled<block_end>@property<def_stmt>overrides self<block_start>""" Gets the overrides of this CreateLogAnalyticsObjectCollectionRuleDetails. The override is used to modify some important configuration properties for objects matching a specific pattern inside the bucket. Supported propeties for override are: logSourceName, charEncoding, entityId. Supported matchType for override are \"contains\". :return: The overrides of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: dict(str, list[PropertyOverride]) """<line_sep><return>self._overrides<block_end>@overrides.setter<def_stmt>overrides self overrides<block_start>""" Sets the overrides of this CreateLogAnalyticsObjectCollectionRuleDetails. The override is used to modify some important configuration properties for objects matching a specific pattern inside the bucket. Supported propeties for override are: logSourceName, charEncoding, entityId. Supported matchType for override are \"contains\". :param overrides: The overrides of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: dict(str, list[PropertyOverride]) """<line_sep>self._overrides=overrides<block_end>@property<def_stmt>object_name_filters self<block_start>""" Gets the object_name_filters of this CreateLogAnalyticsObjectCollectionRuleDetails. When the filters are provided, only the objects matching the filters are picked up for processing. The matchType supported is exact match and accommodates wildcard \"*\". For more information on filters, see `Event Filters`__. __ https://docs.oracle.com/en-us/iaas/Content/Events/Concepts/filterevents.htm :return: The object_name_filters of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: list[str] """<line_sep><return>self._object_name_filters<block_end>@object_name_filters.setter<def_stmt>object_name_filters self object_name_filters<block_start>""" Sets the object_name_filters of this CreateLogAnalyticsObjectCollectionRuleDetails. When the filters are provided, only the objects matching the filters are picked up for processing. The matchType supported is exact match and accommodates wildcard \"*\". For more information on filters, see `Event Filters`__. __ https://docs.oracle.com/en-us/iaas/Content/Events/Concepts/filterevents.htm :param object_name_filters: The object_name_filters of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: list[str] """<line_sep>self._object_name_filters=object_name_filters<block_end>@property<def_stmt>defined_tags self<block_start>""" Gets the defined_tags of this CreateLogAnalyticsObjectCollectionRuleDetails. Defined tags for this resource. Each key is predefined and scoped to a namespace. Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` :return: The defined_tags of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: dict(str, dict(str, object)) """<line_sep><return>self._defined_tags<block_end>@defined_tags.setter<def_stmt>defined_tags self defined_tags<block_start>""" Sets the defined_tags of this CreateLogAnalyticsObjectCollectionRuleDetails. Defined tags for this resource. Each key is predefined and scoped to a namespace. Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}` :param defined_tags: The defined_tags of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: dict(str, dict(str, object)) """<line_sep>self._defined_tags=defined_tags<block_end>@property<def_stmt>freeform_tags self<block_start>""" Gets the freeform_tags of this CreateLogAnalyticsObjectCollectionRuleDetails. Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. Example: `{\"bar-key\": \"value\"}` :return: The freeform_tags of this CreateLogAnalyticsObjectCollectionRuleDetails. :rtype: dict(str, str) """<line_sep><return>self._freeform_tags<block_end>@freeform_tags.setter<def_stmt>freeform_tags self freeform_tags<block_start>""" Sets the freeform_tags of this CreateLogAnalyticsObjectCollectionRuleDetails. Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. Example: `{\"bar-key\": \"value\"}` :param freeform_tags: The freeform_tags of this CreateLogAnalyticsObjectCollectionRuleDetails. :type: dict(str, str) """<line_sep>self._freeform_tags=freeform_tags<block_end><def_stmt>__repr__ self<block_start><return>formatted_flat_dict(self)<block_end><def_stmt>__eq__ self other<block_start><if_stmt>other<is><none><block_start><return><false><block_end><return>self.__dict__<eq>other.__dict__<block_end><def_stmt>__ne__ self other<block_start><return><not>self<eq>other<block_end><block_end>
<import_from_future_stmt> print_function<import_stmt>sys<import_from_stmt>subprocess call<import_from_stmt>unittest TestCase<import_from_stmt>testfixtures OutputCapture compare<import_from_stmt>.test_compare CompareHelper<class_stmt>TestOutputCapture(CompareHelper TestCase)<block_start><def_stmt>test_compare_strips self<block_start><with_stmt>OutputCapture()<as>o<block_start>print(' Bar! ')<block_end>o.compare('Bar!')<block_end><def_stmt>test_compare_doesnt_strip self<block_start><with_stmt>OutputCapture(strip_whitespace=<false>)<as>o<block_start>print(' Bar! ')<block_end>self.check_raises('\tBar!' compare=o.compare message="'\\tBar!' (expected) != ' Bar! \\n' (actual)" )<block_end><def_stmt>test_stdout_and_stderr self<block_start><with_stmt>OutputCapture()<as>o<block_start>print('hello' file=sys.stdout)<line_sep>print('out' file=sys.stderr)<line_sep>print('there' file=sys.stdout)<line_sep>print('now' file=sys.stderr)<block_end>o.compare("hello\nout\nthere\nnow\n")<block_end><def_stmt>test_unicode self<block_start><with_stmt>OutputCapture()<as>o<block_start>print(u'\u65e5' file=sys.stdout)<block_end>o.compare(u'\u65e5\n')<block_end><def_stmt>test_separate_capture self<block_start><with_stmt>OutputCapture(separate=<true>)<as>o<block_start>print('hello' file=sys.stdout)<line_sep>print('out' file=sys.stderr)<line_sep>print('there' file=sys.stdout)<line_sep>print('now' file=sys.stderr)<block_end>o.compare(stdout="hello\nthere\n" stderr="out\nnow\n")<block_end><def_stmt>test_compare_both_at_once self<block_start><with_stmt>OutputCapture(separate=<true>)<as>o<block_start>print('hello' file=sys.stdout)<line_sep>print('out' file=sys.stderr)<block_end>self.check_raises(stdout="out\n" stderr="hello\n" compare=o.compare message=('dict not as expected:\n'<concat>'\n'<concat>'values differ:\n'<concat>"'stderr': 'hello' (expected) != 'out' (actual)\n"<concat>"'stdout': 'out' (expected) != 'hello' (actual)\n"<concat>'\n'<concat>"While comparing ['stderr']: 'hello' (expected) != 'out' (actual)\n"<concat>'\n'<concat>"While comparing ['stdout']: 'out' (expected) != 'hello' (actual)") )<block_end><def_stmt>test_original_restore self<block_start>o_out,o_err=sys.stdout sys.stderr<with_stmt>OutputCapture()<as>o<block_start>self.assertFalse(sys.stdout<is>o_out)<line_sep>self.assertFalse(sys.stderr<is>o_err)<block_end>self.assertTrue(sys.stdout<is>o_out)<line_sep>self.assertTrue(sys.stderr<is>o_err)<block_end><def_stmt>test_double_disable self<block_start>o_out,o_err=sys.stdout sys.stderr<with_stmt>OutputCapture()<as>o<block_start>self.assertFalse(sys.stdout<is>o_out)<line_sep>self.assertFalse(sys.stderr<is>o_err)<line_sep>o.disable()<line_sep>self.assertTrue(sys.stdout<is>o_out)<line_sep>self.assertTrue(sys.stderr<is>o_err)<line_sep>o.disable()<line_sep>self.assertTrue(sys.stdout<is>o_out)<line_sep>self.assertTrue(sys.stderr<is>o_err)<block_end>self.assertTrue(sys.stdout<is>o_out)<line_sep>self.assertTrue(sys.stderr<is>o_err)<block_end><def_stmt>test_double_enable self<block_start>o_out,o_err=sys.stdout sys.stderr<with_stmt>OutputCapture()<as>o<block_start>o.disable()<line_sep>self.assertTrue(sys.stdout<is>o_out)<line_sep>self.assertTrue(sys.stderr<is>o_err)<line_sep>o.enable()<line_sep>self.assertFalse(sys.stdout<is>o_out)<line_sep>self.assertFalse(sys.stderr<is>o_err)<line_sep>o.enable()<line_sep>self.assertFalse(sys.stdout<is>o_out)<line_sep>self.assertFalse(sys.stderr<is>o_err)<block_end>self.assertTrue(sys.stdout<is>o_out)<line_sep>self.assertTrue(sys.stderr<is>o_err)<block_end><block_end><class_stmt>TestOutputCaptureWithDescriptors(object)<block_start><def_stmt>test_fd self capfd<block_start><with_stmt>capfd.disabled() OutputCapture(fd=<true>)<as>o<block_start>call([sys.executable '-c' "import sys; sys.stdout.write('out')"])<line_sep>call([sys.executable '-c' "import sys; sys.stderr.write('err')"])<block_end>compare(o.captured expected=b'outerr')<line_sep>o.compare(expected=b'outerr')<block_end><def_stmt>test_fd_separate self capfd<block_start><with_stmt>capfd.disabled() OutputCapture(fd=<true> separate=<true>)<as>o<block_start>call([sys.executable '-c' "import sys; sys.stdout.write('out')"])<line_sep>call([sys.executable '-c' "import sys; sys.stderr.write('err')"])<block_end>compare(o.captured expected=b'')<line_sep>o.compare(stdout=b'out' stderr=b'err')<block_end><block_end>
"Test systems.py"<import_stmt>unittest<import_from_stmt>systems.errors IllegalSourceStock<import_stmt>systems.models<import_stmt>systems.parse<import_stmt>systems.lexer<class_stmt>TestModels(unittest.TestCase)<block_start><def_stmt>test_stock_maximum_rate self<block_start>m=systems.models.Model("Maximum")<line_sep>a=m.infinite_stock("a")<line_sep>b_max=3<line_sep>b=m.stock("b" systems.models.Formula(0) systems.models.Formula(b_max))<line_sep>m.flow(a b systems.models.Rate(1))<line_sep>results=m.run()<for_stmt>i,result enumerate(results)<block_start><if_stmt>i<g>b_max<block_start>self.assertEqual(b_max result['b'])<block_end><block_end><block_end><def_stmt>test_illegal_conversion_leak_source self<block_start>"You can't apply a Conversion or Leak to an infinite stock."<line_sep>m=systems.models.Model("Maximum")<line_sep>a=m.infinite_stock("a")<line_sep>b=m.stock("b")<line_sep>rates=[systems.models.Conversion(0.25) systems.models.Leak(0.25)]<for_stmt>rate rates<block_start><with_stmt>self.assertRaises(IllegalSourceStock)<block_start>m.flow(a b rate)<block_end><block_end><block_end><def_stmt>test_infinite_destination_stock self<block_start>"Should allow infinite stocks as destinations stock for all rates."<line_sep>rates=[systems.models.Rate(5) systems.models.Conversion(0.25) systems.models.Leak(0.25)]<for_stmt>rate rates<block_start>m=systems.models.Model("Maximum")<line_sep>a=m.stock("a" systems.models.Formula("100"))<line_sep>b=m.infinite_stock("b")<line_sep>m.flow(a b rate)<line_sep>m.run(rounds=3)<block_end><block_end><def_stmt>test_stock_maximum_conversion self<block_start>m=systems.models.Model("Maximum")<line_sep>a_initial=10<line_sep>a=m.stock("a" systems.models.Formula(a_initial))<line_sep>b_max=3<line_sep>b=m.stock("b" 0 systems.models.Formula(b_max))<line_sep>f_rate=0.5<line_sep>m.flow(a b systems.models.Conversion(f_rate))<line_sep>results=m.run(rounds=3)<line_sep>final=results[-1]<line_sep>self.assertEqual(b_max final['b'])<line_sep># 10 - ((1 / 0.5) * 3) = 4 a_expected=a_initial-((1/f_rate)<times>b_max)<line_sep>self.assertEqual(a_expected final['a'])<block_end><def_stmt>test_stock_maximum_leak self<block_start>m=systems.models.Model("Maximum")<line_sep>a_initial=10<line_sep>a=m.stock("a" systems.models.Formula(a_initial))<line_sep>b_max=3<line_sep>b=m.stock("b" systems.models.Formula(0) systems.models.Formula(b_max))<line_sep>m.flow(a b systems.models.Leak(0.5))<line_sep>results=m.run(rounds=2)<line_sep>final=results[-1]<line_sep>self.assertEqual(b_max final['b'])<line_sep>self.assertEqual(a_initial-b_max final['a'])<block_end><def_stmt>test_stock_minimums self<block_start>"Stocks should never dip below their minimum value."<line_sep>m=systems.models.Model("Minimum")<line_sep>a=m.stock("a" systems.models.Formula(2))<line_sep>b=m.stock("b" systems.models.Formula(0))<line_sep>m.flow(a b systems.models.Rate(1))<line_sep>results=m.run(rounds=5)<line_sep>final=results[-1]<line_sep>self.assertEqual(0 final['a'])<line_sep>self.assertEqual(2 final['b'])<block_end><def_stmt>test_stock_negative_flows self<block_start>"Stocks should never dip below their minimum value."<line_sep>m=systems.models.Model("Minimum")<line_sep>c=m.stock("c" systems.models.Formula(2))<line_sep>a=m.stock("a" systems.models.Formula(5))<line_sep>b=m.stock("b" systems.models.Formula(0))<line_sep>m.flow(a b systems.models.Rate("c"))<line_sep>results=m.run(rounds=5)<line_sep>final=results[-1]<line_sep>self.assertEqual(0 final['a'])<line_sep>self.assertEqual(5 final['b'])<block_end><def_stmt>test_partial_fulfillment_rate self<block_start>m=systems.models.Model("Partial")<line_sep>a=m.stock("a" systems.models.Formula(5))<line_sep>b=m.stock("b" systems.models.Formula(0))<line_sep>systems.parse.parse_flow(m a b "10")<line_sep>results=m.run(rounds=3)<line_sep>final=results[-1]<line_sep>self.assertEqual(0 final['a'])<line_sep>self.assertEqual(5 final['b'])<block_end><def_stmt>test_formula_rate self<block_start>m=systems.models.Model("Maximum")<line_sep>a=m.infinite_stock("a")<line_sep>b=m.stock("b")<line_sep>c=m.stock("c")<line_sep>d=m.stock("d" systems.models.Formula(3))<line_sep>systems.parse.parse_flow(m a b "d * 2")<line_sep>systems.parse.parse_flow(m b c "d")<line_sep>results=m.run(rounds=3)<line_sep>final=results[-1]<line_sep>self.assertEqual(12 final['b'])<line_sep>self.assertEqual(6 final['c'])<block_end><block_end><class_stmt>TestFormula(unittest.TestCase)<block_start><def_stmt>test_simple_formulas self<block_start>cases=[("0" 0) ("0.5" 0.5) ("100" 100) ("inf" float("+inf")) ]<for_stmt>case_in,case_out cases<block_start>lexed=systems.lexer.lex_formula(case_in)<line_sep>formula=systems.models.Formula(lexed)<line_sep>self.assertEqual(case_out formula.compute())<block_end><block_end><def_stmt>test_reference_formulas self<block_start>state={'a':10 'b':5 'c':0}<line_sep>cases=[("a" 10) ("b" 5) ("c" 0) ("a * 2" 20) ("b * 3" 15) ("c * 10" 0) ("2 * a" 20) ("3 * b" 15) ("10 * c" 0) ("b * a" 50) ("a * b" 50) ("b * b" 25) ("c * a" 0) ]<for_stmt>case_in,case_out cases<block_start>lexed=systems.lexer.lex_formula(case_in)<line_sep>formula=systems.models.Formula(lexed)<line_sep>self.assertEqual(case_out formula.compute(state))<block_end><block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>unittest.main()<block_end>
# Copyright (c) 2019 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for details. <import_from_future_stmt> absolute_import division print_function<line_sep>__metaclass__=type<import_from_stmt>ansible.module_utils.oracle oci_common_utils<try_stmt><block_start><import_stmt>oci<import_from_stmt>oci.util to_dict<line_sep>HAS_OCI_PY_SDK=<true><block_end><except_stmt>ImportError<block_start>HAS_OCI_PY_SDK=<false><block_end>LIFECYCLE_STATE_WAITER_KEY="LIFECYCLE_STATE_WAITER"<line_sep>WORK_REQUEST_WAITER_KEY="WORK_REQUEST_WAITER"<line_sep>NONE_WAITER_KEY="NONE_WAITER_KEY"<class_stmt>Waiter<block_start>"""Interface defining wait method"""<def_stmt>wait self<block_start><raise>NotImplementedError("Expected to be implemented by the specific waiter classes.")<block_end><block_end><class_stmt>BaseWaiter(Waiter)<block_start>"""Base class for various waiters"""<def_stmt>__init__ self client resource_helper operation_response wait_for_states<block_start>self.client=client<line_sep>self.operation_response=operation_response<line_sep>self.wait_for_states=wait_for_states<line_sep>self.resource_helper=resource_helper<block_end><def_stmt>get_initial_response self<block_start><raise>NotImplementedError("Expected to be implemented by the specific waiter classes.")<block_end><def_stmt>get_evaluate_response_lambda self<block_start><raise>NotImplementedError("Expected to be implemented by the specific waiter classes.")<block_end><def_stmt>wait self<block_start><if_stmt><not>self.resource_helper.module.params.get("wait")<block_start><return>self.operation_response<block_end>wait_response=oci.wait_until(self.client self.get_initial_response() evaluate_response=self.get_evaluate_response_lambda() max_wait_seconds=self.resource_helper.module.params.get("wait_timeout" oci_common_utils.MAX_WAIT_TIMEOUT_IN_SECONDS) )<line_sep><return>self.get_resource_from_wait_response(wait_response)<block_end><def_stmt>get_resource_from_wait_response self wait_response<block_start><raise>NotImplementedError("Expected to be implemented by the specific waiter classes.")<block_end><block_end><class_stmt>LifecycleStateWaiterBase(BaseWaiter)<block_start>"""Base class for various waiters"""<def_stmt>__init__ self client resource_helper operation_response wait_for_states<block_start>self.client=client<line_sep>self.operation_response=operation_response<line_sep>self.wait_for_states=wait_for_states<line_sep>self.resource_helper=resource_helper<block_end><def_stmt>get_initial_response self<block_start><return>self.resource_helper.get_resource()<block_end><def_stmt>get_evaluate_response_lambda self<block_start>lowered_wait_for_states=[state.lower()<for>state self.wait_for_states]<line_sep><return>(<lambda>r:getattr(r.data "lifecycle_state")<and>getattr(r.data "lifecycle_state").lower()<in>lowered_wait_for_states)<block_end><def_stmt>get_resource_from_wait_response self wait_response<block_start><return>wait_response.data<block_end><block_end><class_stmt>LifecycleStateWaiter(LifecycleStateWaiterBase)<block_start>"""Waiter which waits on the lifecycle state of the resource"""<def_stmt>__init__ self client resource_helper operation_response wait_for_states<block_start>super(LifecycleStateWaiter self).__init__(client resource_helper operation_response wait_for_states)<block_end><block_end><class_stmt>CreateOperationLifecycleStateWaiter(LifecycleStateWaiterBase)<block_start>"""Waiter which waits on the lifecycle state of the resource"""<def_stmt>__init__ self client resource_helper operation_response wait_for_states<block_start>super(CreateOperationLifecycleStateWaiter self).__init__(client resource_helper operation_response wait_for_states)<block_end><def_stmt>get_initial_response self<block_start>identifier=self.operation_response.data.id<if_stmt><not>identifier<block_start>self.resource_helper.module.fail_json("Error getting the resource identifier.")<block_end><try_stmt><block_start>id_orig=self.resource_helper.module.params[self.resource_helper.get_module_resource_id_param()]<block_end><except_stmt>NotImplementedError<block_start><return>self.resource_helper.get_resource()<block_end>self.resource_helper.module.params[self.resource_helper.get_module_resource_id_param()]=identifier<line_sep>get_response=self.resource_helper.get_resource()<line_sep>self.resource_helper.module.params[self.resource_helper.get_module_resource_id_param()]=id_orig<line_sep><return>get_response<block_end><block_end><class_stmt>WorkRequestWaiter(BaseWaiter)<block_start>"""Waiter which waits on the work request"""<def_stmt>__init__ self client resource_helper operation_response wait_for_states<block_start>self.client=client<line_sep>self.resource_helper=resource_helper<line_sep>self.operation_response=operation_response<line_sep>self.wait_for_states=wait_for_states<block_end><def_stmt>get_initial_response self<block_start><return>self.client.get_work_request(self.operation_response.headers["opc-work-request-id"])<block_end><def_stmt>get_evaluate_response_lambda self<block_start>lowered_wait_for_states=[state.lower()<for>state self.wait_for_states]<line_sep><return>(<lambda>r:getattr(r.data "status")<and>getattr(r.data "status").lower()<in>lowered_wait_for_states)<block_end><def_stmt>get_resource_from_wait_response self wait_response<block_start>get_response=self.resource_helper.get_resource()<line_sep><return>get_response.data<block_end><block_end><class_stmt>CreateOperationWorkRequestWaiter(WorkRequestWaiter)<block_start>"""Waiter which waits on the work request"""<def_stmt>__init__ self client resource_helper operation_response wait_for_states<block_start>super(CreateOperationWorkRequestWaiter self).__init__(client resource_helper operation_response wait_for_states)<block_end><def_stmt>get_resource_from_wait_response self wait_response<block_start>entity_type=oci_common_utils.get_entity_type(self.resource_helper.resource_type)<line_sep>identifier=<none><for_stmt>resource wait_response.data.resources<block_start><if_stmt>(hasattr(resource "entity_type")<and>getattr(resource "entity_type")<eq>entity_type)<block_start>identifier=resource.identifier<block_end><block_end><if_stmt><not>identifier<block_start>self.resource_helper.module.fail_json(msg="Could not get the resource identifier from work request response {0}".format(to_dict(wait_response.data)))<block_end>get_response=self.resource_helper.get_get_fn()(identifier)<line_sep><return>get_response.data<block_end><block_end><class_stmt>NoneWaiter(Waiter)<block_start>"""Waiter which does not wait"""<def_stmt>__init__ self client resource_helper operation_response wait_for_states<block_start>self.client=client<line_sep>self.resource_helper=resource_helper<line_sep>self.operation_response=operation_response<line_sep>self.wait_for_states=wait_for_states<block_end><def_stmt>wait self<block_start><return>self.operation_response.data<block_end><block_end><class_stmt>AuditConfigurationLifecycleStateWaiter(LifecycleStateWaiter)<block_start><def_stmt>__init__ self client resource_helper operation_response wait_for_states<block_start>super(AuditConfigurationLifecycleStateWaiter self).__init__(client resource_helper operation_response wait_for_states)<block_end><def_stmt>get_evaluate_response_lambda self# The update operation currently returns a work request id but the AuditClient currently does not support # waiting for the work request. So wait until the configuration is updated by checking the value. <block_start><return>(<lambda>r:r.data.retention_period_days<eq>self.resource_helper.module.params.get("retention_period_days"))<block_end><block_end># A map specifying the overrides for the default waiters. # Key is a tuple consisting spec name, resource type and the operation and the value is the waiter class. # For ex: ("waas", "waas_policy", oci_common_utils.UPDATE_OPERATION_KEY) -> CustomWaasWaiterClass _WAITER_OVERRIDE_MAP={# The audit update operation currently returns a work request id but the AuditClient currently does not support # waiting for the work request. So inject NoneWaiter and customize it to manually wait on the update condition. ("audit" "configuration" oci_common_utils.UPDATE_OPERATION_KEY):NoneWaiter}<def_stmt>get_waiter_override namespace resource_type operation<block_start>"""Return the custom waiter class if any for the resource and operation. Else return None."""<line_sep>waiter_override_key=(namespace resource_type operation)<if_stmt>waiter_override_key<in>_WAITER_OVERRIDE_MAP<block_start><return>_WAITER_OVERRIDE_MAP.get(waiter_override_key)<block_end># check if an override exists for ANY_OPERATION_KEY. This is helpful if we need a custom waiter for all(any) # resource operations waiter_override_key=(namespace resource_type oci_common_utils.ANY_OPERATION_KEY)<if_stmt>waiter_override_key<in>_WAITER_OVERRIDE_MAP<block_start><return>_WAITER_OVERRIDE_MAP.get(waiter_override_key)<block_end><return><none><block_end><def_stmt>get_waiter waiter_type operation client resource_helper operation_response wait_for_states<block_start>"""Return appropriate waiter object based on type and the operation."""<line_sep># First check if there is any custom override for the waiter class. If exists, use it. waiter_override_class=get_waiter_override(resource_helper.namespace resource_helper.resource_type operation)<if_stmt>waiter_override_class<block_start><return>waiter_override_class(client resource_helper operation_response wait_for_states)<block_end><if_stmt>waiter_type<eq>LIFECYCLE_STATE_WAITER_KEY<block_start><if_stmt>operation<eq>oci_common_utils.CREATE_OPERATION_KEY<block_start><return>CreateOperationLifecycleStateWaiter(client resource_helper operation_response wait_for_states)<block_end><return>LifecycleStateWaiter(client resource_helper operation_response wait_for_states)<block_end><elif_stmt>waiter_type<eq>WORK_REQUEST_WAITER_KEY<block_start><if_stmt>operation<eq>oci_common_utils.CREATE_OPERATION_KEY<block_start><return>CreateOperationWorkRequestWaiter(client resource_helper operation_response wait_for_states)<block_end><return>WorkRequestWaiter(client resource_helper operation_response wait_for_states)<block_end><return>NoneWaiter(client resource_helper operation_response wait_for_states)<block_end><def_stmt>call_and_wait call_fn call_fn_args call_fn_kwargs waiter_type operation waiter_client resource_helper wait_for_states <block_start>"""Call the given function and wait until the operation is completed and return the resource."""<line_sep>operation_response=oci_common_utils.call_with_backoff(call_fn *call_fn_args **call_fn_kwargs)<line_sep>waiter=get_waiter(waiter_type operation waiter_client resource_helper operation_response=operation_response wait_for_states=wait_for_states )<line_sep><return>waiter.wait()<block_end>
<import_stmt>questionary<if_stmt>__name__<eq>"__main__"<block_start>path=questionary.path("Path to the projects version file").ask()<if_stmt>path<block_start>print(f"Found version file at {path} 🦄")<block_end><else_stmt><block_start>print("No version file it is then!")<block_end><block_end>
#! /usr/bin/env python # standard library imports <import_stmt>argparse<import_stmt>textwrap<import_stmt>warnings<import_stmt>sys# NOQA need this for mock testig <import_from_stmt>pandashells.lib module_checker_lib<line_sep># import required dependencies module_checker_lib.check_for_modules(['pandas' 'numpy' 'matplotlib' 'statsmodels'])<import_from_stmt>pandashells.lib arg_lib io_lib plot_lib<import_stmt>pandas<as>pd<import_stmt>numpy<as>np<line_sep>warnings.filterwarnings('ignore')<import_stmt>pylab<as>pl<line_sep>warnings.resetwarnings()<import_from_stmt>statsmodels.distributions.empirical_distribution ECDF<def_stmt>main <block_start>msg=textwrap.dedent(""" Plots the emperical cumulative distribution function (ECDF). ----------------------------------------------------------------------- Examples: * Plot ECDF for 10k samples from the standard normal distribution. p.rand -t normal -n 10000 | p.cdf -c c0 * Instead of plotting, send ECDF values to stdout p.rand -t normal -n 10000 | p.cdf -c c0 -q | head ----------------------------------------------------------------------- """)<line_sep># read command line arguments parser=argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter description=msg)<line_sep># specify column to use parser.add_argument("-c" "--col" required=<true> nargs=1 help="Column to plot distribution")<line_sep>parser.add_argument('-n' '--n_points' nargs=1 type=int help='Number of output points (default is twice input len)')<line_sep>parser.add_argument('-q' '--quiet' action='store_true' default=<false> help='Quiet mean no plots. Send numeric output to stdout instead')<line_sep># parse arguments arg_lib.add_args(parser 'decorating' 'io_in' 'io_out' )<line_sep>args=parser.parse_args()<line_sep># get the input dataframe and extract column df=io_lib.df_from_input(args)<line_sep>x=df[args.col[0]].values<line_sep># create the output distribution n_out=2<times>len(x)<if>args.n_points<is><none><else>args.n_points[0]<line_sep>x_out=np.linspace(min(x) max(x) n_out)<line_sep>y_out=ECDF(x)(x_out)<line_sep># send values to stdout if quiet specified <if_stmt>args.quiet<block_start>df_out=pd.DataFrame({'x':x_out 'p_less':y_out 'p_greater':1-y_out})<line_sep>df_out=df_out[['x' 'p_less' 'p_greater']]<line_sep>io_lib.df_to_output(args df_out)<line_sep><return><block_end># set the appropriate theme ad make plot plot_lib.set_plot_styling(args)<line_sep>pl.plot(x_out y_out label='P({} < x)'.format(args.col[0]))<line_sep>pl.plot(x_out 1.-y_out label='P({} > x)'.format(args.col[0]))<line_sep>pl.xlabel('x')<line_sep>pl.legend(loc='best')<line_sep>plot_lib.refine_plot(args)<line_sep>plot_lib.show(args)<block_end><if_stmt>__name__<eq>'__main__'# pragma: no cover <block_start>main()<block_end>
# Copyright 2016 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. <import_from_stmt>tempest.lib.services.volume.v3 quotas_client<import_from_stmt>tempest.tests.lib fake_auth_provider<import_from_stmt>tempest.tests.lib.services base<class_stmt>TestQuotasClient(base.BaseServiceTest)<block_start>FAKE_QUOTAS={"quota_set":{"id":'730a1cbd-68ca-4d68-8e09-d603f2dfa72b' "gigabytes":5 "snapshots":10 "volumes":20 'backups':10 'groups':10 'per_volume_gigabytes':1000 'backup_gigabytes':2000}}<line_sep>FAKE_UPDATE_QUOTAS_RESPONSE={"quota_set":{"gigabytes":6 "snapshots":11 "volumes":21 'backups':11 'groups':11 'per_volume_gigabytes':1001 'backup_gigabytes':2001}}<def_stmt>setUp self<block_start>super(TestQuotasClient self).setUp()<line_sep>fake_auth=fake_auth_provider.FakeAuthProvider()<line_sep>self.client=quotas_client.QuotasClient(fake_auth 'volume' 'regionOne')<block_end><def_stmt>_test_show_default_quota_set self bytes_body=<false><block_start>self.check_service_client_function(self.client.show_default_quota_set 'tempest.lib.common.rest_client.RestClient.get' self.FAKE_QUOTAS bytes_body tenant_id="fake_tenant")<block_end><def_stmt>_test_show_quota_set self bytes_body=<false><block_start>self.check_service_client_function(self.client.show_quota_set 'tempest.lib.common.rest_client.RestClient.get' self.FAKE_QUOTAS bytes_body tenant_id="fake_tenant")<block_end><def_stmt>_test_update_quota_set self bytes_body=<false><block_start>self.check_service_client_function(self.client.update_quota_set 'tempest.lib.common.rest_client.RestClient.put' self.FAKE_UPDATE_QUOTAS_RESPONSE bytes_body tenant_id="fake_tenant")<block_end><def_stmt>test_show_default_quota_set_with_str_body self<block_start>self._test_show_default_quota_set()<block_end><def_stmt>test_show_default_quota_set_with_bytes_body self<block_start>self._test_show_default_quota_set(bytes_body=<true>)<block_end><def_stmt>test_show_quota_set_with_str_body self<block_start>self._test_show_quota_set()<block_end><def_stmt>test_show_quota_set_with_bytes_body self<block_start>self._test_show_quota_set(bytes_body=<true>)<block_end><def_stmt>test_update_quota_set_with_str_body self<block_start>self._test_update_quota_set()<block_end><def_stmt>test_update_quota_set_with_bytes_body self<block_start>self._test_update_quota_set(bytes_body=<true>)<block_end><def_stmt>test_delete_quota_set self<block_start>self.check_service_client_function(self.client.delete_quota_set 'tempest.lib.common.rest_client.RestClient.delete' {} tenant_id="fake_tenant")<block_end><block_end>
<import_from_stmt>ipywidgets widgets<import_from_stmt>pandas_profiling.report.presentation.core Variable<class_stmt>WidgetVariable(Variable)<block_start><def_stmt>render self<arrow>widgets.VBox<block_start>items=[self.content["top"].render()]<if_stmt>self.content["bottom"]<is><not><none><block_start>items.append(self.content["bottom"].render())<block_end><return>widgets.VBox(items)<block_end><block_end>
# coding=utf-8 <import_stmt>datetime<import_stmt>logging<import_stmt>traceback<import_from_stmt>config config<def_stmt>parse_frequency s<block_start><if_stmt>s<eq>"never"<or>s<is><none><block_start><return><none> <none><block_end>kind,num,unit=s.split()<line_sep><return>int(num) unit<block_end><class_stmt>DefaultScheduler(object)<block_start>queue_thread=<none><line_sep>scheduler_thread=<none><line_sep>running=<false><line_sep>registry=<none><def_stmt>__init__ self<block_start>self.queue_thread=<none><line_sep>self.scheduler_thread=<none><line_sep>self.running=<false><line_sep>self.registry=[]<line_sep>self.tasks={}<line_sep>self.init_storage()<block_end><def_stmt>init_storage self<block_start><if_stmt>"tasks"<not><in>Dict<block_start>Dict["tasks"]={"queue":[]}<line_sep>Dict.Save()<block_end><if_stmt>"queue"<not><in>Dict["tasks"]<block_start>Dict["tasks"]["queue"]=[]<block_end><block_end><def_stmt>get_task_data self name<block_start><if_stmt>name<not><in>Dict["tasks"]<block_start><raise>NotImplementedError("Task missing! %s"%name)<block_end><if_stmt>"data"<in>Dict["tasks"][name]<block_start><return>Dict["tasks"][name]["data"]<block_end><block_end><def_stmt>clear_task_data self name=<none><block_start><if_stmt>name<is><none># full clean <block_start>Log.Debug("Clearing previous task data")<if_stmt>Dict["tasks"]<block_start><for_stmt>task_name Dict["tasks"].keys()<block_start><if_stmt>task_name<eq>"queue"<block_start>Dict["tasks"][task_name]=[]<line_sep><continue><block_end>Dict["tasks"][task_name]["data"]={}<line_sep>Dict["tasks"][task_name]["running"]=<false><block_end>Dict.Save()<block_end><return><block_end><if_stmt>name<not><in>Dict["tasks"]<block_start><raise>NotImplementedError("Task missing! %s"%name)<block_end>Dict["tasks"][name]["data"]={}<line_sep>Dict["tasks"][name]["running"]=<false><line_sep>Dict.Save()<line_sep>Log.Debug("Task data cleared: %s" name)<block_end><def_stmt>register self task<block_start>self.registry.append(task)<block_end><def_stmt>setup_tasks self# discover tasks; <block_start>self.tasks={}<for_stmt>cls self.registry<block_start>task=cls()<try_stmt><block_start>task_frequency=Prefs["scheduler.tasks.%s.frequency"%task.name]<block_end><except_stmt>KeyError<block_start>task_frequency=getattr(task "frequency" <none>)<block_end>self.tasks[task.name]={"task":task "frequency":parse_frequency(task_frequency)}<block_end><block_end><def_stmt>run self<block_start>self.running=<true><line_sep>self.scheduler_thread=Thread.Create(self.scheduler_worker)<line_sep>self.queue_thread=Thread.Create(self.queue_worker)<block_end><def_stmt>stop self<block_start>self.running=<false><block_end><def_stmt>task self name<block_start><if_stmt>name<not><in>self.tasks<block_start><return><none><block_end><return>self.tasks[name]["task"]<block_end><def_stmt>is_task_running self name<block_start>task=self.task(name)<if_stmt>task<block_start><return>task.running<block_end><block_end><def_stmt>last_run self task<block_start><if_stmt>task<not><in>self.tasks<block_start><return><none><block_end><return>self.tasks[task]["task"].last_run<block_end><def_stmt>next_run self task<block_start><if_stmt>task<not><in>self.tasks<or><not>self.tasks[task]["task"].periodic<block_start><return><none><block_end>frequency_num,frequency_key=self.tasks[task]["frequency"]<if_stmt><not>frequency_num<block_start><return><none><block_end>last=self.tasks[task]["task"].last_run<line_sep>use_date=last<line_sep>now=datetime.datetime.now()<if_stmt><not>use_date<block_start>use_date=now<block_end><return>max(use_date+datetime.timedelta(**{frequency_key:frequency_num}) now)<block_end><def_stmt>run_task self name *args **kwargs<block_start>task=self.tasks[name]["task"]<if_stmt>task.running<block_start>Log.Debug("Scheduler: Not running %s, as it's currently running." name)<line_sep><return><false><block_end>Log.Debug("Scheduler: Running task %s" name)<try_stmt><block_start>task.prepare(*args **kwargs)<line_sep>task.run()<block_end><except_stmt>Exception e<block_start>Log.Error("Scheduler: Something went wrong when running %s: %s" name traceback.format_exc())<block_end><finally_stmt><block_start><try_stmt><block_start>task.post_run(Dict["tasks"][name]["data"])<block_end><except_stmt><block_start>Log.Error("Scheduler: task.post_run failed for %s: %s" name traceback.format_exc())<block_end>Dict.Save()<line_sep>config.sync_cache()<block_end><block_end><def_stmt>dispatch_task self *args **kwargs<block_start><if_stmt>"queue"<not><in>Dict["tasks"]<block_start>Dict["tasks"]["queue"]=[]<block_end>Dict["tasks"]["queue"].append((args kwargs))<block_end><def_stmt>signal self name *args **kwargs<block_start><for_stmt>task_name self.tasks.keys()<block_start>task=self.task(task_name)<if_stmt><not>task<block_start>Log.Error("Scheduler: Task %s not found (?!)"%task_name)<line_sep><continue><block_end><if_stmt><not>task.periodic<block_start><continue><block_end><if_stmt>task.running<block_start>Log.Debug("Scheduler: Sending signal %s to task %s (%s, %s)" name task_name args kwargs)<try_stmt><block_start>status=task.signal(name *args **kwargs)<block_end><except_stmt>NotImplementedError<block_start>Log.Debug("Scheduler: Signal ignored by %s" task_name)<line_sep><continue><block_end><if_stmt>status<block_start>Log.Debug("Scheduler: Signal accepted by %s" task_name)<block_end><else_stmt><block_start>Log.Debug("Scheduler: Signal not accepted by %s" task_name)<block_end><continue><block_end>Log.Debug("Scheduler: Not sending signal %s to task %s, because: not running" name task_name)<block_end><block_end><def_stmt>queue_worker self<block_start>Thread.Sleep(10.0)<while_stmt>1<block_start><if_stmt><not>self.running<block_start><break><block_end># single dispatch requested? <if_stmt>Dict["tasks"]["queue"]# work queue off <block_start>queue=Dict["tasks"]["queue"][:]<line_sep>Dict["tasks"]["queue"]=[]<line_sep>Dict.Save()<for_stmt>args,kwargs queue<block_start>Log.Debug("Queue: Dispatching single task: %s, %s" args kwargs)<line_sep>Thread.Create(self.run_task <true> *args **kwargs)<line_sep>Thread.Sleep(5.0)<block_end><block_end>Thread.Sleep(1)<block_end><block_end><def_stmt>scheduler_worker self<block_start>Thread.Sleep(10.0)<while_stmt>1<block_start><if_stmt><not>self.running<block_start><break><block_end># scheduled tasks <for_stmt>name self.tasks.keys()<block_start>now=datetime.datetime.now()<line_sep>info=self.tasks.get(name)<if_stmt><not>info<block_start>Log.Error("Scheduler: Task %s not found (?!)"%name)<line_sep><continue><block_end>task=info["task"]<if_stmt>name<not><in>Dict["tasks"]<or><not>task.periodic<block_start><continue><block_end><if_stmt>task.running<block_start><continue><block_end>frequency_num,frequency_key=info["frequency"]<if_stmt><not>frequency_num<block_start><continue><block_end># run legacy SARAM once <if_stmt>name<eq>"SearchAllRecentlyAddedMissing"<and>("hasRunLSARAM"<not><in>Dict<or><not>Dict["hasRunLSARAM"])<block_start>task=self.tasks["LegacySearchAllRecentlyAddedMissing"]["task"]<line_sep>task.last_run=<none><line_sep>name="LegacySearchAllRecentlyAddedMissing"<line_sep>Dict["hasRunLSARAM"]=<true><line_sep>Dict.Save()<block_end><if_stmt><not>task.last_run<or>(task.last_run+datetime.timedelta(**{frequency_key:frequency_num})<le>now)# fixme: scheduled tasks run synchronously. is this the best idea? <block_start>Thread.Create(self.run_task <true> name)<line_sep>#Thread.Sleep(5.0) #self.run_task(name) Thread.Sleep(5.0)<block_end><block_end>Thread.Sleep(1)<block_end><block_end><block_end>scheduler=DefaultScheduler()<line_sep>
<import_stmt>pytest<import_stmt>numpy<as>np<import_from_stmt>numpy.testing assert_array_equal assert_array_almost_equal<import_from_stmt>pandas.testing assert_frame_equal<import_stmt>pandas<as>pd<import_stmt>matplotlib<import_from_stmt>pdpbox.pdp pdp_isolate pdp_plot<class_stmt>TestPDPIsolateBinary(object)<block_start><def_stmt>test_pdp_isolate_binary_feature self titanic_model titanic_data titanic_features# feature_type: binary <block_start>pdp_isolate_out=pdp_isolate(model=titanic_model dataset=titanic_data model_features=titanic_features feature="Sex" num_grid_points=10 grid_type="percentile" percentile_range=<none> grid_range=<none> cust_grid_points=<none> memory_limit=0.5 n_jobs=1 predict_kwds={} data_transformer=<none> )<assert_stmt>pdp_isolate_out._type<eq>"PDPIsolate_instance"<assert_stmt>pdp_isolate_out.n_classes<eq>2<assert_stmt>pdp_isolate_out.which_class<is><none><assert_stmt>pdp_isolate_out.feature<eq>"Sex"<assert_stmt>pdp_isolate_out.feature_type<eq>"binary"<assert_stmt>pdp_isolate_out.percentile_info<eq>[]<assert_stmt>pdp_isolate_out.display_columns<eq>["Sex_0" "Sex_1"]<assert_stmt>pdp_isolate_out.hist_data<is><none><block_end><def_stmt>test_pdp_isolate_onehot_feature self titanic_model titanic_data titanic_features# feature_type: onehot <block_start>pdp_isolate_out=pdp_isolate(model=titanic_model dataset=titanic_data model_features=titanic_features feature=["Embarked_C" "Embarked_S" "Embarked_Q"] num_grid_points=10 grid_type="percentile" percentile_range=<none> grid_range=<none> cust_grid_points=<none> memory_limit=0.5 n_jobs=1 predict_kwds={} data_transformer=<none> )<assert_stmt>pdp_isolate_out._type<eq>"PDPIsolate_instance"<assert_stmt>pdp_isolate_out.n_classes<eq>2<assert_stmt>pdp_isolate_out.which_class<is><none><assert_stmt>pdp_isolate_out.feature<eq>["Embarked_C" "Embarked_S" "Embarked_Q"]<assert_stmt>pdp_isolate_out.feature_type<eq>"onehot"<assert_stmt>pdp_isolate_out.percentile_info<eq>[]<assert_stmt>pdp_isolate_out.display_columns<eq>["Embarked_C" "Embarked_S" "Embarked_Q" ]<assert_stmt>pdp_isolate_out.hist_data<is><none><block_end><def_stmt>test_pdp_isolate_numeric_feature self titanic_model titanic_data titanic_features# feature_type: numeric <block_start>pdp_isolate_out=pdp_isolate(model=titanic_model dataset=titanic_data model_features=titanic_features feature="Fare" num_grid_points=10 grid_type="percentile" percentile_range=<none> grid_range=<none> cust_grid_points=<none> memory_limit=0.5 n_jobs=1 predict_kwds={} data_transformer=<none> )<assert_stmt>pdp_isolate_out._type<eq>"PDPIsolate_instance"<assert_stmt>pdp_isolate_out.n_classes<eq>2<assert_stmt>pdp_isolate_out.which_class<is><none><assert_stmt>pdp_isolate_out.feature<eq>"Fare"<assert_stmt>pdp_isolate_out.feature_type<eq>"numeric"<assert_stmt>len(pdp_isolate_out.hist_data)<eq>titanic_data.shape[0]<block_end><def_stmt>test_pdp_isolate_cust_grid_points self titanic_model titanic_data titanic_features# use cust_grid_points <block_start>pdp_isolate_out=pdp_isolate(model=titanic_model dataset=titanic_data model_features=titanic_features feature="Fare" num_grid_points=10 grid_type="percentile" percentile_range=<none> grid_range=<none> cust_grid_points=range(0 100 5) memory_limit=0.5 n_jobs=1 predict_kwds={} data_transformer=<none> )<assert_stmt>pdp_isolate_out._type<eq>"PDPIsolate_instance"<assert_stmt>pdp_isolate_out.n_classes<eq>2<assert_stmt>pdp_isolate_out.which_class<is><none><assert_stmt>pdp_isolate_out.feature<eq>"Fare"<assert_stmt>pdp_isolate_out.feature_type<eq>"numeric"<assert_stmt>pdp_isolate_out.percentile_info<eq>[]<assert_stmt>pdp_isolate_out.display_columns<eq>["0" "5" "10" "15" "20" "25" "30" "35" "40" "45" "50" "55" "60" "65" "70" "75" "80" "85" "90" "95" ]<assert_stmt>len(pdp_isolate_out.hist_data)<eq>titanic_data.shape[0]<block_end><block_end><class_stmt>TestPDPIsolateRegression(object)<block_start><def_stmt>test_pdp_isolate_regression self ross_model ross_data ross_features<block_start>pdp_isolate_out=pdp_isolate(model=ross_model dataset=ross_data model_features=ross_features feature="SchoolHoliday" num_grid_points=10 grid_type="percentile" percentile_range=<none> grid_range=<none> cust_grid_points=<none> memory_limit=0.5 n_jobs=1 predict_kwds={} data_transformer=<none> )<assert_stmt>pdp_isolate_out._type<eq>"PDPIsolate_instance"<assert_stmt>pdp_isolate_out.n_classes<eq>0<assert_stmt>pdp_isolate_out.which_class<is><none><assert_stmt>pdp_isolate_out.feature<eq>"SchoolHoliday"<assert_stmt>pdp_isolate_out.feature_type<eq>"binary"<assert_stmt>pdp_isolate_out.percentile_info<eq>[]<assert_stmt>pdp_isolate_out.display_columns<eq>["SchoolHoliday_0" "SchoolHoliday_1"]<assert_stmt>pdp_isolate_out.hist_data<is><none><block_end><def_stmt>test_pdp_isolate_n_jobs self ross_model ross_data ross_features# test n_jobs > 1 <block_start>_=pdp_isolate(model=ross_model dataset=ross_data model_features=ross_features feature="SchoolHoliday" num_grid_points=10 grid_type="percentile" percentile_range=<none> grid_range=<none> cust_grid_points=<none> memory_limit=0.5 n_jobs=2 predict_kwds={} data_transformer=<none> )<block_end><block_end><def_stmt>test_pdp_isolate_multiclass otto_model otto_data otto_features<block_start>pdp_isolate_out=pdp_isolate(model=otto_model dataset=otto_data model_features=otto_features feature="feat_67" num_grid_points=10 grid_type="percentile" percentile_range=<none> grid_range=<none> cust_grid_points=<none> memory_limit=0.5 n_jobs=1 predict_kwds={} data_transformer=<none> )<assert_stmt>len(pdp_isolate_out)<eq>9<assert_stmt>pdp_isolate_out[0]._type<eq>"PDPIsolate_instance"<assert_stmt>pdp_isolate_out[0].n_classes<eq>9<for_stmt>i range(9)<block_start><assert_stmt>pdp_isolate_out[i].which_class<eq>i<block_end><assert_stmt>pdp_isolate_out[0].feature<eq>"feat_67"<assert_stmt>pdp_isolate_out[0].feature_type<eq>"numeric"<block_end><class_stmt>TestPDPPlotSingle(object)<block_start>@pytest.fixture<def_stmt>pdp_sex self titanic_data titanic_model titanic_features<block_start>result=pdp_isolate(model=titanic_model dataset=titanic_data model_features=titanic_features feature="Sex" )<line_sep><return>result<block_end><def_stmt>test_pdp_plot_single_default self pdp_sex# single chart without data dist plot <block_start>fig,axes=pdp_plot(pdp_sex "sex")<assert_stmt>type(fig)<eq>matplotlib.figure.Figure<assert_stmt>sorted(axes.keys())<eq>["pdp_ax" "title_ax"]<assert_stmt>type(axes["pdp_ax"])<eq>matplotlib.axes._subplots.Subplot<assert_stmt>type(axes["title_ax"])<eq>matplotlib.axes._subplots.Subplot<block_end><def_stmt>test_pdp_plot_single_distplot self pdp_sex# single chart with data dist plot <block_start>fig,axes=pdp_plot(pdp_sex "sex" plot_pts_dist=<true>)<assert_stmt>sorted(axes.keys())<eq>["pdp_ax" "title_ax"]<assert_stmt>sorted(axes["pdp_ax"].keys())<eq>["_count_ax" "_pdp_ax"]<assert_stmt>type(axes["pdp_ax"]["_pdp_ax"])<eq>matplotlib.axes._subplots.Subplot<assert_stmt>type(axes["pdp_ax"]["_count_ax"])<eq>matplotlib.axes._subplots.Subplot<assert_stmt>type(axes["title_ax"])<eq>matplotlib.axes._subplots.Subplot<block_end><block_end><class_stmt>TestPDPPlotMulti(object)<block_start>@pytest.fixture<def_stmt>pdp_feat_67_rf self otto_data otto_model otto_features<block_start>result=pdp_isolate(model=otto_model dataset=otto_data model_features=otto_features feature="feat_67" )<line_sep><return>result<block_end><def_stmt>test_pdp_plot_multi_default self pdp_feat_67_rf# multi charts without data dist plot <block_start>fig,axes=pdp_plot(pdp_isolate_out=pdp_feat_67_rf feature_name="feat_67" center=<true> x_quantile=<true> )<assert_stmt>type(fig)<eq>matplotlib.figure.Figure<assert_stmt>sorted(axes.keys())<eq>["pdp_ax" "title_ax"]<assert_stmt>len(axes["pdp_ax"])<eq>9<assert_stmt>type(axes["title_ax"])<eq>matplotlib.axes._subplots.Subplot<assert_stmt>type(axes["pdp_ax"][0])<eq>matplotlib.axes._subplots.Subplot<block_end><def_stmt>test_pdp_plot_multi_which_classes self pdp_feat_67_rf# change which classes <block_start>fig,axes=pdp_plot(pdp_feat_67_rf "feat_67" center=<true> x_quantile=<true> ncols=2 which_classes=[0 3 7] )<assert_stmt>len(axes["pdp_ax"])<eq>3<block_end><def_stmt>test_pdp_plot_multi_one_class self pdp_feat_67_rf# only keep 1 class <block_start>fig,axes=pdp_plot(pdp_feat_67_rf "feat_67" center=<true> x_quantile=<true> ncols=2 which_classes=[5] )<assert_stmt>type(axes["pdp_ax"])<eq>matplotlib.axes._subplots.Subplot<block_end><def_stmt>test_pdp_plot_multi_distplot self pdp_feat_67_rf# multi charts with data dist plot <block_start>fig,axes=pdp_plot(pdp_isolate_out=pdp_feat_67_rf feature_name="feat_67" center=<true> x_quantile=<true> plot_pts_dist=<true> )<assert_stmt>sorted(axes.keys())<eq>["pdp_ax" "title_ax"]<assert_stmt>len(axes["pdp_ax"])<eq>9<assert_stmt>sorted(axes["pdp_ax"][0].keys())<eq>["_count_ax" "_pdp_ax"]<assert_stmt>type(axes["pdp_ax"][0]["_count_ax"])<eq>matplotlib.axes._subplots.Subplot<assert_stmt>type(axes["pdp_ax"][0]["_pdp_ax"])<eq>matplotlib.axes._subplots.Subplot<block_end><block_end>
<import_stmt>tensorflow<as>tf<import_from_stmt>sklearn.base BaseEstimator<import_from_stmt>sklearn.linear_model LinearRegression<import_from_stmt>.covs CovIdentity<import_from_stmt>brainiak.utils.utils cov2corr<import_stmt>numpy<as>np<import_from_stmt>brainiak.matnormal.matnormal_likelihoods matnorm_logp_marginal_row<import_from_stmt>brainiak.matnormal.utils pack_trainable_vars unpack_trainable_vars make_val_and_grad unflatten_cholesky_unique flatten_cholesky_unique <import_from_stmt>scipy.optimize minimize<line_sep>__all__=["MNRSA"]<class_stmt>MNRSA(BaseEstimator)<block_start>""" Matrix normal version of RSA. The goal of this analysis is to find the covariance of the mapping from some design matrix X to the fMRI signal Y. It does so by marginalizing over the actual mapping (i.e. averaging over the uncertainty in it), which happens to correct a bias imposed by structure in the design matrix on the RSA estimate (see Cai et al., NIPS 2016). This implementation makes different choices about residual covariance relative to `brainiak.reprsimil.BRSA`: Here, the noise covariance is assumed to be kronecker-separable. Informally, this means that all voxels have the same temporal covariance, and all time points have the same spatial covariance. This is in contrast to BRSA, which allows different temporal covariance for each voxel. On the other hand, computational efficiencies enabled by this choice allow MNRSA to support a richer class of space and time covariances (anything in `brainiak.matnormal.covs`). For users: in general, if you are worried about voxels each having different temporal noise structure,you should use `brainiak.reprsimil.BRSA`. If you are worried about between-voxel correlations or temporal covaraince structures that BRSA does not support, you should use MNRSA. .. math:: Y &\\sim \\mathcal{MN}(0, \\Sigma_t + XLL^TX^T+ X_0X_0^T, \\Sigma_s)\\ U &= LL^T Parameters ---------- time_cov : subclass of CovBase Temporal noise covariance class following CovBase interface. space_cov : subclass of CovBase Spatial noise covariance class following CovBase interface. optimizer : string, Default :'L-BFGS' Name of scipy optimizer to use. optCtrl : dict, default: None Additional arguments to pass to scipy.optimize.minimize. """<def_stmt>__init__ self time_cov space_cov n_nureg=5 optimizer="L-BFGS-B" optCtrl=<none><block_start>self.n_T=time_cov.size<line_sep>self.n_V=space_cov.size<line_sep>self.n_nureg=n_nureg<line_sep>self.optMethod=optimizer<if_stmt>optCtrl<is><none><block_start>self.optCtrl={}<block_end>self.X_0=tf.Variable(tf.random.normal([self.n_T n_nureg] dtype=tf.float64) name="X_0")<line_sep>self.train_variables=[self.X_0]<line_sep>self.time_cov=time_cov<line_sep>self.space_cov=space_cov<line_sep>self.train_variables.extend(self.time_cov.get_optimize_vars())<line_sep>self.train_variables.extend(self.space_cov.get_optimize_vars())<block_end>@property<def_stmt>L self<block_start>""" Cholesky factor of the RSA matrix. """<line_sep><return>unflatten_cholesky_unique(self.L_flat)<block_end><def_stmt>fit self X y naive_init=<true><block_start>""" Estimate dimension reduction and cognitive model parameters Parameters ---------- X: 2d array Brain data matrix (TRs by voxels). Y in the math y: 2d array or vector Behavior data matrix (TRs by behavioral obsevations). X in the math max_iter: int, default=1000 Maximum number of iterations to run step: int, default=100 Number of steps between optimizer output restart: bool, default=True If this is true, optimizer is restarted (e.g. for a new dataset). Otherwise optimizer will continue from where it is now (for example for running more iterations if the initial number was not enough). """<line_sep># In the method signature we follow sklearn discriminative API # where brain is X and behavior is y. Internally we are # generative so we flip this here X,Y=y X<line_sep>self.n_c=X.shape[1]<if_stmt>naive_init# initialize from naive RSA <block_start>m=LinearRegression(fit_intercept=<false>)<line_sep>m.fit(X=X y=Y)<line_sep>self.naive_U_=np.cov(m.coef_.T)<line_sep>naiveRSA_L=np.linalg.cholesky(self.naive_U_)<line_sep>self.L_flat=tf.Variable(flatten_cholesky_unique(naiveRSA_L) name="L_flat" dtype="float64")<block_end><else_stmt><block_start>chol_flat_size=(self.n_c<times>(self.n_c+1))<floordiv>2<line_sep>self.L_flat=tf.Variable(tf.random.normal([chol_flat_size] dtype="float64") name="L_flat" dtype="float64" )<block_end>self.train_variables.extend([self.L_flat])<def_stmt>lossfn theta<block_start><return>-self.logp(X Y)<block_end>val_and_grad=make_val_and_grad(lossfn self.train_variables)<line_sep>x0=pack_trainable_vars(self.train_variables)<line_sep>opt_results=minimize(fun=val_and_grad x0=x0 jac=<true> method=self.optMethod **self.optCtrl)<line_sep>unpacked_theta=unpack_trainable_vars(opt_results.x self.train_variables)<for_stmt>var,val zip(self.train_variables unpacked_theta)<block_start>var.assign(val)<block_end>self.U_=self.L.numpy().dot(self.L.numpy().T)<line_sep>self.C_=cov2corr(self.U_)<block_end><def_stmt>logp self X Y<block_start>""" MNRSA Log-likelihood"""<line_sep>rsa_cov=CovIdentity(size=self.n_c+self.n_nureg)<line_sep>x_stack=tf.concat([tf.matmul(X self.L) self.X_0] 1)<line_sep><return>(self.time_cov.logp+self.space_cov.logp+rsa_cov.logp+matnorm_logp_marginal_row(Y row_cov=self.time_cov col_cov=self.space_cov marg=x_stack marg_cov=rsa_cov ))<block_end><block_end>
<import_from_stmt>fate_arch.federation.pulsar._federation Federation MQ PulsarManager<line_sep>__all__=['Federation' 'MQ' 'PulsarManager']<line_sep>
# -*- coding: utf-8 -*- <import_from_stmt>guillotina app_settings<import_from_stmt>guillotina configure<import_from_stmt>guillotina.component ComponentLookupError<import_from_stmt>guillotina.component get_multi_adapter<import_from_stmt>guillotina.component query_utility<import_from_stmt>guillotina.content get_all_behaviors<import_from_stmt>guillotina.content get_cached_factory<import_from_stmt>guillotina.directives merged_tagged_value_dict<import_from_stmt>guillotina.directives read_permission<import_from_stmt>guillotina.interfaces IAsyncBehavior<import_from_stmt>guillotina.interfaces IFolder<import_from_stmt>guillotina.interfaces IPermission<import_from_stmt>guillotina.interfaces IResource<import_from_stmt>guillotina.interfaces IResourceSerializeToJson<import_from_stmt>guillotina.interfaces IResourceSerializeToJsonSummary<import_from_stmt>guillotina.json.serialize_value json_compatible<import_from_stmt>guillotina.profile profilable<import_from_stmt>guillotina.schema get_fields<import_from_stmt>guillotina.utils apply_coroutine<import_from_stmt>guillotina.utils get_object_url<import_from_stmt>guillotina.utils get_security_policy<import_from_stmt>zope.interface Interface<import_stmt>asyncio<import_stmt>logging<line_sep>logger=logging.getLogger("guillotina")<line_sep>MAX_ALLOWED=20<line_sep>@configure.adapter(for_=(IResource Interface) provides=IResourceSerializeToJson)<class_stmt>SerializeToJson(object)<block_start><def_stmt>__init__ self context request<block_start>self.context=context<line_sep>self.request=request<line_sep>self.permission_cache={}<block_end>@profilable<async_keyword><def_stmt>__call__ self include=<none> omit=<none><block_start>self.include=include<or>[]<line_sep>self.omit=omit<or>[]<line_sep>parent=self.context.__parent__<if_stmt>parent<is><not><none># We render the summary of the parent <block_start><try_stmt><block_start>parent_summary=<await>get_multi_adapter((parent self.request) IResourceSerializeToJsonSummary)()<block_end><except_stmt>ComponentLookupError<block_start>parent_summary={}<block_end><block_end><else_stmt><block_start>parent_summary={}<block_end>factory=get_cached_factory(self.context.type_name)<line_sep>behaviors=[]<for_stmt>behavior_schema factory.behaviors<or>()<block_start>behaviors.append(behavior_schema.__identifier__)<block_end>result={"@id":get_object_url(self.context self.request) "@type":self.context.type_name "@name":self.context.__name__ "@uid":self.context.uuid "@static_behaviors":behaviors "parent":parent_summary # should be @parent "is_folderish":IFolder.providedBy(self.context) # eek, should be @folderish? "creation_date":json_compatible(self.context.creation_date) "modification_date":json_compatible(self.context.modification_date) }<line_sep>main_schema=factory.schema<line_sep><await>self.get_schema(main_schema self.context result <false>)<line_sep># include can be one of: # - <field name> on content schema # - namespace.IBehavior # - namespace.IBehavior.field_name included_ifaces=[name<for>name self.include<if>"."<in>name]<line_sep>included_ifaces.extend([name.rsplit("." 1)[0]<for>name self.include<if>"."<in>name])<for_stmt>behavior_schema,behavior <await>get_all_behaviors(self.context load=<false>)<block_start><if_stmt>"*"<not><in>self.include<block_start>dotted_name=behavior_schema.__identifier__<if_stmt>dotted_name<in>self.omit<or>(len(included_ifaces)<g>0<and>dotted_name<not><in>included_ifaces)# make sure the schema isn't filtered <block_start><continue><block_end><if_stmt><not>getattr(behavior "auto_serialize" <true>)<and>dotted_name<not><in>included_ifaces<block_start><continue><block_end><block_end><if_stmt>IAsyncBehavior.implementedBy(behavior.__class__)# providedBy not working here? <block_start><await>behavior.load(create=<false>)<block_end><await>self.get_schema(behavior_schema behavior result <true>)<block_end><for_stmt>post_serialize_processors app_settings["post_serialize"]<block_start><await>apply_coroutine(post_serialize_processors self.context result)<block_end><return>result<block_end>@profilable<async_keyword><def_stmt>get_schema self schema context result behavior<block_start>read_permissions=merged_tagged_value_dict(schema read_permission.key)<line_sep>schema_serial={}<for_stmt>name,field get_fields(schema).items()<block_start><if_stmt><not>self.check_permission(read_permissions.get(name))<block_start><continue><block_end><if_stmt>behavior# omit/include for behaviors need full name <block_start>dotted_name=schema.__identifier__+"."+name<block_end><else_stmt><block_start>dotted_name=name<block_end><if_stmt>"*"<not><in>self.include<and>(dotted_name<in>self.omit<or>(len(self.include)<g>0<and>(dotted_name<not><in>self.include<and>schema.__identifier__<not><in>self.include)))# make sure the fields aren't filtered <block_start><continue><block_end>value=<await>self.serialize_field(context field)<if_stmt><not>behavior<block_start>result[name]=value<block_end><else_stmt><block_start>schema_serial[name]=value<block_end><block_end><if_stmt>behavior<and>len(schema_serial)<g>0<block_start>result[schema.__identifier__]=schema_serial<block_end><block_end>@profilable<async_keyword><def_stmt>serialize_field self context field default=<none><block_start><try_stmt><block_start>value=<await>apply_coroutine(field.get context)<block_end><except_stmt>Exception<block_start>logger.warning(f"Could not find value for schema field"<concat>f"({field.__name__}), falling back to getattr")<line_sep>value=getattr(context field.__name__ default)<block_end>result=json_compatible(value)<if_stmt>asyncio.iscoroutine(result)<block_start>result=<await>result<block_end><return>result<block_end><def_stmt>check_permission self permission_name<block_start><if_stmt>permission_name<is><none><block_start><return><true><block_end><if_stmt>permission_name<not><in>self.permission_cache<block_start>permission=query_utility(IPermission name=permission_name)<if_stmt>permission<is><none><block_start>self.permission_cache[permission_name]=<true><block_end><else_stmt><block_start>security=get_security_policy()<line_sep>self.permission_cache[permission_name]=bool(security.check_permission(permission.id self.context))<block_end><block_end><return>self.permission_cache[permission_name]<block_end><block_end>@configure.adapter(for_=(IFolder Interface) provides=IResourceSerializeToJson)<class_stmt>SerializeFolderToJson(SerializeToJson)<block_start>@profilable<async_keyword><def_stmt>__call__ self include=<none> omit=<none><block_start>include=include<or>[]<line_sep>omit=omit<or>[]<line_sep>result=<await>super(SerializeFolderToJson self).__call__(include=include omit=omit)<line_sep>security=get_security_policy()<line_sep>length=<await>self.context.async_len()<line_sep>fullobjects=self.request.query.get("fullobjects" <false>)<in>(<none> "" "true")<if_stmt>(length<g>MAX_ALLOWED<or>length<eq>0)<and><not>fullobjects<block_start>result["items"]=[]<block_end><else_stmt><block_start>result["items"]=[]<async_keyword><for_stmt>ident,member self.context.async_items(suppress_events=<true>)<block_start><if_stmt><not>ident.startswith("_")<and>bool(security.check_permission("guillotina.AccessContent" member))<block_start><if_stmt>fullobjects<block_start>result["items"].append(<await>get_multi_adapter((member self.request) IResourceSerializeToJson)())<block_end><else_stmt><block_start>result["items"].append(<await>get_multi_adapter((member self.request) IResourceSerializeToJsonSummary)())<block_end><block_end><block_end><block_end>result["length"]=length<line_sep><return>result<block_end><block_end>@configure.adapter(for_=(IResource Interface) provides=IResourceSerializeToJsonSummary)<class_stmt>DefaultJSONSummarySerializer(object)<block_start>"""Default ISerializeToJsonSummary adapter. Requires context to be adaptable to IContentListingObject, which is the case for all content objects providing IResource. """<def_stmt>__init__ self context request<block_start>self.context=context<line_sep>self.request=request<block_end><async_keyword><def_stmt>__call__ self<block_start>summary=json_compatible({"@id":get_object_url(self.context self.request) "@name":self.context.__name__ "@type":self.context.type_name "@uid":self.context.uuid })<line_sep><return>summary<block_end><block_end>
# -*- coding: utf-8 -*- <import_from_stmt>.config BaseConfig DevConfig TestConfig get_config<line_sep>
<import_from_stmt>abc ABC<import_stmt>scipy.sparse<import_from_stmt>rasa.nlu.featurizers.featurizer Featurizer<class_stmt>SparseFeaturizer(Featurizer[scipy.sparse.spmatrix] ABC)<block_start>"""Base class for all sparse featurizers."""<line_sep><pass><block_end>
<import_from_stmt>vit.formatter.status Status<class_stmt>StatusLong(Status)<block_start><pass><block_end>
<import_stmt>matplotlib<line_sep>matplotlib.use("Agg")<import_stmt>matplotlib.pylab<as>plt<import_stmt>os<import_stmt>logging<def_stmt>plots imvs alphas mel_preds mel_gts step out_dir num_plots=4<block_start>output_dir=f"{out_dir}/images/"<line_sep>os.makedirs(output_dir exist_ok=<true>)<line_sep>imvs=imvs.detach().cpu().numpy()<line_sep>alphas=alphas.detach().cpu().numpy()<line_sep>mel_preds=mel_preds.detach().cpu().numpy()<line_sep>mel_gts=mel_gts.detach().cpu().numpy()<line_sep># logging.info(mel_gts.shape) i=1<line_sep># w, h = plt.figaspect(1.0 / len(imvs)) # fig = plt.Figure(figsize=(w * 1.3, h * 1.3)) <for_stmt>imv,alpha,mel_pred,mel_gt zip(imvs alphas mel_preds mel_gts)<block_start>fig,ax=plt.subplots(4)<line_sep>ax[0].plot(range(len(imv)) imv)<line_sep>ax[1].imshow(alpha[::-1])<line_sep>ax[2].imshow(mel_pred.T)<line_sep>ax[3].imshow(mel_gt.T)<line_sep>fig.savefig(f"{output_dir}/step{step}_{i}.png")<line_sep>i<augadd>1<if_stmt>i<g>4<block_start><break><block_end><block_end><block_end><def_stmt>plots2 alphas mel_preds mel_gts step out_dir num_plots=4<block_start>output_dir=f"{out_dir}/images/"<line_sep>os.makedirs(output_dir exist_ok=<true>)<line_sep>alphas=alphas.detach().cpu().numpy()<line_sep>mel_preds=mel_preds.detach().cpu().numpy()<line_sep>mel_gts=mel_gts.detach().cpu().numpy()<line_sep>i=1<for_stmt>alpha,mel_pred,mel_gt zip(alphas mel_preds mel_gts)<block_start>fig,ax=plt.subplots(3)<line_sep>ax[0].imshow(alpha[::-1])<line_sep>ax[1].imshow(mel_pred.T)<line_sep>ax[2].imshow(mel_gt.T)<line_sep>fig.savefig(f"{output_dir}/step{step}_{i}.png")<line_sep>i<augadd>1<if_stmt>i<g>4<block_start><break><block_end><block_end><block_end>
<import_stmt>torch<import_from_stmt>torch nn<as>nn<import_from_stmt>..utils.transformations transform_points_Rt<import_from_stmt>.alignment align<import_from_stmt>.backbones ResNetDecoder ResNetEncoder<import_from_stmt>.correspondence get_correspondences<import_from_stmt>.model_util get_grid grid_to_pointcloud points_to_ndc<import_from_stmt>.renderer PointsRenderer<def_stmt>project_rgb pc_0in1_X rgb_src renderer# create rgb_features <block_start>B,_,H,W=rgb_src.shape<line_sep>rgb_src=rgb_src.view(B 3 H<times>W)<line_sep>rgb_src=rgb_src.permute(0 2 1).contiguous()<line_sep># Rasterize and Blend project_0in1=renderer(pc_0in1_X rgb_src)<line_sep><return>project_0in1["feats"]<block_end><class_stmt>PCReg(nn.Module)<block_start><def_stmt>__init__ self cfg<block_start>super(PCReg self).__init__()<line_sep># set encoder decoder chan_in=3<line_sep>self.cfg=cfg<line_sep>feat_dim=cfg.feat_dim<line_sep># No imagenet pretraining pretrained=<false><line_sep>self.encode=ResNetEncoder(chan_in feat_dim pretrained)<line_sep>self.decode=ResNetDecoder(feat_dim 3 nn.Tanh() pretrained)<line_sep>self.renderer=PointsRenderer(cfg.renderer)<line_sep>self.num_corres=cfg.alignment.num_correspodances<line_sep>self.pointcloud_source=cfg.renderer.pointcloud_source<line_sep>self.align_cfg=cfg.alignment<block_end><def_stmt>forward self rgbs K deps vps=<none># Estimate Depth -- now for 1 and 2 <block_start>n_views=len(rgbs)<line_sep>output={}<line_sep># Encode features feats=[self.encode(rgbs[i])<for>i range(n_views)]<line_sep># generate pointclouds - generate grid once for efficience B,_,H,W=feats[0].shape<assert_stmt>feats[0].shape[-1]<eq>deps[0].shape[-1] "Same size"<line_sep>grid=get_grid(B H W)<line_sep>grid=grid.to(deps[0])<line_sep>K_inv=K.inverse()<line_sep>pointclouds=[grid_to_pointcloud(K_inv deps[i] feats[i] grid)<for>i range(n_views)]<line_sep>pcs_X=[pc[0]<for>pc pointclouds]<line_sep>pcs_F=[pc[1]<for>pc pointclouds]<if_stmt>vps<is><not><none># Drop first viewpoint -- assumed to be identity transformation <block_start>vps=vps[1:]<block_end><elif_stmt>self.align_cfg.algorithm<eq>"weighted_procrustes"<block_start>vps=[]<line_sep>cor_loss=[]<for_stmt>i range(1 n_views)<block_start>corr_i=get_correspondences(P1=pcs_F[0] P2=pcs_F[i] P1_X=pcs_X[0] P2_X=pcs_X[i] num_corres=self.num_corres ratio_test=(self.align_cfg.base_weight<eq>"nn_ratio") )<line_sep>Rt_i,cor_loss_i=align(corr_i pcs_X[0] pcs_X[i] self.align_cfg)<line_sep>vps.append(Rt_i)<line_sep>cor_loss.append(cor_loss_i)<line_sep># add for visualization output[f"corres_0{i}"]=corr_i<line_sep>output[f"vp_{i}"]=Rt_i<block_end><block_end><else_stmt><block_start><raise>ValueError(f"How to align using {self.align_cfg.algorithm}?")<block_end># add correspondance loss to output output["corr_loss"]=sum(cor_loss)<line_sep># Rotate points into the frame of the view image pcs_X_rot=[transform_points_Rt(pcs_X[i+1] vps[i] inverse=<true>)<for>i range(n_views-1)]<line_sep>pcs_X=pcs_X[0:1]+pcs_X_rot<line_sep>output["joint_pointcloud"]=torch.cat(pcs_X dim=1).detach().cpu()<line_sep># Get RGB pointcloud as well for direct rendering pcs_rgb=[rgb.view(B 3 -1).permute(0 2 1).contiguous()<for>rgb rgbs]<line_sep>projs=[]<line_sep># get joint for all values <if_stmt>self.pointcloud_source<eq>"joint"<block_start>pcs_X_joint=torch.cat(pcs_X dim=1)<line_sep>pcs_F_joint=torch.cat(pcs_F dim=1)<line_sep>pcs_RGB_joint=torch.cat(pcs_rgb dim=1)<line_sep>pcs_FRGB_joint=torch.cat((pcs_F_joint pcs_RGB_joint) dim=2)<block_end># Rasterize and Blend <for_stmt>i range(n_views)<block_start><if_stmt>self.pointcloud_source<eq>"other"# get joint for all values except the one <block_start>pcs_X_joint=torch.cat(pcs_X[0:i]+pcs_X[i+1:n_views] dim=1)<line_sep>pcs_F_joint=torch.cat(pcs_F[0:i]+pcs_F[i+1:n_views] dim=1)<line_sep>pcs_RGB_joint=torch.cat(pcs_rgb[0:i]+pcs_rgb[i+1:n_views] dim=1)<line_sep>pcs_FRGB_joint=torch.cat((pcs_F_joint pcs_RGB_joint) dim=2)<block_end><if_stmt>i<g>0<block_start>rot_joint_X=transform_points_Rt(pcs_X_joint vps[i-1])<line_sep>rot_joint_X=points_to_ndc(rot_joint_X K (H W))<block_end><else_stmt><block_start>rot_joint_X=points_to_ndc(pcs_X_joint K (H W))<block_end>projs.append(self.renderer(rot_joint_X pcs_FRGB_joint))<block_end># Decode <for_stmt>i range(n_views)<block_start>proj_FRGB_i=projs[i]["feats"]<line_sep>proj_RGB_i=proj_FRGB_i[: -3:]<line_sep>proj_F_i=proj_FRGB_i[: :-3]<line_sep>output[f"rgb_decode_{i}"]=self.decode(proj_F_i)<line_sep>output[f"rgb_render_{i}"]=proj_RGB_i<line_sep>output[f"ras_depth_{i}"]=projs[i]["depth"]<line_sep>output[f"cover_{i}"]=projs[i]["mask"].unsqueeze(1)<block_end># useless <return>output<block_end><def_stmt>forward_pcreg self rgbs K deps# Estimate Depth -- now for 1 and 2 <block_start>n_views=len(rgbs)<line_sep>output={}<line_sep># Encode features feats=[self.encode(rgbs[i])<for>i range(n_views)]<line_sep># generate pointclouds - generate grid once for efficience B,_,H,W=feats[0].shape<assert_stmt>feats[0].shape[-1]<eq>deps[0].shape[-1] "Same size"<line_sep>grid=get_grid(B H W)<line_sep>grid=grid.to(deps[0])<line_sep>K_inv=K.inverse()<line_sep>pointclouds=[grid_to_pointcloud(K_inv deps[i] feats[i] grid)<for>i range(n_views)]<line_sep>pcs_X=[pc[0]<for>pc pointclouds]<line_sep>pcs_F=[pc[1]<for>pc pointclouds]<line_sep>vps=[]<line_sep>cor_loss=[]<for_stmt>i range(1 n_views)<block_start>corr_i=get_correspondences(P1=pcs_F[0] P2=pcs_F[i] P1_X=pcs_X[0] P2_X=pcs_X[i] num_corres=self.num_corres ratio_test=(self.align_cfg.base_weight<eq>"nn_ratio") )<line_sep>Rt_i,cor_loss_i=align(corr_i pcs_X[0] pcs_X[i] self.align_cfg)<line_sep>vps.append(Rt_i)<line_sep>cor_loss.append(cor_loss_i)<line_sep># add for visualization output[f"corres_0{i}"]=corr_i<line_sep>output[f"vp_{i}"]=Rt_i<block_end># add correspondance loss to output output["corr_loss"]=sum(cor_loss)<line_sep># Rotate points into the frame of the view image pcs_X_rot=[transform_points_Rt(pcs_X[i+1] vps[i] inverse=<true>)<for>i range(n_views-1)]<line_sep>pcs_X=pcs_X[0:1]+pcs_X_rot<line_sep>output["joint_pointcloud"]=torch.cat(pcs_X dim=1).detach().cpu()<line_sep><return>output<block_end><def_stmt>generate_pointclouds self K deps vps=<none><block_start>n_views=len(deps)<line_sep># generate pointclouds - generate grid once for efficiency B,_,H,W=deps[0].shape<line_sep>grid=get_grid(B H W)<line_sep>grid=grid.to(deps[0])<line_sep>K_inv=K.inverse()<line_sep>pcs_X=[grid_to_pointcloud(K_inv deps[i] <none> grid)[0]<for>i range(n_views)]<if_stmt>vps<is><not><none><block_start>pcs_X_rot=[transform_points_Rt(pcs_X[i+1] vps[i+1] inverse=<true> )<for>i range(n_views-1)]<line_sep>pcs_X=pcs_X[0:1]+pcs_X_rot<line_sep>pcs_X=torch.cat(pcs_X dim=1).detach().cpu()<block_end><return>pcs_X<block_end><def_stmt>get_feature_pcs self rgbs K deps# Estimate Depth -- now for 1 and 2 <block_start>n_views=len(rgbs)<line_sep># Encode features feats=[self.encode(rgbs[i])<for>i range(n_views)]<line_sep># generate pointclouds - generate grid once for efficience B,_,H,W=feats[0].shape<assert_stmt>(feats[0].shape[-1]<eq>deps[0].shape[-1]) f"Same size {feats[0].shape} - {deps[0].shape}"<line_sep>grid=get_grid(B H W)<line_sep>grid=grid.to(deps[0])<line_sep>K_inv=K.inverse()<line_sep>pointclouds=[grid_to_pointcloud(K_inv deps[i] feats[i] grid)<for>i range(n_views)]<line_sep>pcs_X=[pc[0]<for>pc pointclouds]<line_sep>pcs_F=[pc[1]<for>pc pointclouds]<line_sep><return>pcs_X pcs_F <none><block_end><block_end>
<import_stmt>torch<import_stmt>torch.nn<as>nn<import_from_stmt>timm.models.helpers load_pretrained<import_from_stmt>timm.models.registry register_model<import_from_stmt>timm.models.layers trunc_normal_<import_from_stmt>timm.models.resnet resnet26d resnet50d resnet101d<import_stmt>numpy<as>np<import_from_stmt>.layers *<def_stmt>_cfg url='' **kwargs<block_start><return>{'url':url 'num_classes':1000 'input_size':(3 224 224) 'pool_size':<none> 'crop_pct':.9 'interpolation':'bicubic' 'mean':(0.485 0.456 0.406) 'std':(0.229 0.224 0.225) 'classifier':'head' **kwargs}<block_end>default_cfgs={'LV_ViT_Tiny':_cfg() 'LV_ViT':_cfg() 'LV_ViT_Medium':_cfg(crop_pct=1.0) 'LV_ViT_Large':_cfg(crop_pct=1.0) }<def_stmt>get_block block_type **kargs<block_start><if_stmt>block_type<eq>'mha'# multi-head attention block <block_start><return>MHABlock(**kargs)<block_end><elif_stmt>block_type<eq>'ffn'# feed forward block <block_start><return>FFNBlock(**kargs)<block_end><elif_stmt>block_type<eq>'tr'# transformer block <block_start><return>Block(**kargs)<block_end><block_end><def_stmt>rand_bbox size lam<block_start>W=size[2]<line_sep>H=size[3]<line_sep>cut_rat=np.sqrt(1.-lam)<line_sep>cut_w=np.int(W<times>cut_rat)<line_sep>cut_h=np.int(H<times>cut_rat)<line_sep># uniform cx=np.random.randint(W)<line_sep>cy=np.random.randint(H)<line_sep>bbx1=np.clip(cx-cut_w<floordiv>2 0 W)<line_sep>bby1=np.clip(cy-cut_h<floordiv>2 0 H)<line_sep>bbx2=np.clip(cx+cut_w<floordiv>2 0 W)<line_sep>bby2=np.clip(cy+cut_h<floordiv>2 0 H)<line_sep><return>bbx1 bby1 bbx2 bby2<block_end><def_stmt>get_dpr drop_path_rate depth drop_path_decay='linear'<block_start><if_stmt>drop_path_decay<eq>'linear'# linear dpr decay <block_start>dpr=[x.item()<for>x torch.linspace(0 drop_path_rate depth)]# stochastic depth decay rule <block_end><elif_stmt>drop_path_decay<eq>'fix'# use fixed dpr <block_start>dpr=[drop_path_rate]<times>depth<block_end><else_stmt># use predefined drop_path_rate list <block_start><assert_stmt>len(drop_path_rate)<eq>depth<line_sep>dpr=drop_path_rate<block_end><return>dpr<block_end><class_stmt>LV_ViT(nn.Module)<block_start>""" Vision Transformer with tricks Arguements: p_emb: different conv based position embedding (default: 4 layer conv) skip_lam: residual scalar for skip connection (default: 1.0) order: which order of layers will be used (default: None, will override depth if given) mix_token: use mix token augmentation for batch of tokens (default: False) return_dense: whether to return feature of all tokens with an additional aux_head (default: False) """<def_stmt>__init__ self img_size=224 patch_size=16 in_chans=3 num_classes=1000 embed_dim=768 depth=12 num_heads=12 mlp_ratio=4. qkv_bias=<false> qk_scale=<none> drop_rate=0. attn_drop_rate=0. drop_path_rate=0. drop_path_decay='linear' hybrid_backbone=<none> norm_layer=nn.LayerNorm p_emb='4_2' head_dim=<none> skip_lam=1.0 order=<none> mix_token=<false> return_dense=<false><block_start>super().__init__()<line_sep>self.num_classes=num_classes<line_sep>self.num_features=self.embed_dim=embed_dim# num_features for consistency with other models self.output_dim=embed_dim<if>num_classes<eq>0<else>num_classes<if_stmt>hybrid_backbone<is><not><none><block_start>self.patch_embed=HybridEmbed(hybrid_backbone img_size=img_size in_chans=in_chans embed_dim=embed_dim)<block_end><else_stmt><block_start><if_stmt>p_emb<eq>'4_2'<block_start>patch_embed_fn=PatchEmbed4_2<block_end><elif_stmt>p_emb<eq>'4_2_128'<block_start>patch_embed_fn=PatchEmbed4_2_128<block_end><else_stmt><block_start>patch_embed_fn=PatchEmbedNaive<block_end>self.patch_embed=patch_embed_fn(img_size=img_size patch_size=patch_size in_chans=in_chans embed_dim=embed_dim)<block_end>num_patches=self.patch_embed.num_patches<line_sep>self.cls_token=nn.Parameter(torch.zeros(1 1 embed_dim))<line_sep>self.pos_embed=nn.Parameter(torch.zeros(1 num_patches+1 embed_dim))<line_sep>self.pos_drop=nn.Dropout(p=drop_rate)<if_stmt>order<is><none><block_start>dpr=get_dpr(drop_path_rate depth drop_path_decay)<line_sep>self.blocks=nn.ModuleList([Block(dim=embed_dim num_heads=num_heads head_dim=head_dim mlp_ratio=mlp_ratio qkv_bias=qkv_bias qk_scale=qk_scale drop=drop_rate attn_drop=attn_drop_rate drop_path=dpr[i] norm_layer=norm_layer skip_lam=skip_lam)<for>i range(depth)])<block_end><else_stmt># use given order to sequentially generate modules <block_start>dpr=get_dpr(drop_path_rate len(order) drop_path_decay)<line_sep>self.blocks=nn.ModuleList([get_block(order[i] dim=embed_dim num_heads=num_heads head_dim=head_dim mlp_ratio=mlp_ratio qkv_bias=qkv_bias qk_scale=qk_scale drop=drop_rate attn_drop=attn_drop_rate drop_path=dpr[i] norm_layer=norm_layer skip_lam=skip_lam)<for>i range(len(order))])<block_end>self.norm=norm_layer(embed_dim)<line_sep>self.head=nn.Linear(embed_dim num_classes)<if>num_classes<g>0<else>nn.Identity()<line_sep>self.return_dense=return_dense<line_sep>self.mix_token=mix_token<if_stmt>return_dense<block_start>self.aux_head=nn.Linear(embed_dim num_classes)<if>num_classes<g>0<else>nn.Identity()<block_end><if_stmt>mix_token<block_start>self.beta=1.0<assert_stmt>return_dense "always return all features when mixtoken is enabled"<block_end>trunc_normal_(self.pos_embed std=.02)<line_sep>trunc_normal_(self.cls_token std=.02)<line_sep>self.apply(self._init_weights)<block_end><def_stmt>_init_weights self m<block_start><if_stmt>isinstance(m nn.Linear)<block_start>trunc_normal_(m.weight std=.02)<if_stmt>isinstance(m nn.Linear)<and>m.bias<is><not><none><block_start>nn.init.constant_(m.bias 0)<block_end><block_end><elif_stmt>isinstance(m GroupLinear)<block_start>trunc_normal_(m.group_weight std=.02)<if_stmt>isinstance(m GroupLinear)<and>m.group_bias<is><not><none><block_start>nn.init.constant_(m.group_bias 0)<block_end><block_end><elif_stmt>isinstance(m nn.LayerNorm)<block_start>nn.init.constant_(m.bias 0)<line_sep>nn.init.constant_(m.weight 1.0)<block_end><block_end>@torch.jit.ignore<def_stmt>no_weight_decay self<block_start><return>{'pos_embed' 'cls_token'}<block_end><def_stmt>get_classifier self<block_start><return>self.head<block_end><def_stmt>reset_classifier self num_classes global_pool=''<block_start>self.num_classes=num_classes<line_sep>self.head=nn.Linear(self.embed_dim num_classes)<if>num_classes<g>0<else>nn.Identity()<block_end><def_stmt>forward_embeddings self x<block_start>x=self.patch_embed(x)<line_sep><return>x<block_end><def_stmt>forward_tokens self x<block_start>B=x.shape[0]<line_sep>cls_tokens=self.cls_token.expand(B -1 -1)<line_sep>x=torch.cat((cls_tokens x) dim=1)<line_sep>x=x+self.pos_embed<line_sep>x=self.pos_drop(x)<for_stmt>blk self.blocks<block_start>x=blk(x)<block_end>x=self.norm(x)<line_sep><return>x<block_end><def_stmt>forward_features self x# simple forward to obtain feature map (without mixtoken) <block_start>x=self.forward_embeddings(x)<line_sep>x=x.flatten(2).transpose(1 2)<line_sep>x=self.forward_tokens(x)<line_sep><return>x<block_end><def_stmt>forward self x<block_start>x=self.forward_embeddings(x)<line_sep># token level mixtoken augmentation <if_stmt>self.mix_token<and>self.training<block_start>lam=np.random.beta(self.beta self.beta)<line_sep>patch_h,patch_w=x.shape[2] x.shape[3]<line_sep>bbx1,bby1,bbx2,bby2=rand_bbox(x.size() lam)<line_sep>temp_x=x.clone()<line_sep>temp_x[: : bbx1:bbx2 bby1:bby2]=x.flip(0)[: : bbx1:bbx2 bby1:bby2]<line_sep>x=temp_x<block_end><else_stmt><block_start>bbx1,bby1,bbx2,bby2=0 0 0 0<block_end>x=x.flatten(2).transpose(1 2)<line_sep>x=self.forward_tokens(x)<line_sep>x_cls=self.head(x[: 0])<if_stmt>self.return_dense<block_start>x_aux=self.aux_head(x[: 1:])<if_stmt><not>self.training<block_start><return>x_cls+0.5<times>x_aux.max(1)[0]<block_end># recover the mixed part <if_stmt>self.mix_token<and>self.training<block_start>x_aux=x_aux.reshape(x_aux.shape[0] patch_h patch_w x_aux.shape[-1])<line_sep>temp_x=x_aux.clone()<line_sep>temp_x[: bbx1:bbx2 bby1:bby2 :]=x_aux.flip(0)[: bbx1:bbx2 bby1:bby2 :]<line_sep>x_aux=temp_x<line_sep>x_aux=x_aux.reshape(x_aux.shape[0] patch_h<times>patch_w x_aux.shape[-1])<block_end><return>x_cls x_aux (bbx1 bby1 bbx2 bby2)<block_end><return>x_cls<block_end><block_end>@register_model<def_stmt>vit pretrained=<false> **kwargs<block_start>model=LV_ViT(patch_size=16 embed_dim=384 depth=16 num_heads=6 mlp_ratio=3. p_emb=1 **kwargs)<line_sep>model.default_cfg=default_cfgs['LV_ViT']<line_sep><return>model<block_end>@register_model<def_stmt>lvvit pretrained=<false> **kwargs<block_start>model=LV_ViT(patch_size=16 embed_dim=384 depth=16 num_heads=6 mlp_ratio=3. p_emb='4_2' skip_lam=2. **kwargs)<line_sep>model.default_cfg=default_cfgs['LV_ViT']<line_sep><return>model<block_end>@register_model<def_stmt>lvvit_s pretrained=<false> **kwargs<block_start>model=LV_ViT(patch_size=16 embed_dim=384 depth=16 num_heads=6 mlp_ratio=3. p_emb='4_2' skip_lam=2. return_dense=<true> mix_token=<true> **kwargs)<line_sep>model.default_cfg=default_cfgs['LV_ViT']<line_sep><return>model<block_end>@register_model<def_stmt>lvvit_m pretrained=<false> **kwargs<block_start>model=LV_ViT(patch_size=16 embed_dim=512 depth=20 num_heads=8 mlp_ratio=3. p_emb='4_2' skip_lam=2. return_dense=<true> mix_token=<true> **kwargs)<line_sep>model.default_cfg=default_cfgs['LV_ViT_Medium']<line_sep><return>model<block_end>@register_model<def_stmt>lvvit_l pretrained=<false> **kwargs<block_start>order=['tr']<times>24# this will override depth, can also be set as None model=LV_ViT(patch_size=16 embed_dim=768 depth=24 num_heads=12 mlp_ratio=3. p_emb='4_2_128' skip_lam=3. return_dense=<true> mix_token=<true> order=order **kwargs)<line_sep>model.default_cfg=default_cfgs['LV_ViT_Large']<line_sep><return>model<block_end>
<import_from_stmt>django.conf settings<import_from_stmt>portia_api.jsonapi JSONResponse<import_from_stmt>portia_api.jsonapi.renderers JSONRenderer<import_from_stmt>.models Job Log Schedule JobItem <import_stmt>time datetime<import_stmt>requests<import_from_stmt>storage get_storage_class create_project_storage <import_from_stmt>portia_orm.models Project<import_stmt>inspect<import_stmt>uuid<import_stmt>re<import_from_stmt>django.db.models Max<import_stmt>logging<line_sep>logger=logging.getLogger('portia_dashboard')<def_stmt>_request_get url<block_start>retryTime=5<line_sep>res=<none><for_stmt>i range(retryTime)<block_start><try_stmt><block_start>res=requests.get(url)#self.proxyUtil.getRandomProxy()) <if_stmt>res.status_code<ne>200<block_start><continue><block_end><break><block_end><except_stmt><block_start><continue><block_end><block_end><return>res<block_end><def_stmt>_request_post url<block_start>retryTime=5<line_sep>res=<none><for_stmt>i range(retryTime)<block_start><try_stmt><block_start>res=requests.post(url)#self.proxyUtil.getRandomProxy()) <if_stmt>res.status_code<ne>200<block_start><continue><block_end><break><block_end><except_stmt><block_start><continue><block_end><block_end><return>res<block_end><def_stmt>matchDate line<block_start>matchThis=""<line_sep>matched=re.match(r'\d\d\d\d-\d\d-\d\d\ \d\d:\d\d:\d\d' line)<if_stmt>matched#matches a date and adds it to matchThis <block_start>matchThis=matched.group()<block_end><else_stmt><block_start>matchThis="NONE"<block_end><return>matchThis<block_end><def_stmt>parseLine line<block_start><return>re.findall(r'(?P<date>\d\d\d\d-\d\d-\d\d\ \d\d:\d\d:\d\d) \[(?P<source>[^\]]+)\] (?P<level>INFO|DEBUG|ERROR|WARNING|CRITICAL): (?P<text>.*)' line)[0]<block_end><def_stmt>generateDicts log<block_start>currentDict={}<line_sep>index=1<for_stmt>line log.splitlines()<block_start><if_stmt>line.startswith(matchDate(line))<block_start><if_stmt>currentDict<block_start><yield>currentDict<block_end>date,source,level,text=parseLine(line)<line_sep>currentDict={"index":index "date":date "source":source "level":level "text":text}<line_sep>index=index+1<block_end><else_stmt><block_start>currentDict["text"]<augadd>line<block_end><block_end><yield>currentDict<block_end><def_stmt>_get_log_from_scrapyd project_id spider_id job_id<block_start>res=_request_get("%s/logs/%s/%s/%s.log"%(settings.SCRAPYD_URL project_id spider_id job_id))<line_sep><return>res.text<if>res.status_code<eq>200<else>''<block_end><def_stmt>_get_log project_id spider_id job_id job_status<block_start>log=<none><try_stmt><block_start>log=Log.objects.get(id=job_id)<block_end><except_stmt>Log.DoesNotExist<block_start>content=_get_log_from_scrapyd(project_id spider_id job_id)<line_sep>log=Log.objects.create(id=job_id content=content)<line_sep><return>log<block_end><if_stmt>job_status<ne>'finished'<block_start>log.content=_get_log_from_scrapyd(project_id spider_id job_id)<line_sep>log.save()<block_end><return>log<block_end><def_stmt>job_log request<block_start>result=[]<line_sep>project_id=request.GET.get('project')<line_sep>spider_id=request.GET.get('spider')<line_sep>job_id=request.GET.get('job')<line_sep>job=Job.objects.get(id=job_id)<if_stmt>job<block_start>log=_get_log(project_id job.spider job.id job.status)<if_stmt>log<block_start>result=list(generateDicts(log.content))<block_end><block_end><return>JSONResponse({"project":project_id "spider":spider_id "job":job_id "log":result})<block_end><def_stmt>_get_log_count project_id spider_id job_id job_status<block_start>warnings,errors,criticals=0 0 0<line_sep>log=_get_log(project_id spider_id job_id job_status)<if_stmt>log<block_start><try_stmt><block_start>result=list(generateDicts(log.content))<for_stmt>item result<block_start><if_stmt>item['level']<eq>'WARNING'<block_start>warnings<augadd>1<block_end><elif_stmt>item['level']<eq>'ERROR'<block_start>errors<augadd>1<block_end><elif_stmt>item['level']<eq>'CRITICAL'<block_start>criticals<augadd>1<block_end><block_end><block_end><except_stmt>KeyError<block_start><pass><block_end><block_end><return>warnings errors criticals<block_end><def_stmt>job_cancel request<block_start>project_id=request.GET.get('project')<line_sep>job_id=request.GET.get('job')<line_sep>res=_request_post("%s/cancel.json?project=%s&job=%s"%(settings.SCRAPYD_URL project_id job_id))<if_stmt>res<block_start>result=res.json()<if_stmt>result.get("status" '')<eq>'ok'<block_start><return>JSONResponse({'status':'ok'})<block_end><block_end><return>JSONResponse({'status':'error'})<block_end><def_stmt>job_delete request<block_start>id=request.GET.get('job')<if_stmt>id<block_start>Job.objects.get(id=id).delete()<line_sep>Log.objects.get(id=id).delete()<line_sep><return>JSONResponse({'status':'ok'})<block_end><else_stmt><block_start><return>JSONResponse({'status':'error'})<block_end><block_end><def_stmt>_get_timestamp_from_string timestring<block_start>dt=datetime.datetime.strptime(timestring "%Y-%m-%d %H:%M:%S.%f")<line_sep>ts=time.mktime(dt.timetuple())<times>1000<line_sep><return>ts<block_end><def_stmt>_get_stub_job <block_start><try_stmt><block_start>job=Job.objects.get(id='ffffffffffffffff0000000000000000')<block_end><except_stmt>Job.DoesNotExist<block_start>job=Job.objects.create(id='ffffffffffffffff0000000000000000' spider='' start_time=0 index=0)<block_end><return>job<block_end><def_stmt>_get_last_start_time <block_start>job=_get_stub_job()<line_sep>max_start_time=job.start_time<line_sep><return>max_start_time<block_end><def_stmt>_set_last_start_time last_start_time<block_start>job=_get_stub_job()<line_sep>job.start_time=last_start_time<line_sep>job.save()<block_end><def_stmt>_get_last_index <block_start>job=_get_stub_job()<line_sep>last_index=job.index<line_sep><return>last_index<block_end><def_stmt>_set_last_index last_index<block_start>job=_get_stub_job()<line_sep>job.index=last_index<line_sep>job.save()<block_end><def_stmt>_update_jobs_model project_id#last_start_time = _get_last_start_time() <block_start>updated_count=0<line_sep>created_count=0<line_sep>res=_request_get("%s/listjobs.json?project=%s"%(settings.SCRAPYD_URL project_id))<if_stmt>res<block_start><for_stmt>status ['pending' 'running' 'finished']<block_start>data=res.json().get(status [])<line_sep>jobs=[]<for_stmt>item data<block_start>created=<false><try_stmt><block_start>job=Job.objects.get(id=item['id'])<block_end><except_stmt>Job.DoesNotExist<block_start><if_stmt>'start_time'<in>item<and>_get_timestamp_from_string(item['start_time'])<le>_get_last_start_time()# the job must be removed, so skip it <block_start><continue><block_end>job=Job.objects.create(id=item['id'] spider=item['spider'] index=(_get_last_index()+1))<line_sep>_set_last_index(job.index)<line_sep>created=<true><line_sep>created_count<augadd>1<block_end>#job maybe changed if not in 'finished' status. <if_stmt>job.status<ne>'finished'<or>job.start_time<eq>0<or>job.end_time<eq>0<block_start><if_stmt>'start_time'<in>item<block_start>job.start_time=_get_timestamp_from_string(item['start_time'])<block_end><if_stmt>'end_time'<in>item<block_start>job.end_time=_get_timestamp_from_string(item['end_time'])<block_end><if_stmt>status<eq>'finished'<block_start>job.warning_count,job.error_count,job.critical_count=_get_log_count(project_id job.spider job.id job.status)<block_end>job.status=status<line_sep>job.save()<line_sep>updated_count<augadd>1<block_end><if_stmt>created<eq><true><and>job.start_time<g>_get_last_start_time()<block_start>_set_last_start_time(job.start_time)<block_end><block_end><block_end><block_end><return>created_count updated_count<block_end><def_stmt>_get_string_from_timestamp timestamp<block_start><return>datetime.datetime.fromtimestamp(timestamp/1000).strftime("%Y-%m-%d %H:%M:%S")<block_end><def_stmt>job_list request<block_start>result={}<line_sep>project_id=request.GET.get('project')<line_sep>spider=request.GET.get('spider' '')<line_sep>_update_jobs_model(project_id)<for_stmt>status ['pending' 'running' 'finished']<block_start>res_jobs=[]<line_sep>jobs=Job.objects.filter(status=status).order_by('-start_time')<for_stmt>job jobs<block_start><if_stmt>(spider<eq>''<or>spider<eq>job.spider)<block_start>res_jobs.append({'id':job.id 'index':job.index 'project':project_id 'spider':job.spider 'start_time':_get_string_from_timestamp(job.start_time) 'end_time':_get_string_from_timestamp(job.end_time) 'error_count':job.error_count 'warning_count':job.warning_count 'critical_count':job.critical_count})<block_end><block_end>result[status]=res_jobs<block_end><return>JSONResponse(result)<block_end><def_stmt>schedule_add request<block_start>project=request.GET.get('project')<line_sep>spider=request.GET.get('spider')<line_sep>interval=request.GET.get('interval')<line_sep>times=request.GET.get('times')<if_stmt>project<and>spider<and>interval<block_start>schedule=Schedule(id=uuid.uuid1().hex project=project spider=spider start_time=int(time.time()<times>1000) interval=interval times=times date_update=int(time.time()<times>1000))<line_sep>schedule.save()<line_sep><return>JSONResponse({'status':'ok'})<block_end><else_stmt><block_start><return>JSONResponse({'status':'error'})<block_end><block_end><def_stmt>schedule_list request<block_start>result=[]<line_sep>schedules=Schedule.objects.all()<for_stmt>schedule schedules<block_start>result.append({'id':schedule.id 'project':schedule.project 'spider':schedule.spider 'start_time':_get_string_from_timestamp(schedule.start_time) 'update_time':_get_string_from_timestamp(schedule.date_update) 'interval':schedule.interval 'times':schedule.times})<block_end><return>JSONResponse(result)<block_end><def_stmt>schedule_del request<block_start>id=request.GET.get('id')<if_stmt>id<block_start>Schedule.objects.get(id=id).delete()<line_sep><return>JSONResponse({'status':'ok'})<block_end><else_stmt><block_start><return>JSONResponse({'status':'error'})<block_end><block_end><def_stmt>article_list request<block_start>result=[]<line_sep>job=request.GET.get('job')<line_sep>items=JobItem.objects(job=job)<for_stmt>item items<block_start>res={'id':str(item.id) 'item-display-name':'item' 'job':item.job 'spider':item.spider 'url':item.url 'time':item.time.strftime("%Y-%m-%d %H:%M:%S")}<line_sep>result.append(res)<block_end><return>JSONResponse(result)<block_end><def_stmt>article_detail request<block_start>result={}<line_sep>job_item_id=request.GET.get('job_item')<line_sep>job_items=JobItem.objects(id=job_item_id)<if_stmt>job_items[0]<block_start><for_stmt>name,value job_items[0].__dict__.iteritems()<block_start><if_stmt><not>name.startswith('_')<and><not>inspect.ismethod(value)#value = getattr(item, name ) <block_start>result[name]=value<block_end><block_end><block_end><return>JSONResponse(result)<block_end><def_stmt>article_del request<block_start>spider_id=request.GET.get('spider')<line_sep>job_id=request.GET.get('job')<line_sep>job_item_id=request.GET.get('job_item')<if_stmt>spider_id<block_start>jobItems=JobItem.objects.filter(spider=spider_id)<for_stmt>item jobItems<block_start>item.delete()<block_end><return>JSONResponse({'status':'ok'})<block_end><elif_stmt>job_id<block_start>jobItems=JobItem.objects.filter(job=job_id)<for_stmt>item jobItems<block_start>item.delete()<block_end><return>JSONResponse({'status':'ok'})<block_end><elif_stmt>job_item_id<block_start>JobItem.objects.get(id=job_item_id).delete()<line_sep><return>JSONResponse({'status':'ok'})<block_end><else_stmt><block_start><return>JSONResponse({'status':'error'})<block_end><block_end>
# -*- coding: utf-8 -*- """Test file."""<line_sep>""" >>> from pyrgg import * >>> import pyrgg.params >>> import random >>> import os >>> import json >>> import yaml >>> import pickle >>> pyrgg.params.PYRGG_TEST_MODE = True >>> get_precision(2) 0 >>> get_precision(2.2) 1 >>> get_precision(2.22) 2 >>> get_precision(2.223) 3 >>> convert_str_to_number("20") 20 >>> convert_str_to_number("20.2") 20.2 >>> convert_str_to_bool("1") True >>> convert_str_to_bool("3") True >>> convert_str_to_bool("0") False >>> is_float(10) False >>> is_float(10.2) True >>> is_float(None) False >>> result = input_filter({"file_name": "test","vertices": 5,"max_weight": 1000,"min_weight":455,"min_edge": -45,"max_edge": -11,"sign": False,"output_format": 19, "direct": False,"self_loop": True,"multigraph":False,"number_of_files":2}) >>> result == {'output_format': 1, 'min_weight': 455, 'min_edge': 5, 'max_edge': 5, 'file_name': 'test', 'vertices': 5, 'max_weight': 1000, 'sign': False, "direct": False,"self_loop": True,"multigraph":False,"number_of_files":2} True >>> result = input_filter({"file_name": "test","vertices": 5,"max_weight": 1000,"min_weight":455,"min_edge": -45,"max_edge": -11,"sign": False,"output_format": 19, "direct": False,"self_loop": False,"multigraph":False,"number_of_files":2}) >>> result == {'output_format': 1, 'min_weight': 455, 'min_edge': 4, 'max_edge': 4, 'file_name': 'test', 'vertices': 5, 'max_weight': 1000, 'sign': False, "direct": False,"self_loop": False,"multigraph":False,"number_of_files":2} True >>> result = input_filter({"file_name": "test","vertices": -5,"max_weight": 1000,"min_weight":455,"min_edge": -45,"max_edge": -11,"sign": False,"output_format": 19, "direct": False,"self_loop": False,"multigraph":True,"number_of_files":-1}) >>> result == {'output_format': 1, 'min_weight': 455, 'min_edge': 11, 'max_edge': 45, 'file_name': 'test', 'vertices': 5, 'max_weight': 1000, 'sign': False, "direct": False,"self_loop": False,"multigraph":True,"number_of_files":1} True >>> result = input_filter({"file_name": "test2","vertices": 23,"max_weight": 2,"min_weight": 80,"min_edge": 23,"max_edge": 1,"sign": True,"output_format": 1, "direct": False,"self_loop": True,"multigraph":False,"number_of_files":100}) >>> result == {'min_weight': 2, 'vertices': 23, 'file_name': 'test2', 'max_edge': 23, 'min_edge': 1, 'max_weight': 80, 'output_format': 1, 'sign': True, "direct": False,"self_loop": True,"multigraph":False,"number_of_files":100} True >>> logger('test',100,50,1000,10,1,0,0,1,20,1,'2min') >>> file=open('logfile.log','r') >>> print("\n".join(file.read().splitlines()[1:-1])) Filename : test Vertices : 100 Total Edges : 50 Max Edge : 1000 Min Edge : 10 Directed : True Signed : False Multigraph : False Self Loop : True Weighted : True Max Weight : 20 Min Weight : 1 Elapsed Time : 2min >>> convert_bytes(200) '200.0 bytes' >>> convert_bytes(6000) '5.9 KB' >>> convert_bytes(80000) '78.1 KB' >>> time_convert(33) '00 days, 00 hours, 00 minutes, 33 seconds' >>> time_convert(15000) '00 days, 04 hours, 10 minutes, 00 seconds' >>> time_convert('sadasdasd') Traceback (most recent call last): ... ValueError: could not convert string to float: 'sadasdasd' >>> line(12,"*") ************ >>> random.seed(2) >>> sign_gen() 1 >>> random.seed(11) >>> sign_gen() -1 >>> used_vertices = {k:[] for k in range(1,41)} >>> degree_dict = {k:0 for k in range(1,41)} >>> degree_dict_sort = {k:{} for k in range(41)} >>> degree_dict_sort[0] = {i:i for i in range(1,41)} >>> all_vertices = list(range(1, 41)) >>> random.seed(2) >>> branch_gen(1,10,10,1,20,True,True,True,False,used_vertices,degree_dict,degree_dict_sort) [[4, 25, 18, 3, 30, 34, 2, 26, 14, 11], [3, 10, 20, 14, -18, -2, -15, -14, 8, 6]] >>> random.seed(20) >>> branch_gen(1,10,4,1,20,False,True,True,False,used_vertices,degree_dict,degree_dict_sort) [[], []] >>> used_vertices = {k:[] for k in range(1,41)} >>> degree_dict = {k:0 for k in range(1,41)} >>> degree_dict_sort = {k:{} for k in range(41)} >>> degree_dict_sort[0] = {i:i for i in range(1,41)} >>> branch_gen(1,10,4,1,20,False,True,True,False,used_vertices,degree_dict,degree_dict_sort) [[10, 7, 39, 2], [9, 11, 6, 14]] >>> branch_gen(40,1,20,1) Traceback (most recent call last): ... TypeError: branch_gen() missing 8 required positional arguments: 'max_weight', 'sign', 'direct', 'self_loop', 'multigraph', 'used_vertices', 'degree_dict', and 'degree_sort_dict' >>> random.seed(2) >>> edge_gen(20,0,400,2,10,True,True,True,False) [{1: [3, 7], 2: [4, 17, 20, 9, 11], 3: [14, 8, 5, 12, 16, 19, 15], 4: [15, 17, 12, 8, 14, 13], 5: [16, 9, 7, 20, 19, 18, 13, 5], 6: [6, 10], 7: [18, 10, 11], 8: [], 9: [], 10: [12, 18, 8, 1, 14], 11: [9, 11], 12: [], 13: [], 14: [19, 16, 17, 20, 15], 15: [6, 1, 19], 16: [12, 13, 8, 9, 17], 17: [], 18: [9, 12, 17, 6, 20, 19, 1], 19: [13], 20: []}, {1: [184, -128], 2: [220, -278, -257, 14, -163], 3: [286, 118, 166, 261, -263, 228, -303], 4: [-82, -335, 250, -256, -338, -179], 5: [-337, -358, -395, -155, -159, 250, -350, -371], 6: [30, -302], 7: [386, -125, 216], 8: [], 9: [], 10: [127, 42, 12, 191, 80], 11: [-301, 77], 12: [], 13: [], 14: [146, -15, -282, 135, 242], 15: [-52, -65, -249], 16: [-132, -334, 343, -17, 87], 17: [], 18: [126, -37, 302, -131, -142, 77, -209], 19: [123], 20: []}, 61] >>> random.seed(11) >>> edge_gen(20,0,100,2,10,False,True,True,False) [{1: [18, 15, 19, 7, 20, 11, 2, 6, 3], 2: [17], 3: [8, 4, 5, 9, 12, 10, 14, 16], 4: [20, 13, 4, 6], 5: [12, 7, 11, 10, 14], 6: [9], 7: [19], 8: [8, 18, 11, 2, 16, 17, 10], 9: [15, 12, 18], 10: [20, 14, 13, 15, 17, 16], 11: [19, 7, 20], 12: [13], 13: [2, 16, 13], 14: [18, 19, 6, 14, 17, 15], 15: [6, 7, 16], 16: [17, 20, 12, 18], 17: [19], 18: [7, 6, 9, 12, 20], 19: [19, 11, 4], 20: []}, {1: [99, 57, 75, 23, 80, 23, 57, 18, 68], 2: [50], 3: [79, 67, 7, 24, 76, 99, 41, 75], 4: [29, 63, 84, 58], 5: [70, 90, 40, 65, 3], 6: [51], 7: [37], 8: [2, 0, 26, 60, 90, 53, 72], 9: [43, 39, 1], 10: [15, 31, 1, 59, 22, 57], 11: [98, 53, 49], 12: [53], 13: [34, 2, 23], 14: [82, 12, 18, 56, 1, 37], 15: [9, 26, 1], 16: [47, 58, 75, 73], 17: [23], 18: [39, 78, 92, 20, 49], 19: [10, 6, 13], 20: []}, 74] >>> edge_gen(0,400,2,10,1) Traceback (most recent call last): ... TypeError: edge_gen() missing 4 required positional arguments: 'sign', 'direct', 'self_loop', and 'multigraph' >>> random.seed(2) >>> dimacs_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.gr','r') >>> print(file.read()) c FILE :testfile.gr c No. of vertices :10 c No. of edges :7 c Max. weight :200 c Min. weight :0 c Min. edge :0 c Max. edge :2 p sp 10 7 a 4 3 -64 a 5 6 148 a 5 9 110 a 6 10 -139 a 7 7 7 a 8 2 -97 a 9 1 60 <BLANKLINE> >>> random.seed(4) >>> dimacs_maker('testfile2',0,50,30,0,4,True,True,True,False) 35 >>> file=open('testfile2.gr','r') >>> print(file.read()) c FILE :testfile2.gr c No. of vertices :30 c No. of edges :35 c Max. weight :50 c Min. weight :0 c Min. edge :0 c Max. edge :4 p sp 30 35 a 1 10 46 a 2 18 5 a 2 4 25 a 2 22 -48 a 4 23 -17 a 5 7 -13 a 7 15 10 a 7 17 -40 a 8 8 -42 a 8 25 11 a 9 29 -5 a 10 3 -36 a 10 27 -48 a 11 13 -27 a 11 26 -27 a 11 21 14 a 11 16 -2 a 14 20 -44 a 14 14 43 a 14 12 26 a 15 28 -11 a 16 30 -40 a 16 24 20 a 19 19 7 a 20 12 -29 a 20 1 22 a 22 24 20 a 22 23 -9 a 23 18 18 a 23 27 28 a 24 6 -24 a 25 17 23 a 27 6 -50 a 28 21 28 a 28 13 -13 <BLANKLINE> >>> random.seed(20) >>> dimacs_maker('testfile3',10,30,100,0,4,False,True,True,False) 137 >>> file=open('testfile3.gr','r') >>> print(file.read()) c FILE :testfile3.gr c No. of vertices :100 c No. of edges :137 c Max. weight :30 c Min. weight :10 c Min. edge :0 c Max. edge :4 p sp 100 137 a 1 34 30 a 3 76 15 a 3 5 23 a 4 13 13 a 4 21 20 a 4 67 28 a 5 60 16 a 5 32 20 a 5 92 20 a 6 64 12 a 6 94 26 a 7 62 12 a 7 36 28 a 7 42 11 a 8 20 12 a 9 47 19 a 10 49 15 a 10 27 10 a 11 48 17 a 11 51 11 a 13 58 14 a 13 70 29 a 14 37 30 a 14 61 27 a 14 87 15 a 15 84 13 a 16 83 28 a 17 45 17 a 17 24 29 a 17 18 26 a 18 59 15 a 19 98 12 a 21 2 30 a 21 99 20 a 22 69 26 a 22 96 11 a 22 88 15 a 24 79 20 a 24 12 12 a 24 82 13 a 26 50 30 a 26 30 19 a 29 52 26 a 31 25 26 a 32 68 14 a 33 65 13 a 33 78 13 a 33 55 17 a 34 63 13 a 35 44 27 a 35 57 14 a 37 74 10 a 37 41 16 a 37 100 30 a 38 72 13 a 38 56 16 a 39 91 19 a 39 43 13 a 41 28 22 a 41 81 19 a 42 90 13 a 42 46 28 a 42 97 16 a 45 86 10 a 45 53 18 a 46 85 13 a 46 23 11 a 47 71 29 a 48 95 12 a 48 77 19 a 48 93 11 a 49 75 22 a 50 73 18 a 50 40 24 a 50 54 28 a 51 80 17 a 51 66 19 a 51 89 20 a 52 58 29 a 52 16 21 a 52 43 12 a 53 8 13 a 53 98 17 a 54 55 10 a 56 62 26 a 56 27 10 a 57 70 26 a 58 44 22 a 59 90 27 a 59 91 19 a 59 78 29 a 60 87 12 a 60 92 25 a 61 69 14 a 61 79 17 a 62 25 21 a 63 97 27 a 63 29 30 a 65 9 26 a 65 64 21 a 66 67 27 a 66 95 19 a 66 93 30 a 68 30 18 a 70 83 12 a 70 99 15 a 71 31 17 a 71 89 20 a 73 36 18 a 75 72 12 a 76 2 26 a 76 12 25 a 76 86 22 a 78 23 19 a 78 100 27 a 79 40 24 a 80 84 26 a 80 80 14 a 81 20 16 a 82 15 16 a 82 88 22 a 83 19 19 a 84 85 13 a 84 28 16 a 85 77 16 a 85 94 23 a 86 1 21 a 87 74 15 a 87 96 19 a 90 93 22 a 92 49 14 a 95 98 26 a 95 55 11 a 97 38 28 a 99 19 29 a 99 89 24 a 100 40 11 <BLANKLINE> >>> dimacs_maker('testfile', 0, 200, 10, 0,0,True) Traceback (most recent call last): ... TypeError: dimacs_maker() missing 3 required positional arguments: 'direct', 'self_loop', and 'multigraph' >>> random.seed(2) >>> json_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.json','r') >>> testfile_1=json.load(file) >>> testfile_1['graph']['nodes'][1] {'id': 2} >>> testfile_1['graph']['edges'][1]['source'] 5 >>> testfile_1['graph']['edges'][1]['target'] 6 >>> testfile_1['graph']['edges'][1]['weight'] 148 >>> json_to_yaml('testfile') >>> file=open('testfile.yaml','r') >>> testfile_1_yaml=yaml.load(file) >>> testfile_1_yaml['graph']['edges'][1]['source'] 5 >>> testfile_1_yaml['graph']['edges'][1]['target'] 6 >>> testfile_1_yaml['graph']['edges'][1]['weight'] 148 >>> json_to_pickle('testfile') >>> testfile_1_p=pickle.load( open( 'testfile.p', 'rb' ) ) >>> testfile_1_p['graph']['edges'][1]['source'] 5 >>> testfile_1_p['graph']['edges'][1]['target'] 6 >>> testfile_1_p['graph']['edges'][1]['weight'] 148 >>> random.seed(4) >>> json_maker('testfile2',0,50,30,0,4,True,True,True,False) 35 >>> file=open('testfile2.json','r') >>> testfile_2=json.load(file) >>> testfile_2['graph']['nodes'][1] {'id': 2} >>> testfile_2['graph']['edges'][1]['source'] 2 >>> testfile_2['graph']['edges'][1]['target'] 18 >>> testfile_2['graph']['edges'][1]['weight'] 5 >>> json_to_yaml('testfile2') >>> file=open('testfile2.yaml','r') >>> testfile_2_yaml=yaml.load(file) >>> testfile_2_yaml['graph']['nodes'][1] {'id': 2} >>> testfile_2_yaml['graph']['edges'][1]['source'] 2 >>> testfile_2_yaml['graph']['edges'][1]['target'] 18 >>> testfile_2_yaml['graph']['edges'][1]['weight'] 5 >>> json_to_pickle('testfile2') >>> testfile_2_p=pickle.load( open( 'testfile2.p', 'rb' ) ) >>> testfile_2_p['graph']['edges'][1]['source'] 2 >>> testfile_2_p['graph']['edges'][1]['target'] 18 >>> testfile_2_p['graph']['edges'][1]['weight'] 5 >>> random.seed(20) >>> json_maker('testfile3',10,30,100,0,4,False,True,True,False) 137 >>> file=open('testfile3.json','r') >>> testfile_3=json.load(file) >>> testfile_3['graph']['nodes'][1] {'id': 2} >>> testfile_3['graph']['edges'][1]['source'] 3 >>> testfile_3['graph']['edges'][1]['target'] 76 >>> testfile_3['graph']['edges'][1]['weight'] 15 >>> json_to_yaml('testfile3') >>> file=open('testfile3.yaml','r') >>> testfile_3_yaml=yaml.load(file) >>> testfile_3_yaml['graph']['nodes'][1] {'id': 2} >>> testfile_3_yaml['graph']['edges'][1]['source'] 3 >>> testfile_3_yaml['graph']['edges'][1]['target'] 76 >>> testfile_3_yaml['graph']['edges'][1]['weight'] 15 >>> json_to_yaml('testfile24') [Error] Bad Input File! >>> json_to_pickle('testfile24') [Error] Bad Input File! >>> json_maker('testfile', 0, 200, 10, 0, 0,True) Traceback (most recent call last): ... TypeError: json_maker() missing 3 required positional arguments: 'direct', 'self_loop', and 'multigraph' >>> json_to_pickle('testfile3') >>> testfile_3_p=pickle.load( open( 'testfile3.p', 'rb' ) ) >>> testfile_3_p['graph']['edges'][1]['source'] 3 >>> testfile_3_p['graph']['edges'][1]['target'] 76 >>> testfile_3_p['graph']['edges'][1]['weight'] 15 >>> random.seed(2) >>> csv_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> random.seed(2) >>> gml_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.gml','r') >>> print(file.read()) graph [ multigraph 0 directed 1 node [ id 1 label "Node 1" ] node [ id 2 label "Node 2" ] node [ id 3 label "Node 3" ] node [ id 4 label "Node 4" ] node [ id 5 label "Node 5" ] node [ id 6 label "Node 6" ] node [ id 7 label "Node 7" ] node [ id 8 label "Node 8" ] node [ id 9 label "Node 9" ] node [ id 10 label "Node 10" ] edge [ source 4 target 3 value -64 ] edge [ source 5 target 6 value 148 ] edge [ source 5 target 9 value 110 ] edge [ source 6 target 10 value -139 ] edge [ source 7 target 7 value 7 ] edge [ source 8 target 2 value -97 ] edge [ source 9 target 1 value 60 ] ] >>> random.seed(2) >>> gexf_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.gexf', 'r') >>> random.seed(2) >>> mtx_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> random.seed(2) >>> tsv_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.mtx','r') >>> print(file.read()) %%MatrixMarket matrix coordinate real general 10 10 7 4 3 -64 5 6 148 5 9 110 6 10 -139 7 7 7 8 2 -97 9 1 60 <BLANKLINE> >>> random.seed(2) >>> gdf_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.gdf','r') >>> print(file.read()) nodedef>name VARCHAR,label VARCHAR 1,Node1 2,Node2 3,Node3 4,Node4 5,Node5 6,Node6 7,Node7 8,Node8 9,Node9 10,Node10 edgedef>node1 VARCHAR,node2 VARCHAR,weight DOUBLE 4,3,-64 5,6,148 5,9,110 6,10,-139 7,7,7 8,2,-97 9,1,60 <BLANKLINE> >>> random.seed(2) >>> gl_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.gl','r') >>> print(file.read()) 4 3:-64 5 6:148 9:110 6 10:-139 7 7:7 8 2:-97 9 1:60 <BLANKLINE> >>> file=open('testfile.csv','r') >>> print(file.read()) 4,3,-64 5,6,148 5,9,110 6,10,-139 7,7,7 8,2,-97 9,1,60 <BLANKLINE> >>> random.seed(4) >>> csv_maker('testfile2',0,50,30,0,4,True,True,True,False) 35 >>> file=open('testfile2.csv','r') >>> print(file.read()) 1,10,46 2,18,5 2,4,25 2,22,-48 4,23,-17 5,7,-13 7,15,10 7,17,-40 8,8,-42 8,25,11 9,29,-5 10,3,-36 10,27,-48 11,13,-27 11,26,-27 11,21,14 11,16,-2 14,20,-44 14,14,43 14,12,26 15,28,-11 16,30,-40 16,24,20 19,19,7 20,12,-29 20,1,22 22,24,20 22,23,-9 23,18,18 23,27,28 24,6,-24 25,17,23 27,6,-50 28,21,28 28,13,-13 <BLANKLINE> >>> random.seed(4) >>> csv_maker('testfile4',0,50.2,30,0,4,True,True,True,False) 41 >>> file=open('testfile4.csv','r') >>> print(file.read()) 1,10,36.2 2,6,3.3 2,16,-40.2 2,29,11.1 3,17,-39.1 3,7,-10.8 3,3,-40.2 4,12,-14.5 5,9,-33.7 5,28,8.9 6,21,47.4 6,27,-0.4 6,15,-42.6 7,20,-30.1 8,23,11.7 8,18,4.1 8,25,-26.0 9,24,50.1 9,13,20.7 9,14,-13.9 10,26,-31.8 10,19,-5.1 12,22,6.1 13,30,-1.3 14,11,-36.9 14,22,16.2 15,16,-43.2 15,11,-31.0 16,19,12.6 17,21,18.2 18,18,-39.3 18,25,-28.7 19,23,-46.0 24,20,27.4 25,4,-50.1 25,1,-38.8 26,27,-10.1 26,30,-24.7 26,29,-12.5 27,28,-9.4 29,20,26.4 <BLANKLINE> >>> random.seed(20) >>> csv_maker('testfile3',10,30,100,0,4,False,True,True,False) 137 >>> file=open('testfile3.csv','r') >>> print(file.read()) 1,34,30 3,76,15 3,5,23 4,13,13 4,21,20 4,67,28 5,60,16 5,32,20 5,92,20 6,64,12 6,94,26 7,62,12 7,36,28 7,42,11 8,20,12 9,47,19 10,49,15 10,27,10 11,48,17 11,51,11 13,58,14 13,70,29 14,37,30 14,61,27 14,87,15 15,84,13 16,83,28 17,45,17 17,24,29 17,18,26 18,59,15 19,98,12 21,2,30 21,99,20 22,69,26 22,96,11 22,88,15 24,79,20 24,12,12 24,82,13 26,50,30 26,30,19 29,52,26 31,25,26 32,68,14 33,65,13 33,78,13 33,55,17 34,63,13 35,44,27 35,57,14 37,74,10 37,41,16 37,100,30 38,72,13 38,56,16 39,91,19 39,43,13 41,28,22 41,81,19 42,90,13 42,46,28 42,97,16 45,86,10 45,53,18 46,85,13 46,23,11 47,71,29 48,95,12 48,77,19 48,93,11 49,75,22 50,73,18 50,40,24 50,54,28 51,80,17 51,66,19 51,89,20 52,58,29 52,16,21 52,43,12 53,8,13 53,98,17 54,55,10 56,62,26 56,27,10 57,70,26 58,44,22 59,90,27 59,91,19 59,78,29 60,87,12 60,92,25 61,69,14 61,79,17 62,25,21 63,97,27 63,29,30 65,9,26 65,64,21 66,67,27 66,95,19 66,93,30 68,30,18 70,83,12 70,99,15 71,31,17 71,89,20 73,36,18 75,72,12 76,2,26 76,12,25 76,86,22 78,23,19 78,100,27 79,40,24 80,84,26 80,80,14 81,20,16 82,15,16 82,88,22 83,19,19 84,85,13 84,28,16 85,77,16 85,94,23 86,1,21 87,74,15 87,96,19 90,93,22 92,49,14 95,98,26 95,55,11 97,38,28 99,19,29 99,89,24 100,40,11 <BLANKLINE> >>> csv_maker('testfile', 0, 200, 10, 0,0,True) Traceback (most recent call last): ... TypeError: csv_maker() missing 3 required positional arguments: 'direct', 'self_loop', and 'multigraph' >>> random.seed(2) >>> wel_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.wel','r') >>> print(file.read()) 4 3 -64 5 6 148 5 9 110 6 10 -139 7 7 7 8 2 -97 9 1 60 <BLANKLINE> >>> random.seed(4) >>> wel_maker('testfile2',0,50,30,0,4,True,True,True,False) 35 >>> file=open('testfile2.wel','r') >>> print(file.read()) 1 10 46 2 18 5 2 4 25 2 22 -48 4 23 -17 5 7 -13 7 15 10 7 17 -40 8 8 -42 8 25 11 9 29 -5 10 3 -36 10 27 -48 11 13 -27 11 26 -27 11 21 14 11 16 -2 14 20 -44 14 14 43 14 12 26 15 28 -11 16 30 -40 16 24 20 19 19 7 20 12 -29 20 1 22 22 24 20 22 23 -9 23 18 18 23 27 28 24 6 -24 25 17 23 27 6 -50 28 21 28 28 13 -13 <BLANKLINE> >>> random.seed(20) >>> wel_maker('testfile3',10,30,100,0,4,False,True,True,False) 137 >>> file=open('testfile3.wel','r') >>> print(file.read()) 1 34 30 3 76 15 3 5 23 4 13 13 4 21 20 4 67 28 5 60 16 5 32 20 5 92 20 6 64 12 6 94 26 7 62 12 7 36 28 7 42 11 8 20 12 9 47 19 10 49 15 10 27 10 11 48 17 11 51 11 13 58 14 13 70 29 14 37 30 14 61 27 14 87 15 15 84 13 16 83 28 17 45 17 17 24 29 17 18 26 18 59 15 19 98 12 21 2 30 21 99 20 22 69 26 22 96 11 22 88 15 24 79 20 24 12 12 24 82 13 26 50 30 26 30 19 29 52 26 31 25 26 32 68 14 33 65 13 33 78 13 33 55 17 34 63 13 35 44 27 35 57 14 37 74 10 37 41 16 37 100 30 38 72 13 38 56 16 39 91 19 39 43 13 41 28 22 41 81 19 42 90 13 42 46 28 42 97 16 45 86 10 45 53 18 46 85 13 46 23 11 47 71 29 48 95 12 48 77 19 48 93 11 49 75 22 50 73 18 50 40 24 50 54 28 51 80 17 51 66 19 51 89 20 52 58 29 52 16 21 52 43 12 53 8 13 53 98 17 54 55 10 56 62 26 56 27 10 57 70 26 58 44 22 59 90 27 59 91 19 59 78 29 60 87 12 60 92 25 61 69 14 61 79 17 62 25 21 63 97 27 63 29 30 65 9 26 65 64 21 66 67 27 66 95 19 66 93 30 68 30 18 70 83 12 70 99 15 71 31 17 71 89 20 73 36 18 75 72 12 76 2 26 76 12 25 76 86 22 78 23 19 78 100 27 79 40 24 80 84 26 80 80 14 81 20 16 82 15 16 82 88 22 83 19 19 84 85 13 84 28 16 85 77 16 85 94 23 86 1 21 87 74 15 87 96 19 90 93 22 92 49 14 95 98 26 95 55 11 97 38 28 99 19 29 99 89 24 100 40 11 <BLANKLINE> >>> wel_maker('testfile', 0, 200, 10, 0,0,True) Traceback (most recent call last): ... TypeError: wel_maker() missing 3 required positional arguments: 'direct', 'self_loop', and 'multigraph' >>> random.seed(2) >>> lp_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.lp','r') >>> print(file.read()) node(1). node(2). node(3). node(4). node(5). node(6). node(7). node(8). node(9). node(10). edge(4,3,-64). edge(5,6,148). edge(5,9,110). edge(6,10,-139). edge(7,7,7). edge(8,2,-97). edge(9,1,60). <BLANKLINE> >>> random.seed(4) >>> lp_maker('testfile2',0,50,30,0,4,True,True,True,False) 35 >>> file=open('testfile2.lp','r') >>> print(file.read()) node(1). node(2). node(3). node(4). node(5). node(6). node(7). node(8). node(9). node(10). node(11). node(12). node(13). node(14). node(15). node(16). node(17). node(18). node(19). node(20). node(21). node(22). node(23). node(24). node(25). node(26). node(27). node(28). node(29). node(30). edge(1,10,46). edge(2,18,5). edge(2,4,25). edge(2,22,-48). edge(4,23,-17). edge(5,7,-13). edge(7,15,10). edge(7,17,-40). edge(8,8,-42). edge(8,25,11). edge(9,29,-5). edge(10,3,-36). edge(10,27,-48). edge(11,13,-27). edge(11,26,-27). edge(11,21,14). edge(11,16,-2). edge(14,20,-44). edge(14,14,43). edge(14,12,26). edge(15,28,-11). edge(16,30,-40). edge(16,24,20). edge(19,19,7). edge(20,12,-29). edge(20,1,22). edge(22,24,20). edge(22,23,-9). edge(23,18,18). edge(23,27,28). edge(24,6,-24). edge(25,17,23). edge(27,6,-50). edge(28,21,28). edge(28,13,-13). <BLANKLINE> >>> input_dic=get_input(input_func=lambda x: str(len(x))) >>> input_dic['sign'] True >>> input_dic['vertices'] 20 >>> input_dic['min_edge'] 20 >>> input_dic['min_weight'] 15 >>> input_dic['output_format'] 1 >>> input_dic['max_weight'] 15 >>> input_dic['file_name'] '14' >>> input_dic['max_edge'] 20 >>> random.seed(2) >>> tgf_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.tgf','r') >>> print(file.read()) 1 2 3 4 5 6 7 8 9 10 # 4 3 -64 5 6 148 5 9 110 6 10 -139 7 7 7 8 2 -97 9 1 60 <BLANKLINE> >>> random.seed(4) >>> tgf_maker('testfile2',0,50,30,0,4,True,True,True,False) 35 >>> file=open('testfile2.tgf','r') >>> print(file.read()) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 # 1 10 46 2 18 5 2 4 25 2 22 -48 4 23 -17 5 7 -13 7 15 10 7 17 -40 8 8 -42 8 25 11 9 29 -5 10 3 -36 10 27 -48 11 13 -27 11 26 -27 11 21 14 11 16 -2 14 20 -44 14 14 43 14 12 26 15 28 -11 16 30 -40 16 24 20 19 19 7 20 12 -29 20 1 22 22 24 20 22 23 -9 23 18 18 23 27 28 24 6 -24 25 17 23 27 6 -50 28 21 28 28 13 -13 <BLANKLINE> >>> random.seed(2) >>> dl_maker('testfile', 0, 200, 10, 0, 2, True,True,True,False) 7 >>> file=open('testfile.dl','r') >>> print(file.read()) dl format=edgelist1 n=10 data: 4 3 -64 5 6 148 5 9 110 6 10 -139 7 7 7 8 2 -97 9 1 60 <BLANKLINE> >>> random.seed(4) >>> dl_maker('testfile2',0,50,30,0,4,True,True,True,False) 35 >>> file=open('testfile2.dl','r') >>> print(file.read()) dl format=edgelist1 n=30 data: 1 10 46 2 18 5 2 4 25 2 22 -48 4 23 -17 5 7 -13 7 15 10 7 17 -40 8 8 -42 8 25 11 9 29 -5 10 3 -36 10 27 -48 11 13 -27 11 26 -27 11 21 14 11 16 -2 14 20 -44 14 14 43 14 12 26 15 28 -11 16 30 -40 16 24 20 19 19 7 20 12 -29 20 1 22 22 24 20 22 23 -9 23 18 18 23 27 28 24 6 -24 25 17 23 27 6 -50 28 21 28 28 13 -13 <BLANKLINE> >>> file.close() >>> os.remove('testfile.csv') >>> os.remove('testfile.gml') >>> os.remove('testfile.gexf') >>> os.remove('testfile.tsv') >>> os.remove('testfile.dl') >>> os.remove('testfile.gr') >>> os.remove('testfile.json') >>> os.remove('testfile.lp') >>> os.remove('testfile.p') >>> os.remove('testfile.tgf') >>> os.remove('testfile.wel') >>> os.remove('testfile.yaml') >>> os.remove('testfile.mtx') >>> os.remove('testfile.gdf') >>> os.remove('testfile.gl') >>> os.remove('testfile2.csv') >>> os.remove('testfile2.dl') >>> os.remove('testfile2.gr') >>> os.remove('testfile2.json') >>> os.remove('testfile2.lp') >>> os.remove('testfile2.p') >>> os.remove('testfile2.tgf') >>> os.remove('testfile2.wel') >>> os.remove('testfile2.yaml') >>> os.remove('testfile3.csv') >>> os.remove('testfile4.csv') >>> os.remove('testfile3.gr') >>> os.remove('testfile3.json') >>> os.remove('testfile3.p') >>> os.remove('testfile3.wel') >>> os.remove('testfile3.yaml') >>> os.remove('logfile.log') """<line_sep>
<import_stmt>pytest<import_from_stmt>django.core.exceptions ImproperlyConfigured<import_from_stmt>django.db connection models<import_from_stmt>psqlextra.backend.schema PostgresSchemaEditor<import_from_stmt>psqlextra.types PostgresPartitioningMethod<import_from_stmt>. db_introspection<import_from_stmt>.fake_model define_fake_partitioned_model<def_stmt>test_schema_editor_create_delete_partitioned_model_range <block_start>"""Tests whether creating a partitioned model and adding a list partition to it using the :see:PostgresSchemaEditor works."""<line_sep>method=PostgresPartitioningMethod.RANGE<line_sep>key=["timestamp"]<line_sep>model=define_fake_partitioned_model({"name":models.TextField() "timestamp":models.DateTimeField()} {"method":method "key":key} )<line_sep>schema_editor=PostgresSchemaEditor(connection)<line_sep>schema_editor.create_partitioned_model(model)<line_sep>schema_editor.add_range_partition(model "pt1" "2019-01-01" "2019-02-01")<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>table.name<eq>model._meta.db_table<assert_stmt>table.method<eq>method<assert_stmt>table.key<eq>key<assert_stmt>table.partitions[0].full_name<eq>model._meta.db_table+"_pt1"<line_sep>schema_editor.delete_partitioned_model(model)<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt><not>table<line_sep>partitions=db_introspection.get_partitions(model._meta.db_table)<assert_stmt>len(partitions)<eq>0<block_end><def_stmt>test_schema_editor_create_delete_partitioned_model_list <block_start>"""Tests whether creating a partitioned model and adding a range partition to it using the :see:PostgresSchemaEditor works."""<line_sep>method=PostgresPartitioningMethod.LIST<line_sep>key=["category"]<line_sep>model=define_fake_partitioned_model({"name":models.TextField() "category":models.TextField()} {"method":method "key":key} )<line_sep>schema_editor=PostgresSchemaEditor(connection)<line_sep>schema_editor.create_partitioned_model(model)<line_sep>schema_editor.add_list_partition(model "pt1" ["car" "boat"])<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>table.name<eq>model._meta.db_table<assert_stmt>table.method<eq>method<assert_stmt>table.key<eq>key<assert_stmt>table.partitions[0].full_name<eq>model._meta.db_table+"_pt1"<line_sep>schema_editor.delete_partitioned_model(model)<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt><not>table<line_sep>partitions=db_introspection.get_partitions(model._meta.db_table)<assert_stmt>len(partitions)<eq>0<block_end><def_stmt>test_schema_editor_create_delete_partitioned_model_default <block_start>"""Tests whether creating a partitioned model and adding a default partition to it using the :see:PostgresSchemaEditor works."""<line_sep>method=PostgresPartitioningMethod.LIST<line_sep>key=["category"]<line_sep>model=define_fake_partitioned_model({"name":models.TextField() "category":models.TextField()} {"method":method "key":key} )<line_sep>schema_editor=PostgresSchemaEditor(connection)<line_sep>schema_editor.create_partitioned_model(model)<line_sep>schema_editor.add_default_partition(model "default")<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>table.name<eq>model._meta.db_table<assert_stmt>table.method<eq>method<assert_stmt>table.key<eq>key<assert_stmt>table.partitions[0].full_name<eq>model._meta.db_table+"_default"<line_sep>schema_editor.delete_partitioned_model(model)<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt><not>table<line_sep>partitions=db_introspection.get_partitions(model._meta.db_table)<assert_stmt>len(partitions)<eq>0<block_end><def_stmt>test_schema_editor_create_partitioned_model_no_method <block_start>"""Tests whether its possible to create a partitioned model without explicitly setting a partitioning method. The default is "range" so setting one explicitely should not be needed. """<line_sep>model=define_fake_partitioned_model({"name":models.TextField() "timestamp":models.DateTimeField()} {"key":["timestamp"]} )<line_sep>schema_editor=PostgresSchemaEditor(connection)<line_sep>schema_editor.create_partitioned_model(model)<line_sep>pt=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>pt.method<eq>PostgresPartitioningMethod.RANGE<assert_stmt>len(pt.partitions)<eq>0<block_end><def_stmt>test_schema_editor_create_partitioned_model_no_key <block_start>"""Tests whether trying to create a partitioned model without a partitioning key raises :see:ImproperlyConfigured as its not possible to create a partitioned model without one and we cannot have a sane default."""<line_sep>model=define_fake_partitioned_model({"name":models.TextField() "timestamp":models.DateTimeField()} {"method":PostgresPartitioningMethod.RANGE} )<line_sep>schema_editor=PostgresSchemaEditor(connection)<with_stmt>pytest.raises(ImproperlyConfigured)<block_start>schema_editor.create_partitioned_model(model)<block_end><block_end><def_stmt>test_schema_editor_add_range_partition <block_start>"""Tests whether adding a range partition works."""<line_sep>model=define_fake_partitioned_model({"name":models.TextField() "timestamp":models.DateTimeField()} {"key":["timestamp"]} )<line_sep>schema_editor=PostgresSchemaEditor(connection)<line_sep>schema_editor.create_partitioned_model(model)<line_sep>schema_editor.add_range_partition(model name="mypartition" from_values="2019-1-1" to_values="2019-2-1" comment="test" )<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>len(table.partitions)<eq>1<assert_stmt>table.partitions[0].name<eq>"mypartition"<assert_stmt>(table.partitions[0].full_name<eq>f"{model._meta.db_table}_mypartition")<assert_stmt>table.partitions[0].comment<eq>"test"<line_sep>schema_editor.delete_partition(model "mypartition")<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>len(table.partitions)<eq>0<block_end><def_stmt>test_schema_editor_add_list_partition <block_start>"""Tests whether adding a list partition works."""<line_sep>model=define_fake_partitioned_model({"name":models.TextField()} {"method":PostgresPartitioningMethod.LIST "key":["name"]} )<line_sep>schema_editor=PostgresSchemaEditor(connection)<line_sep>schema_editor.create_partitioned_model(model)<line_sep>schema_editor.add_list_partition(model name="mypartition" values=["1"] comment="test")<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>len(table.partitions)<eq>1<assert_stmt>table.partitions[0].name<eq>"mypartition"<assert_stmt>(table.partitions[0].full_name<eq>f"{model._meta.db_table}_mypartition")<assert_stmt>table.partitions[0].comment<eq>"test"<line_sep>schema_editor.delete_partition(model "mypartition")<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>len(table.partitions)<eq>0<block_end>@pytest.mark.parametrize("method,key" [(PostgresPartitioningMethod.RANGE ["timestamp"]) (PostgresPartitioningMethod.LIST ["name"]) ] )<def_stmt>test_schema_editor_add_default_partition method key<block_start>model=define_fake_partitioned_model({"name":models.TextField() "timestamp":models.DateTimeField()} {"method":method "key":key} )<line_sep>schema_editor=PostgresSchemaEditor(connection)<line_sep>schema_editor.create_partitioned_model(model)<line_sep>schema_editor.add_default_partition(model name="mypartition" comment="test")<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>len(table.partitions)<eq>1<assert_stmt>table.partitions[0].name<eq>"mypartition"<assert_stmt>(table.partitions[0].full_name<eq>f"{model._meta.db_table}_mypartition")<assert_stmt>table.partitions[0].comment<eq>"test"<line_sep>schema_editor.delete_partition(model "mypartition")<line_sep>table=db_introspection.get_partitioned_table(model._meta.db_table)<assert_stmt>len(table.partitions)<eq>0<block_end>
<import_stmt>fiona<import_stmt>numpy<as>np<import_stmt>os<import_stmt>pytest<import_stmt>rasterio<import_stmt>mapchete<import_from_stmt>mapchete.index zoom_index_gen<import_from_stmt>mapchete.io get_boto3_bucket<line_sep>@pytest.mark.remote<def_stmt>test_remote_indexes mp_s3_tmpdir gtiff_s3<block_start>zoom=7<line_sep>gtiff_s3.dict.update(zoom_levels=zoom)<def_stmt>gen_indexes_and_check # generate indexes <block_start>list(zoom_index_gen(mp=mp zoom=zoom out_dir=mp.config.output.path geojson=<true> txt=<true> vrt=<true> ))<line_sep># assert GeoJSON exists <with_stmt>fiona.open(os.path.join(mp.config.output.path "%s.geojson"%zoom))<as>src<block_start><assert_stmt>len(src)<eq>2<block_end># assert TXT exists txt_index=os.path.join(mp.config.output.path "%s.txt"%zoom)<line_sep>bucket=get_boto3_bucket(txt_index.split("/")[2])<line_sep>key="/".join(txt_index.split("/")[3:])<for_stmt>obj bucket.objects.filter(Prefix=key)<block_start><if_stmt>obj.key<eq>key<block_start>content=obj.get()["Body"].read().decode()<assert_stmt>len([l+"\n"<for>l content.split("\n")<if>l])<eq>2<block_end><block_end># assert VRT exists <with_stmt>rasterio.open(os.path.join(mp.config.output.path "%s.vrt"%zoom))<as>src<block_start><assert_stmt>src.read().any()<block_end><block_end><with_stmt>mapchete.open(gtiff_s3.dict)<as>mp# write output data <block_start>mp.batch_process(zoom=zoom)<line_sep># generate indexes and check gen_indexes_and_check()<line_sep># generate indexes again and assert nothing has changes gen_indexes_and_check()<block_end><block_end><def_stmt>test_vrt mp_tmpdir cleantopo_br<block_start>zoom=8<with_stmt>mapchete.open(dict(cleantopo_br.dict zoom_levels=dict(min=0 max=zoom)))<as>mp# generate output <block_start>mp.batch_process(zoom=zoom)<line_sep># generate index list(zoom_index_gen(mp=mp zoom=zoom out_dir=mp.config.output.path vrt=<true> ))<line_sep>output_tiles=list(mp.config.output_pyramid.tiles_from_bounds(mp.config.bounds_at_zoom(zoom=zoom) zoom=zoom))<line_sep>bounds=(min([t.left<for>t output_tiles]) min([t.bottom<for>t output_tiles]) max([t.right<for>t output_tiles]) max([t.top<for>t output_tiles]) )<line_sep># bounds = mp.config.effective_bounds <block_end>vrt_index=os.path.join(mp.config.output.path "%s.vrt"%zoom)<with_stmt>rasterio.open(vrt_index)<as>vrt<block_start><assert_stmt>vrt.driver<eq>"VRT"<assert_stmt>vrt.dtypes[0]<eq>"uint16"<assert_stmt>vrt.meta["dtype"]<eq>"uint16"<assert_stmt>vrt.count<eq>1<assert_stmt>vrt.nodata<eq>0<assert_stmt>vrt.bounds<eq>bounds<line_sep>vrt_data=vrt.read()<assert_stmt>vrt_data.any()<block_end># generate a VRT using GDAL and compare out_dir=os.path.join(mp_tmpdir "cleantopo_br")<line_sep>temp_vrt=os.path.join(out_dir str(zoom)+"_gdal.vrt")<line_sep>gdalbuildvrt="gdalbuildvrt %s %s/%s/*/*.tif > /dev/null"%(temp_vrt out_dir zoom )<line_sep>os.system(gdalbuildvrt)<with_stmt>rasterio.open(temp_vrt "r")<as>gdal_vrt<block_start><assert_stmt>gdal_vrt.dtypes[0]<eq>"uint16"<assert_stmt>gdal_vrt.meta["dtype"]<eq>"uint16"<assert_stmt>gdal_vrt.count<eq>1<assert_stmt>gdal_vrt.nodata<eq>0<assert_stmt>gdal_vrt.bounds<eq>bounds<line_sep>gdal_vrt_data=gdal_vrt.read()<assert_stmt>np.array_equal(vrt_data gdal_vrt_data)<block_end># make sure handling an existing VRT works <with_stmt>mapchete.open(dict(cleantopo_br.dict zoom_levels=dict(min=0 max=zoom)))<as>mp# generate output <block_start>mp.batch_process(zoom=zoom)<line_sep># generate index list(zoom_index_gen(mp=mp zoom=zoom out_dir=mp.config.output.path vrt=<true> ))<block_end><block_end><def_stmt>test_vrt_mercator mp_tmpdir cleantopo_br_mercator<block_start>zoom=8<with_stmt>mapchete.open(dict(cleantopo_br_mercator.dict zoom_levels=dict(min=0 max=zoom)))<as>mp# generate output <block_start>mp.batch_process(zoom=zoom)<line_sep># generate index list(zoom_index_gen(mp=mp zoom=zoom out_dir=mp.config.output.path vrt=<true> ))<line_sep>output_tiles=list(mp.config.output_pyramid.tiles_from_bounds(mp.config.bounds_at_zoom(zoom=zoom) zoom=zoom))<line_sep>bounds=(min([t.left<for>t output_tiles]) min([t.bottom<for>t output_tiles]) max([t.right<for>t output_tiles]) max([t.top<for>t output_tiles]) )<line_sep># bounds = mp.config.effective_bounds <block_end>vrt_index=os.path.join(mp.config.output.path "%s.vrt"%zoom)<with_stmt>rasterio.open(vrt_index)<as>vrt<block_start><assert_stmt>vrt.driver<eq>"VRT"<assert_stmt>vrt.dtypes[0]<eq>"uint16"<assert_stmt>vrt.meta["dtype"]<eq>"uint16"<assert_stmt>vrt.count<eq>1<assert_stmt>vrt.nodata<eq>0<for_stmt>vrt_b,b zip(vrt.bounds bounds)<block_start><assert_stmt>round(vrt_b 6)<eq>round(b 6)<block_end>vrt_data=vrt.read()<assert_stmt>vrt_data.any()<block_end># generate a VRT using GDAL and compare out_dir=os.path.join(mp_tmpdir "cleantopo_br_mercator")<line_sep>temp_vrt=os.path.join(out_dir str(zoom)+"_gdal.vrt")<line_sep>gdalbuildvrt="gdalbuildvrt %s %s/%s/*/*.tif > /dev/null"%(temp_vrt out_dir zoom )<line_sep>os.system(gdalbuildvrt)<with_stmt>rasterio.open(temp_vrt "r")<as>gdal_vrt<block_start><assert_stmt>gdal_vrt.dtypes[0]<eq>"uint16"<assert_stmt>gdal_vrt.meta["dtype"]<eq>"uint16"<assert_stmt>gdal_vrt.count<eq>1<assert_stmt>gdal_vrt.nodata<eq>0<for_stmt>vrt_b,b zip(vrt.bounds bounds)<block_start><assert_stmt>round(vrt_b 6)<eq>round(b 6)<block_end>gdal_vrt_data=gdal_vrt.read()<assert_stmt>np.array_equal(vrt_data gdal_vrt_data)<assert_stmt>gdal_vrt_data.any()<block_end># make sure handling an existing VRT works <with_stmt>mapchete.open(dict(cleantopo_br_mercator.dict zoom_levels=dict(min=0 max=zoom)))<as>mp# generate output <block_start>mp.batch_process(zoom=zoom)<line_sep># generate index list(zoom_index_gen(mp=mp zoom=zoom out_dir=mp.config.output.path vrt=<true> ))<block_end><block_end>
<import_from_stmt>typing Optional<line_sep>__all__=("log" "camel_case_to_snake_case" "snake_case_to_camel_case" "snake_case_to_title_case" "python_condition_to_js_condition" )<def_stmt>log *args **kwargs<block_start>kwargs["flush"]=<true><line_sep>print(*args **kwargs)<block_end><def_stmt>camel_case_to_snake_case text:str<arrow>str<block_start><return>"".join("_"+i.lower()<if>i.isupper()<else>i<for>i text).lstrip("_")<block_end><def_stmt>snake_case_to_camel_case text:Optional[str]<arrow>Optional[str]<block_start><if_stmt>text<is><none><block_start><return><none><block_end>temp=text.split("_")<line_sep><return>temp[0]+"".join(ele.title()<for>ele temp[1:])<block_end><def_stmt>snake_case_to_title_case text:Optional[str]<arrow>Optional[str]<block_start><if_stmt>text<is><none><block_start><return><none><block_end><return>text.replace("_" " ").title()<block_end><def_stmt>python_condition_to_js_condition condition:Optional[str]<arrow>Optional[str]<block_start><if_stmt>condition<is><none><block_start><return><none><block_end>condition=" ".join(i<if>"_"<not><in>i<else>snake_case_to_camel_case(i)<for>i condition.split(" "))<line_sep>condition=condition.replace(" and " " && ")<line_sep>condition=condition.replace(" or " " || ")<if_stmt>" not "<in>condition<block_start><if_stmt>"("<not><in>condition<or>")"<not><in>condition<block_start><raise>SyntaxError("Use parenthesis '()' while using 'not' otherwise your conditions might not work as expected!")<block_end><else_stmt><block_start>condition=condition.replace(" not " " !")<block_end><block_end><return>condition<block_end>
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 <import_from_stmt>mo.front.extractor FrontExtractorOp<import_from_stmt>mo.front.mxnet.extractors.utils get_mxnet_layer_attrs<import_from_stmt>mo.ops.squeeze Squeeze<class_stmt>SqueezeExtractor(FrontExtractorOp)<block_start>op='squeeze'<line_sep>enabled=<true><line_sep>@classmethod<def_stmt>extract cls node<block_start>attrs=get_mxnet_layer_attrs(node.symbol_dict)<line_sep>Squeeze.update_node_stat(node {'squeeze_dims':attrs.int("axis" <none>) 'keep_at_least_1d':<true>})<line_sep><return>cls.enabled<block_end><block_end>
<import_stmt>enum<import_stmt>pathlib<import_from_stmt>typing DefaultDict Dict List Optional Sequence Tuple<import_from_stmt>pysen ComponentBase<import_from_stmt>pysen.command CommandBase<import_from_stmt>pysen.diagnostic Diagnostic<import_from_stmt>pysen.reporter Reporter<import_from_stmt>pysen.runner_options PathContext RunOptions<import_from_stmt>pysen.setting SettingFile<class_stmt>Operation(enum.Enum)<block_start>ADD="+"<line_sep>MUL="*"<block_end><class_stmt>FakeCommand(CommandBase)<block_start><def_stmt>__init__ self coef:int op:Operation ref:List[float] options:RunOptions<arrow><none><block_start>self.coef=coef<line_sep>self.op=op<line_sep>self.ref=ref<line_sep>self.options=options<assert_stmt>len(ref)<eq>1<block_end>@property<def_stmt>name self<arrow>str<block_start><return>f"{self.op.value} {self.coef}"<block_end><def_stmt>__call__ self reporter:Reporter<arrow>int<block_start>value=self.ref[0]<line_sep>coef=float(self.coef)<if_stmt>self.op<eq>Operation.ADD<block_start>value<augadd>coef<block_end><elif_stmt>self.op<eq>Operation.MUL<block_start>value<augmul>coef<block_end><else_stmt><block_start><raise>AssertionError(f"invalid op: {self.op}")<block_end>self.ref[0]=value<if_stmt>value<ge>0.0<block_start><return>0<block_end><else_stmt><block_start><if_stmt>self.options.require_diagnostics<block_start>reporter.report_diagnostics([Diagnostic(pathlib.Path(".").resolve() message="")])<block_end><return>1<block_end><block_end><block_end><class_stmt>FakeComponent(ComponentBase)<block_start><def_stmt>__init__ self name:str ops:Dict[str Tuple[int Operation]] expected_base_dir:Optional[pathlib.Path] expected_settings_dir:Optional[pathlib.Path] ref:List[float] <arrow><none><block_start>self._name=name<line_sep>self._ops=ops<line_sep>self._expected_base_dir=expected_base_dir<line_sep>self._expected_settings_dir=expected_settings_dir<line_sep>self._ref=ref<assert_stmt>len(ref)<eq>1<block_end>@property<def_stmt>name self<arrow>str<block_start><return>self._name<block_end><def_stmt>export_settings self paths:PathContext files:DefaultDict[str SettingFile] <arrow><none><block_start><if_stmt>self._expected_base_dir<is><not><none><block_start><assert_stmt>paths.base_dir<eq>self._expected_base_dir<block_end><if_stmt>self._expected_settings_dir<is><not><none><block_start><assert_stmt>paths.settings_dir<eq>self._expected_settings_dir<block_end><for_stmt>name,op self._ops.items()<block_start>fname=f"{name}.yaml"<line_sep>setting_file=files[fname]<line_sep>setting_file.set_section((self.name ) {"coef":op[0] "op":op[1].value})<block_end><block_end>@property<def_stmt>targets self<arrow>Sequence[str]<block_start><return>list(self._ops.keys())<block_end><def_stmt>create_command self target:str paths:PathContext options:RunOptions<arrow>CommandBase<block_start><if_stmt>self._expected_base_dir<is><not><none><block_start><assert_stmt>paths.base_dir<eq>self._expected_base_dir<block_end><if_stmt>self._expected_settings_dir<is><not><none><block_start><assert_stmt>paths.settings_dir<eq>self._expected_settings_dir<block_end>op=self._ops[target]<line_sep><return>FakeCommand(op[0] op[1] self._ref options)<block_end><block_end>
<import_stmt>torch<import_stmt>shutil<import_stmt>torch.nn<as>nn<import_stmt>torch.nn.functional<as>F<import_stmt>numpy<as>np<import_stmt>numbers<import_stmt>random<import_stmt>math<import_from_stmt>torch.optim Optimizer<def_stmt>init_seed seed<block_start>torch.manual_seed(seed)<line_sep>torch.cuda.manual_seed_all(seed)<line_sep>np.random.seed(seed)<line_sep>random.seed(seed)<block_end><def_stmt>weight_parameters module<block_start><return>[param<for>name,param module.named_parameters()<if>'weight'<in>name]<block_end><def_stmt>bias_parameters module<block_start><return>[param<for>name,param module.named_parameters()<if>'bias'<in>name]<block_end><def_stmt>load_checkpoint model_path<block_start>weights=torch.load(model_path)<line_sep>epoch=<none><if_stmt>'epoch'<in>weights<block_start>epoch=weights.pop('epoch')<block_end><if_stmt>'state_dict'<in>weights<block_start>state_dict=(weights['state_dict'])<block_end><else_stmt><block_start>state_dict=weights<block_end><return>epoch state_dict<block_end><def_stmt>save_checkpoint save_path states file_prefixes is_best filename='ckpt.pth.tar'<block_start><def_stmt>run_one_sample save_path state prefix is_best filename<block_start>torch.save(state save_path/'{}_{}'.format(prefix filename))<if_stmt>is_best<block_start>shutil.copyfile(save_path/'{}_{}'.format(prefix filename) save_path/'{}_model_best.pth.tar'.format(prefix))<block_end><block_end><if_stmt><not>isinstance(file_prefixes str)<block_start><for_stmt>(prefix state) zip(file_prefixes states)<block_start>run_one_sample(save_path state prefix is_best filename)<block_end><block_end><else_stmt><block_start>run_one_sample(save_path states file_prefixes is_best filename)<block_end><block_end><def_stmt>restore_model model pretrained_file<block_start>epoch,weights=load_checkpoint(pretrained_file)<line_sep>model_keys=set(model.state_dict().keys())<line_sep>weight_keys=set(weights.keys())<line_sep># load weights by name weights_not_in_model=sorted(list(weight_keys-model_keys))<line_sep>model_not_in_weights=sorted(list(model_keys-weight_keys))<if_stmt>len(model_not_in_weights)<block_start>print('Warning: There are weights in model but not in pre-trained.')<for_stmt>key (model_not_in_weights)<block_start>print(key)<line_sep>weights[key]=model.state_dict()[key]<block_end><block_end><if_stmt>len(weights_not_in_model)<block_start>print('Warning: There are pre-trained weights not in model.')<for_stmt>key (weights_not_in_model)<block_start>print(key)<block_end><import_from_stmt>collections OrderedDict<line_sep>new_weights=OrderedDict()<for_stmt>key model_keys<block_start>new_weights[key]=weights[key]<block_end>weights=new_weights<block_end>model.load_state_dict(weights)<line_sep><return>model<block_end><class_stmt>AdamW(Optimizer)<block_start>"""Implements AdamW algorithm. It has been proposed in `Fixing Weight Decay Regularization in Adam`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) .. Fixing Weight Decay Regularization in Adam: https://arxiv.org/abs/1711.05101 """<def_stmt>__init__ self params lr=1e-3 betas=(0.9 0.999) eps=1e-8 weight_decay=0<block_start>defaults=dict(lr=lr betas=betas eps=eps weight_decay=weight_decay)<line_sep>super(AdamW self).__init__(params defaults)<block_end><def_stmt>step self closure=<none><block_start>"""Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """<line_sep>loss=<none><if_stmt>closure<is><not><none><block_start>loss=closure()<block_end><for_stmt>group self.param_groups<block_start><for_stmt>p group['params']<block_start><if_stmt>p.grad<is><none><block_start><continue><block_end>grad=p.grad.data<if_stmt>grad.is_sparse<block_start><raise>RuntimeError('AdamW does not support sparse gradients, please consider SparseAdam instead')<block_end>state=self.state[p]<line_sep># State initialization <if_stmt>len(state)<eq>0<block_start>state['step']=0<line_sep># Exponential moving average of gradient values state['exp_avg']=torch.zeros_like(p.data)<line_sep># Exponential moving average of squared gradient values state['exp_avg_sq']=torch.zeros_like(p.data)<block_end>exp_avg,exp_avg_sq=state['exp_avg'] state['exp_avg_sq']<line_sep>beta1,beta2=group['betas']<line_sep>state['step']<augadd>1<line_sep># according to the paper, this penalty should come after the bias correction # if group['weight_decay'] != 0: # grad = grad.add(group['weight_decay'], p.data) # Decay the first and second moment running average coefficient exp_avg.mul_(beta1).add_(1-beta1 grad)<line_sep>exp_avg_sq.mul_(beta2).addcmul_(1-beta2 grad grad)<line_sep>denom=exp_avg_sq.sqrt().add_(group['eps'])<line_sep>bias_correction1=1-beta1<power>state['step']<line_sep>bias_correction2=1-beta2<power>state['step']<line_sep>step_size=group['lr']<times>math.sqrt(bias_correction2)/bias_correction1<line_sep>p.data.addcdiv_(-step_size exp_avg denom)<if_stmt>group['weight_decay']<ne>0<block_start>p.data.add_(-group['weight_decay'] p.data)<block_end><block_end><block_end><return>loss<block_end><block_end>
<import_stmt>os<import_from_stmt>homeassistant.core HomeAssistant<import_stmt>pytest<import_from_stmt>custom_components.hacs.websocket acknowledge_critical_repository get_critical_repositories hacs_config hacs_removed hacs_repositories hacs_repository hacs_repository_data hacs_settings hacs_status <line_sep>@pytest.mark.asyncio<async_keyword><def_stmt>test_check_local_path hacs connection tmpdir<block_start>hacs.hass=HomeAssistant()<line_sep>os.makedirs(tmpdir exist_ok=<true>)<line_sep>get_critical_repositories(hacs.hass connection {"id":1})<line_sep>hacs_config(hacs.hass connection {"id":1})<line_sep>hacs_removed(hacs.hass connection {"id":1})<line_sep>hacs_repositories(hacs.hass connection {"id":1})<line_sep>hacs_repository(hacs.hass connection {"id":1})<line_sep>hacs_repository_data(hacs.hass connection {"id":1})<line_sep>hacs_settings(hacs.hass connection {"id":1})<line_sep>hacs_status(hacs.hass connection {"id":1})<line_sep>acknowledge_critical_repository(hacs.hass connection {"repository":"test/test" "id":1})<block_end>
<import_from_future_stmt> unicode_literals<import_from_stmt>django.core.files.base File<import_from_stmt>django.test override_settings<import_from_stmt>common.tests BaseTestCase<import_from_stmt>documents.models DocumentType<import_from_stmt>documents.tests TEST_DOCUMENT_PATH TEST_DOCUMENT_TYPE_LABEL<import_from_stmt>..parsers PopplerParser<line_sep>@override_settings(OCR_AUTO_OCR=<false>)<class_stmt>ParserTestCase(BaseTestCase)<block_start><def_stmt>setUp self<block_start>super(ParserTestCase self).setUp()<line_sep>self.document_type=DocumentType.objects.create(label=TEST_DOCUMENT_TYPE_LABEL)<with_stmt>open(TEST_DOCUMENT_PATH)<as>file_object<block_start>self.document=self.document_type.new_document(file_object=File(file_object))<block_end><block_end><def_stmt>tearDown self<block_start>self.document_type.delete()<line_sep>super(ParserTestCase self).tearDown()<block_end><def_stmt>test_poppler_parser self<block_start>parser=PopplerParser()<line_sep>parser.process_document_version(self.document.latest_version)<line_sep>self.assertTrue('Mayan EDMS Documentation'<in>self.document.pages.first().content.content)<block_end><block_end>
<import_from_future_stmt> division<import_stmt>sys<import_stmt>time<import_stmt>re<import_stmt>threading<import_from_stmt>..runtime min_version runtime_info read_vm_size<import_from_stmt>..utils timestamp<import_from_stmt>..metric Metric<import_from_stmt>..metric Breakdown<if_stmt>min_version(3 4)<block_start><import_stmt>tracemalloc<block_end><class_stmt>AllocationProfiler(object)<block_start>MAX_TRACEBACK_SIZE=25# number of frames MAX_MEMORY_OVERHEAD=10<times>1e6# 10MB MAX_PROFILED_ALLOCATIONS=25<def_stmt>__init__ self agent<block_start>self.agent=agent<line_sep>self.ready=<false><line_sep>self.profile=<none><line_sep>self.profile_lock=threading.Lock()<line_sep>self.overhead_monitor=<none><line_sep>self.start_ts=<none><block_end><def_stmt>setup self<block_start><if_stmt>self.agent.get_option('allocation_profiler_disabled')<block_start><return><block_end><if_stmt><not>runtime_info.OS_LINUX<and><not>runtime_info.OS_DARWIN<block_start>self.agent.log('CPU profiler is only supported on Linux and OS X.')<line_sep><return><block_end><if_stmt><not>min_version(3 4)<block_start>self.agent.log('Memory allocation profiling is available for Python 3.4 or higher')<line_sep><return><block_end>self.ready=<true><block_end><def_stmt>reset self<block_start>self.profile=Breakdown('Allocation call graph' Breakdown.TYPE_CALLGRAPH)<block_end><def_stmt>start_profiler self<block_start>self.agent.log('Activating memory allocation profiler.')<def_stmt>start <block_start>tracemalloc.start(self.MAX_TRACEBACK_SIZE)<block_end>self.agent.run_in_main_thread(start)<line_sep>self.start_ts=time.time()<def_stmt>monitor_overhead <block_start><if_stmt>tracemalloc.is_tracing()<and>tracemalloc.get_tracemalloc_memory()<g>self.MAX_MEMORY_OVERHEAD<block_start>self.agent.log('Allocation profiler memory overhead limit exceeded: {0} bytes'.format(tracemalloc.get_tracemalloc_memory()))<line_sep>self.stop_profiler()<block_end><block_end>self.overhead_monitor=self.agent.schedule(0.5 0.5 monitor_overhead)<block_end><def_stmt>stop_profiler self<block_start>self.agent.log('Deactivating memory allocation profiler.')<with_stmt>self.profile_lock<block_start><if_stmt>self.overhead_monitor<block_start>self.overhead_monitor.cancel()<line_sep>self.overhead_monitor=<none><block_end><if_stmt>tracemalloc.is_tracing()<block_start>snapshot=tracemalloc.take_snapshot()<line_sep>self.agent.log('Allocation profiler memory overhead {0} bytes'.format(tracemalloc.get_tracemalloc_memory()))<line_sep>tracemalloc.stop()<line_sep>self.process_snapshot(snapshot time.time()-self.start_ts)<block_end><block_end><block_end><def_stmt>build_profile self duration<block_start><with_stmt>self.profile_lock<block_start>self.profile.normalize(duration)<line_sep>self.profile.propagate()<line_sep>self.profile.floor()<line_sep>self.profile.filter(2 1000 float("inf"))<line_sep><return>[{'category':Metric.CATEGORY_MEMORY_PROFILE 'name':Metric.NAME_UNCOLLECTED_ALLOCATIONS 'unit':Metric.UNIT_BYTE 'unit_interval':1 'profile':self.profile}]<block_end><block_end><def_stmt>destroy self<block_start><pass><block_end><def_stmt>process_snapshot self snapshot duration<block_start>stats=snapshot.statistics('traceback')<for_stmt>stat stats[:self.MAX_PROFILED_ALLOCATIONS]<block_start><if_stmt>stat.traceback<block_start>skip_stack=<false><for_stmt>frame stat.traceback<block_start><if_stmt>self.agent.frame_cache.is_agent_frame(frame.filename)<block_start>skip_stack=<true><line_sep><break><block_end><block_end><if_stmt>skip_stack<block_start><continue><block_end>current_node=self.profile<for_stmt>frame reversed(stat.traceback)<block_start><if_stmt>frame.filename<eq>'<unknown>'<block_start><continue><block_end>frame_name='{0}:{1}'.format(frame.filename frame.lineno)<line_sep>current_node=current_node.find_or_add_child(frame_name)<line_sep>current_node.set_type(Breakdown.TYPE_CALLSITE)<block_end>current_node.increment(stat.size stat.count)<block_end><block_end><block_end><block_end>
# -*- coding: utf-8 -*- <import_stmt>os<import_stmt>re<import_stmt>sys<import_stmt>json<import_stmt>shutil<import_stmt>hashlib<import_stmt>inspect<import_stmt>datetime<as>dt<import_stmt>click<import_stmt>requests<import_stmt>sqlalchemy<import_stmt>textdistance<import_from_stmt>rich.table Table<import_from_stmt>rich.console Console<try_stmt><block_start><import_stmt>bs4<import_stmt>git<import_stmt>pandas<import_stmt>cerberus<import_stmt>googleapiclient<block_end><except_stmt>ImportError<block_start>_HAS_CRAWL_REQUIREMENTS=<false><block_end><else_stmt><block_start>_HAS_CRAWL_REQUIREMENTS=<true><block_end><if_stmt>_HAS_CRAWL_REQUIREMENTS<block_start><import_stmt>crawlers<import_from_stmt>crawlers *<block_end><import_from_stmt>. __version__ CONRAD_HOME<import_from_stmt>.schema *<import_from_stmt>.db engine Session<import_from_stmt>.models Base Event Reminder<import_from_stmt>.utils apply_schema initialize_database validate_events mkdir<line_sep>DATE_FMT="%Y-%m-%dT%H:%M:%S"<def_stmt>has_less <block_start><return>shutil.which("less")<block_end><def_stmt>set_default_pager <block_start><if_stmt>has_less()<is><not><none><block_start>os.environ["LESS"]="-SRXF"<block_end><block_end><def_stmt>get_events <block_start>click.echo("Fetching latest events!")<line_sep>events_filename=eval(f"f{LATEST}")<line_sep>response=requests.get(f"https://raw.githubusercontent.com/vinayak-mehta/conrad/master/data/{events_filename}" timeout=5 )<with_stmt>open(os.path.join(CONRAD_HOME events_filename) "w")<as>f<block_start>f.write(json.dumps(response.json()))<block_end><block_end><def_stmt>rebuild_events_table <block_start>events_filename=eval(f"f{LATEST}")<with_stmt>open(os.path.join(CONRAD_HOME events_filename) "r")<as>f<block_start>events=json.load(f)<block_end>session=Session()<for_stmt>event events<block_start>event_id=hashlib.md5((event["name"]+event["start_date"]).encode("utf-8")).hexdigest()<line_sep>e=Event(id=event_id[:6] name=event["name"] url=event["url"] city=event["city"] state=event["state"] country=event["country"] location=event["location"] cfp_open=event["cfp_open"] cfp_end_date=dt.datetime.strptime(event["cfp_end_date"] "%Y-%m-%d") start_date=dt.datetime.strptime(event["start_date"] "%Y-%m-%d") end_date=dt.datetime.strptime(event["end_date"] "%Y-%m-%d") source=event["source"] tags=json.dumps(event["tags"]) kind=event["kind"] by=event["by"] )<line_sep>session.add(e)<line_sep>session.commit()<block_end>session.close()<block_end><def_stmt>set_update_timestamp overwrite=<false><block_start>updated_at=os.path.join(CONRAD_HOME ".updated_at")<if_stmt>overwrite<or><not>os.path.exists(updated_at)<block_start><with_stmt>open(updated_at "w")<as>f<block_start>f.write(dt.datetime.now().strftime(DATE_FMT))<block_end><block_end><block_end><def_stmt>initialize_conrad <block_start>set_update_timestamp()<if_stmt><not>os.path.exists(os.path.join(CONRAD_HOME "conrad.db"))<block_start>get_events()<line_sep>initialize_database()<line_sep>rebuild_events_table()<block_end><block_end><def_stmt>refresh_conrad <block_start>get_events()<if_stmt><not>os.path.exists(os.path.join(CONRAD_HOME "conrad.db"))<block_start>initialize_database()<block_end><else_stmt><block_start>Event.__table__.drop(engine)<line_sep>Base.metadata.tables["event"].create(bind=engine)<block_end>rebuild_events_table()<line_sep>set_update_timestamp(overwrite=<true>)<block_end><def_stmt>clean_old_events <block_start>session=Session()<line_sep>now=dt.datetime.now()<line_sep>reminders=list(session.query(Event Reminder).filter(Event.id<eq>Reminder.id Event.end_date<l>now).all())<for_stmt>r,__ reminders<block_start>session.query(Reminder).filter(Reminder.id<eq>r.id).delete()<block_end>events=list(session.query(Event).filter(Event.end_date<l>now).all())<for_stmt>e events<block_start>session.query(Event).filter(Event.id<eq>e.id).delete()<block_end>session.commit()<line_sep>session.close()<block_end><def_stmt>auto_refresh <block_start><try_stmt><block_start>updated_at=os.path.join(CONRAD_HOME ".updated_at")<with_stmt>open(updated_at "r")<as>f<block_start>last_updated_at=dt.datetime.strptime(f.read().strip() DATE_FMT)<block_end><block_end><except_stmt>(IOError FileNotFoundError)<block_start>last_updated_at=dt.datetime.strptime("1970-01-01T00:00:00" DATE_FMT)<block_end><if_stmt>(dt.datetime.now()-last_updated_at)<g>dt.timedelta(days=7)<block_start>refresh_conrad()<line_sep>clean_old_events()<block_end><block_end># https://stackoverflow.com/a/50889894 <def_stmt>make_exclude_hook_command callback<block_start>"""for any command that is not decorated, call the callback"""<line_sep>hook_attr_name="hook_"+callback.__name__<class_stmt>HookGroup(click.Group)<block_start>"""group to hook context invoke to see if the callback is needed"""<def_stmt>group self *args **kwargs<block_start>"""new group decorator to make sure sub groups are also hooked"""<if_stmt>"cls"<not><in>kwargs<block_start>kwargs["cls"]=type(self)<block_end><return>super(HookGroup self).group(*args **kwargs)<block_end><def_stmt>command self *args **kwargs<block_start>"""new command decorator to monkey patch command invoke"""<line_sep>cmd=super(HookGroup self).command(*args **kwargs)<def_stmt>hook_command_decorate f# decorate the command <block_start>ret=cmd(f)<line_sep># grab the original command invoke orig_invoke=ret.invoke<def_stmt>invoke ctx<block_start>"""call the call back right before command invoke"""<line_sep>parent=ctx.parent<line_sep>sub_cmd=(parent<and>parent.command.commands[parent.invoked_subcommand])<if_stmt>(<not>sub_cmd<or><not>isinstance(sub_cmd click.Group)<and>getattr(sub_cmd hook_attr_name <true>))# invoke the callback <block_start>callback()<block_end><return>orig_invoke(ctx)<block_end># hook our command invoke to command and return cmd ret.invoke=invoke<line_sep><return>ret<block_end># return hooked command decorator <return>hook_command_decorate<block_end><block_end><def_stmt>decorator func=<none><block_start><if_stmt>func<is><none># if called other than as decorator, return group class <block_start><return>HookGroup<block_end>setattr(func hook_attr_name <false>)<block_end><return>decorator<block_end>bypass_auto_refresh=make_exclude_hook_command(auto_refresh)<line_sep>@click.group(name="conrad" cls=bypass_auto_refresh())@click.version_option(version=__version__)@click.pass_context<def_stmt>cli ctx *args **kwargs<block_start>"""conrad: Track conferences and meetups on your terminal."""<line_sep>set_default_pager()<block_end>@bypass_auto_refresh@cli.command("refresh" short_help="Refresh event database.")@click.confirmation_option(prompt="Would you like conrad to look for new events?")@click.pass_context<def_stmt>_refresh ctx *args **kwargs# TODO: print("10 new events found!") <block_start>refresh_conrad()<line_sep>click.echo("All done! ✨ 🍰 ✨")<line_sep>click.echo("Event database updated.")<block_end>@cli.command("show" short_help="Show all saved events.")@click.option("--id" "-i" help="Show event with a particular id." )@click.option("--kind" "-k" help="Show kind of event, conference or meetup." )@click.option("--cfp" "-c" is_flag=<true> help="Show only events which have an open CFP (call for proposals)." )@click.option("--tag" "-t" default="" help="Look at conferences with a specific tag.")@click.option("--name" "-n" default="" help="Look at conferences containing a specific word in their name." )@click.option("--location" "-l" default="" help="Look at conferences in a specific city, state or country." )@click.option("--date" "-d" default=[] multiple=<true> help='Look at conferences based on when they\'re happening. For example: conrad show --date ">= 2019-10-01" --date "<= 2020-01-01".' )@click.pass_context<def_stmt>_show ctx *args **kwargs# TODO: conrad show --new <block_start>initialize_conrad()<line_sep>_id=kwargs["id"]<line_sep>kind=kwargs["kind"]<line_sep>cfp=kwargs["cfp"]<line_sep>tag=kwargs["tag"]<line_sep>name=kwargs["name"]<line_sep>date=list(kwargs["date"])<line_sep>location=kwargs["location"]<line_sep>filters=[]<if_stmt>_id<block_start>filters.append(Event.id<eq>_id)<block_end><if_stmt>kind<block_start>filters.append(Event.kind<eq>kind)<block_end><if_stmt>cfp<block_start>filters.append(Event.cfp_open.is_(cfp))<block_end><if_stmt>tag<block_start>filters.append(Event.tags.contains(tag))<block_end><if_stmt>name<block_start>filters.append(Event.name.ilike(f"%{name}%"))<block_end><if_stmt>date<block_start>date_filters=[]<for_stmt>d date<block_start>cmp,date=d.split(" ")<if_stmt><not>(">"<in>cmp<or>"<"<in>cmp)<block_start><raise>click.UsageError("Wrong comparison operator!")<block_end><try_stmt><block_start>__=dt.datetime.strptime(date "%Y-%m-%d")<block_end><except_stmt>ValueError<block_start><raise>click.UsageError("Wrong date format!")<block_end><if_stmt>">"<in>cmp<block_start>date_filters.append(Event.start_date<ge>date)<block_end><elif_stmt>"<"<in>cmp<block_start>date_filters.append(Event.start_date<le>date)<block_end><block_end>filters.append(sqlalchemy.and_(*date_filters))<block_end><if_stmt>location<block_start>filters.append(sqlalchemy.or_(Event.name.ilike(f"%{location}%") Event.city.ilike(f"%{location}%") Event.state.ilike(f"%{location}%") Event.country.ilike(f"%{location}%") Event.location.ilike(f"%{location}%") ))<block_end>session=Session()<try_stmt><block_start>events=list(session.query(Event).filter(*filters).order_by(Event.start_date).all())<block_end><except_stmt>sqlalchemy.exc.OperationalError<block_start>refresh_conrad()<line_sep>events=list(session.query(Event).filter(*filters).order_by(Event.start_date).all())<block_end><if_stmt>len(events)<g>0<block_start>console=Console()<line_sep>table=Table(show_header=<true> header_style="bold magenta" show_lines=<true>)<line_sep>table.add_column("id")<line_sep>table.add_column("Name")<line_sep>table.add_column("Website")<line_sep>table.add_column("City")<line_sep>table.add_column("Country")<line_sep>table.add_column("Start Date")<line_sep>table.add_column("End Date")<line_sep>events_output=[]<line_sep>rids=[r.id<for>r session.query(Reminder).all()]<for_stmt>event events<block_start>event_output=[event.id event.name event.url event.city event.country event.start_date.strftime("%Y-%m-%d") event.end_date.strftime("%Y-%m-%d") ]<line_sep># highlight event which has a reminder set <if_stmt>event.id<in>rids<block_start>event_output=list(map(<lambda>x:f"[bold][green]{x}[/green][/bold]" event_output ))<block_end>table.add_row(*event_output)<block_end>session.close()<line_sep>console_kwargs={}<if_stmt>has_less()<block_start>console_kwargs["styles"]=<true><block_end><with_stmt>console.pager(**console_kwargs)<block_start>console.print(table)<block_end><block_end><else_stmt><block_start>click.echo("No events found!")<block_end><block_end>@cli.command("remind" short_help="Set and display reminders.")@click.option("--id" "-i" default=<none> help="Conference identifier.")@click.pass_context<def_stmt>_remind ctx *args **kwargs<block_start><def_stmt>get_days_left event<block_start>start=dt.datetime.now()<line_sep>cfp_days_left=(event.cfp_end_date-start).days<line_sep>event_days_left=(event.start_date-start).days<if_stmt>event.cfp_open<and>cfp_days_left<ge>0<block_start>days_left=cfp_days_left<block_end><elif_stmt>event_days_left<ge>0<block_start>days_left=event_days_left<block_end><else_stmt><block_start>days_left=-1<block_end><return>days_left event.cfp_open<block_end>initialize_conrad()<line_sep>_id=kwargs["id"]<if_stmt>_id<is><none><block_start>session=Session()<line_sep>reminders=list(session.query(Event Reminder).filter(Event.id<eq>Reminder.id).order_by(Event.start_date).all())<if_stmt>len(reminders)<g>0<block_start>console=Console()<line_sep>table=Table(show_header=<true> header_style="bold magenta" show_lines=<true>)<line_sep>table.add_column("id")<line_sep>table.add_column("Name")<line_sep>table.add_column("Start Date")<line_sep>table.add_column("Days Left")<line_sep>reminders_output=[]<for_stmt>reminder,__ reminders<block_start>days_left,cfp_open=get_days_left(reminder)<if_stmt>cfp_open<and>days_left<ge>0<block_start>days_left_output=f"{days_left} days left to cfp deadline!"<block_end><elif_stmt>days_left<ge>0<block_start>days_left_output=f"{days_left} days left!"<block_end><else_stmt><block_start>days_left_output="Event ended."<block_end>style="white"<if_stmt>days_left<ge>30<block_start>style="green"<block_end><elif_stmt>30<g>days_left<ge>10<block_start>style="yellow"<block_end><elif_stmt>10<g>days_left<ge>0<block_start>style="red"<block_end>days_left_output=f"[bold][{style}]{days_left_output}[/{style}][/bold]"<line_sep>reminder_output=[reminder.id reminder.name reminder.start_date.strftime("%Y-%m-%d") days_left_output ]<line_sep>table.add_row(*reminder_output)<block_end>session.close()<line_sep>console_kwargs={}<if_stmt>has_less()<block_start>console_kwargs["styles"]=<true><block_end><with_stmt>console.pager(**console_kwargs)<block_start>console.print(table)<block_end><block_end><else_stmt><block_start>click.echo("No reminders found!")<block_end><block_end><else_stmt><block_start><try_stmt><block_start>session=Session()<line_sep>event=session.query(Event).filter(Event.id<eq>_id).first()<if_stmt>event<is><none><block_start>click.echo("Event not found!")<block_end><else_stmt><block_start>days_left,__=get_days_left(event)<if_stmt>days_left<eq>-1<block_start>click.echo("Event ended.")<block_end><else_stmt><block_start>reminder=Reminder(id=event.id)<line_sep>session.add(reminder)<line_sep>session.commit()<line_sep>session.close()<line_sep>click.echo("Reminder set!")<block_end><block_end><block_end><except_stmt>sqlalchemy.exc.IntegrityError<block_start>session.rollback()<if_stmt>click.confirm("Do you want to remove this reminder?")<block_start>session=Session()<line_sep>session.query(Reminder).filter(Reminder.id<eq>_id).delete()<line_sep>session.commit()<line_sep>session.close()<line_sep>click.echo("Reminder removed!")<block_end><block_end><block_end><block_end>@cli.command("generate" short_help="Generate skeleton crawler code.")@click.argument("entity")@click.argument("entity_name")@click.pass_context<def_stmt>_generate ctx *args **kwargs<block_start>SUPPORTED_ENTITIES=["crawler"]<line_sep>entity=kwargs["entity"]<if_stmt>entity<not><in>SUPPORTED_ENTITIES<block_start>click.UsageError(f"Entity '{entity}' not supported")<block_end>entity_name=kwargs["entity_name"]<line_sep>entity_name_snake_case=re.sub(r"(?<!^)(?=[A-Z])" "_" entity_name).lower()<line_sep>crawler_dir=f"crawlers/{entity_name_snake_case}"<line_sep>mkdir(crawler_dir)<with_stmt>open(os.path.join(crawler_dir "__init__.py") "w")<as>f<block_start>f.write("# -*- coding: utf-8 -*-\n")<block_end>crawler_content=f"""# -*- coding: utf-8 -*- from ..base import BaseCrawler class {entity_name}Crawler(BaseCrawler): def get_events(self): # Populate this list of events using your code events = [] # YOUR CODE HERE # Extend the self.events list with the new list self.events.extend(events) """<line_sep>crawler_path=os.path.join(crawler_dir f"{entity_name_snake_case}_crawler.py")<with_stmt>open(crawler_path "w")<as>f<block_start>f.write(crawler_content)<block_end><with_stmt>open("crawlers/__init__.py" "a")<as>f<block_start>f.write(f"from .{entity_name_snake_case}.{entity_name_snake_case}_crawler import {entity_name}Crawler")<block_end>click.echo(f"\t{click.style('create' fg='green' bold=<true>)}\t{crawler_path}")<block_end>@cli.command("run" short_help="Run crawler code.")@click.argument("entity")@click.argument("entity_name")@click.pass_context<def_stmt>_run ctx *args **kwargs<block_start><if_stmt><not>_HAS_CRAWL_REQUIREMENTS<block_start><raise>click.UsageError("To run crawlers, please install the requirements with\n"<concat>"'pip install --upgrade conference-radar[crawl]'.")<block_end>SUPPORTED_ENTITIES=["crawler"]<line_sep>entity=kwargs["entity"]<if_stmt>entity<not><in>SUPPORTED_ENTITIES<block_start>click.UsageError(f"Entity '{entity}' not supported")<block_end>entity_name=kwargs["entity_name"]<line_sep>entity_name_snake_case=re.sub(r"(?<!^)(?=[A-Z])" "_" entity_name).lower()<line_sep>crawler=[m[0]<for>m inspect.getmembers(crawlers inspect.isclass)<if>m[1].__module__.startswith("crawlers")<and>m[0]<eq>f"{entity_name}Crawler"]<if_stmt>len(crawler)<block_start>filename=crawler[0].lower().replace("crawler" "")<line_sep>Crawler=eval(crawler[0])<line_sep>c=Crawler()<line_sep>c.get_events()<line_sep>crawler_data_path=f"data/{filename}.json"<line_sep>c.export(crawler_data_path)<line_sep>click.echo(f"\t{click.style('save' fg='green' bold=<true>)}\t{crawler_data_path}")<block_end><else_stmt><block_start>print("Crawler not found!")<block_end><block_end>@bypass_auto_refresh@cli.command("import" short_help="Import new events into conrad.")@click.option("--file" "-f" default=<none> help="JSON file to import.")@click.pass_context<def_stmt>_import ctx *args **kwargs<block_start>file=kwargs["file"]<if_stmt>file<is><none><block_start><raise>click.UsageError("No file provided!")<block_end><if_stmt><not>os.path.exists(file)<block_start><raise>click.UsageError("File does not exist!")<block_end><with_stmt>open(file "r")<as>f<block_start>input_events=json.load(f)<block_end>failures=validate_events(input_events version=LATEST)<if_stmt>len(failures)<g>0<block_start><raise>click.UsageError("The following validations failed!\n{}".format("".join(list(map(<lambda>x:"- "+x+"\n" failures[:-1]))+list(map(<lambda>x:"- "+x failures[-1:])))))<block_end>events_path=os.path.join(os.getcwd() "data" f"{eval(f'f{LATEST}')}")<try_stmt><block_start><with_stmt>open(events_path "r")<as>f<block_start>events=json.load(f)<block_end><block_end><except_stmt>(IOError ValueError KeyError FileNotFoundError)<block_start>events=[]<block_end>now=dt.datetime.now()<line_sep>old_events=[]<for_stmt>e events<block_start>event_end_date=dt.datetime.strptime(e["end_date"] "%Y-%m-%d")<if_stmt>event_end_date<l>now<block_start>print(f"Removing {e['name']}")<line_sep><continue><block_end><if_stmt>e["cfp_end_date"]<is><not><none><block_start>cfp_end_date=dt.datetime.strptime(e["cfp_end_date"] "%Y-%m-%d")<if_stmt>cfp_end_date<l>now<block_start>e["cfp_open"]=<false><block_end><block_end>old_events.append(e)<block_end>removed=len(events)-len(old_events)<line_sep>s="s"<if>removed<ne>1<else>""<line_sep>click.echo(f"Removed {removed} old event{s}!")<line_sep>pattern="[0-9]"<line_sep>new_events=[]<for_stmt>ie input_events<block_start><if_stmt>ie["end_date"]<is><none><block_start><continue><block_end>event_end_date=dt.datetime.strptime(ie["end_date"] "%Y-%m-%d")<if_stmt>event_end_date<l>now<block_start><continue><block_end><if_stmt>ie["cfp_end_date"]<is><not><none><block_start>cfp_end_date=dt.datetime.strptime(ie["cfp_end_date"] "%Y-%m-%d")<if_stmt>cfp_end_date<l>now<block_start>ie["cfp_open"]=<false><block_end><block_end>match=<false><for_stmt>oe old_events<block_start>input_event_name=ie["name"].replace(" " "").lower()<line_sep>input_event_name=re.sub(pattern "" input_event_name)<line_sep>old_event_name=oe["name"].replace(" " "").lower()<line_sep>old_event_name=re.sub(pattern "" old_event_name)<line_sep>similarity=textdistance.levenshtein.normalized_similarity(input_event_name old_event_name)<if_stmt>similarity<g>0.9<block_start>click.echo(f"Updating {oe['name']}")<line_sep>oe.update(ie)<line_sep>match=<true><block_end><block_end><if_stmt><not>match<block_start>click.echo(f"Adding {ie['name']}")<line_sep>new_events.append(ie)<block_end><block_end>old_events.extend(new_events)<line_sep>s="s"<if>len(new_events)<ne>1<else>""<line_sep>click.echo(f"Added {len(new_events)} new event{s}!")<with_stmt>open(events_path "w")<as>f<block_start>f.write(json.dumps(old_events indent=4 sort_keys=<true>))<block_end><for_stmt>version reversed(range(1 int(LATEST)))<block_start>events=old_events.copy()<line_sep>events=apply_schema(events version=version)<line_sep>events_path=os.path.join(os.getcwd() "data" f"{eval(f'f{version}')}")<with_stmt>open(events_path "w")<as>f<block_start>f.write(json.dumps(events indent=4 sort_keys=<true>))<block_end><block_end><block_end>
<import_stmt>numpy<as>np<def_stmt>load_MNIST_images filename<block_start>""" returns a 28x28x[number of MNIST images] matrix containing the raw MNIST images :param filename: input data file """<with_stmt>open(filename "r")<as>f<block_start>magic=np.fromfile(f dtype=np.dtype('>i4') count=1)<line_sep>num_images=np.fromfile(f dtype=np.dtype('>i4') count=1)<line_sep>num_rows=np.fromfile(f dtype=np.dtype('>i4') count=1)<line_sep>num_cols=np.fromfile(f dtype=np.dtype('>i4') count=1)<line_sep>images=np.fromfile(f dtype=np.ubyte)<line_sep>images=images.reshape((num_images num_rows<times>num_cols)).transpose()<line_sep>images=images.astype(np.float64)/255<line_sep>f.close()<line_sep><return>images<block_end><block_end><def_stmt>load_MNIST_labels filename<block_start>""" returns a [number of MNIST images]x1 matrix containing the labels for the MNIST images :param filename: input file with labels """<with_stmt>open(filename 'r')<as>f<block_start>magic=np.fromfile(f dtype=np.dtype('>i4') count=1)<line_sep>num_labels=np.fromfile(f dtype=np.dtype('>i4') count=1)<line_sep>labels=np.fromfile(f dtype=np.ubyte)<line_sep>f.close()<line_sep><return>labels<block_end><block_end>
"""Tests for the spc component."""<line_sep>
""" Testing for TG2 Configuration """<import_from_stmt>nose SkipTest<import_from_stmt>nose.tools eq_ raises<import_stmt>sys os<import_from_stmt>datetime datetime<import_from_stmt>sqlalchemy.orm scoped_session<import_from_stmt>sqlalchemy.orm sessionmaker<import_from_stmt>sqlalchemy.engine Engine<import_from_stmt>ming Session<import_from_stmt>ming.orm ThreadLocalORMSession<import_from_stmt>tg.configurator.base ConfigurationComponent Configurator BeforeConfigConfigurationAction<import_from_stmt>tg.configurator.components.app_globals AppGlobalsConfigurationComponent<import_from_stmt>tg.configurator.components.auth SimpleAuthenticationConfigurationComponent<import_from_stmt>tg.configurator.components.caching CachingConfigurationComponent<import_from_stmt>tg.configurator.components.dispatch DispatchConfigurationComponent<import_from_stmt>tg.configurator.components.helpers HelpersConfigurationComponent<import_from_stmt>tg.configurator.components.i18n I18NConfigurationComponent<import_from_stmt>tg.configurator.components.ming MingConfigurationComponent<import_from_stmt>tg.configurator.components.paths PathsConfigurationComponent<import_from_stmt>tg.configurator.components.registry RegistryConfigurationComponent<import_from_stmt>tg.configurator.components.rendering TemplateRenderingConfigurationComponent<import_from_stmt>tg.configurator.components.session SessionConfigurationComponent<import_from_stmt>tg.configurator.components.sqlalchemy SQLAlchemyConfigurationComponent<import_from_stmt>tg.configurator.components.transactions TransactionManagerConfigurationComponent<import_from_stmt>tg.configuration.tgconfig _init_default_global_config<import_from_stmt>tg.appwrappers.mingflush MingApplicationWrapper<import_from_stmt>tg.util Bunch<import_from_stmt>tg.configuration config<import_from_stmt>tg.configurator FullStackApplicationConfigurator<import_from_stmt>tg.configurator ApplicationConfigurator<import_from_stmt>tg.configuration.app_config AppConfig<import_from_stmt>tg.configuration.auth _AuthenticationForgerPlugin<import_from_stmt>tg.configuration.auth.metadata _AuthMetadataAuthenticator<import_from_stmt>tg.configuration.utils coerce_config coerce_options TGConfigError<import_from_stmt>tg.configuration milestones<import_from_stmt>tg.support.converters asint asbool<import_stmt>tg.i18n<import_from_stmt>tg TGController expose response request abort MinimalApplicationConfigurator<import_from_stmt>tests.base setup_session_dir teardown_session_dir<import_from_stmt>webtest TestApp<import_from_stmt>tg.renderers.base RendererFactory<import_from_stmt>tg.wsgiapp TGApp<import_from_stmt>tg._compat PY3<def_stmt>setup <block_start>milestones._reset_all()<line_sep>setup_session_dir()<block_end><def_stmt>teardown <block_start>milestones._reset_all()<line_sep>teardown_session_dir()<block_end><def_stmt>_reset_global_config <block_start>milestones._reset_all()<try_stmt><block_start>config.config_proxy.pop_thread_config()<block_end><except_stmt><block_start><pass><block_end><try_stmt><block_start>config.config_proxy.pop_process_config()<block_end><except_stmt><block_start><pass><block_end><block_end><class_stmt>PackageWithModel<block_start>__name__='tests'<line_sep>__file__=__file__<def_stmt>__init__ self<block_start>self.model=self.ModelClass()<line_sep>self.model.DBSession=self.model.FakeDBSession()<block_end><class_stmt>ModelClass<block_start><class_stmt>FakeDBSession<block_start><def_stmt>remove self<block_start>self.DBSESSION_REMOVED=<true><block_end><block_end><def_stmt>init_model self engine<block_start><if_stmt>isinstance(engine Engine)# SQLA <block_start><return>self.DBSession<block_end><else_stmt># Ming <block_start><return>dict(ming=<true>)<block_end><block_end><block_end><class_stmt>lib<block_start><class_stmt>app_globals<block_start><class_stmt>Globals<block_start><pass><block_end><block_end><block_end><block_end>PackageWithModel.__name__='tests'<class_stmt>UncopiableList(list)<block_start>""" This is to test configuration methods that make a copy of a list to modify it, using this we can check how it has been modified """<def_stmt>__copy__ self<block_start><return>self<block_end><block_end><class_stmt>FakeTransaction<block_start><def_stmt>get self<block_start><return>self<block_end><def_stmt>begin self<block_start>self.aborted=<false><line_sep>self.doomed=<false><line_sep><return>self<block_end><def_stmt>abort self<block_start>self.aborted=<true><block_end><def_stmt>commit self<block_start>self.aborted=<false><block_end><def_stmt>_retryable self *args<block_start><return><true><block_end>note=_retryable<def_stmt>isDoomed self<block_start><return>self.doomed<block_end><def_stmt>doom self<block_start>self.doomed=<true><block_end><block_end><import_from_stmt>tg.configuration.auth TGAuthMetadata<class_stmt>ApplicationAuthMetadata(TGAuthMetadata)<block_start><def_stmt>get_user self identity userid<block_start><return>{'name':'None'}<block_end><block_end><class_stmt>ApplicationAuthMetadataWithAuthentication(TGAuthMetadata)<block_start><def_stmt>authenticate self environ identity<block_start><return>1<block_end><def_stmt>get_user self identity userid<block_start><return>{'name':'None'}<block_end><block_end><class_stmt>AtExitTestException(Exception)<block_start><pass><block_end><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end><class_stmt>TestPylonsConfigWrapper<block_start><def_stmt>setup self<block_start>_reset_global_config()<line_sep>_init_default_global_config()<line_sep>self.config=config<block_end><def_stmt>tearDown self<block_start>_reset_global_config()<line_sep>_init_default_global_config()<block_end><def_stmt>test_create self<block_start><pass><block_end><def_stmt>test_getitem self<block_start>expected_keys=['debug' 'package' 'tg.app_globals' 'tg.strict_tmpl_context']<for_stmt>key expected_keys<block_start>self.config[key]<block_end><block_end><def_stmt>test_repr self<block_start>_reset_global_config()<assert_stmt>repr(self.config)<eq>'<TGConfig: missing>'<line_sep>_init_default_global_config()<assert_stmt>repr(self.config)<eq>repr(self.config.config_proxy.current_conf())<block_end>@raises(KeyError)<def_stmt>test_getitem_bad self<block_start>self.config['no_such_key']<block_end><def_stmt>test_setitem self<block_start>self.config['no_such_key']='something'<block_end><def_stmt>test_delattr self<block_start><del_stmt>self.config.debug<line_sep>eq_(hasattr(self.config 'debug') <false>)<line_sep>self.config.debug=<false><block_end>@raises(AttributeError)<def_stmt>test_delattr_bad self<block_start><del_stmt>self.config.i_dont_exist<block_end><def_stmt>test_keys self<block_start>k=self.config.keys()<assert_stmt>'tg.app_globals'<in>k<block_end><block_end><def_stmt>test_coerce_config <block_start>opts={'ming.connection.max_pool_size':'5'}<line_sep>conf=coerce_config(opts 'ming.connection.' {'max_pool_size':asint})<assert_stmt>conf['max_pool_size']<eq>5<assert_stmt>opts['ming.connection.max_pool_size']<eq>'5'<block_end><def_stmt>test_coerce_options <block_start>opts={'connection':'false'}<line_sep>conf=coerce_options(opts {'connection':asbool})<assert_stmt>conf['connection']<is><false><assert_stmt>opts['connection']<eq>'false'<block_end><class_stmt>TestConfigurator<block_start><def_stmt>setup self<block_start>_reset_global_config()<block_end><def_stmt>teardown self<block_start>_reset_global_config()<line_sep>tg.hooks._clear()<block_end># Reset hooks <def_stmt>test_repr_action self<block_start>act=BeforeConfigConfigurationAction()<assert_stmt>repr(act)<eq>"<BeforeConfigConfigurationAction: None>"<block_end><def_stmt>test_reqlocal_configuration_dictionary self<block_start>cfg=FullStackApplicationConfigurator()<line_sep>cfg.update_blueprint({'RANDOM_VALUE':5})<line_sep>conf=cfg.configure({} {})<assert_stmt>config['RANDOM_VALUE']<eq>5<assert_stmt>len(config)<eq>len(conf)<block_end><def_stmt>test_blueprint_invalid_view self<block_start>cfg=FullStackApplicationConfigurator()<try_stmt><block_start>cfg.get_blueprint_view('this.that.')<block_end><except_stmt>ValueError<as>e<block_start><assert_stmt>str(e)<eq>'A Blueprint key cannot end with a .'<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_invalid_component self<block_start>cfg=FullStackApplicationConfigurator()<try_stmt><block_start>cfg.register(str)<block_end><except_stmt>ValueError<as>e<block_start><assert_stmt>str(e)<eq>'Configuration component must inherit ConfigurationComponent'<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_replace_component self<block_start>cfg=FullStackApplicationConfigurator()<class_stmt>TestComponentFirst(ConfigurationComponent)<block_start>id='TESTCOMPONENT'<block_end><class_stmt>TestComponentSecond(ConfigurationComponent)<block_start>id='TESTCOMPONENT2'<block_end>cfg.register(TestComponentFirst)<try_stmt><block_start>cfg.replace(TestComponentFirst str)<block_end><except_stmt>ValueError<as>e<block_start><assert_stmt>str(e)<eq>'Configuration component must inherit ConfigurationComponent'<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end>cfg.replace('TESTCOMPONENT' TestComponentSecond)<line_sep>comp=cfg.get_component('TESTCOMPONENT')<assert_stmt>isinstance(comp TestComponentSecond) comp<block_end><def_stmt>test_component_without_id self<block_start>cfg=FullStackApplicationConfigurator()<class_stmt>TestComponentFirst(ConfigurationComponent)<block_start><pass><block_end><try_stmt><block_start>cfg.register(TestComponentFirst)<block_end><except_stmt>ValueError<as>e<block_start><assert_stmt>str(e).startswith('ConfigurationComponent must provide an id class attribute')<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><try_stmt><block_start>cfg.replace(TestComponentFirst TestComponentFirst)<block_end><except_stmt>ValueError<as>e<block_start><assert_stmt>str(e).startswith('ConfigurationComponent must provide an id class attribute')<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_retrieve_current_configurator self<block_start>cfg=FullStackApplicationConfigurator()<line_sep>cfg.update_blueprint({'RANDOM_VALUE':5})<line_sep>cfg.configure({} {})<line_sep>configurator=FullStackApplicationConfigurator.current()<assert_stmt>configurator.get_blueprint_value('RANDOM_VALUE')<eq>5<block_end><def_stmt>test_application_wrapper_replacement self<block_start><class_stmt>AppWrapperTest(object)<block_start><def_stmt>__init__ self *args **kwargs<block_start><pass><block_end><def_stmt>__call__ self *args **kw<block_start><return>tg.Response('AppWrapper #1')<block_end><block_end><class_stmt>AppWrapperTestReplacement(object)<block_start><def_stmt>__init__ self *args **kwargs<block_start><pass><block_end><def_stmt>__call__ self *args **kw<block_start><return>tg.Response('AppWrapper #2')<block_end><block_end>cfg=FullStackApplicationConfigurator()<line_sep>cfg.update_blueprint({'root_controller':Bunch(index=<lambda>*args **kwargs:'HI')})<line_sep>cfg.register_application_wrapper(AppWrapperTest)<line_sep>app=TestApp(cfg.make_wsgi_app({'debug':<true>} {}))<assert_stmt>app.get('/').text<eq>'AppWrapper #1' app.get('/').text<line_sep>cfg.replace_application_wrapper('AppWrapperTest' AppWrapperTestReplacement)<line_sep>app=TestApp(cfg.make_wsgi_app({} {}))<assert_stmt>app.get('/').text<eq>'AppWrapper #2' app.get('/').text<block_end><def_stmt>test_sa_auth_requires_app_config self<block_start>configurator=Configurator()<line_sep>configurator.register(SimpleAuthenticationConfigurationComponent)<try_stmt><block_start>configurator.configure({} {})<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e)<eq>'Simple Authentication only works on an ApplicationConfigurator'<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_sa_auth_authmetadata_without_authenticate self<block_start>cfg=FullStackApplicationConfigurator()<class_stmt>FakeAuthMetadata()<block_start><pass><block_end>cfg.update_blueprint({'root_controller':Bunch(index=<lambda>*args **kwargs:'HI') 'auth_backend':'authmetadata' 'sa_auth.authmetadata':FakeAuthMetadata() 'sa_auth.cookie_secret':'SECRET!'})<line_sep>cfg.make_wsgi_app({} {})<block_end><def_stmt>test_caching_required_app_config self<block_start>configurator=Configurator()<line_sep>configurator.register(CachingConfigurationComponent)<try_stmt><block_start>configurator.configure({} {})<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e)<eq>'Caching only works on an ApplicationConfigurator'<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_i18n_required_app_config self<block_start>configurator=Configurator()<line_sep>configurator.register(I18NConfigurationComponent)<try_stmt><block_start>configurator.configure({} {})<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e)<eq>'I18N only works on an ApplicationConfigurator'<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_ming_required_app_config self<block_start>configurator=Configurator()<line_sep>configurator.register(MingConfigurationComponent)<try_stmt><block_start>configurator.configure({} {})<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e).endswith('only works on an ApplicationConfigurator')<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_session_required_app_config self<block_start>configurator=Configurator()<line_sep>configurator.register(SessionConfigurationComponent)<try_stmt><block_start>configurator.configure({} {})<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e).endswith('only work on an ApplicationConfigurator')<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_sqlalchemy_required_app_config self<block_start>configurator=Configurator()<line_sep>configurator.register(SQLAlchemyConfigurationComponent)<try_stmt><block_start>configurator.configure({} {})<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e).endswith('only works on an ApplicationConfigurator')<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_transaction_required_app_config self<block_start>configurator=Configurator()<line_sep>configurator.register(TransactionManagerConfigurationComponent)<try_stmt><block_start>configurator.configure({} {})<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e).endswith('only works on an ApplicationConfigurator')<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised'<block_end><block_end><def_stmt>test_dispatch_without_mimetypes self# This is exactly like MinimalApplicationConfigurator # but without the mimetypes component. <block_start>apc=ApplicationConfigurator()<line_sep>apc.register(PathsConfigurationComponent after=<false>)<line_sep>apc.register(DispatchConfigurationComponent after=<false>)<line_sep>apc.register(AppGlobalsConfigurationComponent)<line_sep>apc.register(HelpersConfigurationComponent)<line_sep>apc.register(TemplateRenderingConfigurationComponent)<line_sep>apc.register(RegistryConfigurationComponent after=<true>)<class_stmt>MinimalController(TGController)<block_start>@expose()<def_stmt>index self<block_start><return>'HI'<block_end><block_end>apc.update_blueprint({'root_controller':MinimalController()})<line_sep>app=TestApp(apc.make_wsgi_app({} {}))<assert_stmt>app.get('/').text<eq>'HI'<block_end><def_stmt>test_app_without_controller self<block_start>cfg=MinimalApplicationConfigurator()<line_sep>app=TestApp(cfg.make_wsgi_app({} {}))<try_stmt><block_start>app.get('/')<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e)<eq>'Unable to load controllers, no controllers path configured!'<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised.'<block_end><block_end><def_stmt>test_tgapp_caches_controller_classes self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>index self<block_start><return>'HI'<block_end><block_end>tgapp=Bunch(app=<none>)<def_stmt>save_app app<block_start>tgapp.app=app<line_sep><return>app<block_end>cfg=MinimalApplicationConfigurator()<line_sep>app=TestApp(cfg.make_wsgi_app({} {} wrap_app=save_app))<line_sep>tgapp.app.controller_classes['root']=RootController<assert_stmt>app.get('/').text<eq>'HI'<block_end><block_end><class_stmt>TestAppConfig<block_start><def_stmt>__init__ self<block_start>self.fake_package=PackageWithModel<block_end><def_stmt>setup self<block_start>_reset_global_config()<block_end><def_stmt>teardown self<block_start>_reset_global_config()<line_sep>tg.hooks._clear()<block_end># Reset hooks <def_stmt>test_get_value self<block_start>conf=AppConfig(minimal=<true>)<line_sep>conf['existing_value']=5<assert_stmt>conf['existing_value']<eq>5<assert_stmt>conf.get('non_existing_value')<eq><none><block_end><def_stmt>test_missing_attribute self<block_start>conf=AppConfig(minimal=<true>)<line_sep>conf['existing_value']=5<assert_stmt>conf['existing_value']<eq>5<assert_stmt>conf.existing_value<eq>5<try_stmt><block_start>conf['missing_value']<block_end><except_stmt>KeyError<block_start><pass><block_end><else_stmt><block_start><raise>RuntimeError('Should have raised KeyError')<block_end><try_stmt><block_start>conf.missing_value<block_end><except_stmt>AttributeError<block_start><pass><block_end><else_stmt><block_start><raise>RuntimeError('Should have raised AttributeError')<block_end><block_end><def_stmt>test_lang_can_be_changed_by_ini self<block_start>conf=AppConfig(minimal=<true>)<line_sep>conf.make_wsgi_app(**{'i18n.lang':'ru'})<assert_stmt>config['i18n.lang']<eq>'ru'<block_end><def_stmt>test_create_minimal_app self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<block_end><def_stmt>test_create_minimal_app_with_factory self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>app_factory=conf.setup_tg_wsgi_app()<line_sep>app=app_factory()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<block_end><def_stmt>test_minimal_app_with_sqlalchemy self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>DBSession=scoped_session(sessionmaker(autoflush=<true> autocommit=<false>))<def_stmt>init_model engine<block_start>DBSession.configure(bind=engine)<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['use_sqlalchemy']=<true><line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>conf['model']=Bunch(DBSession=DBSession init_model=init_model)<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<block_end>@raises(TGConfigError)<def_stmt>test_sqlalchemy_without_models self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['use_sqlalchemy']=<true><line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>app=conf.make_wsgi_app()<block_end><def_stmt>test_minimal_app_with_ming self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>mainsession=Session()<line_sep>DBSession=ThreadLocalORMSession(mainsession)<def_stmt>init_model engine<block_start>mainsession.bind=engine<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['use_ming']=<true><line_sep>conf['ming.url']='mim:///dbname'<line_sep>conf['model']=Bunch(init_model=init_model DBSession=DBSession)<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<block_end>@raises(TGConfigError)<def_stmt>test_ming_without_models self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>DBSession=scoped_session(sessionmaker(autoflush=<true> autocommit=<false>))<def_stmt>init_model engine<block_start>DBSession.configure(bind=engine)<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['use_ming']=<true><line_sep>conf['ming.url']='mim://'<line_sep>app=conf.make_wsgi_app()<block_end><def_stmt>test_setup_jinja_without_package self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.renderers=['jinja']<line_sep>app=conf.make_wsgi_app()<block_end><def_stmt>test_setup_sqlalchemy self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_sqlalchemy=<true><line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>package.model.DBSession.DBSESSION_REMOVED<block_end><def_stmt>test_sqlalchemy_commit_veto self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end>@expose()<def_stmt>crash self<block_start><raise>Exception('crash')<block_end>@expose()<def_stmt>forbidden self<block_start>response.status=403<line_sep><return>'FORBIDDEN'<block_end>@expose()<def_stmt>notfound self<block_start>response.status=404<line_sep><return>'NOTFOUND'<block_end><block_end><def_stmt>custom_commit_veto environ status headers<block_start><if_stmt>status.startswith('404')<block_start><return><true><block_end><return><false><block_end>fake_transaction=FakeTransaction()<import_stmt>transaction<line_sep>prev_transaction_manager=transaction.manager<line_sep>transaction.manager=fake_transaction<line_sep>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['package']=package<line_sep>conf['model']=package.model<line_sep>conf['use_sqlalchemy']=<true><line_sep>conf['tm.enabled']=<true><line_sep>conf['tm.commit_veto']=custom_commit_veto<line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>hasattr(conf 'use_transaction_manager')<is><false><line_sep>app.get('/test')<assert_stmt>fake_transaction.aborted<eq><false><try_stmt><block_start>app.get('/crash')<block_end><except_stmt><block_start><pass><block_end><assert_stmt>fake_transaction.aborted<eq><true><line_sep>app.get('/forbidden' status=403)<assert_stmt>fake_transaction.aborted<eq><false><line_sep>app.get('/notfound' status=404)<assert_stmt>fake_transaction.aborted<eq><true><line_sep>transaction.manager=prev_transaction_manager<block_end><def_stmt>test_sqlalchemy_doom self<block_start>fake_transaction=FakeTransaction()<import_stmt>transaction<line_sep>prev_transaction_manager=transaction.manager<line_sep>transaction.manager=fake_transaction<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start>fake_transaction.doom()<line_sep><return>'HI!'<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_sqlalchemy=<true><line_sep>conf['tm.enabled']=<true><line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>hasattr(conf 'use_transaction_manager')<is><false><line_sep>app.get('/test')<assert_stmt>fake_transaction.aborted<eq><true><line_sep>transaction.manager=prev_transaction_manager<block_end><def_stmt>test_sqlalchemy_retry self<block_start>fake_transaction=FakeTransaction()<import_stmt>transaction<line_sep>prev_transaction_manager=transaction.manager<line_sep>transaction.manager=fake_transaction<import_from_stmt>transaction.interfaces TransientError<class_stmt>RootController(TGController)<block_start>attempts=[]<line_sep>@expose()<def_stmt>test self<block_start>self.attempts.append(<true>)<if_stmt>len(self.attempts)<eq>3<block_start><return>'HI!'<block_end><raise>TransientError()<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_sqlalchemy=<true><line_sep>conf['tm.enabled']=<true><line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>conf['tm.attempts']=3<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>hasattr(conf 'use_transaction_manager')<is><false><line_sep>resp=app.get('/test')<assert_stmt>'HI'<in>resp<line_sep>transaction.manager=prev_transaction_manager<block_end><def_stmt>test_setup_sqla_persistance self<block_start>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>conf.use_sqlalchemy=<true><line_sep>conf.package=PackageWithModel()<line_sep>conf.make_wsgi_app()<block_end><def_stmt>test_setup_sqla_balanced self<block_start>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['sqlalchemy.master.url']='sqlite://'<line_sep>conf['sqlalchemy.slaves.slave1.url']='sqlite://'<line_sep>conf.use_sqlalchemy=<true><line_sep>conf.package=PackageWithModel()<line_sep>conf.make_wsgi_app()<block_end>@raises(TGConfigError)<def_stmt>test_setup_sqla_balanced_prevent_slave_named_master self<block_start>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['sqlalchemy.master.url']='sqlite://'<line_sep>conf['sqlalchemy.slaves.master.url']='sqlite://'<line_sep>conf.use_sqlalchemy=<true><line_sep>conf.package=PackageWithModel()<line_sep>conf.make_wsgi_app()<block_end>@raises(TGConfigError)<def_stmt>test_setup_sqla_balanced_no_slaves self<block_start>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['sqlalchemy.master.url']='sqlite://'<line_sep>conf.use_sqlalchemy=<true><line_sep>conf.package=PackageWithModel()<line_sep>conf.make_wsgi_app()<block_end><def_stmt>test_setup_ming_persistance self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf['ming.url']='mim://'<line_sep>conf['ming.db']='inmemdb'<line_sep>app=conf.make_wsgi_app()<line_sep>tgapp=app.application<while_stmt><not>isinstance(tgapp TGApp)<block_start>tgapp=tgapp.app<block_end>ming_handler=tgapp.wrapped_dispatch<while_stmt>ming_handler<ne>tgapp._dispatch<block_start><if_stmt>isinstance(ming_handler MingApplicationWrapper)<block_start><break><block_end>ming_handler=ming_handler.next_handler<block_end><assert_stmt>isinstance(ming_handler MingApplicationWrapper) ming_handler<class_stmt>FakeMingSession(object)<block_start>actions=[]<def_stmt>flush_all self<block_start>self.actions.append('FLUSH')<block_end><def_stmt>close_all self<block_start>self.actions.append('CLOSE')<block_end><block_end>ming_handler.ThreadLocalODMSession=FakeMingSession()<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>'HI'<in>resp<assert_stmt>ming_handler.ThreadLocalODMSession.actions<eq>['FLUSH']<block_end><def_stmt>test_setup_ming_persistance_closes_on_failure self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><raise>Exception('CRASH!')<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf['ming.url']='mim://'<line_sep>conf['ming.db']='inmemdb'<line_sep>app=conf.make_wsgi_app()<line_sep>tgapp=app.application<while_stmt><not>isinstance(tgapp TGApp)<block_start>tgapp=tgapp.app<block_end>ming_handler=tgapp.wrapped_dispatch<while_stmt>ming_handler<ne>tgapp._dispatch<block_start><if_stmt>isinstance(ming_handler MingApplicationWrapper)<block_start><break><block_end>ming_handler=ming_handler.next_handler<block_end><assert_stmt>isinstance(ming_handler MingApplicationWrapper) ming_handler<class_stmt>FakeMingSession(object)<block_start>actions=[]<def_stmt>flush_all self<block_start>self.actions.append('FLUSH')<block_end><def_stmt>close_all self<block_start>self.actions.append('CLOSE')<block_end><block_end>ming_handler.ThreadLocalODMSession=FakeMingSession()<line_sep>app=TestApp(app)<try_stmt><block_start>app.get('/test' status=500)<block_end><except_stmt><block_start><assert_stmt>ming_handler.ThreadLocalODMSession.actions<eq>['CLOSE']<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised exception'<block_end><block_end><def_stmt>test_setup_ming_persistance_with_url_alone self<block_start>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=<none>)<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf['ming.url']='mim://inmemdb'<line_sep>app=conf.make_wsgi_app()<assert_stmt>app<is><not><none><line_sep>dstore=config['tg.app_globals'].ming_datastore<line_sep>dstore_name=dstore.name<line_sep># Looks like ming has empty dstore.name when using MIM. <assert_stmt>dstore_name<eq>'' dstore<block_end><def_stmt>test_setup_sqla_and_ming_both self<block_start>package=PackageWithModel()<line_sep>base_config=AppConfig(minimal=<true> root_controller=<none>)<line_sep>base_config.package=package<line_sep>base_config.model=package.model<line_sep>base_config.use_ming=<true><line_sep>base_config['ming.url']='mim://inmemdb'<line_sep>base_config.use_sqlalchemy=<true><line_sep>base_config['sqlalchemy.url']='sqlite://'<line_sep>app=base_config.make_wsgi_app()<assert_stmt>app<is><not><none><assert_stmt>config['MingSession'] config<assert_stmt>config['tg.app_globals'].ming_datastore config['tg.app_globals']<assert_stmt>config['SQLASession'] config<assert_stmt>config['tg.app_globals'].sa_engine config['tg.app_globals']<assert_stmt>config['DBSession']<is>config['SQLASession'] config<block_end><def_stmt>test_setup_ming_persistance_with_url_and_db self<block_start>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=<none>)<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf['ming.url']='mim://inmemdb'<line_sep>conf['ming.db']='realinmemdb'<line_sep>app=conf.make_wsgi_app()<assert_stmt>app<is><not><none><line_sep>dstore=config['tg.app_globals'].ming_datastore<line_sep>dstore_name=dstore.name<assert_stmt>dstore_name<eq>'realinmemdb' dstore<block_end><def_stmt>test_setup_ming_persistance_advanced_options self<block_start>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=<none>)<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf['ming.url']='mim://inmemdb'<line_sep>conf['ming.connection.read_preference']='PRIMARY'<line_sep>app=conf.make_wsgi_app()<assert_stmt>app<is><not><none><block_end><def_stmt>test_setup_ming_persistance_replica_set self<block_start><if_stmt>sys.version_info[:2]<eq>(2 6)<block_start><raise>SkipTest()<block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=<none>)<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf['ming.url']='mongodb://localhost:27017,localhost:27018/testdb?replicaSet=test'<line_sep>conf['ming.db']=''<line_sep>app=conf.make_wsgi_app()<assert_stmt>app<is><not><none><line_sep>expected_url='mongodb://localhost:27017,localhost:27018/testdb?replicaSet=test'<line_sep>expected_db='testdb'<line_sep>dstore=config['tg.app_globals'].ming_datastore<assert_stmt>expected_db<eq>dstore.name dstore.name<assert_stmt>dstore.bind._conn_args[0]<eq>expected_url<block_end><def_stmt>test_setup_ming_persistance_replica_set_option self<block_start>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=<none>)<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf['ming.url']='mongodb://localhost:27017,localhost:27018/testdb'<line_sep>conf['ming.connection.replicaSet']='test'<line_sep>app=conf.make_wsgi_app()<assert_stmt>app<is><not><none><line_sep>expected_url='mongodb://localhost:27017,localhost:27018/testdb'<line_sep>expected_db='testdb'<line_sep>dstore=config['tg.app_globals'].ming_datastore<assert_stmt>expected_db<eq>dstore.name dstore.name<assert_stmt>dstore.bind._conn_args[0]<eq>expected_url<assert_stmt>'test'<eq>dstore.bind._conn_kwargs.get('replicaSet') dstore.bind._conn_kwargs<block_end><def_stmt>test_setup_sqla_auth_repozesqla self<block_start><if_stmt>PY3<block_start><raise>SkipTest()<block_end><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>str(request.environ)<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_sqlalchemy=<true><line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf['sa_auth']={'authmetadata':ApplicationAuthMetadata() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345'}<line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>'repoze.who.plugins'<in>resp resp<block_end><def_stmt>test_setup_sqla_auth self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>str(request.environ)<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_sqlalchemy=<true><line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf['sa_auth']={'authmetadata':ApplicationAuthMetadataWithAuthentication() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345'}<line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>'repoze.who.plugins'<in>resp resp<block_end><def_stmt>test_setup_ming_auth_tgming self<block_start><if_stmt>PY3<block_start><raise>SkipTest()<block_end><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>str(request.environ)<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf.auth_backend='ming'<line_sep>conf['sa_auth']={'authmetadata':ApplicationAuthMetadata() 'cookie_secret':'12345' 'user_class':<none>}<line_sep>conf['ming.url']='mim:///testdb'<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>'repoze.who.plugins'<in>resp resp<block_end><def_stmt>test_setup_ming_auth self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>str(request.environ)<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_ming=<true><line_sep>conf.auth_backend='ming'<line_sep>conf['sa_auth']={'authmetadata':ApplicationAuthMetadataWithAuthentication() 'cookie_secret':'12345' 'user_class':<none>}<line_sep>conf['ming.url']='mim:///testdb'<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>'repoze.who.plugins'<in>resp resp<block_end><def_stmt>test_setup_authtkt self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>str(request.environ)<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.use_sqlalchemy=<true><line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf['sa_auth']={'authmetadata':ApplicationAuthMetadataWithAuthentication() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345' 'post_login_url':'/'}<line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>secure_app=conf.make_wsgi_app(**{'sa_auth.authtkt.secure':<true>})<line_sep>secure_app=TestApp(secure_app)<line_sep>resp=secure_app.post('/login_handler' params={'login':'l' 'password':'p'})<assert_stmt>'HttpOnly'<in>resp.headers["Set-Cookie"] resp.headers<line_sep>insecure_app=conf.make_wsgi_app(**{'sa_auth.authtkt.secure':<false>})<line_sep>insecure_app=TestApp(insecure_app)<line_sep>resp=insecure_app.post('/login_handler' params={'login':'l' 'password':'p'})<assert_stmt>'HttpOnly'<not><in>resp.headers["Set-Cookie"] resp.headers<block_end><def_stmt>test_sessions_enabled self<block_start><class_stmt>RootController(TGController)<block_start>@expose('json')<def_stmt>test self<block_start><try_stmt><block_start>tg.session['counter']<augadd>1<block_end><except_stmt>KeyError<block_start>tg.session['counter']=0<block_end>tg.session.save()<line_sep><return>dict(counter=tg.session['counter'])<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['session.enabled']=<true><line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>resp.json['counter']<eq>0 resp<line_sep>resp=app.get('/test')<assert_stmt>resp.json['counter']<eq>1 resp<block_end><def_stmt>test_caching_enabled self<block_start><class_stmt>RootController(TGController)<block_start>@expose('json')<def_stmt>test self<block_start>cache=tg.cache.get_cache('test_caching_enabled')<line_sep>now=cache.get_value('test_cache_key' createfunc=datetime.utcnow)<line_sep><return>dict(now=now)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['cache.enabled']=<true><line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<line_sep>now=resp.json['now']<for_stmt>x range(20)<block_start>resp=app.get('/test')<assert_stmt>resp.json['now']<eq>now (resp now)<block_end><block_end><def_stmt>test_controler_wrapper_setup self<block_start><import_from_stmt>tg.configurator.components.dispatch _call_controller<line_sep>orig_caller=_call_controller<line_sep>appcfg=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf={}<line_sep>dispatch=appcfg._configurator.get_component('dispatch')<line_sep>dispatch._controller_wrappers[:]=[]<line_sep>dispatch._setup_controller_wrappers(conf <none>)<assert_stmt>conf['controller_caller']<eq>orig_caller<def_stmt>controller_wrapper caller<block_start><def_stmt>call *args **kw<block_start><return>caller(*args **kw)<block_end><return>call<block_end>conf={}<line_sep>dispatch=appcfg._configurator.get_component('dispatch')<line_sep>dispatch._controller_wrappers[:]=[controller_wrapper]<line_sep>dispatch._setup_controller_wrappers(conf <none>)<assert_stmt>conf['controller_caller'].__name__<eq>controller_wrapper(orig_caller).__name__<block_end><def_stmt>test_global_controller_wrapper self<block_start>milestones._reset_all()<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>wrapper_has_been_visited=[]<def_stmt>controller_wrapper caller<block_start><def_stmt>call *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_controller_wrapper(controller_wrapper)<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>wrapper_has_been_visited[0]<is><true><block_end><def_stmt>test_multiple_global_controller_wrapper self<block_start>milestones._reset_all()<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>wrapper_has_been_visited=[]<def_stmt>controller_wrapper caller<block_start><def_stmt>call *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end><def_stmt>controller_wrapper2 caller<block_start><def_stmt>call *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end><def_stmt>controller_wrapper3 caller<block_start><def_stmt>call *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_controller_wrapper(controller_wrapper2)<line_sep>conf.register_controller_wrapper(controller_wrapper3)<line_sep>conf.register_controller_wrapper(controller_wrapper)<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>len(wrapper_has_been_visited)<eq>3<block_end><def_stmt>test_dedicated_controller_wrapper self<block_start>milestones._reset_all()<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>wrapper_has_been_visited=[]<def_stmt>controller_wrapper caller<block_start><def_stmt>call *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_controller_wrapper(controller_wrapper controller=RootController.test)<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>wrapper_has_been_visited[0]<is><true><block_end><def_stmt>test_dedicated_controller_wrapper_old self<block_start>milestones._reset_all()<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>wrapper_has_been_visited=[]<def_stmt>controller_wrapper caller<block_start><def_stmt>call *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_controller_wrapper(controller_wrapper controller=RootController.test)<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>wrapper_has_been_visited[0]<is><true><block_end><def_stmt>test_mixed_controller_wrapper self<block_start>milestones._reset_all()<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>app_wrapper_has_been_visited=[]<def_stmt>app_controller_wrapper caller<block_start><def_stmt>call *args **kw<block_start>app_wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end>wrapper_has_been_visited=[]<def_stmt>controller_wrapper caller<block_start><def_stmt>call *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_controller_wrapper(app_controller_wrapper)<line_sep>conf.register_controller_wrapper(controller_wrapper controller=RootController.test)<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>wrapper_has_been_visited[0]<is><true><assert_stmt>app_wrapper_has_been_visited[0]<is><true><block_end><def_stmt>test_controler_wrapper_after_environment_setup self<block_start>milestones._reset_all()<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>wrapper_has_been_visited=[]<def_stmt>controller_wrapper caller<block_start><def_stmt>call *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>caller(*args **kw)<block_end><return>call<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_controller_wrapper(controller_wrapper)<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>wrapper_has_been_visited[0]<is><true><assert_stmt>len(wrapper_has_been_visited)<eq>1<line_sep>conf.register_controller_wrapper(controller_wrapper)<line_sep>app2=conf.make_wsgi_app()<line_sep>app2=TestApp(app2)<line_sep>wrapper_has_been_visited[:]=[]<assert_stmt>'HI!'<in>app2.get('/test')<assert_stmt>wrapper_has_been_visited[0]<is><true><assert_stmt>len(wrapper_has_been_visited)<eq>2<block_end><def_stmt>test_application_wrapper_setup self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>wrapper_has_been_visited=[]<class_stmt>AppWrapper(object)<block_start><def_stmt>__init__ self dispatcher<block_start>self.dispatcher=dispatcher<block_end><def_stmt>__call__ self *args **kw<block_start>wrapper_has_been_visited.append(<true>)<line_sep><return>self.dispatcher(*args **kw)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_wrapper(AppWrapper)<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>wrapper_has_been_visited[0]<eq><true><block_end><def_stmt>test_application_wrapper_ordering_after self<block_start><class_stmt>AppWrapper1<block_start><pass><block_end><class_stmt>AppWrapper2<block_start><pass><block_end><class_stmt>AppWrapper3<block_start><pass><block_end><class_stmt>AppWrapper4<block_start><pass><block_end><class_stmt>AppWrapper5<block_start><pass><block_end>conf=AppConfig(minimal=<true>)<line_sep>conf.register_wrapper(AppWrapper2)<line_sep>conf.register_wrapper(AppWrapper4 after=AppWrapper3)<line_sep>conf.register_wrapper(AppWrapper3)<line_sep>conf.register_wrapper(AppWrapper1 after=<false>)<line_sep>conf.register_wrapper(AppWrapper5 after=AppWrapper3)<line_sep>milestones.environment_loaded.reach()<line_sep>app_wrappers=list(conf._configurator._application_wrappers.values())<assert_stmt>app_wrappers[0]<eq>AppWrapper1<assert_stmt>app_wrappers[1]<eq>AppWrapper2<assert_stmt>app_wrappers[2]<eq>AppWrapper3<assert_stmt>app_wrappers[3]<eq>AppWrapper4<assert_stmt>app_wrappers[4]<eq>AppWrapper5<block_end><def_stmt>test_wrap_app self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>middleware_has_been_visited=[]<class_stmt>AppWrapper(object)<block_start><def_stmt>__init__ self app<block_start>self.app=app<block_end><def_stmt>__call__ self environ start_response<block_start>middleware_has_been_visited.append(<true>)<line_sep><return>self.app(environ start_response)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app(wrap_app=AppWrapper)<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<assert_stmt>middleware_has_been_visited[0]<eq><true><block_end>@raises(TGConfigError)<def_stmt>test_unsupported_renderer self<block_start>conf=AppConfig(root_controller=RootController())<line_sep>conf['renderers']=['unknwon']<try_stmt><block_start>conf.make_wsgi_app()<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>'This configuration object does not support the unknwon renderer'<in>str(e)<line_sep><raise><block_end><block_end>@raises(TGConfigError)<def_stmt>test_cookie_secret_required self<block_start>conf=AppConfig(root_controller=RootController())<line_sep>conf['auth_backend']='sqlalchemy'<line_sep>conf['sa_auth']={}<try_stmt><block_start>conf.make_wsgi_app()<block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>str(e).startswith('You must provide a value for authentication cookies secret')<line_sep><raise><block_end><block_end><def_stmt>test_sqla_auth_middleware self<block_start><if_stmt>PY3<block_start><raise>SkipTest()<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf.skip_authentication=<true><line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadata() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345' 'authenticators':UncopiableList([('default' <none>)])})<line_sep>conf.make_wsgi_app()<line_sep>authenticators=[x[0]<for>x config['sa_auth.authenticators']]<assert_stmt>'cookie'<in>authenticators<assert_stmt>'sqlauth'<in>authenticators<block_end><def_stmt>test_sqla_auth_middleware_using_translations self<block_start><if_stmt>PY3<block_start><raise>SkipTest()<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadata() 'dbsession':<none> 'user_class':<none> 'translations':{'user_name':'SomethingElse'} 'cookie_secret':'12345' 'authenticators':UncopiableList([('default' <none>)])})<line_sep>conf.make_wsgi_app()<line_sep>authenticators=[x[0]<for>x config['sa_auth.authenticators']]<assert_stmt>'cookie'<in>authenticators<assert_stmt>'sqlauth'<in>authenticators<line_sep>auth=<none><for_stmt>authname,authobj config['sa_auth.authenticators']<block_start><if_stmt>authname<eq>'sqlauth'<block_start>auth=authobj<line_sep><break><block_end><block_end><assert_stmt>auth<is><not><none> config['sa_auth.authenticators']<assert_stmt>auth.translations['user_name']<eq>'SomethingElse' auth.translations<block_end><def_stmt>test_sqla_auth_middleware_default_after self<block_start><if_stmt>PY3<block_start><raise>SkipTest()<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadata() 'cookie_secret':'12345' 'dbsession':<none> 'user_class':<none> 'authenticators':UncopiableList([('superfirst' <none>) ('default' <none>)])})<line_sep>conf.make_wsgi_app()<line_sep>authenticators=[x[0]<for>x config['sa_auth.authenticators']]<assert_stmt>authenticators[1]<eq>'superfirst'<assert_stmt>'cookie'<in>authenticators<assert_stmt>'sqlauth'<in>authenticators<block_end><def_stmt>test_sqla_auth_middleware_no_authenticators self<block_start><if_stmt>PY3<block_start><raise>SkipTest()<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadata() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345'})<line_sep># In this case we can just test it doesn't crash # as the sa_auth dict doesn't have an authenticators key to check for conf.make_wsgi_app()<block_end><def_stmt>test_sqla_auth_middleware_only_mine self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>str(request.environ)<block_end>@expose()<def_stmt>forbidden self<block_start>response.status="401"<block_end><block_end>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf.use_sqlalchemy=<true><line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>alwaysadmin=_AuthenticationForgerPlugin(fake_user_key='FAKE_USER')<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadata() 'cookie_secret':'12345' 'form_plugin':alwaysadmin 'authenticators':UncopiableList([('alwaysadmin' alwaysadmin)]) 'identifiers':[('alwaysadmin' alwaysadmin)] 'challengers':[]})<line_sep>app=conf.make_wsgi_app()<line_sep>authenticators=[x[0]<for>x config['sa_auth.authenticators']]<assert_stmt>authenticators[0]<eq>'alwaysadmin'<assert_stmt>'sqlauth'<not><in>authenticators<line_sep>challengers=[x[1]<for>x config['sa_auth.challengers']]<assert_stmt>alwaysadmin<in>challengers<line_sep>app=TestApp(app)<assert_stmt>'repoze.who.identity'<in>app.get('/test' extra_environ={'FAKE_USER':'admin'})<assert_stmt>app.get('/forbidden' status=401)<block_end><def_stmt>test_sqla_auth_logging_stderr self<block_start>package=PackageWithModel()<line_sep>conf=AppConfig(minimal=<true> root_controller=<none>)<line_sep>conf.package=package<line_sep>conf.model=package.model<line_sep>conf.auth_backend='sqlalchemy'<line_sep>conf.use_sqlalchemy=<true><line_sep>conf['sqlalchemy.url']='sqlite://'<line_sep>alwaysadmin=_AuthenticationForgerPlugin(fake_user_key='FAKE_USER')<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadata() 'cookie_secret':'12345' 'form_plugin':alwaysadmin 'log_level':'DEBUG' 'authenticators':UncopiableList([('alwaysadmin' alwaysadmin)]) 'identifiers':[('alwaysadmin' alwaysadmin)] 'challengers':[]})<line_sep>conf['sa_auth']['log_file']='stderr'<line_sep>app=conf.make_wsgi_app()<line_sep>conf['sa_auth']['log_file']='stdout'<line_sep>app=conf.make_wsgi_app()<import_stmt>tempfile<line_sep>f=tempfile.NamedTemporaryFile()<line_sep>conf['sa_auth']['log_file']=f.name<line_sep>app=conf.make_wsgi_app()<block_end><def_stmt>test_ming_auth_middleware self<block_start><if_stmt>PY3<block_start><raise>SkipTest()<block_end>conf=AppConfig(root_controller=RootController() auth_backend='ming')<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadata() 'user_class':<none> 'cookie_secret':'12345' 'authenticators':UncopiableList([('default' <none>)])})<line_sep>conf.make_wsgi_app()<line_sep>authenticators=[x[0]<for>x config['sa_auth.authenticators']]<assert_stmt>'cookie'<in>authenticators<assert_stmt>'mingauth'<in>authenticators<block_end>@raises(KeyError)<def_stmt>test_sqla_auth_middleware_no_backend self<block_start>conf=AppConfig(root_controller=RootController())<line_sep>conf.auth_backend=<none><line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadata() 'cookie_secret':'12345'})<line_sep>conf.make_wsgi_app()<line_sep>authenticators=[x[0]<for>x config['sa_auth.authenticators']]<assert_stmt>'cookie'<in>authenticators<assert_stmt>len(authenticators)<eq>1<block_end><def_stmt>test_tgauthmetadata_auth_middleware self<block_start>conf=AppConfig(root_controller=RootController() auth_backend='sqlalchemy')<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadataWithAuthentication() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345' 'authenticators':UncopiableList([('default' <none>)])})<line_sep>conf.make_wsgi_app()<line_sep>authenticators=[x[0]<for>x config['sa_auth.authenticators']]<assert_stmt>'cookie'<in>authenticators<assert_stmt>'tgappauth'<in>authenticators<block_end><def_stmt>test_auth_setup_default_identifier self<block_start>conf=AppConfig(root_controller=RootController() auth_backend='sqlalchemy')<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadataWithAuthentication() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345' 'identifiers':UncopiableList([('default' <none>)])})<line_sep>conf.make_wsgi_app()<line_sep>identifiers=[x[0]<for>x tg.config['sa_auth.identifiers']]<assert_stmt>'cookie'<in>identifiers<block_end><def_stmt>test_auth_setup_custom_identifier self<block_start>conf=AppConfig(root_controller=RootController() auth_backend='sqlalchemy')<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadataWithAuthentication() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345' 'identifiers':UncopiableList([('custom' <none>)])})<line_sep>conf.make_wsgi_app()<line_sep>identifiers=[x[0]<for>x config['sa_auth.identifiers']]<assert_stmt>'custom'<in>identifiers<block_end><def_stmt>test_auth_middleware_doesnt_touch_authenticators self# Checks that the auth middleware process doesn't touch original authenticators # list, to prevent regressions on this. <block_start>conf=AppConfig(root_controller=RootController() auth_backend='sqlalchemy')<line_sep>conf['sa_auth'].update({'authmetadata':ApplicationAuthMetadataWithAuthentication() 'dbsession':<none> 'user_class':<none> 'cookie_secret':'12345' 'authenticators':[('default' <none>)]})<line_sep>conf.make_wsgi_app()<line_sep>authenticators=[x[0]<for>x conf['sa_auth.authenticators']]<assert_stmt>len(authenticators)<eq>1<block_end><def_stmt>test_tgauthmetadata_loginpwd self<block_start>who_authenticator=_AuthMetadataAuthenticator(ApplicationAuthMetadataWithAuthentication() using_password=<true>)<assert_stmt>who_authenticator.authenticate({} {})<eq><none><block_end><def_stmt>test_tgauthmetadata_nologinpwd self<block_start>who_authenticator=_AuthMetadataAuthenticator(ApplicationAuthMetadataWithAuthentication() using_password=<false>)<assert_stmt>who_authenticator.authenticate({} {})<eq>1<block_end><def_stmt>test_error_middleware_disabled_with_optimize self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=PackageWithModel()<line_sep>os.environ['PYTHONOPTIMIZE']='2'<line_sep>app=conf.make_wsgi_app()<line_sep>os.environ.pop('PYTHONOPTIMIZE')<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<block_end><def_stmt>test_serve_statics self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=PackageWithModel()<line_sep>conf.serve_static=<true><line_sep>app=conf.make_wsgi_app()<assert_stmt>app.__class__.__name__.startswith('Statics')<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<block_end><def_stmt>test_mount_point_with_minimal self<block_start><class_stmt>SubController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>self.mount_point<block_end><block_end><class_stmt>RootController(TGController)<block_start>sub=SubController()<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'/sub'<in>app.get('/sub/test')<block_end><def_stmt>test_application_test_vars self<block_start><class_stmt>RootController(TGController)<block_start><pass><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'DONE'<in>app.get('/_test_vars')<assert_stmt>request.path<eq>'/_test_vars'<line_sep># This should trash away the preserved registry to avoid # leaking memory. app.get('/' status=404)<try_stmt><block_start>request.path<block_end><except_stmt>TypeError# TypeError means the request has been properly removed <block_start><pass><block_end><else_stmt><block_start><assert_stmt><false> 'There should have been no requests in place...'<block_end><block_end><def_stmt>test_application_empty_controller self<block_start><class_stmt>RootController(object)<block_start><def_stmt>__call__ self environ start_response<block_start><return><none><block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<try_stmt><block_start>r=app.get('/something')<block_end><except_stmt>Exception<as>e<block_start><assert_stmt>'No content returned by controller'<in>str(e)<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised "No content returned by controller"'<block_end><block_end><def_stmt>test_application_test_mode_detection self<block_start><class_stmt>FakeRegistry(object)<block_start><def_stmt>register self *args **kw<block_start><pass><block_end><block_end><def_stmt>track_app app# Save a reference to the plain TGApp before it's wrapped by middlewares. <block_start>track_app.app=app<line_sep><return>app<block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=PackageWithModel()<line_sep>conf.make_wsgi_app(wrap_app=track_app)<line_sep>testmode,__,__=track_app.app._setup_app_env({'paste.registry':FakeRegistry()})<assert_stmt>testmode<is><false><line_sep>testmode,__,__=track_app.app._setup_app_env({'paste.registry':FakeRegistry() 'paste.testing_variables':{}})<assert_stmt>testmode<is><true><block_end><def_stmt>test_application_no_controller_hijacking self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><return>'HI!'<block_end><block_end><class_stmt>AppWrapper(object)<block_start><def_stmt>__init__ self dispatcher<block_start>self.dispatcher=dispatcher<block_end><def_stmt>__call__ self controller environ start_response<block_start><return>self.dispatcher(<none> environ start_response)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_wrapper(AppWrapper)<line_sep>conf.package=PackageWithModel()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<line_sep>app.get('/test' status=404)<block_end><def_stmt>test_package_no_app_globals self<block_start><class_stmt>RootController(TGController)<block_start><pass><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.package=sys.modules[__name__]<line_sep>app=conf.make_wsgi_app()<block_end><def_stmt>test_custom_error_document self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(403)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=403)<assert_stmt>'ERROR!!!'<in>resp resp<block_end><def_stmt>test_custom_error_document_with_streamed_response self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>response.status_code=403<def_stmt>_output <block_start><yield>'Hi'<line_sep><yield>'World'<block_end><return>_output()<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=403)<assert_stmt>'ERROR!!!'<in>resp resp<block_end><def_stmt>test_error_document_passthrough self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>request.disable_error_pages()<line_sep>abort(403 detail='Custom Detail')<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=403)<assert_stmt>'Custom Detail'<in>resp resp<block_end><def_stmt>test_custom_old_error_document self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(403)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf.status_code_redirect=<true><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=403)<assert_stmt>'ERROR!!!'<in>resp resp<block_end><def_stmt>test_custom_old_error_document_with_streamed_response self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>response.status_code=403<def_stmt>_output <block_start><yield>'Hi'<line_sep><yield>'World'<block_end><return>_output()<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf.status_code_redirect=<true><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=403)<assert_stmt>'ERROR!!!'<in>resp resp<block_end><def_stmt>test_custom_500_document self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(500)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf['debug']=<false><line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>conf['errorpage.status_codes']<augadd>[500]<line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=500)<assert_stmt>'ERROR!!!'<in>resp resp<block_end><def_stmt>test_custom_500_document_on_crash self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start><raise>Exception('Crash!')<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf['debug']=<false><line_sep>conf['errorpage.handle_exceptions']=<true><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=500)<assert_stmt>'ERROR!!!'<in>resp resp<block_end><def_stmt>test_errorpage_reraises_exceptions self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start><raise>Exception('Crash!')<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf['debug']=<false><line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>app=conf.make_wsgi_app(full_stack=<false>)<line_sep>app=TestApp(app)<try_stmt><block_start>resp=app.get('/test' status=500)<block_end><except_stmt>Exception<as>e<block_start><assert_stmt>'Crash!'<in>str(e)<block_end><else_stmt><block_start><assert_stmt><false> 'Should have raised Crash! exception'<block_end><block_end><def_stmt>test_old_custom_500_document self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(500)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['debug']=<false><line_sep>conf.status_code_redirect=<true><line_sep>conf['errorpage.enabled']=<true><line_sep>conf['errorpage.status_codes']<augadd>[500]<line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=500)<assert_stmt>'ERROR!!!'<in>resp resp<block_end><def_stmt>test_skips_custom_500_document_when_debug self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(500)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf['debug']=<true><line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=500)<assert_stmt>'ERROR!!!'<not><in>resp resp<block_end><def_stmt>test_skips_old_custom_500_document_when_debug self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(500)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['debug']=<true><line_sep>conf.status_code_redirect=<true><line_sep>conf['errorpage.enabled']=<true><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=500)<assert_stmt>'ERROR!!!'<not><in>resp resp<block_end><def_stmt>test_skips_custom_error_document_when_disabled self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(403)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<false><line_sep>conf['errorpage.status_codes']=(403 404)<line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=403)<assert_stmt>'ERROR!!!'<not><in>resp resp<block_end><def_stmt>test_skips_custom_error_document_when_disabled_and_manually_registered self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose()<def_stmt>document self *args **kw<block_start><return>'ERROR!!!'<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(403)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<false><line_sep>conf['errorpage.status_codes']=(403 404)<line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=403)<assert_stmt>'ERROR!!!'<not><in>resp resp<block_end><def_stmt>test_custom_500_json self<block_start><class_stmt>ErrorController(TGController)<block_start>@expose(content_type="text/html")@expose('json' content_type="application/json")<def_stmt>document self *args **kw<block_start><return>dict(a=5)<block_end><block_end><class_stmt>RootController(TGController)<block_start>error=ErrorController()<line_sep>@expose()<def_stmt>test self<block_start>abort(500)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>conf['debug']=<false><line_sep>conf['errorpage.handle_exceptions']=<false><line_sep>conf['errorpage.status_codes']<augadd>[500]<line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=500 headers={'Accept':'application/json'})<assert_stmt>'{"a": 5}'<in>resp.text resp<assert_stmt>'application/json'<eq>resp.content_type<block_end><def_stmt>test_errorware_configuration self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self *args **kwargs<block_start><return>'HI'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>app=conf.make_wsgi_app(full_stack=<true> **{'trace_errors.error_email':'<EMAIL>'})<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>'HI'<in>resp resp<assert_stmt>config['tg.errorware']['error_email']<eq>'<EMAIL>'<assert_stmt>config['tg.errorware']['error_subject_prefix']<eq>'WebApp Error: '<assert_stmt>config['tg.errorware']['error_message']<eq>'An internal server error occurred'<block_end><def_stmt>test_tw2_unsupported_renderer self<block_start><import_stmt>tw2.core<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self *args **kwargs<block_start>rl=tw2.core.core.request_local()<line_sep>tw2conf=rl['middleware'].config<line_sep><return>','.join(tw2conf.preferred_rendering_engines)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.prefer_toscawidgets2=<true><line_sep>conf.renderers=['json' 'kajiki']<line_sep>conf.default_renderer='json'<line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>'kajiki'<in>resp resp<block_end><def_stmt>test_tw2_renderers_preference self<block_start><import_stmt>tw2.core<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self *args **kwargs<block_start>rl=tw2.core.core.request_local()<line_sep>tw2conf=rl['middleware'].config<line_sep><return>','.join(tw2conf.preferred_rendering_engines)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.prefer_toscawidgets2=<true><line_sep>conf.renderers=['kajiki']<line_sep>conf.default_renderer='kajiki'<line_sep>app=conf.make_wsgi_app(full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test')<assert_stmt>'kajiki'<in>resp resp<block_end><def_stmt>test_tw2_unsupported self<block_start><import_stmt>tw2.core<class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self *args **kwargs<block_start>rl=tw2.core.core.request_local()<line_sep>tw2conf=rl['middleware'].config<line_sep><return>','.join(tw2conf.preferred_rendering_engines)<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.prefer_toscawidgets2=<true><line_sep>conf.renderers=['json']<line_sep>conf.default_renderer='json'<try_stmt><block_start>app=conf.make_wsgi_app(full_stack=<true>)<assert_stmt><false><block_end><except_stmt>TGConfigError<as>e<block_start><assert_stmt>'None of the configured rendering engines'<in>str(e)<assert_stmt>'is supported by ToscaWidgets2, unable to configure ToscaWidgets.'<in>str(e)<block_end><block_end><def_stmt>test_render_factory_success self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self *args **kwargs<block_start><return>'HELLO'<block_end><block_end><class_stmt>FailedFactory(RendererFactory)<block_start>engines={'broken':{'content_type':'text/plain'}}<line_sep>@classmethod<def_stmt>create cls config app_globals<block_start><return>{'broken':'BROKEN'}<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_rendering_engine(FailedFactory)<line_sep>conf.renderers=['json' 'broken']<line_sep>app=conf.make_wsgi_app(full_stack=<true>)<assert_stmt>config['renderers']<eq>['json' 'broken']<assert_stmt>config['render_functions']['broken']<eq>'BROKEN'<block_end><def_stmt>test_render_factory_failure self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self *args **kwargs<block_start><return>'HELLO'<block_end><block_end><class_stmt>FailedFactory(RendererFactory)<block_start>engines={'broken':{'content_type':'text/plain'}}<line_sep>@classmethod<def_stmt>create cls config app_globals<block_start><return><none><block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.register_rendering_engine(FailedFactory)<line_sep>conf.renderers=['json' 'broken']<line_sep>conf.make_wsgi_app(full_stack=<true>)<assert_stmt>config['renderers']<eq>['json']<block_end><def_stmt>test_make_body_seekable self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self *args **kwargs<block_start>request.body_file.seek(0)<line_sep><return>'HELLO'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['make_body_seekable']=<true><line_sep>app=conf.make_wsgi_app(full_stack=<false>)<assert_stmt>app.application.__class__.__name__<eq>'SeekableRequestBodyMiddleware' app.application.__class__<line_sep>app=TestApp(app)<assert_stmt>'HELLO'<in>app.get('/test')<block_end><def_stmt>test_make_body_seekable_disabled self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self *args **kwargs<block_start>request.body_file.seek(0)<line_sep><return>'HELLO'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf['make_body_seekable']=<false><line_sep>app=conf.make_wsgi_app(full_stack=<false>)<line_sep>app=TestApp(app)<assert_stmt>'HELLO'<in>app.get('/test')<block_end><def_stmt>test_debug_middleware self<block_start><class_stmt>RootController(TGController)<block_start>@expose()<def_stmt>test self<block_start><raise>Exception('Crash!')<block_end><block_end>conf=AppConfig(root_controller=RootController())<line_sep>conf['errorpage.enabled']=<true><line_sep>app=conf.make_wsgi_app(debug=<true> full_stack=<true>)<line_sep>app=TestApp(app)<line_sep>resp=app.get('/test' status=500 expect_errors=<true>)<assert_stmt>'Exception: Crash! // Backlash'<in>resp resp<block_end><def_stmt>test_make_app_with_custom_appglobals self<block_start><class_stmt>RootController(TGController)<block_start>@expose('')<def_stmt>test self *args **kwargs<block_start><return>tg.app_globals.TEXT<block_end><block_end><class_stmt>FakeGlobals(Bunch)<block_start><def_stmt>__init__ self<block_start>super(FakeGlobals self).__init__()<line_sep>self['TEXT']='HI!'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.app_globals=FakeGlobals<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<block_end><def_stmt>test_make_app_with_appglobals_submodule self<block_start><class_stmt>RootController(TGController)<block_start>@expose('')<def_stmt>test self *args **kwargs<block_start><return>tg.app_globals.text<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<import_from_stmt>.fixtures package_with_helpers_submodule<line_sep>conf['package']=package_with_helpers_submodule<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!!'<in>app.get('/test')<block_end><def_stmt>test_make_app_with_custom_helpers self<block_start><class_stmt>RootController(TGController)<block_start>@expose('')<def_stmt>test self *args **kwargs<block_start><return>config['helpers'].get_text()<block_end><block_end><class_stmt>FakeHelpers(object)<block_start>@classmethod<def_stmt>get_text cls<block_start><return>'HI!'<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<line_sep>conf.helpers=FakeHelpers()<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!'<in>app.get('/test')<block_end><def_stmt>test_make_app_with_helpers_submodule self<block_start><class_stmt>RootController(TGController)<block_start>@expose('')<def_stmt>test self *args **kwargs<block_start><return>config['helpers'].get_text()<block_end><block_end>conf=AppConfig(minimal=<true> root_controller=RootController())<import_from_stmt>.fixtures package_with_helpers_submodule<line_sep>conf['package']=package_with_helpers_submodule<line_sep>app=conf.make_wsgi_app()<line_sep>app=TestApp(app)<assert_stmt>'HI!!'<in>app.get('/test')<block_end><block_end>
<import_from_stmt>training *<import_from_stmt>findLeaf *<import_stmt>re<import_from_stmt>lxml.html fromstring<import_from_stmt>lxml.html tostring<def_stmt>stripReasonableWhite x<block_start><return>re.sub(r"\s+" " " x).strip()<block_end><def_stmt>splitN txt outcome# consider splitting to get result <block_start>txt=stripReasonableWhite(txt)<line_sep>outcome=stripReasonableWhite(outcome)<line_sep>splitables=set(txt.replace(outcome '' 1))-set(' ')<line_sep>options=set()<for_stmt>s splitables<block_start><for_stmt>i,x enumerate(txt.split(s))<block_start><if_stmt>stripReasonableWhite(x)<eq>stripReasonableWhite(outcome)<block_start>options.add((s i))<block_end><block_end><block_end><return>options<block_end><def_stmt>splitSolution how<block_start><def_stmt>solution txt<block_start><return>txt.split(how[0])[how[1]]<block_end><return>solution<block_end><def_stmt>asNumeric x<block_start><return>re.sub("[^0-9]" "" x)<block_end><def_stmt>applySolutionChain solution x<block_start><for_stmt>sol solution<block_start><if_stmt>isinstance(sol dict)<block_start>x=x.find(**sol)<block_end><else_stmt><block_start>x=sol(x)<block_end><block_end><return>x<block_end><def_stmt>buildSolution training<block_start>res=findLeaf(training)<line_sep>print("len(res)" len(res))<line_sep>x=findSharedKeyValues(training res)<line_sep>print("len(shared)" len(x))<line_sep>solutions=secondLevelDown(training.soups[0] training.targets[0] x)<line_sep>print("len(solutions)" len(solutions))<line_sep><return>solutions<block_end><def_stmt>tryUniqueID c sp<block_start><return>len(sp.findAll(c.name attrs=c.attrs))<eq>1<block_end><def_stmt>buildNewSolution tr<block_start>childs=[]<line_sep>num=0<line_sep>options=[]<for_stmt>soup,target zip(tr.soups tr.targets)<block_start>print('num' num)<line_sep>num<augadd>1<for_stmt>c soup.findChildren()<block_start><try_stmt><block_start><if_stmt>c.name<not><in>['body' 'html']<block_start><if_stmt>target<in>c.text<block_start>childs.append([c len(c.text)])<block_end><block_end><block_end><except_stmt><block_start><pass><block_end><block_end>tmp=[]<for_stmt>i,x enumerate(childs[::-1])<block_start><if_stmt>tryUniqueID(x[0] soup)<block_start>attrs=x[0].attrs<line_sep>attrs['name']=x[0].name<line_sep>attrs={'attrs':attrs}<if_stmt>x[0].text<eq>target<block_start>tmp.append((attrs BeautifulSoup.get_text))<block_end><elif_stmt>stripReasonableWhite(x[0].text)<eq>stripReasonableWhite(target)<block_start>tmp.append((attrs BeautifulSoup.get_text stripReasonableWhite))<block_end><elif_stmt>splitN(x[0].text target)<block_start><for_stmt>splitable splitN(x[0].text target)<block_start>tmp.append((attrs BeautifulSoup.get_text splitSolution(splitable)))<block_end><block_end><else_stmt><block_start>print(len([y<for>y x[0].children]))<block_end><block_end><else_stmt><block_start>print('not unique' len([y<for>y x[0].children]))<block_end><block_end>options.append(tmp)<block_end>good_options=[]<if_stmt>options<block_start><for_stmt>x options[0]<block_start><if_stmt>all(x<in>y<for>y options[1:])<block_start>good_options.append(x)<block_end><block_end><block_end><return>good_options<block_end>#testAutoScraperSolutions(buildSolution(tr), tr, False) tr1=Training("marktplaats-testcase1" "/Users/pascal/egoroot/sky_package/sky/tests/").load()<line_sep># tr2 = Training("nieuwsdumper-testcase1", "/Users/pascal/egoroot/sky_package/sky/tests/").load() tr3=Training("nieuwsdumper-testcase2" "/Users/pascal/egoroot/sky_package/sky/tests/").load()<line_sep># tr4 = Training("bouwmaterieel-testcase1", "/Users/pascal/egoroot/sky_package/sky/tests/").load() # tr5 = Training('betterdoctor-doctor-referalls', '/Users/pascal/egoroot/sky_package/sky/tests/').load() tr6=Training("pypi-author" "/Users/pascal/egoroot/sky_package/sky/tests/").load()<line_sep># Moet wel text_content zijn, anders ga je dingen mislopen!!!!!!!!!!!!! # plottwist misschien gewoon 2 methoden <def_stmt>getMatchedNodes tr<block_start>matchedLeafs=[]<for_stmt>tree,outcome zip(tr.trees tr.targets)<block_start>matchedLeaf={'text':[] 'tail':[] 'attrib':[] 'content':[]}<for_stmt>x tree.iter()<block_start><if_stmt>x.text<and>outcome<in>x.text<block_start>matchedLeaf['text'].append(x)<block_end><if_stmt>x.tail<and>outcome<in>x.tail<block_start>matchedLeaf['tail'].append(x)<block_end><if_stmt>x.attrib<and>any([outcome<in>y<for>y x.attrib.values()])<block_start>matchedLeaf['attrib'].append(x)<block_end><block_end>matchedLeafs.append(matchedLeaf)<block_end><return>matchedLeafs<block_end><def_stmt>getMatchedTextContentNodes tree outcome container<block_start>children=tree.getchildren()<if_stmt>children<block_start><for_stmt>c children<block_start><if_stmt>outcome<in>c.text_content()<block_start>container.append(c)<line_sep>getMatchedTextContentNodes(c outcome container)<block_end><block_end><block_end><return>container<block_end><for_stmt>i range(1000)<block_start>res=getMatchedNodes(tr3)<for_stmt>tree,outcome,r zip(tr3.trees tr3.targets res)<block_start>r['content']=getMatchedTextContentNodes(tree outcome [])<block_end><block_end>div=fromstring('<div>I have <strong>5</strong> friends</div>')<line_sep>
<import_stmt>dash<import_stmt>dash_html_components<as>html<import_stmt>json<import_stmt>dash_leaflet<as>dl<import_from_stmt>examples geojson_csf<import_from_stmt>dash_extensions.transpile inject_js module_to_props<line_sep># Create geojson. <with_stmt>open("assets/us-states.json" 'r')<as>f<block_start>data=json.load(f)<block_end>js=module_to_props(geojson_csf)# do transcrypt to enable passing python functions as props geojson=dl.GeoJSON(data=data id="geojson" options=dict(style=geojson_csf.style) hoverStyle=geojson_csf.hover_style)<line_sep># Create app. app=dash.Dash(prevent_initial_callbacks=<true>)<line_sep>app.layout=html.Div([dl.Map(children=[dl.TileLayer() geojson] center=[39 -98] zoom=4 id="map")] style={'width':'100%' 'height':'50vh' 'margin':"auto" "display":"block"})<line_sep># Inject transcrypted javascript. inject_js(app js)<if_stmt>__name__<eq>'__main__'<block_start>app.run_server(port=7777 debug=<true>)<block_end>
""" Note ---- 'import pycaw.magic' must be generally at the topmost. To be more specific: It needs to be imported before any other pycaw or comtypes import. Reserved Atrributes ------------------- Note that certain methods and attributes are reserved for the magic module. Please look into the source code of MagicApp for more information. But to avoid conflicts now and in the future, i recommend using a prefix for each of your custom methods and attributes. Features -------- Instantiate a new MagicApp with one or more app executables: magic = MagicApp({"msedge.exe", "another.exe"}) -------- you could also inherit from MagicApp and create customized callbacks: class MyCustomApp(MagicApp): def __init__(self, app_execs): super().__init__(app_execs, volume_callback=self.custom_volume_callback, mute_callback=self..., state_callback=self..., session_callback=self...) def custom_volume_callback(self, volume): print(volume) print(self.mute) self.mute = True print(self.mute) mega_magic = MyCustomApp({"msedge.exe"}) """<import_stmt>time<import_from_stmt>contextlib suppress<import_from_stmt>pycaw.magic MagicApp<def_stmt>handle_all *args<block_start>print("callback")<line_sep>print(args)<block_end>magic=MagicApp({"msedge.exe"} volume_callback=handle_all mute_callback=handle_all state_callback=handle_all session_callback=handle_all)<def_stmt>main <block_start><with_stmt>suppress(KeyboardInterrupt)<block_start><for_stmt>_ range(5)<block_start>""" open and close your MagicApp app_exec (msedge.exe) and see how it will change the volume as long as the app is opened. When you close app_exec it wont change the volume and None is printed. if you change for example the volume in the Windows sound mixer handle_all() is fired. """<if_stmt>magic.state<is><none><block_start>print(f"No session active for: {magic}")<line_sep>time.sleep(2)<line_sep><continue><block_end>print("Volume:")<line_sep>magic.volume=0.1<line_sep>print(magic.volume)<line_sep>time.sleep(1)<line_sep>magic.volume=0.9<line_sep>print(magic.volume)<line_sep>time.sleep(1)<line_sep>print(f"{str(magic.state)} {magic.app_execs}")<line_sep>print("Mute:")<line_sep>magic.mute=<true><line_sep>print(magic.mute)<line_sep>time.sleep(1)<line_sep>magic.mute=<false><line_sep>print(magic.mute)<block_end><block_end>print("\nTschüss")<block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end>
<import_from_stmt>RecoBTag.PerformanceDB.measure.Btag_mistag101220 *<line_sep>
# -*- coding: utf-8 -*- <import_from_stmt>datetime date<import_from_stmt>datetime datetime<import_from_stmt>datetime time<import_from_stmt>datetime timedelta<import_from_stmt>decimal Decimal<import_from_stmt>guillotina configure<import_from_stmt>guillotina.component query_adapter<import_from_stmt>guillotina.i18n Message<import_from_stmt>guillotina.interfaces IValueToJson<import_from_stmt>guillotina.profile profilable<import_from_stmt>guillotina.schema.vocabulary SimpleVocabulary<line_sep>_MISSING=object()<line_sep>@profilable<def_stmt>json_compatible value<block_start><if_stmt>value<is><none><block_start><return>value<block_end>type_=type(value)<if_stmt>type_<in>(str bool int float)<block_start><return>value<block_end>result_value=query_adapter(value IValueToJson default=_MISSING)<if_stmt>result_value<is>_MISSING<block_start><raise>TypeError("No converter for making"<concat>" {0!r} ({1}) JSON compatible.".format(value type(value)))<block_end><else_stmt><block_start><return>result_value<block_end><block_end>@configure.value_serializer(SimpleVocabulary)<def_stmt>vocabulary_converter value<block_start><return>[x.token<for>x value]<block_end>@configure.value_serializer(str)<def_stmt>string_converter value<block_start><return>str(value)<block_end>@configure.value_serializer(bytes)<def_stmt>bytes_converter value<block_start><return>str(value encoding="utf-8")<block_end>@configure.value_serializer(list)<def_stmt>list_converter value<block_start><return>list(map(json_compatible value))<block_end>@configure.value_serializer(tuple)<def_stmt>tuple_converter value<block_start><return>list(map(json_compatible value))<block_end>@configure.value_serializer(frozenset)<def_stmt>frozenset_converter value<block_start><return>list(map(json_compatible value))<block_end>@configure.value_serializer(set)<def_stmt>set_converter value<block_start><return>list(map(json_compatible value))<block_end>@configure.value_serializer(dict)<def_stmt>dict_converter value<block_start><if_stmt>value<eq>{}<block_start><return>{}<block_end>keys,values=zip(*value.items())<line_sep>keys=map(json_compatible keys)<line_sep>values=map(json_compatible values)<line_sep><return>dict(zip(keys values))<block_end>@configure.value_serializer(datetime)<def_stmt>python_datetime_converter value<block_start><try_stmt><block_start><return>value.isoformat()<block_end><except_stmt>AttributeError# handle date problems <block_start><return><none><block_end><block_end>@configure.value_serializer(date)<def_stmt>date_converter value<block_start><return>value.isoformat()<block_end>@configure.value_serializer(time)<def_stmt>time_converter value<block_start><return>value.isoformat()<block_end>@configure.value_serializer(timedelta)<def_stmt>timedelta_converter value<block_start><return>value.total_seconds()<block_end>@configure.value_serializer(Message)<def_stmt>i18n_message_converter value# TODO: # value = translate(value, context=getRequest()) <block_start><return>value<block_end>@configure.value_serializer(Decimal)<def_stmt>decimal_converter value<block_start><return>str(value)<block_end>
<import_stmt>os<line_sep># face_data (directory) represents the path component to be joined. FACE_DATA_PATH=os.path.join(os.getcwd() 'face_cluster')<line_sep>ENCODINGS_PATH=os.path.join(os.getcwd() 'encodings.pickle')<line_sep>CLUSTERING_RESULT_PATH=os.getcwd()<line_sep>
#-*- coding:utf-8 -*- <import_stmt>keras<import_stmt>tensorflow<as>tf<import_from_stmt>keras.layers *<import_from_stmt>keras.activations softmax<import_from_stmt>keras.models Model<import_from_stmt>keras.layers.merge concatenate<import_from_stmt>keras.layers.normalization BatchNormalization<import_from_stmt>keras.utils multi_gpu_model<import_from_stmt>encoder EncoderBase<line_sep>#refer:https://arxiv.org/abs/1609.06038 <class_stmt>ESIM(EncoderBase)<block_start><def_stmt>__init__ self **kwargs<block_start>super(ESIM self).__init__(**kwargs)<line_sep>self.embedding_size=kwargs['embedding_size']<line_sep>self.recurrent_units=300<line_sep>self.dense_units=300<block_end><def_stmt>update_features self features<block_start><pass><block_end><def_stmt>__call__ self x_query x_sample reuse=tf.AUTO_REUSE **kwargs#embedding_sequence_q1 = BatchNormalization(axis=2)(x_query) #embedding_sequence_q2 = BatchNormalization(axis=2)(x_sample) #final_embedding_sequence_q1 = SpatialDropout1D(0.25)(embedding_sequence_q1) #final_embedding_sequence_q2 = SpatialDropout1D(0.25)(embedding_sequence_q2) #################### 输入编码input encoding ####################### #分别对query和sample进行双向编码 <block_start>rnn_layer_q1=Bidirectional(LSTM(self.recurrent_units return_sequences=<true>))(x_query)<line_sep>rnn_layer_q2=Bidirectional(LSTM(self.recurrent_units return_sequences=<true>))(x_sample)<line_sep>#rnn_layer_q1 = Bidirectional(LSTM(self.recurrent_units, return_sequences=True))(final_embedding_sequence_q1) #rnn_layer_q2 = Bidirectional(LSTM(self.recurrent_units, return_sequences=True))(final_embedding_sequence_q2) ############## 局部推理local inference modeling ################### #计算dot attention attention=Dot(axes=-1)([rnn_layer_q1 rnn_layer_q2])<line_sep>#分别计算query和sample进行attention后的结果 w_attn_1=Lambda(<lambda>x:softmax(x axis=1))(attention)<line_sep>w_attn_2=Permute((2 1))(Lambda(<lambda>x:softmax(x axis=2))(attention))<line_sep>align_layer_1=Dot(axes=1)([w_attn_1 rnn_layer_q1])<line_sep>align_layer_2=Dot(axes=1)([w_attn_2 rnn_layer_q2])<line_sep>############# 推理组合Inference Composition ####################### subtract_layer_1=subtract([rnn_layer_q1 align_layer_1])<line_sep>subtract_layer_2=subtract([rnn_layer_q2 align_layer_2])<line_sep>multiply_layer_1=multiply([rnn_layer_q1 align_layer_1])<line_sep>multiply_layer_2=multiply([rnn_layer_q2 align_layer_2])<line_sep>m_q1=concatenate([rnn_layer_q1 align_layer_1 subtract_layer_1 multiply_layer_1])<line_sep>m_q2=concatenate([rnn_layer_q2 align_layer_2 subtract_layer_2 multiply_layer_2])<line_sep>############### 编码+池化 ####################### v_q1_i=Bidirectional(LSTM(self.recurrent_units return_sequences=<true>))(m_q1)<line_sep>v_q2_i=Bidirectional(LSTM(self.recurrent_units return_sequences=<true>))(m_q2)<line_sep>avgpool_q1=GlobalAveragePooling1D()(v_q1_i)<line_sep>avgpool_q2=GlobalAveragePooling1D()(v_q2_i)<line_sep>maxpool_q1=GlobalMaxPooling1D()(v_q1_i)<line_sep>maxpool_q2=GlobalMaxPooling1D()(v_q2_i)<line_sep>merged_q1=concatenate([avgpool_q1 maxpool_q1])<line_sep>merged_q2=concatenate([avgpool_q2 maxpool_q2])<line_sep>final_v=BatchNormalization()(concatenate([merged_q1 merged_q2]))<line_sep>#output = Dense(units=self.dense_units, activation='relu')(final_v) output=Dense(units=self.num_output activation=<none>)(final_v)<line_sep>#output = BatchNormalization()(output) #output = Dropout(self.dropout_rate)(output) #output = tf.nn.dropout(output, self.keep_prob) #高级api tf.layer.dropout 与 keras的Dropout都使用dropout #tf.nn.dropout使用keep_prob #output = Dense(units=self.num_output, activation='sigmoid')(output) #output = Dense(units=self.num_output, activation=None)(output) #output = tf.squeeze(output, -1) <return>output<block_end><block_end>
<import_stmt>unittest<import_stmt>asyncio<import_stmt>sys<import_stmt>os<import_stmt>re<import_stmt>io<import_from_stmt>molotov.util multiprocessing<import_from_stmt>molotov.sharedconsole SharedConsole<import_from_stmt>molotov.tests.support dedicatedloop catch_output<line_sep>OUTPUT="""\ one two 3 TypeError\\("unsupported operand type(.*)? TypeError\\("unsupported operand type.*"""<line_sep># pre-forked variable _CONSOLE=SharedConsole(interval=0.0)<line_sep>_PROC=[]<def_stmt>run_worker input<block_start><if_stmt>os.getpid()<not><in>_PROC<block_start>_PROC.append(os.getpid())<block_end>_CONSOLE.print("hello")<try_stmt><block_start>3+""<block_end><except_stmt>Exception<block_start>_CONSOLE.print_error("meh")<block_end><with_stmt>catch_output()<as>(stdout stderr)<block_start>loop=asyncio.new_event_loop()<line_sep>fut=asyncio.ensure_future(_CONSOLE.display() loop=loop)<line_sep>loop.run_until_complete(fut)<line_sep>loop.close()<block_end>stdout=stdout.read()<assert_stmt>stdout<eq>"" stdout<block_end><class_stmt>TestSharedConsole(unittest.TestCase)<block_start>@dedicatedloop<def_stmt>test_simple_usage self<block_start>test_loop=asyncio.get_event_loop()<line_sep>stream=io.StringIO()<line_sep>console=SharedConsole(interval=0.0 stream=stream)<async_keyword><def_stmt>add_lines <block_start>console.print("one")<line_sep>console.print("two")<line_sep>console.print("3")<try_stmt><block_start>1+"e"<block_end><except_stmt>Exception<as>e<block_start>console.print_error(e)<line_sep>console.print_error(e sys.exc_info()[2])<block_end><await>asyncio.sleep(0.2)<line_sep><await>console.stop()<block_end><with_stmt>catch_output()<as>(stdout stderr)<block_start>adder=asyncio.ensure_future(add_lines())<line_sep>displayer=asyncio.ensure_future(console.display())<line_sep>test_loop.run_until_complete(asyncio.gather(adder displayer))<block_end>stream.seek(0)<line_sep>output=stream.read()<line_sep>test_loop.close()<line_sep>self.assertTrue(re.match(OUTPUT output re.S|re.M)<is><not><none> output)<block_end>@unittest.skipIf(os.name<eq>"nt" "win32")@dedicatedloop<def_stmt>test_multiprocess self<block_start>test_loop=asyncio.get_event_loop()<line_sep># now let's try with several processes pool=multiprocessing.Pool(3)<try_stmt><block_start>inputs=[1]<times>3<line_sep>pool.map(run_worker inputs)<block_end><finally_stmt><block_start>pool.close()<block_end><async_keyword><def_stmt>stop <block_start><await>asyncio.sleep(1)<line_sep><await>_CONSOLE.stop()<block_end><with_stmt>catch_output()<as>(stdout stderr)<block_start>stop=asyncio.ensure_future(stop())<line_sep>display=asyncio.ensure_future(_CONSOLE.display())<line_sep>test_loop.run_until_complete(asyncio.gather(stop display))<block_end>output=stdout.read()<for_stmt>pid _PROC<block_start>self.assertTrue("[%d]"%pid<in>output)<block_end>test_loop.close()<block_end><block_end>
# -*- coding: utf-8 -*- <import_from_future_stmt> division<import_from_stmt>.parsing Parser<as>BaseParser<import_from_stmt>.tz UTC<import_from_stmt>.pendulum Pendulum<import_from_stmt>.date Date<import_from_stmt>.time Time<import_from_stmt>._global Global<class_stmt>Parser(BaseParser)<block_start>""" Parser that returns known types (Pendulum, Date, Time) """<def_stmt>parse self text<block_start>""" Parses a string with the given options. :param text: The string to parse. :type text: str :rtype: mixed """<line_sep># Handling special cases <if_stmt>text<eq>'now'<block_start><return>Pendulum.now()<block_end>parsed=super(Parser self).parse(text)<if_stmt><not>self.is_exact()<block_start><return>self._create_pendulum_object(parsed)<block_end># Checking for date <if_stmt>'year'<in>parsed# Checking for time <block_start><if_stmt>'hour'<in>parsed<block_start><return>self._create_pendulum_object(parsed)<block_end><else_stmt><block_start><return>self._create_date_object(parsed)<block_end><block_end><return>self._create_time_object(parsed)<block_end><def_stmt>_create_pendulum_object self parsed<block_start><if_stmt>parsed['offset']<is><none><block_start>tz=self._options.get('tz' UTC)<block_end><else_stmt><block_start>tz=parsed['offset']/3600<block_end><return>Pendulum(parsed['year'] parsed['month'] parsed['day'] parsed['hour'] parsed['minute'] parsed['second'] parsed['subsecond'] tzinfo=tz)<block_end><def_stmt>_create_date_object self parsed<block_start><return>Date(parsed['year'] parsed['month'] parsed['day'])<block_end><def_stmt>_create_time_object self parsed<block_start><return>Time(parsed['hour'] parsed['minute'] parsed['second'] parsed['subsecond'])<block_end><block_end><def_stmt>parse text **options# Use the mock now value if it exists <block_start>options['now']=options.get('now' Global.get_test_now())<line_sep><return>Parser(**options).parse(text)<block_end>
# Copyright 2014 Intel Corporation, All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ MDSes interface. """<import_stmt>urllib<import_from_stmt>vsmclient base<class_stmt>Mds(base.Resource)<block_start>"""A mds stores metadata on behalf of the Ceph Filesystem."""<def_stmt>__repr__ self<block_start><return>"<MDS: %s>"%self.id<block_end><def_stmt>delete self<block_start>"""Delete this mds."""<line_sep>self.manager.delete(self)<block_end><block_end><class_stmt>MdsesManager(base.ManagerWithFind)<block_start>""" Manage :class:`MDS` resources. """<line_sep>resource_class=Mds<def_stmt>get self mds_id<block_start>""" Get a mds. :param mds_id: The ID of the mds. :rtype: :class:`MDS` """<line_sep><return>self._get("/mdses/%s"%mds_id "mds")<block_end><def_stmt>list self detailed=<false> search_opts=<none><block_start>""" Get a list of all mdses. :rtype: list of :class:`MDS` """<if_stmt>search_opts<is><none><block_start>search_opts={}<block_end>qparams={}<for_stmt>opt,val search_opts.iteritems()<block_start><if_stmt>val<block_start>qparams[opt]=val<block_end><block_end>query_string="?%s"%urllib.urlencode(qparams)<if>qparams<else>""<line_sep>detail=""<if_stmt>detailed<block_start>detail="/detail"<block_end>ret=self._list("/mdses%s%s"%(detail query_string) "mdses")<line_sep><return>ret<block_end><def_stmt>restart self mds<block_start>self._action('restart' mds)<block_end><def_stmt>remove self mds<block_start>self._action('remove' mds)<block_end><def_stmt>delete self mds<block_start>self._delete("/mdses/%s"%base.getid(mds))<block_end><def_stmt>restore self mds<block_start>self._action('restore' mds)<block_end><def_stmt>summary self<block_start>""" summary """<line_sep>url="/mdses/summary"<line_sep><return>self._get(url 'mds-summary')<block_end><def_stmt>_action self action mds info=<none> **kwargs<block_start>""" Perform a mds "action." """<line_sep>body={action:info}<line_sep>self.run_hooks('modify_body_for_action' body **kwargs)<line_sep>url='/mdses/%s/action'%base.getid(mds)<line_sep><return>self.api.client.post(url body=body)<block_end><block_end>
<import_stmt>os<import_stmt>sys<import_stmt>unittest<line_sep>sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)) "../src"))<import_stmt>amd<line_sep>PACKAGE_DIRECTORY_COM=os.path.dirname(os.path.abspath(__file__))<class_stmt>TestAmd(unittest.TestCase)<block_start><def_stmt>setUp self<block_start><try_stmt><block_start>os.chdir(PACKAGE_DIRECTORY_COM)<block_end><except_stmt>OSError<block_start><pass><block_end><block_end><def_stmt>test_parse_rocm_smi_result self<block_start>sample_path="data/rocm_smi.json"<with_stmt>open(sample_path "r")<as>f<block_start>rocm_smi_result=f.read()<block_end>rocm_smi_parse_result=amd.parse_smi_json_result(rocm_smi_result)<line_sep>expect=[{"pci_addr":"0000:03:00.0" "temperature":31} {"pci_addr":"0000:06:00.0" "temperature":25}]<for_stmt>e,v zip(expect rocm_smi_parse_result.values())<block_start>self.assertEqual(e["pci_addr"] v.pci_addr)<line_sep>self.assertEqual(e["temperature"] v.temperature)<block_end><block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>unittest.main()<block_end>
<import_stmt>os<import_stmt>mmap<import_from_stmt>chariot.util xtqdm<class_stmt>DataFile()<block_start><def_stmt>__init__ self path encoding="utf-8"<block_start>self.path=path<line_sep>self.encoding=encoding<line_sep>file_name=os.path.basename(path)<line_sep>base_name,ext=os.path.splitext(file_name)<line_sep>self.base_name=base_name<line_sep>self.ext=ext<block_end><def_stmt>exists self<block_start><return>os.path.exists(self.path)<block_end><def_stmt>convert self data_dir_to="" add_attribute="" attribute_to=() ext_to=""<block_start>_dir=os.path.dirname(self.path)<line_sep>elements=self._elements()<line_sep>ext=self.ext<if_stmt>data_dir_to<block_start>_dir=os.path.join(_dir "../"+data_dir_to)<block_end><if_stmt>add_attribute<block_start>elements.append(add_attribute)<block_end><elif_stmt>len(attribute_to)<g>0# File name format is name + "__".join(attributes) # So attribute is elements[1:] <block_start><for_stmt>a attribute_to<block_start><if_stmt>a<in>elements[1:]<block_start>index=elements[1:].index(a)<line_sep>elements[1+index]=attribute_to[a]<block_end><block_end><block_end><if_stmt>ext_to<block_start>ext=ext_to<block_end>base_name="__".join(elements)<line_sep>new_path=os.path.join(_dir base_name+ext)<line_sep><return>self.__class__(new_path)<block_end>@property<def_stmt>name self<block_start><return>self._elements[0]<block_end>@property<def_stmt>attributes self<block_start><return>self._elements[1:]<block_end><def_stmt>_elements self<block_start>elements=self.base_name.split("__")<line_sep><return>elements<block_end><def_stmt>get_line_count self<block_start>count=0<with_stmt>open(self.path "r+")<as>f<block_start>buf=mmap.mmap(f.fileno() 0)<while_stmt>buf.readline()<block_start>count<augadd>1<block_end><block_end><return>count<block_end><def_stmt>fetch self progress=<false><block_start>total_count=0<if_stmt>progress<block_start>total_count=self.get_line_count()<block_end><with_stmt>open(self.path encoding=self.encoding)<as>f<block_start>iterator=f<if_stmt>progress<block_start>iterator=xtqdm(f total=total_count)<block_end><for_stmt>line iterator<block_start><yield>line.strip()<block_end><block_end><block_end><def_stmt>to_array self<block_start>lines=[]<with_stmt>open(self.path encoding=self.encoding)<as>f<block_start>lines=f.readlines()<line_sep>lines=[ln.strip()<for>ln lines]<block_end><return>lines<block_end><block_end>
"""Easy context-based interface for generating a sheet and cells. Comparable to matplotlib pylab interface, this interface keeps track of the current sheet. Using the ``cell`` function, ``Cell`` widgets are added to the current sheet. """<line_sep>__all__=['sheet' 'current' 'cell' 'calculation' 'row' 'column' 'cell_range' 'hold_cells' 'renderer']<import_stmt>numbers<import_stmt>six<import_from_stmt>contextlib contextmanager<import_stmt>ipywidgets<as>widgets<import_from_stmt>.sheet Cell Sheet Renderer<import_from_stmt>.utils transpose<as>default_transpose<import_from_stmt>.utils adapt_value<import_from_stmt>.docutils doc_subst<line_sep>_last_sheet=<none><line_sep>_sheets={}# maps from key to Sheet instance _hold_cells=<false># when try (using hold_cells() it does not add cells directly) _cells=()# cells that aren't added directly _common_doc={'args':""" type (string): Type of cell, options are: text, numeric, checkbox, dropdown, numeric, date, widget. If type is None, the type is inferred from the type of the value being passed, numeric (float or int type), boolean (bool type), widget (any widget object), or else text. When choice is given the type will be assumed to be dropdown. The types refer (currently) to the handsontable types: https://handsontable.com/docs/6.2.2/demo-custom-renderers.html color (string): The text color in the cell background_color (string): The background color in the cell read_only (bool): Whether the cell is editable or not numeric_format (string): Numbers format date_format (string): Dates format time_format (string): Time format renderer (string): Renderer name to use for the cell """}<def_stmt>sheet key=<none> rows=5 columns=5 column_width=<none> row_headers=<true> column_headers=<true> stretch_headers='all' cls=Sheet **kwargs<block_start>"""Creates a new ``Sheet`` instance or retrieves one registered with key, and sets this as the 'current'. If the key argument is given, and no sheet is created before with this key, it will be registered under this key. If this function is called again with the same key argument, that ``Sheet`` instance will be returned. Args: key (string): If not used before, register the sheet under this key. If used before, return the previous ``Sheet`` instance registered with this key. rows (int): The number of rows in the sheet columns (int): The number of columns in the sheet row_headers (bool, list): Either a boolean specifying if row headers should be displayed or not, or a list of strings containing the row headers column_headers (bool, list): Either a boolean specifying if column headers should be displayed or not, or a list of strings containing the column headers Returns: The new ``Sheet`` widget, or if key is given, the previously created sheet registered with this key. Example: >>> from ipysheet import sheet, current >>> >>> s1 = sheet('key1') >>> s2 = sheet('key2') >>> >>> assert s2 is current() >>> assert s1 is sheet('key1') >>> assert s1 is current() """<line_sep><global>_last_sheet<if_stmt>isinstance(key Sheet)<block_start>_last_sheet=key<block_end><elif_stmt>key<is><none><or>key<not><in>_sheets<block_start>_last_sheet=cls(rows=rows columns=columns column_width=column_width row_headers=row_headers column_headers=column_headers stretch_headers=stretch_headers **kwargs)<if_stmt>key<is><not><none><block_start>_sheets[key]=_last_sheet<block_end><block_end><else_stmt><block_start>_last_sheet=_sheets[key]<block_end><return>_last_sheet<block_end><def_stmt>current <block_start>""" Returns: the current ``Sheet`` instance """<line_sep><return>_last_sheet<block_end>@doc_subst(_common_doc)<def_stmt>cell row column value=0. type=<none> color=<none> background_color=<none> font_style=<none> font_weight=<none> style=<none> label_left=<none> choice=<none> read_only=<false> numeric_format='0.000' date_format='YYYY/MM/DD' renderer=<none> **kwargs<block_start>"""Adds a new ``Cell`` widget to the current ``Sheet`` Args: row (int): Zero based row index where to put the cell in the sheet column (int): Zero based column index where to put the cell in the sheet value (int, float, string, bool, Widget): The value of the cell {args} Returns: The new ``Cell`` widget. Example: >>> from ipysheet import sheet, cell >>> >>> s1 = sheet() >>> cell(0, 0, 36.) # The Cell type will be 'numeric' >>> cell(1, 0, True) # The Cell type will be 'checkbox' >>> cell(0, 1, 'Hello World!') # The Cell type will be 'text' >>> c = cell(1, 1, True) >>> c.value = False # Dynamically changing the cell value at row=1, column=1 """<line_sep><global>_cells<if_stmt>type<is><none><block_start><if_stmt>isinstance(value bool)<block_start>type='checkbox'<block_end><elif_stmt>isinstance(value numbers.Number)<block_start>type='numeric'<block_end><elif_stmt>isinstance(value widgets.Widget)<block_start>type='widget'<block_end><else_stmt><block_start>type='text'<block_end><if_stmt>choice<is><not><none><block_start>type='dropdown'<block_end><block_end>style=style<or>{}<if_stmt>color<is><not><none><block_start>style['color']=color<block_end><if_stmt>background_color<is><not><none><block_start>style['backgroundColor']=background_color<block_end><if_stmt>font_style<is><not><none><block_start>style['fontStyle']=font_style<block_end><if_stmt>font_weight<is><not><none><block_start>style['fontWeight']=font_weight<block_end>c=Cell(value=value row_start=row column_start=column row_end=row column_end=column squeeze_row=<true> squeeze_column=<true> type=type style=style choice=choice read_only=read_only numeric_format=numeric_format date_format=date_format renderer=renderer **kwargs)<if_stmt>_hold_cells<block_start>_cells<augadd>(c )<block_end><else_stmt><block_start>_last_sheet.cells=_last_sheet.cells+(c )<block_end><if_stmt>label_left<block_start><if_stmt>column-1<l>0<block_start><raise>IndexError("cannot put label to the left of column 0")<block_end>cell(row column-1 value=label_left font_weight='bold')<block_end><return>c<block_end>@doc_subst(_common_doc)<def_stmt>row row value column_start=0 column_end=<none> type=<none> color=<none> background_color=<none> font_style=<none> font_weight=<none> style=<none> choice=<none> read_only=<false> numeric_format='0.000' date_format='YYYY/MM/DD' renderer=<none> **kwargs<block_start>"""Create a ``Cell`` widget, representing multiple cells in a sheet, in a horizontal row Args: row (int): Zero based row index where to put the row in the sheet value (list): The list of cell values representing the row column_start (int): Which column the row will start, default 0. column_end (int): Which column the row will end, default is the last. {args} Returns: The new ``Cell`` widget. Example: >>> from ipysheet import sheet, row >>> >>> s1 = sheet() >>> row(0, [1, 2, 3, 34, 5]) # The Cell type will be 'numeric' >>> row(1, [True, False, True], column_start=2) # The Cell type will be 'checkbox' """<line_sep><return>cell_range(value column_start=column_start column_end=column_end row_start=row row_end=row squeeze_row=<true> squeeze_column=<false> color=color background_color=background_color font_style=font_style font_weight=font_weight style=style type=type choice=choice read_only=read_only numeric_format=numeric_format date_format=date_format renderer=renderer **kwargs)<block_end>@doc_subst(_common_doc)<def_stmt>column column value row_start=0 row_end=<none> type=<none> color=<none> background_color=<none> font_style=<none> font_weight=<none> style=<none> choice=<none> read_only=<false> numeric_format='0.000' date_format='YYYY/MM/DD' renderer=<none> **kwargs<block_start>"""Create a ``Cell`` widget, representing multiple cells in a sheet, in a vertical column Args: column (int): Zero based column index where to put the column in the sheet value (list): The list of cell values representing the column row_start (int): Which row the column will start, default 0. row_end (int): Which row the column will end, default is the last. {args} Returns: The new ``Cell`` widget. Example: >>> from ipysheet import sheet, column >>> >>> s1 = sheet() >>> column(0, [1, 2, 3, 34, 5]) # The Cell type will be 'numeric' >>> column(1, [True, False, True], row_start=2) # The Cell type will be 'checkbox' """<line_sep><return>cell_range(value column_start=column column_end=column row_start=row_start row_end=row_end squeeze_row=<false> squeeze_column=<true> style=style choice=choice read_only=read_only numeric_format=numeric_format date_format=date_format renderer=renderer color=color background_color=background_color type=type font_style=font_style font_weight=font_weight **kwargs)<block_end>@doc_subst(_common_doc)<def_stmt>cell_range value row_start=0 column_start=0 row_end=<none> column_end=<none> transpose=<false> squeeze_row=<false> squeeze_column=<false> type=<none> color=<none> background_color=<none> font_style=<none> font_weight=<none> style=<none> choice=<none> read_only=<false> numeric_format='0.000' date_format='YYYY/MM/DD' renderer=<none> **kwargs<block_start>"""Create a ``Cell`` widget, representing multiple cells in a sheet Args: value (list): The list of cell values representing the range row_start (int): Which row the range will start, default 0. column_start (int): Which column the range will start, default 0. row_end (int): Which row the range will end, default is the last. column_end (int): Which column the range will end, default is the last. transpose (bool): Whether to interpret the value array as value[column_index][row_index] or not. squeeze_row (bool): Take out the row dimensions, meaning only value[column_index] is used. squeeze_column (bool): Take out the column dimensions, meaning only value[row_index] is used. {args} Returns: The new ``Cell`` widget. Example: >>> from ipysheet import sheet, cell_range >>> >>> s1 = sheet() >>> cell_range([[1, 2, 3, 34, 5], [6, 7, 8, 89, 10]]) """<line_sep><global>_cells<line_sep>value_original=value<line_sep>value=adapt_value(value)<line_sep># instead of an if statements, we just use T to transpose or not when needed T=(<lambda>x:x)<if><not>transpose<else>default_transpose<line_sep># we work with the optionally transposed values for simplicity value=T(value)<if_stmt>squeeze_row<block_start>value=[value]<block_end><if_stmt>squeeze_column<block_start>value=[[k]<for>k value]<block_end><if_stmt>row_end<is><none><block_start>row_end=row_start+len(value)-1<block_end>row_length=row_end-row_start+1<if_stmt>row_length<ne>len(value)<block_start><raise>ValueError("length or array doesn't match number of rows")<block_end><if_stmt>row_length<eq>0<block_start><raise>ValueError("0 rows not supported")<block_end><if_stmt>column_end<is><none><block_start>column_end=column_start+len(value[0])-1<block_end>column_length=column_end-column_start+1<if_stmt>column_length<eq>0<block_start><raise>ValueError("0 columns not supported")<block_end><for_stmt>row value<block_start><if_stmt>column_length<ne>len(row)<block_start><raise>ValueError("not a regular matrix, columns lengths differ")<block_end><block_end><if_stmt>row_start+row_length<g>_last_sheet.rows<block_start><raise>ValueError("array will go outside of sheet, too many rows")<block_end><if_stmt>column_start+column_length<g>_last_sheet.columns<block_start><raise>ValueError("array will go outside of sheet, too many columns")<block_end># see if we an infer a type from the data, otherwise leave it None <if_stmt>type<is><none><block_start>type_check_map=[('checkbox' <lambda>x:isinstance(x bool)) ('numeric' <lambda>x:isinstance(x numbers.Number)) ('text' <lambda>x:isinstance(x six.string_types)) ('widget' <lambda>x:isinstance(x widgets.Widget)) ]<for_stmt>type_check,check type_check_map<block_start>checks=<true># ok until proven wrong <for_stmt>i range(row_length)<block_start><for_stmt>j range(column_length)<block_start><if_stmt><not>check(value[i][j])<block_start>checks=<false><block_end><block_end><block_end><if_stmt>checks# we found a matching type <block_start>type=type_check<line_sep><break><block_end><block_end><block_end>style=style<or>{}<if_stmt>color<is><not><none><block_start>style['color']=color<block_end><if_stmt>background_color<is><not><none><block_start>style['backgroundColor']=background_color<block_end><if_stmt>font_style<is><not><none><block_start>style['fontStyle']=font_style<block_end><if_stmt>font_weight<is><not><none><block_start>style['fontWeight']=font_weight<block_end>c=Cell(value=value_original row_start=row_start column_start=column_start row_end=row_end column_end=column_end squeeze_row=squeeze_row squeeze_column=squeeze_column transpose=transpose type=type read_only=read_only choice=choice renderer=renderer numeric_format=numeric_format date_format=date_format style=style **kwargs)<if_stmt>_hold_cells<block_start>_cells<augadd>(c )<block_end><else_stmt><block_start>_last_sheet.cells=_last_sheet.cells+(c )<block_end><return>c<block_end><def_stmt>renderer code name<block_start>"""Create a ``Renderer`` widget Args: code (string or code or function object): If a string object, it is assumed to be a JavaScript snippet, else it is assumed to be a function or code object and will be transpiled to javascript using flexxui/pscript. name (string): Name of the renderer Returns: The new ``Renderer`` widget. Example: >>> from ipysheet import sheet, renderer, cell >>> >>> s1 = sheet() >>> >>> def renderer_negative(instance, td, row, col, prop, value, cellProperties): >>> Handsontable.renderers.TextRenderer.apply(this, arguments); >>> if value < 0: >>> td.style.backgroundColor = 'orange' >>> else: >>> td.style.backgroundColor = '' >>> >>> renderer(code=renderer_negative, name='negative'); >>> cell(0, 0, 36, renderer='negative') # Will be white >>> cell(1, 0, -36, renderer='negative') # Will be orange """<if_stmt><not>isinstance(code six.string_types)<block_start><import_from_stmt>pscript py2js<line_sep>code_transpiled=py2js(code new_name='the_renderer' indent=4)<line_sep>code=''' function() { %s return the_renderer }() '''%code_transpiled<block_end>renderer=Renderer(code=code name=name)<line_sep><return>renderer<block_end><def_stmt>_assign object value<block_start><if_stmt>isinstance(object widgets.Widget)<block_start>object,trait=object 'value'<block_end><else_stmt><block_start>object,trait=object<block_end>setattr(object trait value)<block_end><def_stmt>calculation inputs output initial_calculation=<true><block_start>"""A decorator that assigns to output cell a calculation depending on the inputs Args: inputs (list of widgets, or (widget, 'traitname') pairs): List of all widget, whose values (default 'value', otherwise specified by 'traitname') are input of the function that is decorated output (widget or (widget, 'traitname')): The output of the decorator function will be assigned to output.value or output.<traitname>. initial_calculation (bool): When True the calculation will be done directly for the first time. Example: >>> from ipywidgets import IntSlider >>> from ipysheet import cell, calculation >>> >>> a = cell(0, 0, value=1) >>> b = cell(1, 0, value=IntSlider(value=2)) >>> c = IntSlider(max=56) >>> d = cell(3, 0, value=1) >>> >>> @calculation(inputs=[a, (b, 'value'), (c, 'max')], output=d) >>> def add(a, b, c): >>> return a + b + c """<def_stmt>decorator f<block_start><def_stmt>get_value input<block_start><if_stmt>isinstance(input widgets.Widget)<block_start>object,trait=input 'value'<block_end><else_stmt><block_start>object,trait=input# assume it's a tup;e <block_end><if_stmt>isinstance(object Cell)<and>isinstance(object.value widgets.Widget)<block_start>object=object.value<block_end><return>getattr(object trait)<block_end><def_stmt>calculate *ignore_args<block_start>values=map(get_value inputs)<line_sep>result=f(*values)<line_sep>_assign(output result)<block_end><for_stmt>input inputs<block_start><if_stmt>isinstance(input widgets.Widget)<block_start>object,trait=input 'value'<block_end><else_stmt><block_start>object,trait=input<block_end># assume it's a tuple <if_stmt>isinstance(object Cell)<and>isinstance(object.value widgets.Widget)# when it is a cell which holds a widget, we actually want the widgets' value <block_start>object.value.observe(calculate trait)<block_end><else_stmt><block_start>object.observe(calculate trait)<block_end><def_stmt>handle_possible_widget_change change trait=trait<block_start><if_stmt>isinstance(change['old'] widgets.Widget)<block_start>change['old'].unobserve(calculate trait)<block_end><if_stmt>isinstance(change['new'] widgets.Widget)<block_start>change['new'].observe(calculate trait)<block_end>calculate()<block_end>object.observe(handle_possible_widget_change 'value')<block_end><if_stmt>initial_calculation<block_start>calculate()<block_end><block_end><return>decorator<block_end>@contextmanager<def_stmt>hold_cells <block_start>"""Hold adding any cell widgets until leaving this context. This may give a better performance when adding many cells. Example: >>> from ipysheet import sheet, cell, hold_cells >>> >>> sheet(rows=10,columns=10) >>> with hold_cells() >>> for i in range(10): >>> for j in range(10): >>> cell(i, j, value=i * 10 + j) >>> # at this line, the Cell widgets are added """<line_sep><global>_hold_cells<line_sep><global>_cells<if_stmt>_hold_cells<is><true><block_start><yield><block_end><else_stmt><block_start><try_stmt><block_start>_hold_cells=<true><line_sep><yield><block_end><finally_stmt><block_start>_hold_cells=<false><line_sep># print(_cells, _last_sheet.cells) _last_sheet.cells=tuple(_last_sheet.cells)+tuple(_cells)<line_sep>_cells=()<block_end><block_end><block_end>
<import_from_stmt>fontbakery.callable check<import_from_stmt>fontbakery.status FAIL PASS SKIP WARN<import_from_stmt>fontbakery.message Message<line_sep># used to inform get_module_profile whether and how to create a profile <import_from_stmt>fontbakery.fonts_profile profile_factory# NOQA pylint: disable=unused-import profile_imports=[('.shared_conditions' ('glyph_metrics_stats' 'is_ttf'))]<line_sep>@check(id='com.google.fonts/check/linegaps' proposal='legacy:check/041')<def_stmt>com_google_fonts_check_linegaps ttFont<block_start>"""Checking Vertical Metric Linegaps."""<if_stmt>ttFont["hhea"].lineGap<ne>0<block_start><yield>WARN Message("hhea" "hhea lineGap is not equal to 0.")<block_end><elif_stmt>ttFont["OS/2"].sTypoLineGap<ne>0<block_start><yield>WARN Message("OS/2" "OS/2 sTypoLineGap is not equal to 0.")<block_end><else_stmt><block_start><yield>PASS "OS/2 sTypoLineGap and hhea lineGap are both 0."<block_end><block_end>@check(id='com.google.fonts/check/maxadvancewidth' proposal='legacy:check/073')<def_stmt>com_google_fonts_check_maxadvancewidth ttFont<block_start>"""MaxAdvanceWidth is consistent with values in the Hmtx and Hhea tables?"""<line_sep>hhea_advance_width_max=ttFont['hhea'].advanceWidthMax<line_sep>hmtx_advance_width_max=<none><for_stmt>g ttFont['hmtx'].metrics.values()<block_start><if_stmt>hmtx_advance_width_max<is><none><block_start>hmtx_advance_width_max=max(0 g[0])<block_end><else_stmt><block_start>hmtx_advance_width_max=max(g[0] hmtx_advance_width_max)<block_end><block_end><if_stmt>hmtx_advance_width_max<ne>hhea_advance_width_max<block_start><yield>FAIL Message("mismatch" f"AdvanceWidthMax mismatch:"<concat>f" expected {hmtx_advance_width_max} (from hmtx);"<concat>f" got {hhea_advance_width_max} (from hhea)")<block_end><else_stmt><block_start><yield>PASS ("MaxAdvanceWidth is consistent"<concat>" with values in the Hmtx and Hhea tables.")<block_end><block_end>
<import_stmt>torch<import_stmt>torch.nn<as>nn<import_from_stmt>torch.autograd Variable<import_stmt>math<import_stmt>torch.nn.functional<as>F<class_stmt>GMMLogLoss(nn.Module)<block_start>''' compute the GMM loss between model output and the groundtruth data. Args: ncenter: numbers of gaussian distribution ndim: dimension of each gaussian distribution sigma_bias: sigma_min: current we do not use it. '''<def_stmt>__init__ self ncenter ndim sigma_min=0.03<block_start>super(GMMLogLoss self).__init__()<line_sep>self.ncenter=ncenter<line_sep>self.ndim=ndim<line_sep>self.sigma_min=sigma_min<block_end><def_stmt>forward self output target<block_start>''' Args: output: [b, T, ncenter + ncenter * ndim * 2]: [:, :, : ncenter] shows each gaussian probability [:, :, ncenter : ncenter + ndim * ncenter] shows the average values of each dimension of each gaussian [: ,:, ncenter + ndim * ncenter : ncenter + ndim * 2 * ncenter] show the negative log sigma of each dimension of each gaussian target: [b, T, ndim], the ground truth target landmark data is shown here To maximize the log-likelihood equals to minimize the negative log-likelihood. NOTE: It is unstable to directly compute the log results of sigma, e.g. ln(-0.1) as we need to clip the sigma results into positive. Hence here we predict the negative log sigma results to avoid numerical instablility, which mean: `` sigma = 1/exp(predict), predict = -ln(sigma) `` Also, it will be just the 'B' term below! Currently we only implement single gaussian distribution, hence the first values of pred are meaningless. For single gaussian distribution: L(mu, sigma) = -n/2 * ln(2pi * sigma^2) - 1 / (2 x sigma^2) * sum^n (x_i - mu)^2 (n for prediction times, n=1 for one frame, x_i for gt) = -1/2 * ln(2pi) - 1/2 * ln(sigma^2) - 1/(2 x sigma^2) * (x - mu)^2 == min -L(mu, sgima) = 0.5 x ln(2pi) + 0.5 x ln(sigma^2) + 1/(2 x sigma^2) * (x - mu)^2 = 0.5 x ln_2PI + ln(sigma) + 0.5 x (MU_DIFF/sigma)^2 = A - B + C In batch and Time sample, b and T are summed and averaged. '''<line_sep>b,T,_=target.shape<line_sep># read prediction paras mus=output[: : self.ncenter:(self.ncenter+self.ncenter<times>self.ndim)].view(b T self.ncenter self.ndim)# [b, T, ncenter, ndim] # apply min sigma neg_log_sigmas_out=output[: : (self.ncenter+self.ncenter<times>self.ndim):].view(b T self.ncenter self.ndim)# [b, T, ncenter, ndim] inv_sigmas_min=torch.ones(neg_log_sigmas_out.size()).cuda()<times>(1./self.sigma_min)<line_sep>inv_sigmas_min_log=torch.log(inv_sigmas_min)<line_sep>neg_log_sigmas=torch.min(neg_log_sigmas_out inv_sigmas_min_log)<line_sep>inv_sigmas=torch.exp(neg_log_sigmas)<line_sep># replicate the target of ncenter to minus mu target_rep=target.unsqueeze(2).expand(b T self.ncenter self.ndim)# [b, T, ncenter, ndim] MU_DIFF=target_rep-mus# [b, T, ncenter, ndim] # sigma process A=0.5<times>math.log(2<times>math.pi)# 0.9189385332046727 B=neg_log_sigmas# [b, T, ncenter, ndim] C=0.5<times>(MU_DIFF<times>inv_sigmas)<power>2# [b, T, ncenter, ndim] negative_loglikelihood=A-B+C# [b, T, ncenter, ndim] <return>negative_loglikelihood.mean()<block_end><block_end><def_stmt>Sample_GMM gmm_params ncenter ndim weight_smooth=0.0 sigma_scale=0.0<block_start>''' Sample values from a given a GMM distribution. Args: gmm_params: [b, target_length, (2 * ndim + 1) * ncenter], including the distribution weights, average and sigma ncenter: numbers of gaussian distribution ndim: dimension of each gaussian distribution weight_smooth: float, smooth the gaussian distribution weights sigma_scale: float, adjust the gaussian scale, larger for sharper prediction, 0 for zero sigma which always return average values Returns: current_sample: [] '''<line_sep># reshape as [b*T, (2 * ndim + 1) * ncenter] b,T,_=gmm_params.shape<line_sep>gmm_params_cpu=gmm_params.cpu().view(-1 (2<times>ndim+1)<times>ncenter)<line_sep># compute each distrubution probability prob=nn.functional.softmax(gmm_params_cpu[: :ncenter]<times>(1+weight_smooth) dim=1)<line_sep># select the gaussian distribution according to their weights selected_idx=torch.multinomial(prob num_samples=1 replacement=<true>)<line_sep>mu=gmm_params_cpu[: ncenter:ncenter+ncenter<times>ndim]<line_sep># please note that we use -logsigma as output, hence here we need to take the negative sigma=torch.exp(-gmm_params_cpu[: ncenter+ncenter<times>ndim:])<times>sigma_scale<line_sep># print('sigma average:', sigma.mean()) selected_sigma=torch.empty(b<times>T ndim).float()<line_sep>selected_mu=torch.empty(b<times>T ndim).float()<line_sep>current_sample=torch.randn(b<times>T ndim).float()<line_sep># current_sample = test_sample <for_stmt>i range(b<times>T)<block_start>idx=selected_idx[i 0]<line_sep>selected_sigma[i :]=sigma[i idx<times>ndim:(idx+1)<times>ndim]<line_sep>selected_mu[i :]=mu[i idx<times>ndim:(idx+1)<times>ndim]<block_end># sample with sel sigma and sel mean current_sample=current_sample<times>selected_sigma+selected_mu<line_sep># cur_sample = sel_mu # return current_sample.unsqueeze(1).cuda() <return>current_sample.reshape(b T -1).cuda()<block_end><class_stmt>GANLoss(nn.Module)<block_start><def_stmt>__init__ self use_lsgan=<true> target_real_label=1.0 target_fake_label=0.0 tensor=torch.FloatTensor<block_start>super(GANLoss self).__init__()<line_sep>self.real_label=target_real_label<line_sep>self.fake_label=target_fake_label<line_sep>self.real_label_var=<none><line_sep>self.fake_label_var=<none><line_sep>self.Tensor=tensor<if_stmt>use_lsgan<block_start>self.loss=nn.MSELoss()<block_end><else_stmt><block_start>self.loss=nn.BCELoss()<block_end><block_end><def_stmt>get_target_tensor self input target_is_real<block_start>target_tensor=<none><line_sep>gpu_id=input.get_device()<if_stmt>target_is_real<block_start>create_label=((self.real_label_var<is><none>)<or>(self.real_label_var.numel()<ne>input.numel()))<if_stmt>create_label<block_start>real_tensor=self.Tensor(input.size()).cuda(gpu_id).fill_(self.real_label)<line_sep>self.real_label_var=Variable(real_tensor requires_grad=<false>)<block_end>target_tensor=self.real_label_var<block_end><else_stmt><block_start>create_label=((self.fake_label_var<is><none>)<or>(self.fake_label_var.numel()<ne>input.numel()))<if_stmt>create_label<block_start>fake_tensor=self.Tensor(input.size()).cuda(gpu_id).fill_(self.fake_label)<line_sep>self.fake_label_var=Variable(fake_tensor requires_grad=<false>)<block_end>target_tensor=self.fake_label_var<block_end><return>target_tensor<block_end><def_stmt>__call__ self input target_is_real<block_start><if_stmt>isinstance(input[0] list)<block_start>loss=0<for_stmt>input_i input<block_start>pred=input_i[-1]<line_sep>target_tensor=self.get_target_tensor(pred target_is_real)<line_sep>loss<augadd>self.loss(pred target_tensor)<block_end><return>loss<block_end><else_stmt><block_start>target_tensor=self.get_target_tensor(input[-1] target_is_real)<line_sep><return>self.loss(input[-1] target_tensor)<block_end><block_end><block_end><class_stmt>VGGLoss(nn.Module)<block_start><def_stmt>__init__ self model=<none><block_start>super(VGGLoss self).__init__()<if_stmt>model<is><none><block_start>self.vgg=Vgg19()<block_end><else_stmt><block_start>self.vgg=model<block_end>self.vgg.cuda()<line_sep># self.vgg.eval() self.criterion=nn.L1Loss()<line_sep>self.style_criterion=StyleLoss()<line_sep>self.weights=[1.0 1.0 1.0 1.0 1.0]<line_sep>self.style_weights=[1.0 1.0 1.0 1.0 1.0]<line_sep># self.weights = [5.0, 1.0, 0.5, 0.4, 0.8] # self.style_weights = [10e4, 1000, 50, 15, 50] <block_end><def_stmt>forward self x y style=<false><block_start>x_vgg,y_vgg=self.vgg(x) self.vgg(y)<line_sep>loss=0<if_stmt>style# return both perceptual loss and style loss. <block_start>style_loss=0<for_stmt>i range(len(x_vgg))<block_start>this_loss=(self.weights[i]<times>self.criterion(x_vgg[i] y_vgg[i].detach()))<line_sep>this_style_loss=(self.style_weights[i]<times>self.style_criterion(x_vgg[i] y_vgg[i].detach()))<line_sep>loss<augadd>this_loss<line_sep>style_loss<augadd>this_style_loss<block_end><return>loss style_loss<block_end><for_stmt>i range(len(x_vgg))<block_start>this_loss=(self.weights[i]<times>self.criterion(x_vgg[i] y_vgg[i].detach()))<line_sep>loss<augadd>this_loss<block_end><return>loss<block_end><block_end><def_stmt>gram_matrix input<block_start>a,b,c,d=input.size()# a=batch size(=1) # b=number of feature maps # (c,d)=dimensions of a f. map (N=c*d) features=input.view(a<times>b c<times>d)# resise F_XL into \hat F_XL G=torch.mm(features features.t())# compute the gram product # we 'normalize' the values of the gram matrix # by dividing by the number of element in each feature maps. <return>G.div(a<times>b<times>c<times>d)<block_end><class_stmt>StyleLoss(nn.Module)<block_start><def_stmt>__init__ self<block_start>super(StyleLoss self).__init__()<block_end><def_stmt>forward self x y<block_start>Gx=gram_matrix(x)<line_sep>Gy=gram_matrix(y)<line_sep><return>F.mse_loss(Gx Gy)<times>30000000<block_end><block_end><class_stmt>MaskedL1Loss(nn.Module)<block_start><def_stmt>__init__ self<block_start>super(MaskedL1Loss self).__init__()<line_sep>self.criterion=nn.L1Loss()<block_end><def_stmt>forward self input target mask<block_start>mask=mask.expand(-1 input.size()[1] -1 -1)<line_sep>loss=self.criterion(input<times>mask target<times>mask)<line_sep><return>loss<block_end><block_end><import_from_stmt>torchvision models<class_stmt>Vgg19(nn.Module)<block_start><def_stmt>__init__ self requires_grad=<false><block_start>super(Vgg19 self).__init__()<line_sep>vgg_pretrained_features=models.vgg19(pretrained=<true>).features<line_sep>self.slice1=torch.nn.Sequential()<line_sep>self.slice2=torch.nn.Sequential()<line_sep>self.slice3=torch.nn.Sequential()<line_sep>self.slice4=torch.nn.Sequential()<line_sep>self.slice5=torch.nn.Sequential()<for_stmt>x range(2)<block_start>self.slice1.add_module(str(x) vgg_pretrained_features[x])<block_end><for_stmt>x range(2 7)<block_start>self.slice2.add_module(str(x) vgg_pretrained_features[x])<block_end><for_stmt>x range(7 12)<block_start>self.slice3.add_module(str(x) vgg_pretrained_features[x])<block_end><for_stmt>x range(12 21)<block_start>self.slice4.add_module(str(x) vgg_pretrained_features[x])<block_end><for_stmt>x range(21 30)<block_start>self.slice5.add_module(str(x) vgg_pretrained_features[x])<block_end><if_stmt><not>requires_grad<block_start><for_stmt>param self.parameters()<block_start>param.requires_grad=<false><block_end><block_end><block_end><def_stmt>forward self X<block_start>h_relu1=self.slice1(X)<line_sep>h_relu2=self.slice2(h_relu1)<line_sep>h_relu3=self.slice3(h_relu2)<line_sep>h_relu4=self.slice4(h_relu3)<line_sep>h_relu5=self.slice5(h_relu4)<line_sep>out=[h_relu1 h_relu2 h_relu3 h_relu4 h_relu5]<line_sep><return>out<block_end><block_end>
<import_from_stmt>tornado.web StaticFileHandler<import_from_stmt>cloudtunes settings<import_from_stmt>cloudtunes.base.handlers BaseHandler<class_stmt>MainHandler(BaseHandler)<block_start><def_stmt>get self<block_start>webapp_dir=self.settings['static_path']<line_sep>homepage_dir=settings.HOMEPAGE_SITE_DIR<if_stmt>self.current_user<block_start>app_dir=webapp_dir<block_end><else_stmt><block_start><if_stmt>self.request.path<ne>'/'<block_start><return>self.redirect('/')<block_end>app_dir=homepage_dir<block_end><with_stmt>open(app_dir+'/index.html')<as>f<block_start>self.write(f.read())<block_end><block_end><block_end><class_stmt>NoCacheStaticFileHandler(StaticFileHandler)<block_start><def_stmt>set_extra_headers self path<block_start>self.set_header('Cache-control' 'no-cache')<block_end><block_end>
<import_from_stmt>recipe_scrapers.zenbelly ZenBelly<import_from_stmt>tests ScraperTest<class_stmt>TestZenBellyScraper(ScraperTest)<block_start>scraper_class=ZenBelly<def_stmt>test_host self<block_start>self.assertEqual("zenbelly.com" self.harvester_class.host())<block_end><def_stmt>test_canonical_url self<block_start>self.assertEqual("https://www.zenbelly.com/gingerbread/" self.harvester_class.canonical_url() )<block_end><def_stmt>test_title self<block_start>self.assertEqual(self.harvester_class.title() "Paleo Gingerbread")<block_end><def_stmt>test_yields self<block_start>self.assertEqual("20 serving(s)" self.harvester_class.yields())<block_end><def_stmt>test_total_time self<block_start>self.assertEqual(40 self.harvester_class.total_time())<block_end><def_stmt>test_image self<block_start>self.assertEqual("https://www.zenbelly.com/wp-content/uploads/2019/01/gingerbread-3-225x225.jpeg" self.harvester_class.image() )<block_end><def_stmt>test_ingredients self<block_start>self.assertEqual(["butter (ghee, or shortening for greasing the pan)" "3 cups almond flour" "1 1/2 cups tapioca starch (plus more for flouring pan)" "1/2 cup coconut flour" "1 1/2 teaspoons baking soda" "2 teaspoons ground ginger" "1 teaspoons ground cinnamon" "1/4 teaspoon ground allspice" "1/4 teaspoon ground cardamom" "1/2 teaspoon finely ground sea salt" "1 cup coconut sugar" "1 cup molasses (use true molasses if you can find it)" "2 teaspoons fresh ginger" "1 cup boiling water" "4 eggs" ] self.harvester_class.ingredients() )<block_end><def_stmt>test_instructions self<block_start><return>self.assertEqual("\n".join(["Preheat the oven to 350ºF. Grease a 9×13-inch cake pan." "In a large bowl, whisk together the almond flour, tapioca starch, coconut flour, baking soda, ground ginger, cinnamon, allspice, cardamom, and salt." "In a medium heat proof bowl, whisk together the coconut sugar, molasses, fresh ginger, and boiling water. Once it’s lukewarm (the molasses and coconut sugar should take the temperature down enough), whisk in the eggs." "Pour the wet ingredients into the dry ingredients and whisk until there are no lumps." "Pour into the prepared pan and bake for 28-35 minutes*" ]) self.harvester_class.instructions() )<block_end><block_end>
<import_stmt>logging<import_stmt>os<import_stmt>ray<import_stmt>time<import_from_stmt>enum Enum<import_from_stmt>ray.actor ActorHandle<import_from_stmt>ray.streaming.generated remote_call_pb2<import_from_stmt>ray.streaming.runtime.command WorkerCommitReport WorkerRollbackRequest<line_sep>logger=logging.getLogger(__name__)<class_stmt>CallResult<block_start>""" Call Result """<def_stmt>__init__ self success result_code result_msg result_obj<block_start>self.success=success<line_sep>self.result_code=result_code<line_sep>self.result_msg=result_msg<line_sep>self.result_obj=result_obj<block_end>@staticmethod<def_stmt>success payload=<none><block_start><return>CallResult(<true> CallResultEnum.SUCCESS <none> payload)<block_end>@staticmethod<def_stmt>fail payload=<none><block_start><return>CallResult(<false> CallResultEnum.FAILED <none> payload)<block_end>@staticmethod<def_stmt>skipped msg=<none><block_start><return>CallResult(<true> CallResultEnum.SKIPPED msg <none>)<block_end><def_stmt>is_success self<block_start><if_stmt>self.result_code<is>CallResultEnum.SUCCESS<block_start><return><true><block_end><return><false><block_end><block_end><class_stmt>CallResultEnum(Enum)<block_start>""" call result enum """<line_sep>SUCCESS=0<line_sep>FAILED=1<line_sep>SKIPPED=2<block_end><class_stmt>RemoteCallMst<block_start>""" remote call job master """<line_sep>@staticmethod<def_stmt>request_job_worker_rollback master:ActorHandle request:WorkerRollbackRequest<block_start>logger.info("Remote call mst: request job worker rollback start.")<line_sep>request_pb=remote_call_pb2.BaseWorkerCmd()<line_sep>request_pb.actor_id=request.from_actor_id<line_sep>request_pb.timestamp=int(time.time()<times>1000.0)<line_sep>rollback_request_pb=remote_call_pb2.WorkerRollbackRequest()<line_sep>rollback_request_pb.exception_msg=request.exception_msg()<line_sep>rollback_request_pb.worker_hostname=os.uname()[1]<line_sep>rollback_request_pb.worker_pid=str(os.getpid())<line_sep>request_pb.detail.Pack(rollback_request_pb)<line_sep>return_ids=master.requestJobWorkerRollback.remote(request_pb.SerializeToString())<line_sep>result=remote_call_pb2.BoolResult()<line_sep>result.ParseFromString(ray.get(return_ids))<line_sep>logger.info("Remote call mst: request job worker rollback finish.")<line_sep><return>result.boolRes<block_end>@staticmethod<def_stmt>report_job_worker_commit master:ActorHandle report:WorkerCommitReport<block_start>logger.info("Remote call mst: report job worker commit start.")<line_sep>report_pb=remote_call_pb2.BaseWorkerCmd()<line_sep>report_pb.actor_id=report.from_actor_id<line_sep>report_pb.timestamp=int(time.time()<times>1000.0)<line_sep>wk_commit=remote_call_pb2.WorkerCommitReport()<line_sep>wk_commit.commit_checkpoint_id=report.commit_checkpoint_id<line_sep>report_pb.detail.Pack(wk_commit)<line_sep>return_id=master.reportJobWorkerCommit.remote(report_pb.SerializeToString())<line_sep>result=remote_call_pb2.BoolResult()<line_sep>result.ParseFromString(ray.get(return_id))<line_sep>logger.info("Remote call mst: report job worker commit finish.")<line_sep><return>result.boolRes<block_end><block_end>
<import_from_future_stmt> absolute_import print_function<line_sep>""" Command to start the NSoT server process. """<import_from_stmt>django.conf settings<import_from_stmt>django.core.management call_command<import_stmt>sys<import_from_stmt>nsot.services http<import_from_stmt>nsot.util.commands NsotCommand CommandError<class_stmt>Command(NsotCommand)<block_start>help='Start the NSoT server process.'<def_stmt>add_arguments self parser<block_start>parser.add_argument('service' nargs='?' default='http' help='Starts the specified service.' )<line_sep>parser.add_argument('--debug' action='store_true' default=<false> help='Toggle debug output.' )<line_sep>parser.add_argument('--max-requests' type=int default=settings.NSOT_MAX_REQUESTS help=('The maximum number of requests a worker will process before '<concat>'restarting.') )<line_sep>parser.add_argument('--max-requests-jitter' type=int default=settings.NSOT_MAX_REQUESTS_JITTER help=('The maximum jitter to add to the max_requests setting.') )<line_sep>parser.add_argument('--noinput' action='store_true' default=<false> help='Tells Django to NOT prompt the user for input of any kind.' )<line_sep>parser.add_argument('--no-collectstatic' action='store_false' dest='collectstatic' default=<true> help='Do not automatically collect static files into STATIC_ROOT.' )<line_sep>parser.add_argument('--no-upgrade' action='store_false' dest='upgrade' default=<true> help='Do not automatically perform any database upgrades.' )<line_sep>parser.add_argument('--preload' action='store_true' default=settings.NSOT_PRELOAD help=('Load application code before the worker processes are '<concat>'forked.') )<line_sep>parser.add_argument('-a' '--address' type=str default='%s:%s'%(settings.NSOT_HOST settings.NSOT_PORT) help='Host:port to listen on.' )<line_sep>parser.add_argument('-k' '--worker-class' type=str default=settings.NSOT_WORKER_CLASS help='The type of gunicorn workers to use.' )<line_sep>parser.add_argument('-t' '--timeout' type=int default=settings.NSOT_WORKER_TIMEOUT help='Timeout before gunicorn workers are killed/restarted.' )<line_sep>parser.add_argument('-w' '--workers' type=int default=settings.NSOT_NUM_WORKERS help=('The number of gunicorn worker processes for handling '<concat>'requests.') )<block_end><def_stmt>handle self **options<block_start>address=options.get('address')<line_sep># Break address into host:port <if_stmt>address<block_start><if_stmt>':'<in>address<block_start>host,port=address.split(':' 1)<line_sep>port=int(port)<block_end><else_stmt><block_start>host=address<line_sep>port=<none><block_end><block_end><else_stmt><block_start>host,port=<none> <none><block_end>services={'http':http.NsotHTTPServer }<line_sep># Ensure we perform an upgrade before starting any service. <if_stmt>options.get('upgrade')<block_start>print("Performing upgrade before service startup...")<line_sep>call_command('upgrade' verbosity=0 noinput=options.get('noinput'))<block_end># Ensure we collect static before starting any service, but only if # SERVE_STATIC_FILES=True. <if_stmt>options.get('collectstatic')<and>settings.SERVE_STATIC_FILES<block_start>print("Performing collectstatic before service startup...")<line_sep>call_command('collectstatic' interactive=<false> ignore=['src'])<block_end>service_name=options.get('service')<try_stmt><block_start>service_class=services[service_name]<block_end><except_stmt>KeyError<block_start><raise>CommandError('%r is not a valid service'%service_name)<block_end>service=service_class(debug=options.get('debug') host=host port=port workers=options.get('workers') worker_class=options.get('worker_class') timeout=options.get('timeout') max_requests=options.get('max_requests') max_requests_jitter=options.get('max_requests_jitter') preload=options.get('preload') )<line_sep># Remove command line arguments to avoid optparse failures with service # code that calls call_command which reparses the command line, and if # --no-upgrade is supplied a parse error is thrown. sys.argv=sys.argv[:1]<line_sep>service.run()<block_end><block_end>
# Copyright (C) 2015-2016 Twitter, Inc. # Note: All account_media/media_creatives must be uploaded via the media-upload endpoints # See: https://dev.twitter.com/rest/media/uploading-media <import_from_stmt>twitter_ads.client Client<import_from_stmt>twitter_ads.http Request<import_from_stmt>twitter_ads.enums CREATIVE_TYPE<import_from_stmt>twitter_ads.creative AccountMedia MediaCreative<line_sep>CONSUMER_KEY='your consumer key'<line_sep>CONSUMER_SECRET='your consumer secret'<line_sep>ACCESS_TOKEN='access token'<line_sep>ACCESS_TOKEN_SECRET='access token secret'<line_sep>ACCOUNT_ID='account id'<line_sep># initialize the client client=Client(CONSUMER_KEY CONSUMER_SECRET ACCESS_TOKEN ACCESS_TOKEN_SECRET)<line_sep># load the advertiser account instance account=client.accounts(ACCOUNT_ID)<line_sep># grab the first line_item on the account line_item_id=account.line_items().first.id<line_sep># retrive the `id` of the media creative associated with a line item print(account.media_creatives().first.id)<line_sep># retrieve the `id` of the first account media associated with the account account_media_id=account.account_media().first.id<line_sep># create a new account media account_media=AccountMedia(account)<line_sep>account_media.media_id='your-media-id'<line_sep># OR account_media.video_id OR account_media.vast_url # see the media_upload.py example for more details account_media.creative_type=CREATIVE_TYPE.BANNER<line_sep>account_media.save()<line_sep>#create a new media creative media_creative=MediaCreative(account)<line_sep>media_creative.line_item_id=line_item_id<line_sep>media_creative.account_media_id=account_media_id<line_sep>media_creative.landing_url="https://my-landing-url"<line_sep>media_creative.save()<line_sep># delete the media creative media_creative.delete()<line_sep>
# pylint: skip-file <class_stmt>GitRebase(GitCLI)<block_start>''' Class to wrap the git merge line tools '''<line_sep># pylint: disable=too-many-arguments <def_stmt>__init__ self path branch rebase_branch ssh_key=<none><block_start>''' Constructor for GitPush '''<line_sep>super(GitRebase self).__init__(path ssh_key=ssh_key)<line_sep>self.path=path<line_sep>self.branch=branch<line_sep>self.rebase_branch=rebase_branch<line_sep>self.debug=[]<line_sep>os.chdir(path)<block_end><def_stmt>checkout_branch self<block_start>''' check out the desired branch '''<line_sep>current_branch_results=self._get_current_branch()<if_stmt>current_branch_results['results']<eq>self.branch<block_start><return><true><block_end>current_branch_results=self._checkout(self.branch)<line_sep>self.debug.append(current_branch_results)<if_stmt>current_branch_results['returncode']<eq>0<block_start><return><true><block_end><return><false><block_end><def_stmt>remote_update self<block_start>''' update the git remotes '''<line_sep>remote_update_results=self._remote_update()<line_sep>self.debug.append(remote_update_results)<if_stmt>remote_update_results['returncode']<eq>0<block_start><return><true><block_end><return><false><block_end><def_stmt>need_rebase self<block_start>''' checks to see if rebase is needed '''<line_sep>git_diff_results=self._diff(self.rebase_branch)<line_sep>self.debug.append(git_diff_results)<if_stmt>git_diff_results['results']<block_start><return><true><block_end><return><false><block_end><def_stmt>rebase self<block_start>'''perform a git push '''<if_stmt>self.checkout_branch()<block_start><if_stmt>self.remote_update()<block_start><if_stmt>self.need_rebase()<block_start>rebase_results=self._rebase(self.rebase_branch)<line_sep>rebase_results['debug']=self.debug<line_sep><return>rebase_results<block_end><else_stmt><block_start><return>{'returncode':0 'results':{} 'no_rebase_needed':<true>}<block_end><block_end><block_end><return>{'returncode':1 'results':{} 'debug':self.debug}<block_end><block_end>
<import_from_stmt>allauth.socialaccount.providers.oauth2.urls default_urlpatterns<import_from_stmt>.provider AngelListProvider<line_sep>urlpatterns=default_urlpatterns(AngelListProvider)<line_sep>
''' Defines the set of symbols used in text input to the model. The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. '''<import_from_stmt>jamo h2j j2h<import_from_stmt>jamo.jamo _jamo_char_to_hcj<import_from_stmt>.korean ALL_SYMBOLS PAD EOS<line_sep>#symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\'(),-.:;? ' symbols=ALL_SYMBOLS<line_sep>