id
stringlengths
11
16
language
stringclasses
2 values
question
stringlengths
13
844
answer
stringlengths
1
900
code
stringlengths
162
27.4k
code_original
stringlengths
162
26k
code_word_count
int64
51
5.96k
python-test-758
python
What does the code draw ?
a grid line parameters
def get gridline path world pixel mask np isnan pixel[ 0] np isnan pixel[ 1] codes np zeros world shape[ 0 ] dtype np uint 8 codes[ ] Path LINET Ocodes[ 0 ] Path MOVET Ocodes[mask] Path MOVET Ocodes[ 1 ][mask[ -1 ]] Path MOVET Opath Path pixel codes codes return path
def get_gridline_path world pixel mask np isnan pixel[ 0] np isnan pixel[ 1] codes np zeros world shape[0] dtype np uint8 codes[ ] Path LINETOcodes[0] Path MOVETOcodes[mask] Path MOVETOcodes[1 ][mask[ -1 ]] Path MOVETOpath Path pixel codes codes return path
52
python-test-761
python
Where did metadata set ?
on all instances of a host
@utils arg 'host' metavar '<host>' help ' Nameofhost ' @utils arg 'action' metavar '<action>' choices ['set' 'delete'] help " Actions 'set'or'delete'" @utils arg 'metadata' metavar '<key value>' nargs '+' action 'append' default [] help ' Metadatatosetordelete onlykeyisnecessaryondelete ' def do host meta cs args hyper...
@utils arg 'host' metavar '<host>' help _ 'Nameofhost ' @utils arg 'action' metavar '<action>' choices ['set' 'delete'] help _ "Actions 'set'or'delete'" @utils arg 'metadata' metavar '<key value>' nargs '+' action 'append' default [] help _ 'Metadatatosetordelete onlykeyisnecessaryondelete ' def do_host_meta cs args hy...
90
python-test-763
python
What copy to location in link_path ?
distribution files
def copy dist from dir link path location if os path isdir location rmtree location setup py 'setup py'sdist args [sys executable]sdist args append '-c' sdist args append SETUPTOOLS SHIM % setup py sdist args append 'sdist' sdist args + ['--dist-dir' location]logger info ' Runningsetup pysdistfor%s' link path with inde...
def _copy_dist_from_dir link_path location if os path isdir location rmtree location setup_py 'setup py'sdist_args [sys executable]sdist_args append '-c' sdist_args append SETUPTOOLS_SHIM % setup_py sdist_args append 'sdist' sdist_args + ['--dist-dir' location]logger info 'Runningsetup pysdistfor%s' link_path with inde...
86
python-test-764
python
Where do distribution files copy to location ?
in link_path
def copy dist from dir link path location if os path isdir location rmtree location setup py 'setup py'sdist args [sys executable]sdist args append '-c' sdist args append SETUPTOOLS SHIM % setup py sdist args append 'sdist' sdist args + ['--dist-dir' location]logger info ' Runningsetup pysdistfor%s' link path with inde...
def _copy_dist_from_dir link_path location if os path isdir location rmtree location setup_py 'setup py'sdist_args [sys executable]sdist_args append '-c' sdist_args append SETUPTOOLS_SHIM % setup_py sdist_args append 'sdist' sdist_args + ['--dist-dir' location]logger info 'Runningsetup pysdistfor%s' link_path with inde...
86
python-test-766
python
How do different icrs<->gcrs answers give ?
with and without distance
@pytest mark parametrize u'gframe' gcrs frames def test icrs gcrs dist diff gframe gcrsnod icrs coords[ 0 ] transform to gframe gcrswd icrs coords[ 1 ] transform to gframe assert not allclose gcrswd ra gcrsnod ra rtol 1e- 08 atol 1e- 10 * u deg assert not allclose gcrswd dec gcrsnod dec rtol 1e- 08 atol 1e- 10 * u deg ...
@pytest mark parametrize u'gframe' gcrs_frames def test_icrs_gcrs_dist_diff gframe gcrsnod icrs_coords[0] transform_to gframe gcrswd icrs_coords[1] transform_to gframe assert not allclose gcrswd ra gcrsnod ra rtol 1e-08 atol 1e-10 * u deg assert not allclose gcrswd dec gcrsnod dec rtol 1e-08 atol 1e-10 * u deg assert n...
80
python-test-767
python
What does the code handle ?
a feature permission request
def feature permission url option msg yes action no action abort on config val config get *option if config val 'ask' if url is Valid text ' Allowthewebsiteat<b>{}</b>to{}?' format html escape url to Display String msg else text ' Allowthewebsiteto{}?' format msg return message confirm async yes action yes action no ac...
def feature_permission url option msg yes_action no_action abort_on config_val config get *option if config_val 'ask' if url isValid text 'Allowthewebsiteat<b>{}</b>to{}?' format html escape url toDisplayString msg else text 'Allowthewebsiteto{}?' format msg return message confirm_async yes_action yes_action no_action ...
78
python-test-768
python
What does the code remove ?
all subdirectories in this path
def rm subdirs path onerror None names []try names os listdir path except os error as err if onerror is not None onerror os listdir path sys exc info else raisefor name in names fullname os path join path name if os path isdir fullname if onerror is not None shutil rmtree fullname False onerror else err count 0while Tr...
def rm_subdirs path onerror None names []try names os listdir path except os error as err if onerror is not None onerror os listdir path sys exc_info else raisefor name in names fullname os path join path name if os path isdir fullname if onerror is not None shutil rmtree fullname False onerror else err_count 0while Tr...
83
python-test-769
python
When does the code sanitize positional and keyword arguments ?
before calling a function
def cherry pick args func args dargs if func func code co flags & 4 p args argselse p args if func func code co flags & 8 p dargs dargselse p dargs {}for param in get nonstar args func if param in dargs p dargs[param] dargs[param]return p args p dargs
def _cherry_pick_args func args dargs if func func_code co_flags & 4 p_args argselse p_args if func func_code co_flags & 8 p_dargs dargselse p_dargs {}for param in _get_nonstar_args func if param in dargs p_dargs[param] dargs[param]return p_args p_dargs
51
python-test-770
python
What does the code sanitize before calling a function ?
positional and keyword arguments
def cherry pick args func args dargs if func func code co flags & 4 p args argselse p args if func func code co flags & 8 p dargs dargselse p dargs {}for param in get nonstar args func if param in dargs p dargs[param] dargs[param]return p args p dargs
def _cherry_pick_args func args dargs if func func_code co_flags & 4 p_args argselse p_args if func func_code co_flags & 8 p_dargs dargselse p_dargs {}for param in _get_nonstar_args func if param in dargs p_dargs[param] dargs[param]return p_args p_dargs
51
python-test-776
python
What does this test ?
the performance of the processors scheduler
def threads thread yields [100 200 500 1000 ]thread locks [2 4 8 16 ]test command 'sysbench--num-threads 64 --test threads'test command + '--thread-yields {0 }--thread-locks {1 }run'result Noneret val {}for yields locks in zip thread yields thread locks key ' Yields {0 } Locks {1 }' format yields locks run command test...
def threads thread_yields [100 200 500 1000]thread_locks [2 4 8 16]test_command 'sysbench--num-threads 64--test threads'test_command + '--thread-yields {0}--thread-locks {1}run'result Noneret_val {}for yields locks in zip thread_yields thread_locks key 'Yields {0}Locks {1}' format yields locks run_command test_command ...
69
python-test-777
python
What does the code write to the output stream ?
aggregated records
def aggregate input options output time Field Name aggregator Aggregator aggregation Info options input Fields input get Fields time Field Name time Field Name while True in Record input get Next Record print ' Feedingin ' in Record out Record agg Bookmark aggregator next record in Record cur Input Bookmark None print ...
def _aggregate input options output timeFieldName aggregator Aggregator aggregationInfo options inputFields input getFields timeFieldName timeFieldName while True inRecord input getNextRecord print 'Feedingin ' inRecord outRecord aggBookmark aggregator next record inRecord curInputBookmark None print 'Recordout ' outRe...
79
python-test-782
python
What is region - oblivious a case ?
connecting
@pytest mark skipif 'no real s3 credentials ' def test subdomain compatible creds Credentials os getenv 'AWS ACCESS KEY ID' os getenv 'AWS SECRET ACCESS KEY' bucket name bucket name mangle 'wal-e-test-us-west- 1 -no-dots' cinfo calling format from store name bucket name with Fresh Bucket bucket name host 's 3 -us-west-...
@pytest mark skipif 'no_real_s3_credentials ' def test_subdomain_compatible creds Credentials os getenv 'AWS_ACCESS_KEY_ID' os getenv 'AWS_SECRET_ACCESS_KEY' bucket_name bucket_name_mangle 'wal-e-test-us-west-1-no-dots' cinfo calling_format from_store_name bucket_name with FreshBucket bucket_name host 's3-us-west-1 ama...
95
python-test-784
python
What does the code see ?
discussion in # 2255
@pytest mark parametrize 'fast writer' [ True False] def test write fill masked different fast writer data ascii read tab to fill data table Table data masked True data['a'] mask [ True False]data['c'] mask [ False True]for test def in test def masked fill value check write table test def data fast writer
@pytest mark parametrize 'fast_writer' [True False] def test_write_fill_masked_different fast_writer data ascii read tab_to_fill data table Table data masked True data['a'] mask [True False]data['c'] mask [False True]for test_def in test_def_masked_fill_value check_write_table test_def data fast_writer
53
python-test-791
python
What does the code add ?
github_link function
def add doc link app pagename templatename context doctree if not app config github user and app config github project returnsource suffix app config source suffixsource suffix source suffix if isinstance source suffix basestring else source suffix[ 0 ] context['github link'] lambda mode 'edit' make github link app 'do...
def add_doc_link app pagename templatename context doctree if not app config github_user and app config github_project returnsource_suffix app config source_suffixsource_suffix source_suffix if isinstance source_suffix basestring else source_suffix[0] context['github_link'] lambda mode 'edit' make_github_link app 'doc/...
55
python-test-795
python
What does the code return ?
a arma order
def clean order order order re findall '\\ [0 - 9 ]*?\\ ' order clean lambda x tuple map int re sub '[ ]' '' x split '' if len order > 1 order sorder map clean order else order clean order[ 0 ] sorder 0 0 0 return order sorder
def _clean_order order order re findall '\\ [0-9]*?\\ ' order clean lambda x tuple map int re sub '[ ]' '' x split '' if len order > 1 order sorder map clean order else order clean order[0] sorder 0 0 0 return order sorder
51
python-test-797
python
What does the code get ?
current config of l2 switchport args
def get switchport port module command 'showinterface{ 0 }switchport' format port body execute show command command module try body execute show command command module [0 ]except Index Error body []if body key map {'interface' 'interface' 'oper mode' 'mode' 'switchport' 'switchport' 'access vlan' 'access vlan' 'access ...
def get_switchport port module command 'showinterface{0}switchport' format port body execute_show_command command module try body execute_show_command command module [0]except IndexError body []if body key_map {'interface' 'interface' 'oper_mode' 'mode' 'switchport' 'switchport' 'access_vlan' 'access_vlan' 'access_vlan...
79
python-test-801
python
What do a decorator ensure ?
that any global state is reset before running a test
def cleanup style None def make cleanup func if inspect isgeneratorfunction func @functools wraps func def wrapped callable *args **kwargs original units registry matplotlib units registry copy original settings mpl rc Params copy matplotlib style use style try for yielded in func *args **kwargs yield yielded finally d...
def cleanup style None def make_cleanup func if inspect isgeneratorfunction func @functools wraps func def wrapped_callable *args **kwargs original_units_registry matplotlib units registry copy original_settings mpl rcParams copy matplotlib style use style try for yielded in func *args **kwargs yield yielded finally _d...
110
python-test-805
python
What does current line contain ?
an inherited function
def Is Derived Function clean lines linenum for i in xrange linenum max -1 linenum - 10 -1 match Match '^ [^ ]*\\w+ \\ ' clean lines elided[i] if match line closing paren Close Expression clean lines i len match group 1 return closing paren > 0 and Search '\\boverride\\b' line[closing paren ] return False
def IsDerivedFunction clean_lines linenum for i in xrange linenum max -1 linenum - 10 -1 match Match '^ [^ ]*\\w+ \\ ' clean_lines elided[i] if match line _ closing_paren CloseExpression clean_lines i len match group 1 return closing_paren > 0 and Search '\\boverride\\b' line[closing_paren ] return False
55
python-test-806
python
What do we have ?
a type mismatch for packages
def test merge type mismatch merge log err packages {'pack 1' {'input boolean' [{'ib 1 ' None}]} 'pack 11 ' {'input select' {'ib 1 ' None}} 'pack 2' {'light' {'ib 1 ' None}}}config {config util CONF CORE {config util CONF PACKAGES packages} 'input boolean' {'ib 2 ' None} 'input select' [{'ib 2 ' None}] 'light' [{'platf...
def test_merge_type_mismatch merge_log_err packages {'pack_1' {'input_boolean' [{'ib1' None}]} 'pack_11' {'input_select' {'ib1' None}} 'pack_2' {'light' {'ib1' None}}}config {config_util CONF_CORE {config_util CONF_PACKAGES packages} 'input_boolean' {'ib2' None} 'input_select' [{'ib2' None}] 'light' [{'platform' 'two'}...
83
python-test-810
python
What does the code take ?
a video object
def generate video v params [] sources []if v webm sources append {'src' get video url v webm 'type' 'webm'} if v ogv sources append {'src' get video url v ogv 'type' 'ogg'} data fallback ''if v flv data fallback get video url v flv return render to string 'wikiparser/hook video html' {'fallback' data fallback 'sources...
def generate_video v params [] sources []if v webm sources append {'src' _get_video_url v webm 'type' 'webm'} if v ogv sources append {'src' _get_video_url v ogv 'type' 'ogg'} data_fallback ''if v flv data_fallback _get_video_url v flv return render_to_string 'wikiparser/hook_video html' {'fallback' data_fallback 'sour...
71
python-test-811
python
What does the code return ?
html markup for embedding it
def generate video v params [] sources []if v webm sources append {'src' get video url v webm 'type' 'webm'} if v ogv sources append {'src' get video url v ogv 'type' 'ogg'} data fallback ''if v flv data fallback get video url v flv return render to string 'wikiparser/hook video html' {'fallback' data fallback 'sources...
def generate_video v params [] sources []if v webm sources append {'src' _get_video_url v webm 'type' 'webm'} if v ogv sources append {'src' _get_video_url v ogv 'type' 'ogg'} data_fallback ''if v flv data_fallback _get_video_url v flv return render_to_string 'wikiparser/hook_video html' {'fallback' data_fallback 'sour...
71
python-test-812
python
What does the code create from a wildcard namespace ?
a regexobject
def namespace to regex namespace db name coll name namespace split ' ' 1 db regex re escape db name replace '\\*' ' [^ ]* ' coll regex re escape coll name replace '\\*' ' * ' return re compile '\\A' + db regex + '\\ ' + coll regex + '\\Z'
def namespace_to_regex namespace db_name coll_name namespace split ' ' 1 db_regex re escape db_name replace '\\*' ' [^ ]* ' coll_regex re escape coll_name replace '\\*' ' * ' return re compile '\\A' + db_regex + '\\ ' + coll_regex + '\\Z'
52
python-test-816
python
What does the code get ?
the file name for the active frame
def Get Active File Name b Auto Save 1 path Name Noneactive Get Active View if active is None return Nonetry doc active Get Document path Name doc Get Path Name if b Auto Save and len path Name > 0 or doc Get Title [ 8] ' Untitled' or doc Get Title [ 6] ' Script' if doc Is Modified try doc On Save Document path Name pa...
def GetActiveFileName bAutoSave 1 pathName Noneactive GetActiveView if active is None return Nonetry doc active GetDocument pathName doc GetPathName if bAutoSave and len pathName > 0 or doc GetTitle [ 8] 'Untitled' or doc GetTitle [ 6] 'Script' if doc IsModified try doc OnSaveDocument pathName pathName doc GetPathName ...
98
python-test-817
python
What does a matrix contain ?
the first dim dimensions principal components of data
def p Pca data dim num data shape[ 1 ]data asmatrix make Centered data W asmatrix standard normal num dim W W[ ]while True E inv W T * W * W T * data T W W data T * E T * inv E * E T W if abs W - W max < 0 001 breakreturn W T
def pPca data dim num data shape[1]data asmatrix makeCentered data W asmatrix standard_normal num dim W_ W[ ]while True E inv W T * W * W T * data T W W_ data T * E T * inv E * E T W if abs W - W_ max < 0 001 breakreturn W T
62
python-test-818
python
What does the code run ?
a python interactive interpreter
def run shell use plain False from django db models loading import get modelsloaded models get models try if use plain raise Import Errorimport I Pythonshell I Python Shell IP Shell argv [] shell mainloop except Import Error import codetry import readlineexcept Import Error passelse import rlcompleterreadline parse and...
def run_shell use_plain False from django db models loading import get_modelsloaded_models get_models try if use_plain raise ImportErrorimport IPythonshell IPython Shell IPShell argv [] shell mainloop except ImportError import codetry import readlineexcept ImportError passelse import rlcompleterreadline parse_and_bind ...
54
python-test-823
python
What does the code get ?
the data to show for the given url
def data for url url path url path host url host log misc debug 'url {} path {} host{}' format url to Display String path host try handler HANDLERS[path]except Key Error try handler HANDLERS[host]except Key Error raise No Handler Found url try mimetype data handler url except OS Error as e raise Qute Scheme OS Error e ...
def data_for_url url path url path host url host log misc debug 'url {} path {} host{}' format url toDisplayString path host try handler _HANDLERS[path]except KeyError try handler _HANDLERS[host]except KeyError raise NoHandlerFound url try mimetype data handler url except OSError as e raise QuteSchemeOSError e except Q...
86
python-test-824
python
What exist on the master ?
some files
def ssh run with recursion ssh bin address ec 2 key pair file keyfile cmd args if ' ' in address if keyfile is None raise Value Error 'SS Hkeyfilepathcannotbe None' host 1 host 2 address split ' ' more args ['ssh' '-i' keyfile '-o' ' Strict Host Key Checking no' '-o' ' User Known Hosts File /dev/null' 'hadoop@%s' % hos...
def _ssh_run_with_recursion ssh_bin address ec2_key_pair_file keyfile cmd_args if ' ' in address if keyfile is None raise ValueError 'SSHkeyfilepathcannotbeNone' host1 host2 address split ' ' more_args ['ssh' '-i' keyfile '-o' 'StrictHostKeyChecking no' '-o' 'UserKnownHostsFile /dev/null' 'hadoop@%s' % host2 ]return _s...
94
python-test-826
python
How does the code send a request to the tool shed ?
via the tool shed api
def json from url url error message ''url handle urllib urlopen url url contents url handle read try parsed json json loads url contents except Exception as e error message str url contents print ' Errorparsing JSO Ndatainjson from url ' str e return None error message return parsed json error message
def json_from_url url error_message ''url_handle urllib urlopen url url_contents url_handle read try parsed_json json loads url_contents except Exception as e error_message str url_contents print 'ErrorparsingJSONdatainjson_from_url ' str e return None error_message return parsed_json error_message
52
python-test-827
python
What do tuples indicate ?
the path changes
def show path changes path changes sources destinations zip *path changes sources list map util displayable path sources destinations list map util displayable path destinations col width term width - len '->' // 2 max width len max sources + destinations key len if max width > col width for source dest in zip sources ...
def show_path_changes path_changes sources destinations zip *path_changes sources list map util displayable_path sources destinations list map util displayable_path destinations col_width term_width - len '->' // 2 max_width len max sources + destinations key len if max_width > col_width for source dest in zip sources ...
115
python-test-829
python
For what purpose does the code delete a temporary file from the script ?
so cleanup fails
def test temporary files failed cleanup caplog qtbot py proc runner cmd args py proc "\nimportos\nos remove os environ['QUTE HTML'] \n" with caplog at level logging ERROR with qtbot wait Signal runner finished timeout 10000 runner prepare run cmd *args runner store text '' runner store html '' assert len caplog records...
def test_temporary_files_failed_cleanup caplog qtbot py_proc runner cmd args py_proc "\nimportos\nos remove os environ['QUTE_HTML'] \n" with caplog at_level logging ERROR with qtbot waitSignal runner finished timeout 10000 runner prepare_run cmd *args runner store_text '' runner store_html '' assert len caplog records ...
63
python-test-836
python
What do this method use ?
to send text messages
def send message token chat id text disable web page preview None reply to message id None reply markup None parse mode None disable notification None method url 'send Message'payload {'chat id' str chat id 'text' text}if disable web page preview payload['disable web page preview'] disable web page previewif reply to m...
def send_message token chat_id text disable_web_page_preview None reply_to_message_id None reply_markup None parse_mode None disable_notification None method_url 'sendMessage'payload {'chat_id' str chat_id 'text' text}if disable_web_page_preview payload['disable_web_page_preview'] disable_web_page_previewif reply_to_me...
91
python-test-839
python
What does the code serve on a recommend port or a free one ?
the webapp
def serve webapp webapp port None host None server Noneif port is not None server httpserver serve webapp host host port port start loop False else random seed for i in range 0 9 try port str random randint 8000 10000 server httpserver serve webapp host host port port start loop False breakexcept socket error as e if e...
def serve_webapp webapp port None host None server Noneif port is not None server httpserver serve webapp host host port port start_loop False else random seed for i in range 0 9 try port str random randint 8000 10000 server httpserver serve webapp host host port port start_loop False breakexcept socket error as e if e...
83
python-test-840
python
What does the code get ?
a valid short number for the specified cost category
def example short number for cost region code cost metadata Phone Metadata short metadata for region region code if metadata is None return U EMPTY STRIN Gdesc Noneif cost Short Number Cost TOLL FREE desc metadata toll freeelif cost Short Number Cost STANDARD RATE desc metadata standard rateelif cost Short Number Cost ...
def _example_short_number_for_cost region_code cost metadata PhoneMetadata short_metadata_for_region region_code if metadata is None return U_EMPTY_STRINGdesc Noneif cost ShortNumberCost TOLL_FREE desc metadata toll_freeelif cost ShortNumberCost STANDARD_RATE desc metadata standard_rateelif cost ShortNumberCost PREMIUM...
77
python-test-844
python
What does the code redirect to the runners step - context object by using fake modules during step imports ?
any step / type registration
@contextmanagerdef use step import modules step container orig modules {}import context Step Import Module Context step container with step import lock try for module name fake module in six iteritems import context modules orig module sys modules get module name unknown orig modules[module name] orig modulesys modules...
@contextmanagerdef use_step_import_modules step_container orig_modules {}import_context StepImportModuleContext step_container with _step_import_lock try for module_name fake_module in six iteritems import_context modules orig_module sys modules get module_name unknown orig_modules[module_name] orig_modulesys modules[m...
78
python-test-845
python
When does the code redirect any step / type registration to the runners step - context object by using fake modules ?
during step imports
@contextmanagerdef use step import modules step container orig modules {}import context Step Import Module Context step container with step import lock try for module name fake module in six iteritems import context modules orig module sys modules get module name unknown orig modules[module name] orig modulesys modules...
@contextmanagerdef use_step_import_modules step_container orig_modules {}import_context StepImportModuleContext step_container with _step_import_lock try for module_name fake_module in six iteritems import_context modules orig_module sys modules get module_name unknown orig_modules[module_name] orig_modulesys modules[m...
78
python-test-846
python
How does the code redirect any step / type registration to the runners step - context object during step imports ?
by using fake modules
@contextmanagerdef use step import modules step container orig modules {}import context Step Import Module Context step container with step import lock try for module name fake module in six iteritems import context modules orig module sys modules get module name unknown orig modules[module name] orig modulesys modules...
@contextmanagerdef use_step_import_modules step_container orig_modules {}import_context StepImportModuleContext step_container with _step_import_lock try for module_name fake_module in six iteritems import_context modules orig_module sys modules get module_name unknown orig_modules[module_name] orig_modulesys modules[m...
78
python-test-855
python
What does the code create ?
new keys for fused tasks
def default fused keys renamer keys typ type keys[ 0 ] if typ is str or typ is unicode names [key split x for x in keys[ 0 -1 ]]names append keys[ 0 ] return '-' join names elif typ is tuple and len keys[ 0 ] > 0 and isinstance keys[ 0 ][ 0 ] str unicode names [key split x for x in keys[ 0 -1 ]]names append keys[ 0 ][ ...
def default_fused_keys_renamer keys typ type keys[0] if typ is str or typ is unicode names [key_split x for x in keys[ 0 -1 ]]names append keys[0] return '-' join names elif typ is tuple and len keys[0] > 0 and isinstance keys[0][0] str unicode names [key_split x for x in keys[ 0 -1 ]]names append keys[0][0] return '-'...
88
python-test-859
python
What does the code check ?
the symlink function
def symlink check name target force user group pchanges {}if not os path exists name and not salt ['file is link'] name pchanges['new'] namereturn None ' Symlink{ 0 }to{ 1 }issetforcreation' format name target pchanges if salt ['file is link'] name if salt ['file readlink'] name target pchanges['change'] namereturn Non...
def _symlink_check name target force user group pchanges {}if not os path exists name and not __salt__['file is_link'] name pchanges['new'] namereturn None 'Symlink{0}to{1}issetforcreation' format name target pchanges if __salt__['file is_link'] name if __salt__['file readlink'] name target pchanges['change'] nameretur...
139
python-test-862
python
What does the code retrieve if it exists or all certs ?
the attributes of a server certificate
def get server certs iam name None results dict try if name server certs [iam get server certificate Server Certificate Name name [' Server Certificate']]else server certs iam list server certificates [' Server Certificate Metadata List']for server cert in server certs if not name server cert iam get server certificate...
def get_server_certs iam name None results dict try if name server_certs [iam get_server_certificate ServerCertificateName name ['ServerCertificate']]else server_certs iam list_server_certificates ['ServerCertificateMetadataList']for server_cert in server_certs if not name server_cert iam get_server_certificate ServerC...
120
python-test-871
python
What does the code add ?
to result
def parse userdata options userdata options['userdata']if userdata try if userdata startswith '@' try with open userdata[ 1 ] as f return json load f except IO Error as e usage options ' Invaliduserdatafile {}' format e strerror else return json loads userdata except Value Error as e usage options ' Invaliduserdata {}'...
def parse_userdata options userdata options['userdata']if userdata try if userdata startswith '@' try with open userdata[1 ] as f return json load f except IOError as e usage options 'Invaliduserdatafile {}' format e strerror else return json loads userdata except ValueError as e usage options 'Invaliduserdata {}' form...
59
python-test-872
python
What does the code resize ?
partition and fileystem
def resize part and fs dev start old sectors new sectors size new sectors - start end new sectors - 1 dev path utils make dev path dev partition path utils make dev path dev partition 1 utils execute 'e 2 fsck' '-f' '-y' partition path run as root True check exit code [0 1 2] utils execute 'tune 2 fs' '-O^has journal' ...
def _resize_part_and_fs dev start old_sectors new_sectors size new_sectors - start end new_sectors - 1 dev_path utils make_dev_path dev partition_path utils make_dev_path dev partition 1 utils execute 'e2fsck' '-f' '-y' partition_path run_as_root True check_exit_code [0 1 2] utils execute 'tune2fs' '-O^has_journal' par...
149
python-test-873
python
What do tuples contain ?
weights and cost functions
def get cost functions cost fns conf CONF least cost functionsif cost fns conf is None fn str 'nova scheduler least cost compute fill first cost fn'cost fns conf [fn str]cost fns []for cost fn str in cost fns conf short name cost fn str split ' ' [ -1 ]if not short name startswith 'compute ' or short name startswith 'n...
def _get_cost_functions cost_fns_conf CONF least_cost_functionsif cost_fns_conf is None fn_str 'nova scheduler least_cost compute_fill_first_cost_fn'cost_fns_conf [fn_str]cost_fns []for cost_fn_str in cost_fns_conf short_name cost_fn_str split ' ' [ -1 ]if not short_name startswith 'compute_' or short_name startswith '...
164
python-test-874
python
When was that backup ( ) run ?
before the upgrade
def cleanup print green '%s Cleaningup' % env host with cd '/home/web 2 py/applications/eden/' run '/bin/rm-rfcompiled' pty True run 'find -name* BASE-print xargs/bin/rm-f' pty True run 'find -name* THIS-print xargs/bin/rm-f' pty True run 'foriin`find -name* OTHER` domv$i${i/ OTHER/} done' pty True run 'bzrresolve' pty...
def cleanup print green '%s Cleaningup' % env host with cd '/home/web2py/applications/eden/' run '/bin/rm-rfcompiled' pty True run 'find -name* BASE-print xargs/bin/rm-f' pty True run 'find -name* THIS-print xargs/bin/rm-f' pty True run 'foriin`find -name* OTHER` domv$i${i/ OTHER/} done' pty True run 'bzrresolve' pty T...
67
python-test-875
python
What do we want ?
pokedex
@parametrize 'varname' [attr for attr in dir tables if not attr startswith ' ' ] def test variable names varname table getattr tables varname try if not issubclass table tables Table Base or table is tables Table Base returnexcept Type Error returnclassname table name if classname and varname[ 0 ] isupper assert varnam...
@parametrize 'varname' [attr for attr in dir tables if not attr startswith '_' ] def test_variable_names varname table getattr tables varname try if not issubclass table tables TableBase or table is tables TableBase returnexcept TypeError returnclassname table __name__if classname and varname[0] isupper assert varname ...
58
python-test-878
python
What does line contain ?
a redundant " override " or " final " virt - specifier
def Check Redundant Override Or Final filename clean lines linenum error line clean lines elided[linenum]declarator end line rfind ' ' if declarator end > 0 fragment line[declarator end ]elif linenum > 1 and clean lines elided[ linenum - 1 ] rfind ' ' > 0 fragment lineelse returnif Search '\\boverride\\b' fragment and ...
def CheckRedundantOverrideOrFinal filename clean_lines linenum error line clean_lines elided[linenum]declarator_end line rfind ' ' if declarator_end > 0 fragment line[declarator_end ]elif linenum > 1 and clean_lines elided[ linenum - 1 ] rfind ' ' > 0 fragment lineelse returnif Search '\\boverride\\b' fragment and Sear...
61
python-test-879
python
For what purpose did the divisions shift ?
for the shift method
def maybe shift divisions df periods freq if isinstance freq str freq pd tseries frequencies to offset freq if isinstance freq pd Date Offset and freq is Anchored or not hasattr freq 'delta' return df clear divisions if df known divisions divs pd Series range len df divisions index df divisions divisions divs shift per...
def maybe_shift_divisions df periods freq if isinstance freq str freq pd tseries frequencies to_offset freq if isinstance freq pd DateOffset and freq isAnchored or not hasattr freq 'delta' return df clear_divisions if df known_divisions divs pd Series range len df divisions index df divisions divisions divs shift perio...
69
python-test-880
python
What used to shift the divisions for the shift method ?
periods of size freq
def maybe shift divisions df periods freq if isinstance freq str freq pd tseries frequencies to offset freq if isinstance freq pd Date Offset and freq is Anchored or not hasattr freq 'delta' return df clear divisions if df known divisions divs pd Series range len df divisions index df divisions divisions divs shift per...
def maybe_shift_divisions df periods freq if isinstance freq str freq pd tseries frequencies to_offset freq if isinstance freq pd DateOffset and freq isAnchored or not hasattr freq 'delta' return df clear_divisions if df known_divisions divs pd Series range len df divisions index df divisions divisions divs shift perio...
69
python-test-881
python
When do divisions shift maybe maybe ?
by periods of size
def maybe shift divisions df periods freq if isinstance freq str freq pd tseries frequencies to offset freq if isinstance freq pd Date Offset and freq is Anchored or not hasattr freq 'delta' return df clear divisions if df known divisions divs pd Series range len df divisions index df divisions divisions divs shift per...
def maybe_shift_divisions df periods freq if isinstance freq str freq pd tseries frequencies to_offset freq if isinstance freq pd DateOffset and freq isAnchored or not hasattr freq 'delta' return df clear_divisions if df known_divisions divs pd Series range len df divisions index df divisions divisions divs shift perio...
69
python-test-882
python
What did periods of size freq use ?
to shift the divisions for the shift method
def maybe shift divisions df periods freq if isinstance freq str freq pd tseries frequencies to offset freq if isinstance freq pd Date Offset and freq is Anchored or not hasattr freq 'delta' return df clear divisions if df known divisions divs pd Series range len df divisions index df divisions divisions divs shift per...
def maybe_shift_divisions df periods freq if isinstance freq str freq pd tseries frequencies to_offset freq if isinstance freq pd DateOffset and freq isAnchored or not hasattr freq 'delta' return df clear_divisions if df known_divisions divs pd Series range len df divisions index df divisions divisions divs shift perio...
69
python-test-883
python
Where did speeds give ?
in kbps
def humanize speed speed if speed > 1000000000 and speed % 1000000000 0 return '{} Tbps' format speed / 1000000000 elif speed > 1000000 and speed % 1000000 0 return '{} Gbps' format speed / 1000000 elif speed > 1000 and speed % 1000 0 return '{} Mbps' format speed / 1000 elif speed > 1000 return '{} Mbps' format float ...
def humanize_speed speed if speed > 1000000000 and speed % 1000000000 0 return '{}Tbps' format speed / 1000000000 elif speed > 1000000 and speed % 1000000 0 return '{}Gbps' format speed / 1000000 elif speed > 1000 and speed % 1000 0 return '{}Mbps' format speed / 1000 elif speed > 1000 return '{}Mbps' format float spee...
70
python-test-884
python
What given in kbps ?
speeds
def humanize speed speed if speed > 1000000000 and speed % 1000000000 0 return '{} Tbps' format speed / 1000000000 elif speed > 1000000 and speed % 1000000 0 return '{} Gbps' format speed / 1000000 elif speed > 1000 and speed % 1000 0 return '{} Mbps' format speed / 1000 elif speed > 1000 return '{} Mbps' format float ...
def humanize_speed speed if speed > 1000000000 and speed % 1000000000 0 return '{}Tbps' format speed / 1000000000 elif speed > 1000000 and speed % 1000000 0 return '{}Gbps' format speed / 1000000 elif speed > 1000 and speed % 1000 0 return '{}Mbps' format speed / 1000 elif speed > 1000 return '{}Mbps' format float spee...
70
python-test-885
python
What does the code convert into postgis raster format ?
a gdalraster
def to pgraster rast if rast is None or rast '' returnrasterheader 1 0 len rast bands rast scale x rast scale y rast origin x rast origin y rast skew x rast skew y rast srs srid rast width rast height result pack POSTGIS HEADER STRUCTURE rasterheader for band in rast bands structure 'B' + GDAL TO STRUCT[band datatype ]...
def to_pgraster rast if rast is None or rast '' returnrasterheader 1 0 len rast bands rast scale x rast scale y rast origin x rast origin y rast skew x rast skew y rast srs srid rast width rast height result pack POSTGIS_HEADER_STRUCTURE rasterheader for band in rast bands structure 'B' + GDAL_TO_STRUCT[band datatype ]...
106
python-test-891
python
What does the code allow ?
a new user to register an account
def register request success url None form class Registration Form profile callback None template name 'registration/registration form html' extra context None if request method 'POST' form form class data request POST files request FILES if form is valid new user form save profile callback profile callback return Http...
def register request success_url None form_class RegistrationForm profile_callback None template_name 'registration/registration_form html' extra_context None if request method 'POST' form form_class data request POST files request FILES if form is_valid new_user form save profile_callback profile_callback return HttpR...
96
python-test-892
python
What does the code ensure ?
that a widget too small to hold the entire label text will elide
@pytest mark parametrize 'elidemode check' [ Qt Elide Right lambda s s endswith '\xe 2 \x 80 \xa 6 ' or s endswith ' ' Qt Elide Left lambda s s startswith '\xe 2 \x 80 \xa 6 ' or s startswith ' ' Qt Elide Middle lambda s '\xe 2 \x 80 \xa 6 ' in s or ' ' in s Qt Elide None lambda s '\xe 2 \x 80 \xa 6 ' not in s and ' ' ...
@pytest mark parametrize 'elidemode check' [ Qt ElideRight lambda s s endswith '\xe2\x80\xa6' or s endswith ' ' Qt ElideLeft lambda s s startswith '\xe2\x80\xa6' or s startswith ' ' Qt ElideMiddle lambda s '\xe2\x80\xa6' in s or ' ' in s Qt ElideNone lambda s '\xe2\x80\xa6' not in s and ' ' not in s ] def test_elided_t...
128
python-test-896
python
Where do account deactivate ?
on server
def unregister config unused plugins account storage account Account File Storage config accounts account storage find all reporter util zope component get Utility interfaces I Reporter if not accounts return ' Couldnotfindexistingaccounttodeactivate 'yesno zope component get Utility interfaces I Display yesnoprompt ' ...
def unregister config unused_plugins account_storage account AccountFileStorage config accounts account_storage find_all reporter_util zope component getUtility interfaces IReporter if not accounts return 'Couldnotfindexistingaccounttodeactivate 'yesno zope component getUtility interfaces IDisplay yesnoprompt 'Areyousu...
109
python-test-897
python
What does the code agree ?
to remove on close
@contextmanagerdef ensure clean filename None return filelike False filename filename or '' fd Noneif return filelike f tempfile Temporary File suffix filename try yield f finally f close else if len os path dirname filename raise Value Error " Can'tpassaqualifiednametoensure clean " try fd filename tempfile mkstemp su...
@contextmanagerdef ensure_clean filename None return_filelike False filename filename or '' fd Noneif return_filelike f tempfile TemporaryFile suffix filename try yield f finally f close else if len os path dirname filename raise ValueError "Can'tpassaqualifiednametoensure_clean " try fd filename tempfile mkstemp suffi...
100
python-test-898
python
When was this event generated ?
the server x time
def event 2 json event return jdumps dict type event type send event event send event time event time root str event root window str event window same screen event same screen child str event child root x event root x root y event root y event x event event x event y event event y state event state detail event detail
def event2json event return jdumps dict type event type send_event event send_event time event time root str event root window str event window same_screen event same_screen child str event child root_x event root_x root_y event root_y event_x event event_x event_y event event_y state event state detail event detail
62
python-test-902
python
How does the code estimate the taylor polynomial of f at x ?
by polynomial fitting
def approximate taylor polynomial f x degree scale order None if order is None order degreen order + 1 xs scale * np cos np linspace 0 np pi n endpoint n % 1 + x P Krogh Interpolator xs f xs d P derivatives x der degree + 1 return np poly 1 d d / factorial np arange degree + 1 [ -1 ]
def approximate_taylor_polynomial f x degree scale order None if order is None order degreen order + 1 xs scale * np cos np linspace 0 np pi n endpoint n % 1 + x P KroghInterpolator xs f xs d P derivatives x der degree + 1 return np poly1d d / factorial np arange degree + 1 [ -1 ]
66
python-test-903
python
What does the code estimate by polynomial fitting at x ?
the taylor polynomial of f
def approximate taylor polynomial f x degree scale order None if order is None order degreen order + 1 xs scale * np cos np linspace 0 np pi n endpoint n % 1 + x P Krogh Interpolator xs f xs d P derivatives x der degree + 1 return np poly 1 d d / factorial np arange degree + 1 [ -1 ]
def approximate_taylor_polynomial f x degree scale order None if order is None order degreen order + 1 xs scale * np cos np linspace 0 np pi n endpoint n % 1 + x P KroghInterpolator xs f xs d P derivatives x der degree + 1 return np poly1d d / factorial np arange degree + 1 [ -1 ]
66
python-test-904
python
How do the packages provide the given command ?
using pkgfile
@utils memoizedef get pkgfile command try command command strip if command startswith 'sudo' command command[ 5 ]command command split '' [0 ]packages subprocess check output ['pkgfile' '-b' '-v' command] universal newlines True stderr utils DEVNULL splitlines return [package split [0 ] for package in packages]except s...
@utils memoizedef get_pkgfile command try command command strip if command startswith 'sudo' command command[5 ]command command split '' [0]packages subprocess check_output ['pkgfile' '-b' '-v' command] universal_newlines True stderr utils DEVNULL splitlines return [package split [0] for package in packages]except subp...
51
python-test-905
python
What does the code get ?
the packages that provide the given command using pkgfile
@utils memoizedef get pkgfile command try command command strip if command startswith 'sudo' command command[ 5 ]command command split '' [0 ]packages subprocess check output ['pkgfile' '-b' '-v' command] universal newlines True stderr utils DEVNULL splitlines return [package split [0 ] for package in packages]except s...
@utils memoizedef get_pkgfile command try command command strip if command startswith 'sudo' command command[5 ]command command split '' [0]packages subprocess check_output ['pkgfile' '-b' '-v' command] universal_newlines True stderr utils DEVNULL splitlines return [package split [0] for package in packages]except subp...
51
python-test-907
python
What did the code read ?
the modules parameters
def load params global ANSIBLE ARG Sif ANSIBLE ARGS is not None buffer ANSIBLE ARG Selse if len sys argv > 1 if os path isfile sys argv[ 1 ] fd open sys argv[ 1 ] 'rb' buffer fd read fd close else buffer sys argv[ 1 ]if PY 3 buffer buffer encode 'utf- 8 ' errors 'surrogateescape' elif PY 2 buffer sys stdin read else bu...
def _load_params global _ANSIBLE_ARGSif _ANSIBLE_ARGS is not None buffer _ANSIBLE_ARGSelse if len sys argv > 1 if os path isfile sys argv[1] fd open sys argv[1] 'rb' buffer fd read fd close else buffer sys argv[1]if PY3 buffer buffer encode 'utf-8' errors 'surrogateescape' elif PY2 buffer sys stdin read else buffer sys...
128
python-test-908
python
How do a regex string return ?
based on a provided strftime timestring
def get date regex timestring prev ''curr ''regex ''for s in range 0 len timestring curr timestring[s]if curr '%' passelif curr in settings date regex and prev '%' regex + '\\d{' + settings date regex [curr] + '}' elif curr in [' ' '-'] regex + '\\' + curr else regex + currprev currlogger debug 'regex {0 }' format rege...
def get_date_regex timestring prev ''curr ''regex ''for s in range 0 len timestring curr timestring[s]if curr '%' passelif curr in settings date_regex and prev '%' regex + '\\d{' + settings date_regex [curr] + '}' elif curr in [' ' '-'] regex + '\\' + curr else regex + currprev currlogger debug 'regex {0}' format regex...
62
python-test-911
python
What updates at pathtozip ?
files in the zip file
def update pathtozip patterns filepaths names compression zipfile ZIP DEFLATED verbose True assert len patterns len filepaths len names z zipfile Zip File pathtozip mode 'a' for name in z namelist for pat fname new name in zip patterns filepaths names if pat search name if verbose print ' Updating%swith%s' % name fname...
def update pathtozip patterns filepaths names compression zipfile ZIP_DEFLATED verbose True assert len patterns len filepaths len names z zipfile ZipFile pathtozip mode 'a' for name in z namelist for pat fname new_name in zip patterns filepaths names if pat search name if verbose print 'Updating%swith%s' % name fname i...
80
python-test-912
python
Where do files in the zip file update matching the given patterns ?
at pathtozip
def update pathtozip patterns filepaths names compression zipfile ZIP DEFLATED verbose True assert len patterns len filepaths len names z zipfile Zip File pathtozip mode 'a' for name in z namelist for pat fname new name in zip patterns filepaths names if pat search name if verbose print ' Updating%swith%s' % name fname...
def update pathtozip patterns filepaths names compression zipfile ZIP_DEFLATED verbose True assert len patterns len filepaths len names z zipfile ZipFile pathtozip mode 'a' for name in z namelist for pat fname new_name in zip patterns filepaths names if pat search name if verbose print 'Updating%swith%s' % name fname i...
80
python-test-913
python
What does the code make ?
sure helper wo nt choke on unicode input
def test user link unicode u User Profile username u'jm\xfcller' display name u'J\xfcrgen M\xfcller' pk 1 assert user link u u'<ahref "%s"title "%s">J\xfcrgen M\xfcller</a>' % u get url path u name u User Profile username '\xe 5 \xaf\x 92 \xe 6 \x 98 \x 9 f' pk 1 assert user link u u'<ahref "%s"title "%s">%s</a>' % u g...
def test_user_link_unicode u UserProfile username u'jm\xfcller' display_name u'J\xfcrgenM\xfcller' pk 1 assert user_link u u'<ahref "%s"title "%s">J\xfcrgenM\xfcller</a>' % u get_url_path u name u UserProfile username '\xe5\xaf\x92\xe6\x98\x9f' pk 1 assert user_link u u'<ahref "%s"title "%s">%s</a>' % u get_url_path u ...
64
python-test-914
python
What does the code create ?
the unittest test runner with xml output
def create xml runner test pkg test name results file None is rostest False test name os path basename test name if not results file results file xml results file test pkg test name is rostest test dir os path abspath os path dirname results file if not os path exists test dir try makedirs with parent perms test dir ex...
def create_xml_runner test_pkg test_name results_file None is_rostest False test_name os path basename test_name if not results_file results_file xml_results_file test_pkg test_name is_rostest test_dir os path abspath os path dirname results_file if not os path exists test_dir try makedirs_with_parent_perms test_dir ex...
115
python-test-918
python
What does the code add ?
the path to the flat loops
def is Path Added edges faces loops remaining Edge Table vertexes z if len remaining Edge Table < 1 return Falsepath Indexes []remaining Edge Index Key remaining Edge Table keys [0 ]path Indexes append remaining Edge Index Key del remaining Edge Table[remaining Edge Index Key]next Edge Index Around Z get Next Edge Inde...
def isPathAdded edges faces loops remainingEdgeTable vertexes z if len remainingEdgeTable < 1 return FalsepathIndexes []remainingEdgeIndexKey remainingEdgeTable keys [0]pathIndexes append remainingEdgeIndexKey del remainingEdgeTable[remainingEdgeIndexKey]nextEdgeIndexAroundZ getNextEdgeIndexAroundZ edges[remainingEdgeI...
131
python-test-919
python
What does the code get ?
the path indexes around a triangle mesh carve
def is Path Added edges faces loops remaining Edge Table vertexes z if len remaining Edge Table < 1 return Falsepath Indexes []remaining Edge Index Key remaining Edge Table keys [0 ]path Indexes append remaining Edge Index Key del remaining Edge Table[remaining Edge Index Key]next Edge Index Around Z get Next Edge Inde...
def isPathAdded edges faces loops remainingEdgeTable vertexes z if len remainingEdgeTable < 1 return FalsepathIndexes []remainingEdgeIndexKey remainingEdgeTable keys [0]pathIndexes append remainingEdgeIndexKey del remainingEdgeTable[remainingEdgeIndexKey]nextEdgeIndexAroundZ getNextEdgeIndexAroundZ edges[remainingEdgeI...
131
python-test-924
python
What does the code get from its name ?
python method object
def get attr method string app name method string split u' ' [0 ]if not local flags in install and app name not in get installed apps throw u' App{ 0 }isnotinstalled' format app name App Not Installed Error modulename u' ' join method string split u' ' [ -1 ] methodname method string split u' ' [ -1 ]return getattr get...
def get_attr method_string app_name method_string split u' ' [0]if not local flags in_install and app_name not in get_installed_apps throw _ u'App{0}isnotinstalled' format app_name AppNotInstalledError modulename u' ' join method_string split u' ' [ -1 ] methodname method_string split u' ' [ -1 ]return getattr get_modu...
65
python-test-927
python
What do json update ?
the portfolio editor
def gimme json for portfolio request "JSO Nincludes \n* Theperson'sdata \n*otherstuff"if not request user is authenticated return Http Response Server Error " Oops you'renotloggedin " person request user get profile citations list Citation untrashed filter portfolio entry person person portfolio entries unserialized Po...
def gimme_json_for_portfolio request "JSONincludes \n*Theperson'sdata \n*otherstuff"if not request user is_authenticated return HttpResponseServerError "Oops you'renotloggedin " person request user get_profile citations list Citation untrashed filter portfolio_entry__person person portfolio_entries_unserialized Portfol...
132
python-test-928
python
What are stored the folder ?
the wav and segment files
def speaker Diarization Evaluate Script folder Name LD As types '* wav' wav Files List []for files in types wav Files List extend glob glob os path join folder Name files wav Files List sorted wav Files List N []for wav File in wav Files List gt File wav File replace ' wav' ' segments' if os path isfile gt File [seg St...
def speakerDiarizationEvaluateScript folderName LDAs types '* wav' wavFilesList []for files in types wavFilesList extend glob glob os path join folderName files wavFilesList sorted wavFilesList N []for wavFile in wavFilesList gtFile wavFile replace ' wav' ' segments' if os path isfile gtFile [segStart segEnd segLabels]...
118
python-test-929
python
What does this function print ?
the cluster purity and speaker purity for each wav file stored in a provided directory arguments : - foldername : the full path of the folder where the wav and segment files are stored - ldas : a list of lda dimensions
def speaker Diarization Evaluate Script folder Name LD As types '* wav' wav Files List []for files in types wav Files List extend glob glob os path join folder Name files wav Files List sorted wav Files List N []for wav File in wav Files List gt File wav File replace ' wav' ' segments' if os path isfile gt File [seg St...
def speakerDiarizationEvaluateScript folderName LDAs types '* wav' wavFilesList []for files in types wavFilesList extend glob glob os path join folderName files wavFilesList sorted wavFilesList N []for wavFile in wavFilesList gtFile wavFile replace ' wav' ' segments' if os path isfile gtFile [segStart segEnd segLabels]...
118
python-test-930
python
What does the code get ?
the default hyperparameters
def get default hparams return H Params batch size 64 residual blocks 2 n couplings 2 n scale 4 learning rate 0 001 momentum 0 1 decay 0 001 l2 coeff 5e- 05 clip gradient 100 0 optimizer 'adam' dropout mask 0 base dim 32 bottleneck 0 use batch norm 1 alternate 1 use aff 1 skip 1 data constraint 0 9 n opt 0
def get_default_hparams return HParams batch_size 64 residual_blocks 2 n_couplings 2 n_scale 4 learning_rate 0 001 momentum 0 1 decay 0 001 l2_coeff 5e-05 clip_gradient 100 0 optimizer 'adam' dropout_mask 0 base_dim 32 bottleneck 0 use_batch_norm 1 alternate 1 use_aff 1 skip 1 data_constraint 0 9 n_opt 0
65
python-test-931
python
What takes a user - friendly msg as argument optionally ?
decorator for printing execution time of a function
def print timing msg None debug False prefix msgif isinstance msg types Function Type prefix msg func namedef wrap f func *arg **kargs ' Rawtimingfunction'time 1 time time res func *arg **kargs time 2 time time msg '%stook% 0 3fmins' % prefix time 2 - time 1 / 60 0 if debug log debug msg else log info msg return resif ...
def print_timing msg None debug False prefix msgif isinstance msg types FunctionType prefix msg func_namedef wrap_f func *arg **kargs 'Rawtimingfunction'time1 time time res func *arg **kargs time2 time time msg '%stook%0 3fmins' % prefix time2 - time1 / 60 0 if debug log debug msg else log info msg return resif isinsta...
78
python-test-932
python
What does decorator for printing execution time of a function take as argument optionally ?
a user - friendly msg
def print timing msg None debug False prefix msgif isinstance msg types Function Type prefix msg func namedef wrap f func *arg **kargs ' Rawtimingfunction'time 1 time time res func *arg **kargs time 2 time time msg '%stook% 0 3fmins' % prefix time 2 - time 1 / 60 0 if debug log debug msg else log info msg return resif ...
def print_timing msg None debug False prefix msgif isinstance msg types FunctionType prefix msg func_namedef wrap_f func *arg **kargs 'Rawtimingfunction'time1 time time res func *arg **kargs time2 time time msg '%stook%0 3fmins' % prefix time2 - time1 / 60 0 if debug log debug msg else log info msg return resif isinsta...
78
python-test-934
python
What does csv contain ?
a summary of all registration codes
@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' @require POS Tdef get registration codes request course id course id Slash Separated Course Key from deprecated string course id registration codes Course Registration Code objects filter course id course id order ...
@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' @require_POSTdef get_registration_codes request course_id course_id SlashSeparatedCourseKey from_deprecated_string course_id registration_codes CourseRegistrationCode objects filter course_id course_id order_by 'in...
88
python-test-935
python
How does the collection return ?
with the given alias
def get collection by alias bus alias service obj bus get object bus SS PATH service iface dbus Interface service obj SERVICE IFACE collection path service iface Read Alias alias signature 's' if len collection path < 1 raise Item Not Found Exception ' Nocollectionwithsuchalias ' return Collection bus collection path
def get_collection_by_alias bus alias service_obj bus_get_object bus SS_PATH service_iface dbus Interface service_obj SERVICE_IFACE collection_path service_iface ReadAlias alias signature 's' if len collection_path < 1 raise ItemNotFoundException 'Nocollectionwithsuchalias ' return Collection bus collection_path
51
python-test-936
python
What does the code get ?
either the hub given by the environment variable samp_hub
def get main running hub hubs get running hubs if not hubs raise SAMP Hub Error u' Unabletofindarunning SAMP Hub ' if u'SAMP HUB' in os environ if os environ[u'SAMP HUB'] startswith u'std-lockurl ' lockfilename os environ[u'SAMP HUB'][len u'std-lockurl ' ]else raise SAMP Hub Error u'SAMP Hubprofilenotsupported ' else l...
def get_main_running_hub hubs get_running_hubs if not hubs raise SAMPHubError u'UnabletofindarunningSAMPHub ' if u'SAMP_HUB' in os environ if os environ[u'SAMP_HUB'] startswith u'std-lockurl ' lockfilename os environ[u'SAMP_HUB'][len u'std-lockurl ' ]else raise SAMPHubError u'SAMPHubprofilenotsupported ' else lockfilen...
59
python-test-937
python
What does the code create ?
the user account with the email address and password provided
def create appscale user password uaserver does user exist uaserver does user exist hermes constants USER EMAIL appscale info get secret if does user exist 'true' logging debug ' User{ 0 }alreadyexists sonotcreatingitagain ' format hermes constants USER EMAIL return Trueelif uaserver commit new user hermes constants US...
def create_appscale_user password uaserver does_user_exist uaserver does_user_exist hermes_constants USER_EMAIL appscale_info get_secret if does_user_exist 'true' logging debug 'User{0}alreadyexists sonotcreatingitagain ' format hermes_constants USER_EMAIL return Trueelif uaserver commit_new_user hermes_constants USER_...
69
python-test-940
python
What does the code create ?
a hard link for the volume block device
def make link volume path backup path vol id try utils execute 'ln' volume path backup path run as root True check exit code True except processutils Process Execution Error as exc err 'backup % vol id sfailedtocreatedevicehardlinkfrom% vpath sto% bpath s \nstdout % out s\nstderr % err s' % {'vol id' vol id 'vpath' vol...
def _make_link volume_path backup_path vol_id try utils execute 'ln' volume_path backup_path run_as_root True check_exit_code True except processutils ProcessExecutionError as exc err _ 'backup % vol_id sfailedtocreatedevicehardlinkfrom% vpath sto% bpath s \nstdout % out s\nstderr % err s' % {'vol_id' vol_id 'vpath' vo...
75
python-test-942
python
What does the code compare by billingpos ?
two people
def cmp People p1 p2 p1 b getattr p1 'billing Pos' None or last p2 b getattr p2 'billing Pos' None or last if p1 b > p2 b return 1if p1 b < p2 b return -1 p1 n p1 get 'canonicalname' last p2 n p2 get 'canonicalname' last if p1 n is last and p2 n is last p1 n p1 get 'name' last p2 n p2 get 'name' last if p1 n > p2 n ret...
def cmpPeople p1 p2 p1b getattr p1 'billingPos' None or _last p2b getattr p2 'billingPos' None or _last if p1b > p2b return 1if p1b < p2b return -1 p1n p1 get 'canonicalname' _last p2n p2 get 'canonicalname' _last if p1n is _last and p2n is _last p1n p1 get 'name' _last p2n p2 get 'name' _last if p1n > p2n return 1if p...
118
python-test-943
python
How does the code compare two people ?
by billingpos
def cmp People p1 p2 p1 b getattr p1 'billing Pos' None or last p2 b getattr p2 'billing Pos' None or last if p1 b > p2 b return 1if p1 b < p2 b return -1 p1 n p1 get 'canonicalname' last p2 n p2 get 'canonicalname' last if p1 n is last and p2 n is last p1 n p1 get 'name' last p2 n p2 get 'name' last if p1 n > p2 n ret...
def cmpPeople p1 p2 p1b getattr p1 'billingPos' None or _last p2b getattr p2 'billingPos' None or _last if p1b > p2b return 1if p1b < p2b return -1 p1n p1 get 'canonicalname' _last p2n p2 get 'canonicalname' _last if p1n is _last and p2n is _last p1n p1 get 'name' _last p2n p2 get 'name' _last if p1n > p2n return 1if p...
118
python-test-952
python
What does the code find ?
paths to label files in a subjects label directory
def find label paths subject 'fsaverage' pattern None subjects dir None subjects dir get subjects dir subjects dir raise error True subject dir os path join subjects dir subject lbl dir os path join subject dir 'label' if pattern is None paths []for dirpath filenames in os walk lbl dir rel dir os path relpath dirpath l...
def _find_label_paths subject 'fsaverage' pattern None subjects_dir None subjects_dir get_subjects_dir subjects_dir raise_error True subject_dir os path join subjects_dir subject lbl_dir os path join subject_dir 'label' if pattern is None paths []for dirpath _ filenames in os walk lbl_dir rel_dir os path relpath dirpat...
91
python-test-953
python
Where do files label ?
in a subjects label directory
def find label paths subject 'fsaverage' pattern None subjects dir None subjects dir get subjects dir subjects dir raise error True subject dir os path join subjects dir subject lbl dir os path join subject dir 'label' if pattern is None paths []for dirpath filenames in os walk lbl dir rel dir os path relpath dirpath l...
def _find_label_paths subject 'fsaverage' pattern None subjects_dir None subjects_dir get_subjects_dir subjects_dir raise_error True subject_dir os path join subjects_dir subject lbl_dir os path join subject_dir 'label' if pattern is None paths []for dirpath _ filenames in os walk lbl_dir rel_dir os path relpath dirpat...
91
python-test-954
python
What does this test ?
the memory for read and write operations
def memory memory oper ['read' 'write']memory scope ['local' 'global']test command 'sysbench--num-threads 64 --test memory'test command + '--memory-oper {0 }--memory-scope {1 }'test command + '--memory-block-size 1K--memory-total-size 32 Grun'result Noneret val {}for oper in memory oper for scope in memory scope key ' ...
def memory memory_oper ['read' 'write']memory_scope ['local' 'global']test_command 'sysbench--num-threads 64--test memory'test_command + '--memory-oper {0}--memory-scope {1}'test_command + '--memory-block-size 1K--memory-total-size 32Grun'result Noneret_val {}for oper in memory_oper for scope in memory_scope key 'Opera...
70
python-test-955
python
What does the code create ?
a devicefunctiontemplate object
def compile device template pyfunc debug False inline False from descriptor import CUDA Target Descdft Device Function Template pyfunc debug debug inline inline class device function template Abstract Template key dftdef generic self args kws assert not kws return dft compile args typingctx CUDA Target Desc typingctxty...
def compile_device_template pyfunc debug False inline False from descriptor import CUDATargetDescdft DeviceFunctionTemplate pyfunc debug debug inline inline class device_function_template AbstractTemplate key dftdef generic self args kws assert not kws return dft compile args typingctx CUDATargetDesc typingctxtypingctx...
56
python-test-956
python
What do c convert ?
to an rgba color
def to rgba c alpha None if is nth color c from matplotlib import rc Paramsprop cycler rc Params[u'axes prop cycle']colors prop cycler by key get u'color' [u'k'] c colors[ int c[ 1 ] % len colors ]try rgba colors full map cache[ c alpha ]except Key Error Type Error rgba to rgba no colorcycle c alpha try colors full map...
def to_rgba c alpha None if _is_nth_color c from matplotlib import rcParamsprop_cycler rcParams[u'axes prop_cycle']colors prop_cycler by_key get u'color' [u'k'] c colors[ int c[1] % len colors ]try rgba _colors_full_map cache[ c alpha ]except KeyError TypeError rgba _to_rgba_no_colorcycle c alpha try _colors_full_map c...
70
python-test-958
python
What is logged on the given publisher ?
any error
def stop On Error case reactor publisher None if publisher is None from twisted python import log as publisherrunning [ None]def stop If Error event if running and event get 'is Error' running pop reactor stop publisher add Observer stop If Error case add Cleanup publisher remove Observer stop If Error
def stopOnError case reactor publisher None if publisher is None from twisted python import log as publisherrunning [None]def stopIfError event if running and event get 'isError' running pop reactor stop publisher addObserver stopIfError case addCleanup publisher removeObserver stopIfError
51
python-test-959
python
Where is any error logged ?
on the given publisher
def stop On Error case reactor publisher None if publisher is None from twisted python import log as publisherrunning [ None]def stop If Error event if running and event get 'is Error' running pop reactor stop publisher add Observer stop If Error case add Cleanup publisher remove Observer stop If Error
def stopOnError case reactor publisher None if publisher is None from twisted python import log as publisherrunning [None]def stopIfError event if running and event get 'isError' running pop reactor stop publisher addObserver stopIfError case addCleanup publisher removeObserver stopIfError
51
python-test-960
python
When does the code stop the reactor ?
as soon as any error is logged on the given publisher
def stop On Error case reactor publisher None if publisher is None from twisted python import log as publisherrunning [ None]def stop If Error event if running and event get 'is Error' running pop reactor stop publisher add Observer stop If Error case add Cleanup publisher remove Observer stop If Error
def stopOnError case reactor publisher None if publisher is None from twisted python import log as publisherrunning [None]def stopIfError event if running and event get 'isError' running pop reactor stop publisher addObserver stopIfError case addCleanup publisher removeObserver stopIfError
51
python-test-964
python
What does the code fetch ?
the hcp - mmp parcellation
@verbosedef fetch hcp mmp parcellation subjects dir None verbose None subjects dir get subjects dir subjects dir raise error True destination op join subjects dir 'fsaverage' 'label' fnames [op join destination 'lh HCPMMP 1 annot' op join destination 'rh HCPMMP 1 annot' ]if all op isfile fname for fname in fnames retur...
@verbosedef fetch_hcp_mmp_parcellation subjects_dir None verbose None subjects_dir get_subjects_dir subjects_dir raise_error True destination op join subjects_dir 'fsaverage' 'label' fnames [op join destination 'lh HCPMMP1 annot' op join destination 'rh HCPMMP1 annot' ]if all op isfile fname for fname in fnames returni...
136
python-test-966
python
What does the code normalize ?
a resource url
def normalize resource url resource url try protocol name split resource url resource url except Value Error protocol u'nltk'name resource urlif protocol u'nltk' and os path isabs name protocol u'file //'name normalize resource name name False None elif protocol u'file' protocol u'file //'name normalize resource name n...
def normalize_resource_url resource_url try protocol name split_resource_url resource_url except ValueError protocol u'nltk'name resource_urlif protocol u'nltk' and os path isabs name protocol u'file //'name normalize_resource_name name False None elif protocol u'file' protocol u'file //'name normalize_resource_name na...
69
python-test-970
python
What did we use for both column access and selections ?
getitem
def test from castra with selection castra pytest importorskip 'castra' blosc pytest importorskip 'blosc' if Loose Version blosc version '1 3 0' or Loose Version castra version < '0 1 8' pytest skip df pd Data Frame {'x' ['a' 'b' 'c' 'd'] 'y' [2 3 4 5]} index pd Index [1 0 2 0 3 0 4 0] name 'ind' a dd from pandas df 2 ...
def test_from_castra_with_selection castra pytest importorskip 'castra' blosc pytest importorskip 'blosc' if LooseVersion blosc __version__ '1 3 0' or LooseVersion castra __version__ < '0 1 8' pytest skip df pd DataFrame {'x' ['a' 'b' 'c' 'd'] 'y' [2 3 4 5]} index pd Index [1 0 2 0 3 0 4 0] name 'ind' a dd from_pandas ...
89
python-test-982
python
What does the code create ?
a suitable apierror from requests
def create api error from http exception e response e responsetry explanation response json ['message']except Value Error explanation response content strip cls API Errorif response status code 404 if explanation and ' Nosuchimage' in str explanation or 'notfound doesnotexistornoreadaccess' in str explanation cls Image...
def create_api_error_from_http_exception e response e responsetry explanation response json ['message']except ValueError explanation response content strip cls APIErrorif response status_code 404 if explanation and 'Nosuchimage' in str explanation or 'notfound doesnotexistornoreadaccess' in str explanation cls ImageNot...
55
python-test-983
python
What do decorator error ?
migration on failure
@utils expects func args 'migration' def errors out migration function @functools wraps function def decorated function self context *args **kwargs try return function self context *args **kwargs except Exception as ex with excutils save and reraise exception wrapped func safe utils get wrapped function function keyed ...
@utils expects_func_args 'migration' def errors_out_migration function @functools wraps function def decorated_function self context *args **kwargs try return function self context *args **kwargs except Exception as ex with excutils save_and_reraise_exception wrapped_func safe_utils get_wrapped_function function keyed_...
99
python-test-984
python
What used to identify a particular task ?
a canonical string
def task id str task family params param str json dumps params separators ' ' ' ' sort keys True param hash hashlib md 5 param str encode 'utf- 8 ' hexdigest param summary ' ' join p[ TASK ID TRUNCATE PARAMS] for p in params[p] for p in sorted params [ TASK ID INCLUDE PARAMS] param summary TASK ID INVALID CHAR REGEX su...
def task_id_str task_family params param_str json dumps params separators ' ' ' ' sort_keys True param_hash hashlib md5 param_str encode 'utf-8' hexdigest param_summary '_' join p[ TASK_ID_TRUNCATE_PARAMS] for p in params[p] for p in sorted params [ TASK_ID_INCLUDE_PARAMS] param_summary TASK_ID_INVALID_CHAR_REGEX sub '...
83
python-test-985
python
What did a canonical string use ?
to identify a particular task
def task id str task family params param str json dumps params separators ' ' ' ' sort keys True param hash hashlib md 5 param str encode 'utf- 8 ' hexdigest param summary ' ' join p[ TASK ID TRUNCATE PARAMS] for p in params[p] for p in sorted params [ TASK ID INCLUDE PARAMS] param summary TASK ID INVALID CHAR REGEX su...
def task_id_str task_family params param_str json dumps params separators ' ' ' ' sort_keys True param_hash hashlib md5 param_str encode 'utf-8' hexdigest param_summary '_' join p[ TASK_ID_TRUNCATE_PARAMS] for p in params[p] for p in sorted params [ TASK_ID_INCLUDE_PARAMS] param_summary TASK_ID_INVALID_CHAR_REGEX sub '...
83
python-test-987
python
What does the code validate ?
the structure of a configuration section
def validate config section filename config section if not isinstance config dict raise Configuration Error u" Infile'{filename}' {section}mustbeamapping not{type} " format filename filename section section type anglicize json type python type to yaml type config for key value in config items if not isinstance key six ...
def validate_config_section filename config section if not isinstance config dict raise ConfigurationError u"Infile'{filename}' {section}mustbeamapping not{type} " format filename filename section section type anglicize_json_type python_type_to_yaml_type config for key value in config items if not isinstance key six st...
96
python-test-991
python
What do parse_one_rule_from_dict parse ?
a redactionrule from a dictionary like : " description " : " this is the first rule "
def parse one rule from dict rule rule pop 'description' None trigger rule pop 'trigger' None case sensitive rule pop 'case Sensitive' True if case sensitive 'false' case sensitive Falseelif case sensitive 'true' case sensitive Truetry search rule pop 'search' except Key Error raise Value Error ' Redactionruleismissing...
def parse_one_rule_from_dict rule rule pop 'description' None trigger rule pop 'trigger' None case_sensitive rule pop 'caseSensitive' True if case_sensitive 'false' case_sensitive Falseelif case_sensitive 'true' case_sensitive Truetry search rule pop 'search' except KeyError raise ValueError 'Redactionruleismissing`sea...
81