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-3937
python
What does the code solve ?
a risch differential equation : dy + f*y = = g
def risch DE fa fd ga gd DE fa fd weak normalizer fa fd DE a ba bd ca cd hn normal denom fa fd ga gd DE A B C hs special denom a ba bd ca cd DE try n bound degree A B C DE except Not Implemented Error n oo B C m alpha beta spde A B C n DE if C is zero y Celse y solve poly rde B C m DE return alpha * y + beta hn * hs
def rischDE fa fd ga gd DE _ fa fd weak_normalizer fa fd DE a ba bd ca cd hn normal_denom fa fd ga gd DE A B C hs special_denom a ba bd ca cd DE try n bound_degree A B C DE except NotImplementedError n oo B C m alpha beta spde A B C n DE if C is_zero y Celse y solve_poly_rde B C m DE return alpha * y + beta hn * hs
88
python-test-3944
python
What has an existing account ?
the user specified by the lti launch
def authenticate lti user request lti user id lti consumer try lti user Lti User objects get lti user id lti user id lti consumer lti consumer except Lti User Does Not Exist lti user create lti user lti user id lti consumer if not request user is authenticated and request user lti user edx user switch user request lti ...
def authenticate_lti_user request lti_user_id lti_consumer try lti_user LtiUser objects get lti_user_id lti_user_id lti_consumer lti_consumer except LtiUser DoesNotExist lti_user create_lti_user lti_user_id lti_consumer if not request user is_authenticated and request user lti_user edx_user switch_user request lti_user...
63
python-test-3945
python
What do the user specified by the lti launch have ?
an existing account
def authenticate lti user request lti user id lti consumer try lti user Lti User objects get lti user id lti user id lti consumer lti consumer except Lti User Does Not Exist lti user create lti user lti user id lti consumer if not request user is authenticated and request user lti user edx user switch user request lti ...
def authenticate_lti_user request lti_user_id lti_consumer try lti_user LtiUser objects get lti_user_id lti_user_id lti_consumer lti_consumer except LtiUser DoesNotExist lti_user create_lti_user lti_user_id lti_consumer if not request user is_authenticated and request user lti_user edx_user switch_user request lti_user...
63
python-test-3954
python
What specified in profile_image_names ?
the sizes and filenames
def create profile images image file profile image names storage get profile image storage original Image open image file image set color mode to rgb original image crop image to square image for size name in profile image names items scaled scale image image size exif get corrected exif scaled original with closing cr...
def create_profile_images image_file profile_image_names storage get_profile_image_storage original Image open image_file image _set_color_mode_to_rgb original image _crop_image_to_square image for size name in profile_image_names items scaled _scale_image image size exif _get_corrected_exif scaled original with closin...
68
python-test-3955
python
How does them store ?
according to the sizes and filenames specified in profile_image_names
def create profile images image file profile image names storage get profile image storage original Image open image file image set color mode to rgb original image crop image to square image for size name in profile image names items scaled scale image image size exif get corrected exif scaled original with closing cr...
def create_profile_images image_file profile_image_names storage get_profile_image_storage original Image open image_file image _set_color_mode_to_rgb original image _crop_image_to_square image for size name in profile_image_names items scaled _scale_image image size exif _get_corrected_exif scaled original with closin...
68
python-test-3957
python
What does the code create ?
a compositelayer wrapping two softmax layers
def test flattener layer state separation for softmax soft 1 Softmax 5 'sf 1 ' 0 1 soft 2 Softmax 5 'sf 2 ' 0 1 mlp MLP layers [ Flattener Layer Composite Layer 'comp' [soft 1 soft 2 ] ] nvis 2 X np random rand 20 2 astype theano config float X y np random rand 20 10 astype theano config float X dataset Dense Design Ma...
def test_flattener_layer_state_separation_for_softmax soft1 Softmax 5 'sf1' 0 1 soft2 Softmax 5 'sf2' 0 1 mlp MLP layers [FlattenerLayer CompositeLayer 'comp' [soft1 soft2] ] nvis 2 X np random rand 20 2 astype theano config floatX y np random rand 20 10 astype theano config floatX dataset DenseDesignMatrix X X y y tra...
96
python-test-3958
python
What do the jenkins stash notifier plugin notify after job completes ?
atlassian stash
def stash registry xml parent data top XML Sub Element xml parent 'org jenkinsci plugins stash Notifier Stash Notifier' XML Sub Element top 'stash Server Base Url' text data get 'url' '' if data get 'credentials-id' is not None XML Sub Element top 'credentials Id' text str data get 'credentials-id' else XML Sub Element...
def stash registry xml_parent data top XML SubElement xml_parent 'org jenkinsci plugins stashNotifier StashNotifier' XML SubElement top 'stashServerBaseUrl' text data get 'url' '' if data get 'credentials-id' is not None XML SubElement top 'credentialsId' text str data get 'credentials-id' else XML SubElement top 'stas...
141
python-test-3966
python
Do the supplied actual dict contain all the items in expected ?
No
def assert dict contains test case expected actual message '' missing items []mismatch items []no value object for key expected value in expected items actual value actual get key no value if actual value is no value missing items append key elif actual value expected value mismatch items append '{} {} {}' format key e...
def assert_dict_contains test_case expected actual message '' missing_items []mismatch_items []no_value object for key expected_value in expected items actual_value actual get key no_value if actual_value is no_value missing_items append key elif actual_value expected_value mismatch_items append '{} {} {}' format key e...
81
python-test-3968
python
What turns into list of tuples in format where stat is a value from statistic_types and resource ?
of strings
def parse process statistics statistics if statistics is None statistics DEFAULT STATISTIC Sstatistics util listify statistics statistics [ tuplize statistic for in statistics]for statistic in statistics if statistic[ 0 ] not in STATISTIC TYPES raise Exception ' Unknownstatistictypeencountered%s' % statistic[ 0 ] if st...
def parse_process_statistics statistics if statistics is None statistics DEFAULT_STATISTICSstatistics util listify statistics statistics [_tuplize_statistic _ for _ in statistics]for statistic in statistics if statistic[0] not in STATISTIC_TYPES raise Exception 'Unknownstatistictypeencountered%s' % statistic[0] if stat...
60
python-test-3969
python
Where do of strings turn into list of tuples ?
in format where stat is a value from statistic_types and resource
def parse process statistics statistics if statistics is None statistics DEFAULT STATISTIC Sstatistics util listify statistics statistics [ tuplize statistic for in statistics]for statistic in statistics if statistic[ 0 ] not in STATISTIC TYPES raise Exception ' Unknownstatistictypeencountered%s' % statistic[ 0 ] if st...
def parse_process_statistics statistics if statistics is None statistics DEFAULT_STATISTICSstatistics util listify statistics statistics [_tuplize_statistic _ for _ in statistics]for statistic in statistics if statistic[0] not in STATISTIC_TYPES raise Exception 'Unknownstatistictypeencountered%s' % statistic[0] if stat...
60
python-test-3970
python
What is a value from statistic_types where ?
stat
def parse process statistics statistics if statistics is None statistics DEFAULT STATISTIC Sstatistics util listify statistics statistics [ tuplize statistic for in statistics]for statistic in statistics if statistic[ 0 ] not in STATISTIC TYPES raise Exception ' Unknownstatistictypeencountered%s' % statistic[ 0 ] if st...
def parse_process_statistics statistics if statistics is None statistics DEFAULT_STATISTICSstatistics util listify statistics statistics [_tuplize_statistic _ for _ in statistics]for statistic in statistics if statistic[0] not in STATISTIC_TYPES raise Exception 'Unknownstatistictypeencountered%s' % statistic[0] if stat...
60
python-test-3971
python
What does the code find ?
the full dotted package name for a given python source file name
def getpackage filename src file src filename if os path isdir src file or not src file endswith ' py' and not ispackage src file return None base ext os path splitext os path basename src file if base ' init ' mod parts []else mod parts [base] path part os path split os path split src file [0 ] while part if ispackage...
def getpackage filename src_file src filename if os path isdir src_file or not src_file endswith ' py' and not ispackage src_file return None base ext os path splitext os path basename src_file if base '__init__' mod_parts []else mod_parts [base] path part os path split os path split src_file [0] while part if ispackag...
90
python-test-3973
python
What does the code clean ?
a template temp file
def clean tmp sfn if sfn startswith os path join tempfile gettempdir salt utils files TEMPFILE PREFIX all roots itertools chain from iterable six itervalues opts ['file roots'] in roots any sfn startswith root for root in all roots if os path exists sfn and not in roots os remove sfn
def __clean_tmp sfn if sfn startswith os path join tempfile gettempdir salt utils files TEMPFILE_PREFIX all_roots itertools chain from_iterable six itervalues __opts__['file_roots'] in_roots any sfn startswith root for root in all_roots if os path exists sfn and not in_roots os remove sfn
51
python-test-3977
python
What does the code find ?
a review request given an i d and an optional localsite name
def find review request object review request id local site q Review Request objects all if local site q q filter local site local site local id review request id else q q filter pk review request id try q q select related u'submitter' u'repository' return q get except Review Request Does Not Exist raise Http 404
def _find_review_request_object review_request_id local_site q ReviewRequest objects all if local_site q q filter local_site local_site local_id review_request_id else q q filter pk review_request_id try q q select_related u'submitter' u'repository' return q get except ReviewRequest DoesNotExist raise Http404
57
python-test-3978
python
How does the code verify the output ?
with expected results for gamma correction with gamma equal to two
def test adjust gamma greater one image np arange 0 255 4 np uint 8 reshape 8 8 expected np array [[ 0 0 0 0 1 1 2 3] [4 5 6 7 9 10 12 14 ] [16 18 20 22 25 27 30 33 ] [36 39 42 45 49 52 56 60 ] [64 68 72 76 81 85 90 95 ] [100 105 110 116 121 127 132 138 ] [144 150 156 163 169 176 182 189 ] [196 203 211 218 225 233 241 ...
def test_adjust_gamma_greater_one image np arange 0 255 4 np uint8 reshape 8 8 expected np array [[0 0 0 0 1 1 2 3] [4 5 6 7 9 10 12 14] [16 18 20 22 25 27 30 33] [36 39 42 45 49 52 56 60] [64 68 72 76 81 85 90 95] [100 105 110 116 121 127 132 138] [144 150 156 163 169 176 182 189] [196 203 211 218 225 233 241 249]] dt...
108
python-test-3980
python
What do we trust ?
this reference
def headers url generator resp fuzzable req resp headers resp get headers for parser header names in URL HEADERS iteritems for header name in header names header value resp headers iget header name None if header value is not None header value smart unicode header value encoding resp charset for ref in parser resp head...
def headers_url_generator resp fuzzable_req resp_headers resp get_headers for parser header_names in URL_HEADERS iteritems for header_name in header_names header_value _ resp_headers iget header_name None if header_value is not None header_value smart_unicode header_value encoding resp charset for ref in parser resp he...
64
python-test-3983
python
What does the code delete ?
an amazon kinesis stream
def delete stream client stream name wait False wait timeout 300 check mode False success Falsechanged Falseerr msg ''results dict stream found stream msg current stream find stream client stream name check mode check mode if stream found success err msg stream action client stream name action 'delete' check mode check...
def delete_stream client stream_name wait False wait_timeout 300 check_mode False success Falsechanged Falseerr_msg ''results dict stream_found stream_msg current_stream find_stream client stream_name check_mode check_mode if stream_found success err_msg stream_action client stream_name action 'delete' check_mode check...
120
python-test-3984
python
What does the code get for the user ?
the localsiteprofile for a given localsite
def get site profile self local site if not hasattr self u' site profiles' self site profiles {}if local site pk not in self site profiles site profile Local Site Profile objects get user self local site local site site profile user selfsite profile local site local siteself site profiles[local site pk] site profileret...
def _get_site_profile self local_site if not hasattr self u'_site_profiles' self _site_profiles {}if local_site pk not in self _site_profiles site_profile LocalSiteProfile objects get user self local_site local_site site_profile user selfsite_profile local_site local_siteself _site_profiles[local_site pk] site_profiler...
59
python-test-3988
python
What does this collect ?
all attributes specified into a list
def oo collect data attribute None filters None if not isinstance data list raise errors Ansible Filter Error ' failedexpectstofilterona List' if not attribute raise errors Ansible Filter Error ' failedexpectsattributetobeset' if filters is not None if not isinstance filters dict raise errors Ansible Filter Error ' fai...
def oo_collect data attribute None filters None if not isinstance data list raise errors AnsibleFilterError ' failedexpectstofilteronaList' if not attribute raise errors AnsibleFilterError ' failedexpectsattributetobeset' if filters is not None if not isinstance filters dict raise errors AnsibleFilterError ' failedexpe...
91
python-test-3989
python
What does this take ?
a list of dict
def oo collect data attribute None filters None if not isinstance data list raise errors Ansible Filter Error ' failedexpectstofilterona List' if not attribute raise errors Ansible Filter Error ' failedexpectsattributetobeset' if filters is not None if not isinstance filters dict raise errors Ansible Filter Error ' fai...
def oo_collect data attribute None filters None if not isinstance data list raise errors AnsibleFilterError ' failedexpectstofilteronaList' if not attribute raise errors AnsibleFilterError ' failedexpectsattributetobeset' if filters is not None if not isinstance filters dict raise errors AnsibleFilterError ' failedexpe...
91
python-test-3992
python
What does the code make ?
a template class for attribute * attr * of * typ * overloaded by * overload_func *
def make overload attribute template typ attr overload func base Overload Attribute Template assert isinstance typ types Type or issubclass typ types Type name ' Overload Template %s %s' % typ attr dct dict key typ attr attr impl cache {} overload func staticmethod overload func return type base name base dct
def make_overload_attribute_template typ attr overload_func base _OverloadAttributeTemplate assert isinstance typ types Type or issubclass typ types Type name 'OverloadTemplate_%s_%s' % typ attr dct dict key typ _attr attr _impl_cache {} _overload_func staticmethod overload_func return type base name base dct
52
python-test-4006
python
What did the code parse ?
emerge output
def process emerge err stdout stderr ret {}rexp re compile '^[<> ][^]+/[^]+[^\\n]+' re M slot conflicts re compile '^[^\\n]+/[^]+ [^]' re M findall stderr if slot conflicts ret['slotconflicts'] slot conflictsblocked re compile ' ?m ^\\[blocks +\\] [^]+/[^]+-[ 0 - 9 ]+[^]+ *$' findall stdout unsatisfied re compile ' Err...
def _process_emerge_err stdout stderr ret {}rexp re compile '^[<> ][^]+/[^]+[^\\n]+' re M slot_conflicts re compile '^[^\\n]+/[^]+ [^]' re M findall stderr if slot_conflicts ret['slotconflicts'] slot_conflictsblocked re compile ' ?m ^\\[blocks +\\] [^]+/[^]+-[0-9]+[^]+ *$' findall stdout unsatisfied re compile 'Error T...
106
python-test-4007
python
What did the code use when ?
to parse emerge output
def process emerge err stdout stderr ret {}rexp re compile '^[<> ][^]+/[^]+[^\\n]+' re M slot conflicts re compile '^[^\\n]+/[^]+ [^]' re M findall stderr if slot conflicts ret['slotconflicts'] slot conflictsblocked re compile ' ?m ^\\[blocks +\\] [^]+/[^]+-[ 0 - 9 ]+[^]+ *$' findall stdout unsatisfied re compile ' Err...
def _process_emerge_err stdout stderr ret {}rexp re compile '^[<> ][^]+/[^]+[^\\n]+' re M slot_conflicts re compile '^[^\\n]+/[^]+ [^]' re M findall stderr if slot_conflicts ret['slotconflicts'] slot_conflictsblocked re compile ' ?m ^\\[blocks +\\] [^]+/[^]+-[0-9]+[^]+ *$' findall stdout unsatisfied re compile 'Error T...
106
python-test-4011
python
What does the code run ?
the watcher
def find changes accounts monitor names debug True for account name in accounts monitors get monitors account name monitor names debug for mon in monitors cw mon watcher items exception map cw slurp cw find changes current items exception map exception map cw save audit changes accounts monitor names False debug db ses...
def find_changes accounts monitor_names debug True for account_name in accounts monitors get_monitors account_name monitor_names debug for mon in monitors cw mon watcher items exception_map cw slurp cw find_changes current items exception_map exception_map cw save audit_changes accounts monitor_names False debug db ses...
54
python-test-4013
python
What does the code create ?
an nginx configurator with the specified options
def get nginx configurator config path config dir work dir version 1 6 2 backups os path join work dir 'backups' with mock patch 'certbot nginx configurator Nginx Configurator config test' with mock patch 'certbot nginx configurator util exe exists' as mock exe exists mock exe exists return value Trueconfig configurato...
def get_nginx_configurator config_path config_dir work_dir version 1 6 2 backups os path join work_dir 'backups' with mock patch 'certbot_nginx configurator NginxConfigurator config_test' with mock patch 'certbot_nginx configurator util exe_exists' as mock_exe_exists mock_exe_exists return_value Trueconfig configurator...
127
python-test-4014
python
What does the code show ?
a warning with the provided title and message
def critical title message None details None if message is None message titlembox Resizeable Message Box active window mbox set Window Title title mbox set Text Format Qt Plain Text mbox set Text message mbox set Icon Qt Widgets Q Message Box Critical mbox set Standard Buttons Qt Widgets Q Message Box Close mbox set De...
def critical title message None details None if message is None message titlembox ResizeableMessageBox active_window mbox setWindowTitle title mbox setTextFormat Qt PlainText mbox setText message mbox setIcon QtWidgets QMessageBox Critical mbox setStandardButtons QtWidgets QMessageBox Close mbox setDefaultButton QtWidg...
72
python-test-4015
python
What does the code get ?
the paths by list
def get Path By List vertex List if len vertex List < 1 return Vector 3 if vertex List[ 0 ] class list vertex List [vertex List]path []for float List in vertex List vector 3 get Vector 3 By Float List float List Vector 3 path append vector 3 return path
def getPathByList vertexList if len vertexList < 1 return Vector3 if vertexList[0] __class__ list vertexList [vertexList]path []for floatList in vertexList vector3 getVector3ByFloatList floatList Vector3 path append vector3 return path
51
python-test-4029
python
What does the code get ?
response for one media file
def resolve one media file id resource file app media get file id resource if file if config RETURN MEDIA AS BASE 64 STRING ret file base 64 encodestring file read elif config RETURN MEDIA AS URL prefix config MEDIA BASE URL if config MEDIA BASE URL is not None else app api prefix ret file '%s/%s/%s' % prefix config ME...
def resolve_one_media file_id resource _file app media get file_id resource if _file if config RETURN_MEDIA_AS_BASE64_STRING ret_file base64 encodestring _file read elif config RETURN_MEDIA_AS_URL prefix config MEDIA_BASE_URL if config MEDIA_BASE_URL is not None else app api_prefix ret_file '%s/%s/%s' % prefix config M...
109
python-test-4033
python
What does the code get ?
the contents of an autotest info file
def get info file filename data ''errors re compile '\\b error fail failed \\b' re IGNORECASE if os path isfile filename f open '%s' % filename 'r' lines f readlines f close rx re compile ' \' " ' for line in lines new line rx sub '' line errors found errors findall new line if len errors found > 0 data + '<fontcolor r...
def get_info_file filename data ''errors re compile '\\b error fail failed \\b' re IGNORECASE if os path isfile filename f open '%s' % filename 'r' lines f readlines f close rx re compile ' \' " ' for line in lines new_line rx sub '' line errors_found errors findall new_line if len errors_found > 0 data + '<fontcolor r...
91
python-test-4034
python
What does the code convert to its keys as string ?
a qt qflags value
def qflags key base value add base False klass None if klass is None klass value class if klass int raise Type Error " Can'tguessenumclassofanint " bits []names []mask 1value int value while mask < value if value & mask bits append mask mask << 1for bit in bits names append qenum key base klass bit add base return ' ' ...
def qflags_key base value add_base False klass None if klass is None klass value __class__if klass int raise TypeError "Can'tguessenumclassofanint " bits []names []mask 1value int value while mask < value if value & mask bits append mask mask << 1for bit in bits names append qenum_key base klass bit add_base return ' '...
63
python-test-4038
python
What does a start vector and direction vector assume ?
points segments that already form a somewhat smooth line
def fit Line pts n len pts if n < 1 return 0 0 0 0 a np zeros n - 1 2 for i in range n - 1 v pts[i] - pts[ i + 1 ] a[i] v / np linalg norm v direction np mean a[ 1 -1 ] axis 0 start np mean pts[ 1 -1 ] axis 0 return start start + direction
def fitLine pts n len pts if n < 1 return 0 0 0 0 a np zeros n - 1 2 for i in range n - 1 v pts[i] - pts[ i + 1 ] a[i] v / np linalg norm v direction np mean a[1 -1 ] axis 0 start np mean pts[1 -1 ] axis 0 return start start + direction
68
python-test-4039
python
What form a somewhat smooth line already ?
points segments
def fit Line pts n len pts if n < 1 return 0 0 0 0 a np zeros n - 1 2 for i in range n - 1 v pts[i] - pts[ i + 1 ] a[i] v / np linalg norm v direction np mean a[ 1 -1 ] axis 0 start np mean pts[ 1 -1 ] axis 0 return start start + direction
def fitLine pts n len pts if n < 1 return 0 0 0 0 a np zeros n - 1 2 for i in range n - 1 v pts[i] - pts[ i + 1 ] a[i] v / np linalg norm v direction np mean a[1 -1 ] axis 0 start np mean pts[1 -1 ] axis 0 return start start + direction
68
python-test-4040
python
What assumes points segments that already form a somewhat smooth line ?
a start vector and direction vector
def fit Line pts n len pts if n < 1 return 0 0 0 0 a np zeros n - 1 2 for i in range n - 1 v pts[i] - pts[ i + 1 ] a[i] v / np linalg norm v direction np mean a[ 1 -1 ] axis 0 start np mean pts[ 1 -1 ] axis 0 return start start + direction
def fitLine pts n len pts if n < 1 return 0 0 0 0 a np zeros n - 1 2 for i in range n - 1 v pts[i] - pts[ i + 1 ] a[i] v / np linalg norm v direction np mean a[1 -1 ] axis 0 start np mean pts[1 -1 ] axis 0 return start start + direction
68
python-test-4041
python
What do points segments form already ?
a somewhat smooth line
def fit Line pts n len pts if n < 1 return 0 0 0 0 a np zeros n - 1 2 for i in range n - 1 v pts[i] - pts[ i + 1 ] a[i] v / np linalg norm v direction np mean a[ 1 -1 ] axis 0 start np mean pts[ 1 -1 ] axis 0 return start start + direction
def fitLine pts n len pts if n < 1 return 0 0 0 0 a np zeros n - 1 2 for i in range n - 1 v pts[i] - pts[ i + 1 ] a[i] v / np linalg norm v direction np mean a[1 -1 ] axis 0 start np mean pts[1 -1 ] axis 0 return start start + direction
68
python-test-4044
python
What does this function perform ?
the boolean document probability estimation
def p boolean document corpus segmented topics top ids ret top ids segmented topics per topic postings {}for id in top ids id list set for n document in enumerate corpus if id in frozenset x[ 0 ] for x in document id list add n per topic postings[id] id listnum docs len corpus return per topic postings num docs
def p_boolean_document corpus segmented_topics top_ids _ret_top_ids segmented_topics per_topic_postings {}for id in top_ids id_list set for n document in enumerate corpus if id in frozenset x[0] for x in document id_list add n per_topic_postings[id] id_listnum_docs len corpus return per_topic_postings num_docs
60
python-test-4052
python
How do a detached process start ?
with ok = false
def test start detached error fake proc message mock caplog argv ['foo' 'bar']fake proc proc start Detached return value False 0 fake proc proc error return value ' Errormessage'with caplog at level logging ERROR fake proc start detached *argv msg message mock getmsg usertypes Message Level error assert msg text ' Erro...
def test_start_detached_error fake_proc message_mock caplog argv ['foo' 'bar']fake_proc _proc startDetached return_value False 0 fake_proc _proc error return_value 'Errormessage'with caplog at_level logging ERROR fake_proc start_detached *argv msg message_mock getmsg usertypes MessageLevel error assert msg text 'Errorw...
54
python-test-4061
python
What does the code calculate ?
a one - dimensional filter along the given axis
@docfillerdef generic filter 1 d input function filter size axis -1 output None mode 'reflect' cval 0 0 origin 0 extra arguments extra keywords None if extra keywords is None extra keywords {}input numpy asarray input if numpy iscomplexobj input raise Type Error ' Complextypenotsupported' output return value ni support...
@docfillerdef generic_filter1d input function filter_size axis -1 output None mode 'reflect' cval 0 0 origin 0 extra_arguments extra_keywords None if extra_keywords is None extra_keywords {}input numpy asarray input if numpy iscomplexobj input raise TypeError 'Complextypenotsupported' output return_value _ni_support _g...
124
python-test-4062
python
How does part of a key convert into a slice ?
with a start and step
def format slice key val dim if isinstance key val slice key val slice to int key val start to int key val stop to int key val step return key valelse key val to int key val key val wrap neg index key val dim if 0 < key val < dim return slice key val key val + 1 1 else raise Index Error ' Index/sliceoutofbounds '
def format_slice key_val dim if isinstance key_val slice key_val slice to_int key_val start to_int key_val stop to_int key_val step return key_valelse key_val to_int key_val key_val wrap_neg_index key_val dim if 0 < key_val < dim return slice key_val key_val + 1 1 else raise IndexError 'Index/sliceoutofbounds '
69
python-test-4064
python
What does the code add to content metadata ?
git based permalink i d
@content git object init connectdef git permalink content git content if not content settings['GIT GENERATE PERMALINK'] returnif not string to bool content metadata get 'git permalink' 'yes' returnif not git content is committed returnpermalink hash hashlib sha 1 permalink hash update str git content get oldest commit ...
@content_git_object_init connectdef git_permalink content git_content if not content settings['GIT_GENERATE_PERMALINK'] returnif not string_to_bool content metadata get 'git_permalink' 'yes' returnif not git_content is_committed returnpermalink_hash hashlib sha1 permalink_hash update str git_content get_oldest_commit p...
108
python-test-4068
python
What do views require ?
moderator status of a group
def moderator required function None def decorator request *args **kwargs group get object or 404 Group slug kwargs['slug'] if request user is anonymous return Http Response Redirect reverse 'django contrib auth views login' if Group Member objects is moderator group request user return function request *args **kwargs ...
def moderator_required function None def decorator request *args **kwargs group get_object_or_404 Group slug kwargs['slug'] if request user is_anonymous return HttpResponseRedirect reverse 'django contrib auth views login' if GroupMember objects is_moderator group request user return function request *args **kwargs els...
53
python-test-4069
python
What does the code send employee if no stop birthday reminders is not set ?
birthday reminders
def send birthday reminders if int frappe db get single value u'HR Settings' u'stop birthday reminders' or 0 returnfrom frappe utils user import get enabled system usersusers Nonebirthdays get employees who are born today if birthdays if not users users [ u email id or u name for u in get enabled system users ]for e in...
def send_birthday_reminders if int frappe db get_single_value u'HRSettings' u'stop_birthday_reminders' or 0 returnfrom frappe utils user import get_enabled_system_usersusers Nonebirthdays get_employees_who_are_born_today if birthdays if not users users [ u email_id or u name for u in get_enabled_system_users ]for e in ...
110
python-test-4070
python
What found in the message directory ?
all the msg file
def process message notification request messages path if not messages path returnglobal MESSAGES CACH Eglobal MESSAGES MTIM Eif MESSAGES CACHE is None or MESSAGES MTIME os path getmtime messages path MESSAGES CACHE get processed messages messages path MESSAGES MTIME os path getmtime messages path for msg in MESSAGES C...
def process_message_notification request messages_path if not messages_path returnglobal _MESSAGES_CACHEglobal _MESSAGES_MTIMEif _MESSAGES_CACHE is None or _MESSAGES_MTIME os path getmtime messages_path _MESSAGES_CACHE _get_processed_messages messages_path _MESSAGES_MTIME os path getmtime messages_path for msg in _MESS...
53
python-test-4071
python
Where did all the msg file find ?
in the message directory
def process message notification request messages path if not messages path returnglobal MESSAGES CACH Eglobal MESSAGES MTIM Eif MESSAGES CACHE is None or MESSAGES MTIME os path getmtime messages path MESSAGES CACHE get processed messages messages path MESSAGES MTIME os path getmtime messages path for msg in MESSAGES C...
def process_message_notification request messages_path if not messages_path returnglobal _MESSAGES_CACHEglobal _MESSAGES_MTIMEif _MESSAGES_CACHE is None or _MESSAGES_MTIME os path getmtime messages_path _MESSAGES_CACHE _get_processed_messages messages_path _MESSAGES_MTIME os path getmtime messages_path for msg in _MESS...
53
python-test-4072
python
Where do a polynomial h_{pq } construct ?
in mathbb{z}_{p q}[x ] such that
def chinese remainder reconstruction univariate hp hq p q n hp degree x hp ring gens[ 0 ]hpq hp ring zerofor i in range n + 1 hpq[ i ] crt [p q] [hp coeff x ** i hq coeff x ** i ] symmetric True [0 ]hpq strip zero return hpq
def _chinese_remainder_reconstruction_univariate hp hq p q n hp degree x hp ring gens[0]hpq hp ring zerofor i in range n + 1 hpq[ i ] crt [p q] [hp coeff x ** i hq coeff x ** i ] symmetric True [0]hpq strip_zero return hpq
52
python-test-4076
python
What does the code start ?
the scheduled background tasks
def initialize scheduler from headphones import updater searcher librarysync postprocessor torrentfinishedwith SCHED LOCK start jobs not len SCHED get jobs minutes CONFIG SEARCH INTERVA Lschedule job searcher searchforalbum ' Searchfor Wanted' hours 0 minutes minutes minutes CONFIG DOWNLOAD SCAN INTERVA Lschedule job p...
def initialize_scheduler from headphones import updater searcher librarysync postprocessor torrentfinishedwith SCHED_LOCK start_jobs not len SCHED get_jobs minutes CONFIG SEARCH_INTERVALschedule_job searcher searchforalbum 'SearchforWanted' hours 0 minutes minutes minutes CONFIG DOWNLOAD_SCAN_INTERVALschedule_job postp...
150
python-test-4078
python
What does the code join into a single input ?
their non shared inputs
def join nonshared inputs xs vars shared make shared False joined tt concatenate [var ravel for var in vars] if not make shared tensor type joined typeinarray tensor type 'inarray' else inarray theano shared joined tag test value 'inarray' ordering Array Ordering vars inarray tag test value joined tag test valueget var...
def join_nonshared_inputs xs vars shared make_shared False joined tt concatenate [var ravel for var in vars] if not make_shared tensor_type joined typeinarray tensor_type 'inarray' else inarray theano shared joined tag test_value 'inarray' ordering ArrayOrdering vars inarray tag test_value joined tag test_valueget_var ...
92
python-test-4079
python
What does the code take ?
a list of theano variables
def join nonshared inputs xs vars shared make shared False joined tt concatenate [var ravel for var in vars] if not make shared tensor type joined typeinarray tensor type 'inarray' else inarray theano shared joined tag test value 'inarray' ordering Array Ordering vars inarray tag test value joined tag test valueget var...
def join_nonshared_inputs xs vars shared make_shared False joined tt concatenate [var ravel for var in vars] if not make_shared tensor_type joined typeinarray tensor_type 'inarray' else inarray theano shared joined tag test_value 'inarray' ordering ArrayOrdering vars inarray tag test_value joined tag test_valueget_var ...
92
python-test-4081
python
What will the api tell you only ?
the number associated with the status
def property name property index statuses ['' '' ' Open' ' Pending' ' Resolved' ' Closed' ' Waitingon Customer' ' Job Application' ' Monthly']priorities ['' ' Low' ' Medium' ' High' ' Urgent']if property 'status' return statuses[index] if index < len statuses else str index elif property 'priority' return priorities[in...
def property_name property index statuses ['' '' 'Open' 'Pending' 'Resolved' 'Closed' 'WaitingonCustomer' 'JobApplication' 'Monthly']priorities ['' 'Low' 'Medium' 'High' 'Urgent']if property 'status' return statuses[index] if index < len statuses else str index elif property 'priority' return priorities[index] if index...
64
python-test-4082
python
What does this return ?
a list of image uuids to load
def find apple crash report referenced images binary images threads image map {}for image in binary images image map[image['image addr']] image['uuid']to load set for thread in threads if 'backtrace' not in thread continuefor frame in thread['backtrace']['contents'] img uuid image map get frame['object addr'] if img uu...
def find_apple_crash_report_referenced_images binary_images threads image_map {}for image in binary_images image_map[image['image_addr']] image['uuid']to_load set for thread in threads if 'backtrace' not in thread continuefor frame in thread['backtrace']['contents'] img_uuid image_map get frame['object_addr'] if img_uu...
58
python-test-4083
python
What does the code remove from seqs_fp using chimeraslayer ?
chimeras
def get chimeras from Nast aligned seqs fp ref db aligned fp None ref db fasta fp None HALT EXEC False min div ratio None keep intermediates False files to remove []seqs fp str seqs fp seqs fp seqs fp rstrip '"' seqs fp seqs fp lstrip '"' seqs dir new seqs fp split seqs fp if seqs dir '' seqs dir ' /'params {'--query N...
def get_chimeras_from_Nast_aligned seqs_fp ref_db_aligned_fp None ref_db_fasta_fp None HALT_EXEC False min_div_ratio None keep_intermediates False files_to_remove []seqs_fp str seqs_fp seqs_fp seqs_fp rstrip '"' seqs_fp seqs_fp lstrip '"' seqs_dir new_seqs_fp split seqs_fp if seqs_dir '' seqs_dir ' /'params {'--query_N...
180
python-test-4084
python
How does the code remove chimeras from seqs_fp ?
using chimeraslayer
def get chimeras from Nast aligned seqs fp ref db aligned fp None ref db fasta fp None HALT EXEC False min div ratio None keep intermediates False files to remove []seqs fp str seqs fp seqs fp seqs fp rstrip '"' seqs fp seqs fp lstrip '"' seqs dir new seqs fp split seqs fp if seqs dir '' seqs dir ' /'params {'--query N...
def get_chimeras_from_Nast_aligned seqs_fp ref_db_aligned_fp None ref_db_fasta_fp None HALT_EXEC False min_div_ratio None keep_intermediates False files_to_remove []seqs_fp str seqs_fp seqs_fp seqs_fp rstrip '"' seqs_fp seqs_fp lstrip '"' seqs_dir new_seqs_fp split seqs_fp if seqs_dir '' seqs_dir ' /'params {'--query_N...
180
python-test-4094
python
What does the code create ?
a snapshot of a vm
def snapshot domain name None suffix None if name and name lower domain lower raise Command Execution Error ' Virtual Machine{name}isalreadydefined Pleasechooseanothernameforthesnapshot' format name name if not name name '{domain}-{tsnap}' format domain domain tsnap time strftime '%Y%m%d-%H%M%S' time localtime if suffi...
def snapshot domain name None suffix None if name and name lower domain lower raise CommandExecutionError 'VirtualMachine{name}isalreadydefined Pleasechooseanothernameforthesnapshot' format name name if not name name '{domain}-{tsnap}' format domain domain tsnap time strftime '%Y%m%d-%H%M%S' time localtime if suffix na...
78
python-test-4101
python
What does the code write ?
a string that tells the user what they are seeing in terms of search results
@jingo register functiondef showing query pager format opts pager start index pager end index pager paginator count query escape query if query showing u' Showing{ 0 }-{ 1 }of{ 2 }resultsfor<strong>{ 3 }</strong>' format * format opts + query else showing u' Showing{ 0 }-{ 1 }of{ 2 }results' format *format opts return ...
@jingo register functiondef showing query pager format_opts pager start_index pager end_index pager paginator count query escape query if query showing _ u'Showing{0}-{1}of{2}resultsfor<strong>{3}</strong>' format * format_opts + query else showing _ u'Showing{0}-{1}of{2}results' format *format_opts return jinja2 Marku...
57
python-test-4102
python
How are they seeing what ?
in terms of search results
@jingo register functiondef showing query pager format opts pager start index pager end index pager paginator count query escape query if query showing u' Showing{ 0 }-{ 1 }of{ 2 }resultsfor<strong>{ 3 }</strong>' format * format opts + query else showing u' Showing{ 0 }-{ 1 }of{ 2 }results' format *format opts return ...
@jingo register functiondef showing query pager format_opts pager start_index pager end_index pager paginator count query escape query if query showing _ u'Showing{0}-{1}of{2}resultsfor<strong>{3}</strong>' format * format_opts + query else showing _ u'Showing{0}-{1}of{2}results' format *format_opts return jinja2 Marku...
57
python-test-4105
python
How did the given string split ?
using the different known groups for boundaries
def split on groups string groups if not groups return [string]boundaries sorted set functools reduce lambda l x l + list x groups [] if boundaries[ 0 ] 0 boundaries insert 0 0 if boundaries[ -1 ] len string boundaries append len string groups [string[start end] for start end in zip boundaries[ -1 ] boundaries[ 1 ] ]re...
def split_on_groups string groups if not groups return [string]boundaries sorted set functools reduce lambda l x l + list x groups [] if boundaries[0] 0 boundaries insert 0 0 if boundaries[ -1 ] len string boundaries append len string groups [string[start end] for start end in zip boundaries[ -1 ] boundaries[1 ] ]retur...
65
python-test-4106
python
What do custom threading nt produce ?
arbitrarily long threads
def test threading limit db folder sync engine monkeypatch from inbox models import Message Thread MAX THREAD LENGTH 10 monkeypatch setattr 'inbox mailsync backends imap generic MAX THREAD LENGTH' MAX THREAD LENGTH namespace id folder sync engine namespace idmsg Mock Raw Message [] for i in range 3 * MAX THREAD LENGTH ...
def test_threading_limit db folder_sync_engine monkeypatch from inbox models import Message ThreadMAX_THREAD_LENGTH 10monkeypatch setattr 'inbox mailsync backends imap generic MAX_THREAD_LENGTH' MAX_THREAD_LENGTH namespace_id folder_sync_engine namespace_idmsg MockRawMessage [] for i in range 3 * MAX_THREAD_LENGTH m Me...
139
python-test-4107
python
Do custom threading produce arbitrarily long threads ?
No
def test threading limit db folder sync engine monkeypatch from inbox models import Message Thread MAX THREAD LENGTH 10 monkeypatch setattr 'inbox mailsync backends imap generic MAX THREAD LENGTH' MAX THREAD LENGTH namespace id folder sync engine namespace idmsg Mock Raw Message [] for i in range 3 * MAX THREAD LENGTH ...
def test_threading_limit db folder_sync_engine monkeypatch from inbox models import Message ThreadMAX_THREAD_LENGTH 10monkeypatch setattr 'inbox mailsync backends imap generic MAX_THREAD_LENGTH' MAX_THREAD_LENGTH namespace_id folder_sync_engine namespace_idmsg MockRawMessage [] for i in range 3 * MAX_THREAD_LENGTH m Me...
139
python-test-4108
python
What nt produces arbitrarily long threads ?
custom threading
def test threading limit db folder sync engine monkeypatch from inbox models import Message Thread MAX THREAD LENGTH 10 monkeypatch setattr 'inbox mailsync backends imap generic MAX THREAD LENGTH' MAX THREAD LENGTH namespace id folder sync engine namespace idmsg Mock Raw Message [] for i in range 3 * MAX THREAD LENGTH ...
def test_threading_limit db folder_sync_engine monkeypatch from inbox models import Message ThreadMAX_THREAD_LENGTH 10monkeypatch setattr 'inbox mailsync backends imap generic MAX_THREAD_LENGTH' MAX_THREAD_LENGTH namespace_id folder_sync_engine namespace_idmsg MockRawMessage [] for i in range 3 * MAX_THREAD_LENGTH m Me...
139
python-test-4110
python
What does the code send to vm ?
non - maskable interrupt
def sysrq vm action 'nmi' key 'uuid' ret {}vmadm check vmadm if key not in ['uuid' 'alias' 'hostname'] ret[' Error'] ' Keymustbeeitheruuid aliasorhostname'return retif action not in ['nmi' 'screenshot'] ret[' Error'] ' Actionmustbeeithernmiorscreenshot'return retvm lookup '{ 0 } {1 }' format key vm one True if ' Error'...
def sysrq vm action 'nmi' key 'uuid' ret {}vmadm _check_vmadm if key not in ['uuid' 'alias' 'hostname'] ret['Error'] 'Keymustbeeitheruuid aliasorhostname'return retif action not in ['nmi' 'screenshot'] ret['Error'] 'Actionmustbeeithernmiorscreenshot'return retvm lookup '{0} {1}' format key vm one True if 'Error' in vm ...
84
python-test-4114
python
How does the code extract the repository components from the provided tuple ?
in a backward - compatible manner
def extract components from tuple repository components tuple toolshed repository components tuple[ 0 ]name repository components tuple[ 1 ]owner repository components tuple[ 2 ]changeset revision repository components tuple[ 3 ]components list [toolshed name owner changeset revision]if len repository components tuple ...
def extract_components_from_tuple repository_components_tuple toolshed repository_components_tuple[0]name repository_components_tuple[1]owner repository_components_tuple[2]changeset_revision repository_components_tuple[3]components_list [toolshed name owner changeset_revision]if len repository_components_tuple 5 toolsh...
98
python-test-4115
python
What does the code extract from the provided tuple in a backward - compatible manner ?
the repository components
def extract components from tuple repository components tuple toolshed repository components tuple[ 0 ]name repository components tuple[ 1 ]owner repository components tuple[ 2 ]changeset revision repository components tuple[ 3 ]components list [toolshed name owner changeset revision]if len repository components tuple ...
def extract_components_from_tuple repository_components_tuple toolshed repository_components_tuple[0]name repository_components_tuple[1]owner repository_components_tuple[2]changeset_revision repository_components_tuple[3]components_list [toolshed name owner changeset_revision]if len repository_components_tuple 5 toolsh...
98
python-test-4119
python
How does the code create a symlink at target ?
using the absolute path
def absolute symlink source path target path if not os path isabs source path raise Value Error u' Pathforsource {}mustbeabsolute' format source path if not os path isabs target path raise Value Error u' Pathforlink {}mustbeabsolute' format target path if source path target path raise Value Error u' Pathforlinkisidenti...
def absolute_symlink source_path target_path if not os path isabs source_path raise ValueError u'Pathforsource {}mustbeabsolute' format source_path if not os path isabs target_path raise ValueError u'Pathforlink {}mustbeabsolute' format target_path if source_path target_path raise ValueError u'Pathforlinkisidenticaltos...
109
python-test-4120
python
Where does the code create a symlink using the absolute path ?
at target
def absolute symlink source path target path if not os path isabs source path raise Value Error u' Pathforsource {}mustbeabsolute' format source path if not os path isabs target path raise Value Error u' Pathforlink {}mustbeabsolute' format target path if source path target path raise Value Error u' Pathforlinkisidenti...
def absolute_symlink source_path target_path if not os path isabs source_path raise ValueError u'Pathforsource {}mustbeabsolute' format source_path if not os path isabs target_path raise ValueError u'Pathforlink {}mustbeabsolute' format target_path if source_path target_path raise ValueError u'Pathforlinkisidenticaltos...
109
python-test-4130
python
For what purpose may a subset of labels be requested ?
for ss
@ignore warningsdef test sensitivity specificity ignored labels y true [1 1 2 3]y pred [1 3 3 3]specificity 13 partial specificity score y true y pred labels [1 3] specificity all partial specificity score y true y pred labels None assert allclose [1 0 0 33 ] specificity 13 average None rtol R TOL assert allclose np me...
@ignore_warningsdef test_sensitivity_specificity_ignored_labels y_true [1 1 2 3]y_pred [1 3 3 3]specificity_13 partial specificity_score y_true y_pred labels [1 3] specificity_all partial specificity_score y_true y_pred labels None assert_allclose [1 0 0 33] specificity_13 average None rtol R_TOL assert_allclose np mea...
125
python-test-4131
python
What does the code compute ?
the gauss - chebyshev quadrature [ 1 ] _ points and weights of the second kind
def gauss chebyshev u n n digits xi []w []for i in range 1 n + 1 xi append cos i / n + S One * S Pi n n digits w append S Pi / n + S One * sin i * S Pi / n + S One ** 2 n n digits return xi w
def gauss_chebyshev_u n n_digits xi []w []for i in range 1 n + 1 xi append cos i / n + S One * S Pi n n_digits w append S Pi / n + S One * sin i * S Pi / n + S One ** 2 n n_digits return xi w
60
python-test-4132
python
What does the code write ?
a netpbm pnm / pam file
def write pnm file width height pixels meta bitdepth meta['bitdepth']maxval 2 ** bitdepth - 1 planes meta['planes']assert planes in 1 2 3 4 if planes in 1 3 if 1 planes fmt 'P 5 'else fmt 'P 6 'file write '%s%d%d%d\n' % fmt width height maxval if planes in 2 4 if 2 planes tupltype 'GRAYSCALE ALPHA'else tupltype 'RGB AL...
def write_pnm file width height pixels meta bitdepth meta['bitdepth']maxval 2 ** bitdepth - 1 planes meta['planes']assert planes in 1 2 3 4 if planes in 1 3 if 1 planes fmt 'P5'else fmt 'P6'file write '%s%d%d%d\n' % fmt width height maxval if planes in 2 4 if 2 planes tupltype 'GRAYSCALE_ALPHA'else tupltype 'RGB_ALPHA'...
109
python-test-4142
python
What does the code convert into a profile map ?
the parsed ini config
def build profile map parsed ini config parsed config copy deepcopy parsed ini config profiles {}final config {}for key values in parsed config items if key startswith 'profile' try parts shlex split key except Value Error continueif len parts 2 profiles[parts[ 1 ]] valueselif key 'default' profiles[key] valueselse fin...
def build_profile_map parsed_ini_config parsed_config copy deepcopy parsed_ini_config profiles {}final_config {}for key values in parsed_config items if key startswith 'profile' try parts shlex split key except ValueError continueif len parts 2 profiles[parts[1]] valueselif key 'default' profiles[key] valueselse final_...
55
python-test-4144
python
What does a vcs requirement have ?
distributions on the index
@pytest mark networkdef test upgrade vcs req with dist found script req '%s#egg pretend' % 'git+git //github com/alex/pretend@e 7 f 26 ad 7 dbcb 4 a 02 a 4995 aade 4743 aad 47656 b 27 ' script pip 'install' req expect stderr True result script pip 'install' '-U' req expect stderr True assert 'pypi python org' not in re...
@pytest mark networkdef test_upgrade_vcs_req_with_dist_found script req '%s#egg pretend' % 'git+git //github com/alex/pretend@e7f26ad7dbcb4a02a4995aade4743aad47656b27' script pip 'install' req expect_stderr True result script pip 'install' '-U' req expect_stderr True assert 'pypi python org' not in result stdout result...
62
python-test-4145
python
What can it upgrade ?
a vcs requirement that has distributions on the index
@pytest mark networkdef test upgrade vcs req with dist found script req '%s#egg pretend' % 'git+git //github com/alex/pretend@e 7 f 26 ad 7 dbcb 4 a 02 a 4995 aade 4743 aad 47656 b 27 ' script pip 'install' req expect stderr True result script pip 'install' '-U' req expect stderr True assert 'pypi python org' not in re...
@pytest mark networkdef test_upgrade_vcs_req_with_dist_found script req '%s#egg pretend' % 'git+git //github com/alex/pretend@e7f26ad7dbcb4a02a4995aade4743aad47656b27' script pip 'install' req expect_stderr True result script pip 'install' '-U' req expect_stderr True assert 'pypi python org' not in result stdout result...
62
python-test-4148
python
What does the code decrease ?
ohlc sticks
def make decreasing ohlc open high low close dates **kwargs flat decrease x flat decrease y text decrease OHLC open high low close dates get decrease kwargs setdefault 'line' dict color DEFAULT DECREASING COLOR width 1 kwargs setdefault 'text' text decrease kwargs setdefault 'showlegend' False kwargs setdefault 'name' ...
def make_decreasing_ohlc open high low close dates **kwargs flat_decrease_x flat_decrease_y text_decrease _OHLC open high low close dates get_decrease kwargs setdefault 'line' dict color _DEFAULT_DECREASING_COLOR width 1 kwargs setdefault 'text' text_decrease kwargs setdefault 'showlegend' False kwargs setdefault 'name...
69
python-test-4149
python
What does the code make ?
decreasing ohlc sticks
def make decreasing ohlc open high low close dates **kwargs flat decrease x flat decrease y text decrease OHLC open high low close dates get decrease kwargs setdefault 'line' dict color DEFAULT DECREASING COLOR width 1 kwargs setdefault 'text' text decrease kwargs setdefault 'showlegend' False kwargs setdefault 'name' ...
def make_decreasing_ohlc open high low close dates **kwargs flat_decrease_x flat_decrease_y text_decrease _OHLC open high low close dates get_decrease kwargs setdefault 'line' dict color _DEFAULT_DECREASING_COLOR width 1 kwargs setdefault 'text' text_decrease kwargs setdefault 'showlegend' False kwargs setdefault 'name...
69
python-test-4154
python
What does the code compute ?
the differences between the actual config and the expected config
def compute diff configured expected diff {'add' {} 'update' {} 'remove' {}}configured users set configured keys expected users set expected keys add usernames expected users - configured users remove usernames configured users - expected users common usernames expected users & configured users add dict username expect...
def _compute_diff configured expected diff {'add' {} 'update' {} 'remove' {}}configured_users set configured keys expected_users set expected keys add_usernames expected_users - configured_users remove_usernames configured_users - expected_users common_usernames expected_users & configured_users add dict username expec...
114
python-test-4156
python
Does test that activates setting of echo to off disrupt later echo calls ?
No
@pytest mark installeddef test activate does not leak echo setting shell if not on win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevanton Window's CMD EXE" shell vars format vars shell with Temporary Directory prefix u'envs' dir os path dirname file as envs env dirs env vars gen test env paths envs shell scr...
@pytest mark installeddef test_activate_does_not_leak_echo_setting shell if not on_win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevantonWindow'sCMD EXE" shell_vars _format_vars shell with TemporaryDirectory prefix u'envs' dir os path dirname __file__ as envs env_dirs env_vars gen_test_env_paths envs shell s...
124
python-test-4157
python
What does test activate ?
setting of echo to off
@pytest mark installeddef test activate does not leak echo setting shell if not on win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevanton Window's CMD EXE" shell vars format vars shell with Temporary Directory prefix u'envs' dir os path dirname file as envs env dirs env vars gen test env paths envs shell scr...
@pytest mark installeddef test_activate_does_not_leak_echo_setting shell if not on_win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevantonWindow'sCMD EXE" shell_vars _format_vars shell with TemporaryDirectory prefix u'envs' dir os path dirname __file__ as envs env_dirs env_vars gen_test_env_paths envs shell s...
124
python-test-4158
python
What does test that activates setting of echo to off not disrupt ?
later echo calls
@pytest mark installeddef test activate does not leak echo setting shell if not on win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevanton Window's CMD EXE" shell vars format vars shell with Temporary Directory prefix u'envs' dir os path dirname file as envs env dirs env vars gen test env paths envs shell scr...
@pytest mark installeddef test_activate_does_not_leak_echo_setting shell if not on_win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevantonWindow'sCMD EXE" shell_vars _format_vars shell with TemporaryDirectory prefix u'envs' dir os path dirname __file__ as envs env_dirs env_vars gen_test_env_paths envs shell s...
124
python-test-4159
python
What does not disrupt later echo calls ?
test that activates setting of echo to off
@pytest mark installeddef test activate does not leak echo setting shell if not on win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevanton Window's CMD EXE" shell vars format vars shell with Temporary Directory prefix u'envs' dir os path dirname file as envs env dirs env vars gen test env paths envs shell scr...
@pytest mark installeddef test_activate_does_not_leak_echo_setting shell if not on_win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevantonWindow'sCMD EXE" shell_vars _format_vars shell with TemporaryDirectory prefix u'envs' dir os path dirname __file__ as envs env_dirs env_vars gen_test_env_paths envs shell s...
124
python-test-4160
python
What activates setting of echo to off ?
test
@pytest mark installeddef test activate does not leak echo setting shell if not on win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevanton Window's CMD EXE" shell vars format vars shell with Temporary Directory prefix u'envs' dir os path dirname file as envs env dirs env vars gen test env paths envs shell scr...
@pytest mark installeddef test_activate_does_not_leak_echo_setting shell if not on_win or shell u'cmd exe' pytest skip u"echoleakingisonlyrelevantonWindow'sCMD EXE" shell_vars _format_vars shell with TemporaryDirectory prefix u'envs' dir os path dirname __file__ as envs env_dirs env_vars gen_test_env_paths envs shell s...
124
python-test-4161
python
How did ip set ?
staticly
def Netsh Static Ip interface ip u' 127 0 0 9' subnet u' 255 255 255 255 ' gw u' 127 0 0 1' args ['/c' 'netsh' 'interface' 'ip' 'set' 'address' interface 'static' ip subnet gw '1 ']res client utils common Execute 'cmd' args time limit -1 bypass whitelist True return res
def NetshStaticIp interface ip u'127 0 0 9' subnet u'255 255 255 255' gw u'127 0 0 1' args ['/c' 'netsh' 'interface' 'ip' 'set' 'address' interface 'static' ip subnet gw '1']res client_utils_common Execute 'cmd' args time_limit -1 bypass_whitelist True return res
52
python-test-4163
python
What does the code translate into a set of prefixed aliases ?
a flat sequence of items
def segment sequence aliases if not sequence or aliases returnfor alias parts in aliases items variants {alias Order By Tuple parts Order By alias opposite Order By Tuple parts opposite}for valias vparts in variants items if list sequence[ len vparts ] list vparts tail aliases dict aliases del tail aliases[alias]tail s...
def segment sequence aliases if not sequence or aliases returnfor alias parts in aliases items variants {alias OrderByTuple parts OrderBy alias opposite OrderByTuple parts opposite}for valias vparts in variants items if list sequence[ len vparts ] list vparts tail_aliases dict aliases del tail_aliases[alias]tail_sequen...
74
python-test-4164
python
What does the code remove from the query section of the url ?
all provided parameters
def filter query params url remove params if not url return urlremove params dict p None if isinstance p basestring else p for p in remove params parsed url urlparse urlparse url parsed qsl urlparse parse qsl parsed url query keep blank values True filtered qsl [ p remove params get p v for p v in parsed qsl]filtered q...
def filter_query_params url remove_params if not url return urlremove_params dict p None if isinstance p basestring else p for p in remove_params parsed_url urlparse urlparse url parsed_qsl urlparse parse_qsl parsed_url query keep_blank_values True filtered_qsl [ p remove_params get p v for p v in parsed_qsl]filtered_q...
109
python-test-4168
python
For what purpose did last lines see ?
for path
def lookup lastlines lastlines dirpath path underscored path replace '/' ' ' try lastlines file open os path join lastlines dirpath underscored except OS Error IO Error returnlastlines lastlines file read lastlines file close os remove lastlines file name if not lastlines returntry target file open path except OS Error...
def lookup_lastlines lastlines_dirpath path underscored path replace '/' '_' try lastlines_file open os path join lastlines_dirpath underscored except OSError IOError returnlastlines lastlines_file read lastlines_file close os remove lastlines_file name if not lastlines returntry target_file open path except OSError IO...
81
python-test-4176
python
Where do groups find using passed regular expression ?
in each string in the series
def str extract noexpand arr pat flags 0 from pandas import Data Frame Indexregex re compile pat flags flags groups or na groups or na fun regex if regex groups 1 result np array [groups or na val [0 ] for val in arr] dtype object name get single group name regex else if isinstance arr Index raise Value Error 'onlyoner...
def _str_extract_noexpand arr pat flags 0 from pandas import DataFrame Indexregex re compile pat flags flags groups_or_na _groups_or_na_fun regex if regex groups 1 result np array [groups_or_na val [0] for val in arr] dtype object name _get_single_group_name regex else if isinstance arr Index raise ValueError 'onlyoner...
117
python-test-4177
python
What does this method drop ?
uc
def drop unique constraint migrate engine table name uc name *columns **col name col instance if migrate engine name in ['mysql' 'postgresql'] meta Meta Data meta bind migrate enginet Table table name meta autoload True uc Unique Constraint table t name uc name *columns uc drop else drop unique constraint in sqlite mig...
def drop_unique_constraint migrate_engine table_name uc_name *columns **col_name_col_instance if migrate_engine name in ['mysql' 'postgresql'] meta MetaData meta bind migrate_enginet Table table_name meta autoload True uc UniqueConstraint table t name uc_name *columns uc drop else _drop_unique_constraint_in_sqlite migr...
62
python-test-4179
python
What did the code set ?
the keyboard layout for the system name
def system name ret {'name' name 'changes' {} 'result' None 'comment' ''}if salt ['keyboard get sys'] name ret['result'] Trueret['comment'] ' Systemlayout{ 0 }alreadyset' format name return retif opts ['test'] ret['comment'] ' Systemlayout{ 0 }needstobeset' format name return retif salt ['keyboard set sys'] name ret['c...
def system name ret {'name' name 'changes' {} 'result' None 'comment' ''}if __salt__['keyboard get_sys'] name ret['result'] Trueret['comment'] 'Systemlayout{0}alreadyset' format name return retif __opts__['test'] ret['comment'] 'Systemlayout{0}needstobeset' format name return retif __salt__['keyboard set_sys'] name ret...
60
python-test-4180
python
What do it return ?
fires
def react main argv reactor None if reactor is None from twisted internet import reactor as reactorfinished main reactor *argv codes [0 ]stopping [] reactor add System Event Trigger 'before' 'shutdown' stopping append True def stop result stop Reactor if stop Reactor try reactor stop except Reactor Not Running passif i...
def react main argv _reactor None if _reactor is None from twisted internet import reactor as _reactorfinished main _reactor *argv codes [0]stopping []_reactor addSystemEventTrigger 'before' 'shutdown' stopping append True def stop result stopReactor if stopReactor try _reactor stop except ReactorNotRunning passif isin...
102
python-test-4181
python
Till when does the code run the reactor ?
until the l{deferred } it returns fires
def react main argv reactor None if reactor is None from twisted internet import reactor as reactorfinished main reactor *argv codes [0 ]stopping [] reactor add System Event Trigger 'before' 'shutdown' stopping append True def stop result stop Reactor if stop Reactor try reactor stop except Reactor Not Running passif i...
def react main argv _reactor None if _reactor is None from twisted internet import reactor as _reactorfinished main _reactor *argv codes [0]stopping []_reactor addSystemEventTrigger 'before' 'shutdown' stopping append True def stop result stopReactor if stopReactor try _reactor stop except ReactorNotRunning passif isin...
102
python-test-4183
python
What does the code get from a user ?
all access keys
def get all access keys user name marker None max items None region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile try return conn get all access keys user name marker max items except boto exception Boto Server Error as e log debug e log error " Failedtogetuser's{...
def get_all_access_keys user_name marker None max_items None region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile try return conn get_all_access_keys user_name marker max_items except boto exception BotoServerError as e log debug e log error "Failedtogetuser's{0}...
67
python-test-4186
python
What does the code compute ?
the entropy of a matrix / density object
def entropy density if isinstance density Density density represent density if isinstance density scipy sparse matrix density to numpy density if isinstance density Matrix eigvals density eigenvals keys return expand - sum e * log e for e in eigvals elif isinstance density numpy ndarray import numpy as npeigvals np lin...
def entropy density if isinstance density Density density represent density if isinstance density scipy_sparse_matrix density to_numpy density if isinstance density Matrix eigvals density eigenvals keys return expand - sum e * log e for e in eigvals elif isinstance density numpy_ndarray import numpy as npeigvals np lin...
70
python-test-4187
python
What did the code set ?
whether pretty - printer should use unicode by default
def pretty use unicode flag None global use unicodeglobal unicode warningsif flag is None return use unicodeif unicode warnings known [ 'LATINSUBSCRIPTSMALLLETTER%s' % i for i in 'HKLMNPST']unicode warnings '\n' join [l for l in unicode warnings splitlines if not any i in l for i in known ] if flag and unicode warnings...
def pretty_use_unicode flag None global _use_unicodeglobal unicode_warningsif flag is None return _use_unicodeif unicode_warnings known [ 'LATINSUBSCRIPTSMALLLETTER%s' % i for i in 'HKLMNPST']unicode_warnings '\n' join [l for l in unicode_warnings splitlines if not any i in l for i in known ] if flag and unicode_warnin...
71
python-test-4188
python
What should use unicode by default ?
pretty - printer
def pretty use unicode flag None global use unicodeglobal unicode warningsif flag is None return use unicodeif unicode warnings known [ 'LATINSUBSCRIPTSMALLLETTER%s' % i for i in 'HKLMNPST']unicode warnings '\n' join [l for l in unicode warnings splitlines if not any i in l for i in known ] if flag and unicode warnings...
def pretty_use_unicode flag None global _use_unicodeglobal unicode_warningsif flag is None return _use_unicodeif unicode_warnings known [ 'LATINSUBSCRIPTSMALLLETTER%s' % i for i in 'HKLMNPST']unicode_warnings '\n' join [l for l in unicode_warnings splitlines if not any i in l for i in known ] if flag and unicode_warnin...
71
python-test-4192
python
What do recursive function do for get_cycles ?
the real work
def get cycles graph dict path visited result vertice if vertice in path cycle [vertice]for node in path[ -1 ] if node vertice breakcycle insert 0 node start from min cycle index cycle index start from cycle cycle[index ] + cycle[ 0 index] if not cycle in result result append cycle returnpath append vertice try for nod...
def _get_cycles graph_dict path visited result vertice if vertice in path cycle [vertice]for node in path[ -1 ] if node vertice breakcycle insert 0 node start_from min cycle index cycle index start_from cycle cycle[index ] + cycle[0 index] if not cycle in result result append cycle returnpath append vertice try for nod...
81
python-test-4194
python
Where did the code call ?
when the group
@track state change device tracker ENTITY ID ALL DEVICES def track devices hass entity id old state new state if not TARGET ID returnif new state state STATE HOME and not core is on hass TARGET ID core turn on hass TARGET ID elif new state state STATE NOT HOME and core is on hass TARGET ID core turn off hass TARGET ID
@track_state_change device_tracker ENTITY_ID_ALL_DEVICES def track_devices hass entity_id old_state new_state if not TARGET_ID returnif new_state state STATE_HOME and not core is_on hass TARGET_ID core turn_on hass TARGET_ID elif new_state state STATE_NOT_HOME and core is_on hass TARGET_ID core turn_off hass TARGET_ID
63
python-test-4195
python
What does the code ensure ?
that the named cluster admin or database user is absent
def absent name database None user None password None host None port None ret {'name' name 'changes' {} 'result' True 'comment' ''}if salt ['influxdb 08 user exists'] name database user password host port if opts ['test'] ret['result'] Noneret['comment'] ' User{ 0 }ispresentandneedstoberemoved' format name return retif...
def absent name database None user None password None host None port None ret {'name' name 'changes' {} 'result' True 'comment' ''}if __salt__['influxdb08 user_exists'] name database user password host port if __opts__['test'] ret['result'] Noneret['comment'] 'User{0}ispresentandneedstoberemoved' format name return ret...
87
python-test-4199
python
For what purpose do all associated youtube_ids return ?
for downloads
@set databasedef get download youtube ids paths None downloaded False **kwargs if paths youtube ids dict for path in paths selector Item kind ' Topic' & Item path contains path & Item youtube id is null False if downloaded selector & Item files complete > 0 else selector & Item files complete 0 youtube ids update dict ...
@set_databasedef get_download_youtube_ids paths None downloaded False **kwargs if paths youtube_ids dict for path in paths selector Item kind 'Topic' & Item path contains path & Item youtube_id is_null False if downloaded selector & Item files_complete > 0 else selector & Item files_complete 0 youtube_ids update dict [...
78
python-test-4201
python
For what purpose do precision - recall pairs compute ?
for different probability thresholds note
def precision recall curve y true probas pred pos label None sample weight None fps tps thresholds binary clf curve y true probas pred pos label pos label sample weight sample weight precision tps / tps + fps recall tps / tps[ -1 ] last ind tps searchsorted tps[ -1 ] sl slice last ind None -1 return np r [ precision[sl...
def precision_recall_curve y_true probas_pred pos_label None sample_weight None fps tps thresholds _binary_clf_curve y_true probas_pred pos_label pos_label sample_weight sample_weight precision tps / tps + fps recall tps / tps[ -1 ] last_ind tps searchsorted tps[ -1 ] sl slice last_ind None -1 return np r_[ precision[s...
71
python-test-4202
python
What does the code find ?
the first where on earth i d for the given query
def woeid search query query u'q select*fromgeo placeswheretext "%s"' % query body web get u'http //query yahooapis com/v 1 /public/yql?' + query dont decode True parsed xmltodict parse body get u'query' results parsed get u'results' if results is None or results get u'place' is None return Noneif type results get u'pl...
def woeid_search query query u'q select*fromgeo placeswheretext "%s"' % query body web get u'http //query yahooapis com/v1/public/yql?' + query dont_decode True parsed xmltodict parse body get u'query' results parsed get u'results' if results is None or results get u'place' is None return Noneif type results get u'plac...
62
python-test-4203
python
What does the code take ?
a list of guesses
def merge similar guesses guesses prop choose similar [guess for guess in guesses if prop in guess ]if len similar < 2 returnif len similar 2 merge similar guesses nocheck guesses prop choose if len similar > 2 log debug u'complexmerge tryingourbest ' before len guesses merge similar guesses nocheck guesses prop choose...
def merge_similar_guesses guesses prop choose similar [guess for guess in guesses if prop in guess ]if len similar < 2 returnif len similar 2 _merge_similar_guesses_nocheck guesses prop choose if len similar > 2 log debug u'complexmerge tryingourbest ' before len guesses _merge_similar_guesses_nocheck guesses prop choo...
66
python-test-4204
python
What do those have ?
the same properties
def merge similar guesses guesses prop choose similar [guess for guess in guesses if prop in guess ]if len similar < 2 returnif len similar 2 merge similar guesses nocheck guesses prop choose if len similar > 2 log debug u'complexmerge tryingourbest ' before len guesses merge similar guesses nocheck guesses prop choose...
def merge_similar_guesses guesses prop choose similar [guess for guess in guesses if prop in guess ]if len similar < 2 returnif len similar 2 _merge_similar_guesses_nocheck guesses prop choose if len similar > 2 log debug u'complexmerge tryingourbest ' before len guesses _merge_similar_guesses_nocheck guesses prop choo...
66
python-test-4205
python
What does the code merge ?
those which have the same properties
def merge similar guesses guesses prop choose similar [guess for guess in guesses if prop in guess ]if len similar < 2 returnif len similar 2 merge similar guesses nocheck guesses prop choose if len similar > 2 log debug u'complexmerge tryingourbest ' before len guesses merge similar guesses nocheck guesses prop choose...
def merge_similar_guesses guesses prop choose similar [guess for guess in guesses if prop in guess ]if len similar < 2 returnif len similar 2 _merge_similar_guesses_nocheck guesses prop choose if len similar > 2 log debug u'complexmerge tryingourbest ' before len guesses _merge_similar_guesses_nocheck guesses prop choo...
66
python-test-4206
python
What does the code inject in the twitter search query form ?
a search after save checkbox
def inject search after save output if 'form' in output id 'search after save'label LABEL '%s ' % T ' Search After Save?' for 'msg twitter search' widget INPUT name 'search after save' type 'checkbox' value 'on' id id class 'boolean' comment ''if s3 formstyle 'bootstrap' controls DIV widget comment class 'controls' row...
def inject_search_after_save output if 'form' in output id 'search_after_save'label LABEL '%s ' % T 'SearchAfterSave?' _for 'msg_twitter_search' widget INPUT _name 'search_after_save' _type 'checkbox' value 'on' _id id _class 'boolean' comment ''if s3_formstyle 'bootstrap' _controls DIV widget comment _class 'controls'...
82