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-6093
python
What returns at < ?
information on the vimeo video
@hook regex 'vimeo com/ [0 - 9 ]+ ' def vimeo url match info http get json 'http //vimeo com/api/v 2 /video/%s json' % match group 1 if info info[ 0 ]['duration'] timeformat format time info[ 0 ]['duration'] info[ 0 ]['stats number of likes'] format info[ 0 ]['stats number of likes'] ' d' info[ 0 ]['stats number of pla...
@hook regex 'vimeo com/ [0-9]+ ' def vimeo_url match info http get_json 'http //vimeo com/api/v2/video/%s json' % match group 1 if info info[0]['duration'] timeformat format_time info[0]['duration'] info[0]['stats_number_of_likes'] format info[0]['stats_number_of_likes'] ' d' info[0]['stats_number_of_plays'] format inf...
118
python-test-6094
python
What does the code simplified controller open ?
the list of open tasks for it
def open tasks for project def prep r tablename 'project project's 3 crud strings[tablename] title list T ' Open Tasksfor Project' s3 crud labels READ s3 crud labels UPDATE T ' Select' s3 db configure tablename deletable False listadd False return Trues 3 prep prepdef postp r output if r interactive and not r component...
def open_tasks_for_project def prep r tablename 'project_project's3 crud_strings[tablename] title_list T 'OpenTasksforProject' s3 crud_labels READ s3 crud_labels UPDATE T 'Select' s3db configure tablename deletable False listadd False return Trues3 prep prepdef postp r output if r interactive and not r component taskli...
90
python-test-6095
python
For what purpose did the code simplify controller a project and open the list of open tasks for it ?
to select
def open tasks for project def prep r tablename 'project project's 3 crud strings[tablename] title list T ' Open Tasksfor Project' s3 crud labels READ s3 crud labels UPDATE T ' Select' s3 db configure tablename deletable False listadd False return Trues 3 prep prepdef postp r output if r interactive and not r component...
def open_tasks_for_project def prep r tablename 'project_project's3 crud_strings[tablename] title_list T 'OpenTasksforProject' s3 crud_labels READ s3 crud_labels UPDATE T 'Select' s3db configure tablename deletable False listadd False return Trues3 prep prepdef postp r output if r interactive and not r component taskli...
90
python-test-6096
python
What opens the list of open tasks for it ?
the code simplified controller
def open tasks for project def prep r tablename 'project project's 3 crud strings[tablename] title list T ' Open Tasksfor Project' s3 crud labels READ s3 crud labels UPDATE T ' Select' s3 db configure tablename deletable False listadd False return Trues 3 prep prepdef postp r output if r interactive and not r component...
def open_tasks_for_project def prep r tablename 'project_project's3 crud_strings[tablename] title_list T 'OpenTasksforProject' s3 crud_labels READ s3 crud_labels UPDATE T 'Select' s3db configure tablename deletable False listadd False return Trues3 prep prepdef postp r output if r interactive and not r component taskli...
90
python-test-6099
python
What does the code setup ?
the host objects
def setup scanner hass config see hosts [ Host ip dev id hass config for dev id ip in config[const CONF HOSTS] items ]interval timedelta seconds len hosts * config[CONF PING COUNT] + DEFAULT SCAN INTERVAL LOGGER info ' Startedpingtrackerwithinterval %sonhosts %s' interval ' ' join [host ip address for host in hosts] de...
def setup_scanner hass config see hosts [Host ip dev_id hass config for dev_id ip in config[const CONF_HOSTS] items ]interval timedelta seconds len hosts * config[CONF_PING_COUNT] + DEFAULT_SCAN_INTERVAL _LOGGER info 'Startedpingtrackerwithinterval %sonhosts %s' interval ' ' join [host ip_address for host in hosts] def...
81
python-test-6100
python
What does the code create ?
the transitiontable needed by the cluster status fsm
def build cluster status fsm table S Cluster Status States I Cluster Status Inputs O Cluster Status Outputstable Transition Table table table add Transitions S DISCONNECTED {I CONNECTED TO CONTROL SERVICE [O STORE CLIENT] S IGNORANT I SHUTDOWN [] S SHUTDOWN } table table add Transitions S IGNORANT {I DISCONNECTED FROM ...
def _build_cluster_status_fsm_table S ClusterStatusStatesI ClusterStatusInputsO ClusterStatusOutputstable TransitionTable table table addTransitions S DISCONNECTED {I CONNECTED_TO_CONTROL_SERVICE [O STORE_CLIENT] S IGNORANT I SHUTDOWN [] S SHUTDOWN } table table addTransitions S IGNORANT {I DISCONNECTED_FROM_CONTROL_SE...
126
python-test-6105
python
What does the code do ?
basic token validation
def Validate Token token targets def Get Subject For Error if len targets 1 return list targets [0 ]else return Noneif not token raise access control Unauthorized Access ' Mustgiveanauthorizationtokenfor%s' % targets subject Get Subject For Error token Check Expiry if not token username raise access control Unauthorize...
def ValidateToken token targets def GetSubjectForError if len targets 1 return list targets [0]else return Noneif not token raise access_control UnauthorizedAccess 'Mustgiveanauthorizationtokenfor%s' % targets subject GetSubjectForError token CheckExpiry if not token username raise access_control UnauthorizedAccess 'Mu...
61
python-test-6106
python
How does the last value of other fields use ?
by metric and format
def tabulate results metrics formats column width max max len k for k in formats + 1 8 first width max len k for k in metrics head fmt '{ <{fw}s}' + '{ >{cw}s}' * len formats row fmt '{ <{fw}s}' + '{ >{cw} 3f}' * len formats print head fmt format ' Metric' cw column width fw first width *formats for metric row in zip m...
def _tabulate results metrics formats column_width max max len k for k in formats + 1 8 first_width max len k for k in metrics head_fmt '{ <{fw}s}' + '{ >{cw}s}' * len formats row_fmt '{ <{fw}s}' + '{ >{cw} 3f}' * len formats print head_fmt format 'Metric' cw column_width fw first_width *formats for metric row in zip m...
84
python-test-6107
python
What does the repository contain ?
source distributions and binary distributions for flocker
@dodef upload python packages scratch directory target bucket top level output error check call ['python' 'setup py' 'sdist' '--dist-dir {}' format scratch directory path 'bdist wheel' '--dist-dir {}' format scratch directory path ] cwd top level path stdout output stderr error files set [f basename for f in scratch di...
@dodef upload_python_packages scratch_directory target_bucket top_level output error check_call ['python' 'setup py' 'sdist' '--dist-dir {}' format scratch_directory path 'bdist_wheel' '--dist-dir {}' format scratch_directory path ] cwd top_level path stdout output stderr error files set [f basename for f in scratch_di...
72
python-test-6113
python
How being source observed in the optical ?
using a ccd
def signal to noise oir ccd t source eps sky eps dark eps rd npix gain 1 0 signal t * source eps * gain noise np sqrt t * source eps * gain + npix * sky eps * gain + dark eps + npix * rd ** 2 return signal / noise
def signal_to_noise_oir_ccd t source_eps sky_eps dark_eps rd npix gain 1 0 signal t * source_eps * gain noise np sqrt t * source_eps * gain + npix * sky_eps * gain + dark_eps + npix * rd ** 2 return signal / noise
54
python-test-6114
python
What does the code compute ?
the signal to noise ratio for source being observed in the optical / ir using a ccd
def signal to noise oir ccd t source eps sky eps dark eps rd npix gain 1 0 signal t * source eps * gain noise np sqrt t * source eps * gain + npix * sky eps * gain + dark eps + npix * rd ** 2 return signal / noise
def signal_to_noise_oir_ccd t source_eps sky_eps dark_eps rd npix gain 1 0 signal t * source_eps * gain noise np sqrt t * source_eps * gain + npix * sky_eps * gain + dark_eps + npix * rd ** 2 return signal / noise
54
python-test-6115
python
Where being source observed using a ccd ?
in the optical
def signal to noise oir ccd t source eps sky eps dark eps rd npix gain 1 0 signal t * source eps * gain noise np sqrt t * source eps * gain + npix * sky eps * gain + dark eps + npix * rd ** 2 return signal / noise
def signal_to_noise_oir_ccd t source_eps sky_eps dark_eps rd npix gain 1 0 signal t * source_eps * gain noise np sqrt t * source_eps * gain + npix * sky_eps * gain + dark_eps + npix * rd ** 2 return signal / noise
54
python-test-6118
python
How do api commands respond ?
with err and mountpoint fields
def build path result tests name return build schema test name str name + u' Tests' schema {u'$ref' u'/endpoints json#/definitions/' + name } schema store SCHEMAS failing instances {'additional Properties' [{u' Err' u'' u' Mountpoint' u'/x' u'extra' u'y'} {u' Result' u'hello'}] 'required' [{} {u' Mountpoint' u'/x'}] 't...
def build_path_result_tests name return build_schema_test name str name + u'Tests' schema {u'$ref' u'/endpoints json#/definitions/' + name } schema_store SCHEMAS failing_instances {'additionalProperties' [{u'Err' u'' u'Mountpoint' u'/x' u'extra' u'y'} {u'Result' u'hello'}] 'required' [{} {u'Mountpoint' u'/x'}] 'type' [...
63
python-test-6119
python
What does the code build ?
a test for api commands that respond with err and mountpoint fields
def build path result tests name return build schema test name str name + u' Tests' schema {u'$ref' u'/endpoints json#/definitions/' + name } schema store SCHEMAS failing instances {'additional Properties' [{u' Err' u'' u' Mountpoint' u'/x' u'extra' u'y'} {u' Result' u'hello'}] 'required' [{} {u' Mountpoint' u'/x'}] 't...
def build_path_result_tests name return build_schema_test name str name + u'Tests' schema {u'$ref' u'/endpoints json#/definitions/' + name } schema_store SCHEMAS failing_instances {'additionalProperties' [{u'Err' u'' u'Mountpoint' u'/x' u'extra' u'y'} {u'Result' u'hello'}] 'required' [{} {u'Mountpoint' u'/x'}] 'type' [...
63
python-test-6125
python
What does a decorator check ?
that the currently logged - in user has a webhook post permission
def request user has webhook permission permission type from st 2 common models db webhook import Webhook D Bdef decorate func @wraps func def func wrapper *args **kwargs hook '/' join args[ 1 ] webhook db Webhook DB name hook resource db webhook dbutils assert request user has resource db permission request pecan requ...
def request_user_has_webhook_permission permission_type from st2common models db webhook import WebhookDBdef decorate func @wraps func def func_wrapper *args **kwargs hook '/' join args[1 ] webhook_db WebhookDB name hook resource_db webhook_dbutils assert_request_user_has_resource_db_permission request pecan request re...
70
python-test-6126
python
What does the currently logged - in user have ?
a webhook post permission
def request user has webhook permission permission type from st 2 common models db webhook import Webhook D Bdef decorate func @wraps func def func wrapper *args **kwargs hook '/' join args[ 1 ] webhook db Webhook DB name hook resource db webhook dbutils assert request user has resource db permission request pecan requ...
def request_user_has_webhook_permission permission_type from st2common models db webhook import WebhookDBdef decorate func @wraps func def func_wrapper *args **kwargs hook '/' join args[1 ] webhook_db WebhookDB name hook resource_db webhook_dbutils assert_request_user_has_resource_db_permission request pecan request re...
70
python-test-6128
python
What does the code generate ?
a permission class that grants access if a particular profile field is shared with the requesting user
def is field shared factory field name class Is Field Shared permissions Base Permission '\n Grantsaccessifaparticularprofilefieldissharedwiththerequestinguser \n'def has permission self request view url username request parser context get 'kwargs' {} get 'username' '' if request user username lower url username lower ...
def is_field_shared_factory field_name class IsFieldShared permissions BasePermission '\nGrantsaccessifaparticularprofilefieldissharedwiththerequestinguser \n'def has_permission self request view url_username request parser_context get 'kwargs' {} get 'username' '' if request user username lower url_username lower retu...
75
python-test-6129
python
What grants access if a particular profile field is shared with the requesting user ?
a permission class
def is field shared factory field name class Is Field Shared permissions Base Permission '\n Grantsaccessifaparticularprofilefieldissharedwiththerequestinguser \n'def has permission self request view url username request parser context get 'kwargs' {} get 'username' '' if request user username lower url username lower ...
def is_field_shared_factory field_name class IsFieldShared permissions BasePermission '\nGrantsaccessifaparticularprofilefieldissharedwiththerequestinguser \n'def has_permission self request view url_username request parser_context get 'kwargs' {} get 'username' '' if request user username lower url_username lower retu...
75
python-test-6130
python
What does a permission class grant if a particular profile field is shared with the requesting user ?
access
def is field shared factory field name class Is Field Shared permissions Base Permission '\n Grantsaccessifaparticularprofilefieldissharedwiththerequestinguser \n'def has permission self request view url username request parser context get 'kwargs' {} get 'username' '' if request user username lower url username lower ...
def is_field_shared_factory field_name class IsFieldShared permissions BasePermission '\nGrantsaccessifaparticularprofilefieldissharedwiththerequestinguser \n'def has_permission self request view url_username request parser_context get 'kwargs' {} get 'username' '' if request user username lower url_username lower retu...
75
python-test-6134
python
What does the code insert into the last element of the summary ?
an inline " read more " link
def insert read more link instance if type instance contents Article return SUMMARY MAX LENGTH instance settings get 'SUMMARY MAX LENGTH' READ MORE LINK instance settings get 'READ MORE LINK' None READ MORE LINK FORMAT instance settings get 'READ MORE LINK FORMAT' '<aclass "read-more"href "/{url}">{text}</a>' if not SU...
def insert_read_more_link instance if type instance contents Article returnSUMMARY_MAX_LENGTH instance settings get 'SUMMARY_MAX_LENGTH' READ_MORE_LINK instance settings get 'READ_MORE_LINK' None READ_MORE_LINK_FORMAT instance settings get 'READ_MORE_LINK_FORMAT' '<aclass "read-more"href "/{url}">{text}</a>' if not SUM...
108
python-test-6139
python
What does this convert to a register dump list ?
a pickled datastore
def build conversion option opt value parser try with open value 'r' as input data pickle load input except raise Configuration Exception ' File Not Found%s' % value with open value + ' dump' 'w' as output for dk dv in data iteritems output write '[%s]\n\n' % dk if isinstance dv values list output write '\n' join [ '[%...
def build_conversion option opt value parser try with open value 'r' as input data pickle load input except raise ConfigurationException 'FileNotFound%s' % value with open value + ' dump' 'w' as output for dk dv in data iteritems output write '[%s]\n\n' % dk if isinstance dv values list output write '\n' join [ '[%d] %...
106
python-test-6142
python
What does fast_parser nt parse again ?
everything
def test add to end a dedent '\nclass Abc \ndefabc self \nself x 3\n\nclass Two Abc \ndefh self \nself\n' b 'defg self \nself 'assert jedi Script a 8 12 'example py' completions assert jedi Script a + b path 'example py' completions a a[ -1 ] + ' \n' assert jedi Script a 8 13 'example py' completions assert jedi Script...
def test_add_to_end a dedent '\nclassAbc \ndefabc self \nself x 3\n\nclassTwo Abc \ndefh self \nself\n' b 'defg self \nself 'assert jedi Script a 8 12 'example py' completions assert jedi Script a + b path 'example py' completions a a[ -1 ] + ' \n' assert jedi Script a 8 13 'example py' completions assert jedi Script a...
68
python-test-6143
python
What does nt parse everything again ?
fast_parser
def test add to end a dedent '\nclass Abc \ndefabc self \nself x 3\n\nclass Two Abc \ndefh self \nself\n' b 'defg self \nself 'assert jedi Script a 8 12 'example py' completions assert jedi Script a + b path 'example py' completions a a[ -1 ] + ' \n' assert jedi Script a 8 13 'example py' completions assert jedi Script...
def test_add_to_end a dedent '\nclassAbc \ndefabc self \nself x 3\n\nclassTwo Abc \ndefh self \nself\n' b 'defg self \nself 'assert jedi Script a 8 12 'example py' completions assert jedi Script a + b path 'example py' completions a a[ -1 ] + ' \n' assert jedi Script a 8 13 'example py' completions assert jedi Script a...
68
python-test-6144
python
Does fast_parser parse everything again ?
No
def test add to end a dedent '\nclass Abc \ndefabc self \nself x 3\n\nclass Two Abc \ndefh self \nself\n' b 'defg self \nself 'assert jedi Script a 8 12 'example py' completions assert jedi Script a + b path 'example py' completions a a[ -1 ] + ' \n' assert jedi Script a 8 13 'example py' completions assert jedi Script...
def test_add_to_end a dedent '\nclassAbc \ndefabc self \nself x 3\n\nclassTwo Abc \ndefh self \nself\n' b 'defg self \nself 'assert jedi Script a 8 12 'example py' completions assert jedi Script a + b path 'example py' completions a a[ -1 ] + ' \n' assert jedi Script a 8 13 'example py' completions assert jedi Script a...
68
python-test-6145
python
When does fast_parser nt parse everything ?
again
def test add to end a dedent '\nclass Abc \ndefabc self \nself x 3\n\nclass Two Abc \ndefh self \nself\n' b 'defg self \nself 'assert jedi Script a 8 12 'example py' completions assert jedi Script a + b path 'example py' completions a a[ -1 ] + ' \n' assert jedi Script a 8 13 'example py' completions assert jedi Script...
def test_add_to_end a dedent '\nclassAbc \ndefabc self \nself x 3\n\nclassTwo Abc \ndefh self \nself\n' b 'defg self \nself 'assert jedi Script a 8 12 'example py' completions assert jedi Script a + b path 'example py' completions a a[ -1 ] + ' \n' assert jedi Script a 8 13 'example py' completions assert jedi Script a...
68
python-test-6152
python
What did the code read ?
a tag and the associated data from a socket
def recv tag raw sock s sock recv 4 * 4 if len s 16 raise Runtime Error ' Notenoughbytesreceived somethingiswrong Makesurethemne rt serverisrunning ' tag Tag *np fromstring s '>i 4 ' n received 0rec buff [s]while n received < tag size n buffer min 4096 tag size - n received this buffer sock recv n buffer rec buff appen...
def _recv_tag_raw sock s sock recv 4 * 4 if len s 16 raise RuntimeError 'Notenoughbytesreceived somethingiswrong Makesurethemne_rt_serverisrunning ' tag Tag *np fromstring s '>i4' n_received 0rec_buff [s]while n_received < tag size n_buffer min 4096 tag size - n_received this_buffer sock recv n_buffer rec_buff append t...
92
python-test-6162
python
What did the code set ?
the bom sensor
def setup platform hass config add devices discovery info None station config get CONF STATION zone id wmo id config get CONF ZONE ID config get CONF WMO ID if station is not None if zone id and wmo id LOGGER warning ' Usingconfig"%s" not"%s"and"%s"for BO Msensor' CONF STATION CONF ZONE ID CONF WMO ID elif zone id and ...
def setup_platform hass config add_devices discovery_info None station config get CONF_STATION zone_id wmo_id config get CONF_ZONE_ID config get CONF_WMO_ID if station is not None if zone_id and wmo_id _LOGGER warning 'Usingconfig"%s" not"%s"and"%s"forBOMsensor' CONF_STATION CONF_ZONE_ID CONF_WMO_ID elif zone_id and wm...
138
python-test-6163
python
What does the code implement ?
the ovs - vsctl set commands
def params set module changed Falsemodule params['ovs-vsctl'] module get bin path 'ovs-vsctl' True fmt '% ovs-vsctl s-t% timeout sget% table s% record s% col s % key s'cmd fmt % module params output cmd run module cmd False if module params['value'] not in output fmt '% ovs-vsctl s-t% timeout sset% table s% record s% c...
def params_set module changed Falsemodule params['ovs-vsctl'] module get_bin_path 'ovs-vsctl' True fmt '% ovs-vsctl s-t% timeout sget% table s% record s% col s % key s'cmd fmt % module params _ output _ cmd_run module cmd False if module params['value'] not in output fmt '% ovs-vsctl s-t% timeout sset% table s% record ...
86
python-test-6166
python
What does the code set ?
completion models
def init setting completions log completion debug ' Initializingsettingcompletion ' instances[usertypes Completion section] configmodel Setting Section Completion Model instances[usertypes Completion option] {} instances[usertypes Completion value] {}for sectname in configdata DATA opt model configmodel Setting Option ...
def _init_setting_completions log completion debug 'Initializingsettingcompletion ' _instances[usertypes Completion section] configmodel SettingSectionCompletionModel _instances[usertypes Completion option] {}_instances[usertypes Completion value] {}for sectname in configdata DATA opt_model configmodel SettingOptionCom...
65
python-test-6167
python
What does the code locate the cuda environment on the system return ?
a dict with keys home
def locate cuda if 'CUDAHOME' in os environ home os environ['CUDAHOME']nvcc pjoin home 'bin' 'nvcc' else default path pjoin os sep 'usr' 'local' 'cuda' 'bin' nvcc find in path 'nvcc' os environ['PATH'] + os pathsep + default path if nvcc is None raise Environment Error ' Thenvccbinarycouldnotbelocatedinyour$PATH Either...
def locate_cuda if 'CUDAHOME' in os environ home os environ['CUDAHOME']nvcc pjoin home 'bin' 'nvcc' else default_path pjoin os sep 'usr' 'local' 'cuda' 'bin' nvcc find_in_path 'nvcc' os environ['PATH'] + os pathsep + default_path if nvcc is None raise EnvironmentError 'Thenvccbinarycouldnotbelocatedinyour$PATH Eitherad...
97
python-test-6168
python
What returns a dict with keys home ?
the code locate the cuda environment on the system
def locate cuda if 'CUDAHOME' in os environ home os environ['CUDAHOME']nvcc pjoin home 'bin' 'nvcc' else default path pjoin os sep 'usr' 'local' 'cuda' 'bin' nvcc find in path 'nvcc' os environ['PATH'] + os pathsep + default path if nvcc is None raise Environment Error ' Thenvccbinarycouldnotbelocatedinyour$PATH Either...
def locate_cuda if 'CUDAHOME' in os environ home os environ['CUDAHOME']nvcc pjoin home 'bin' 'nvcc' else default_path pjoin os sep 'usr' 'local' 'cuda' 'bin' nvcc find_in_path 'nvcc' os environ['PATH'] + os pathsep + default_path if nvcc is None raise EnvironmentError 'Thenvccbinarycouldnotbelocatedinyour$PATH Eitherad...
97
python-test-6170
python
What does the code generate ?
an sql expression string with bound parameters rendered inline for the given sqlalchemy statement
def literalquery statement dialect None if isinstance statement sqlalchemy orm Query if dialect is None dialect statement session get bind statement mapper zero or none dialectstatement statement statementif dialect is None dialect getattr statement bind 'dialect' None if dialect is None from sqlalchemy dialects import...
def literalquery statement dialect None if isinstance statement sqlalchemy orm Query if dialect is None dialect statement session get_bind statement _mapper_zero_or_none dialectstatement statement statementif dialect is None dialect getattr statement bind 'dialect' None if dialect is None from sqlalchemy dialects impor...
113
python-test-6171
python
What does this function perform on a list of topics ?
s_one_pre segmentation
def s one pre topics s one pre []for top words in topics s one pre t []for w prime index w prime in enumerate top words[ 1 ] for w star in top words[ w prime index + 1 ] s one pre t append w prime w star s one pre append s one pre t return s one pre
def s_one_pre topics s_one_pre []for top_words in topics s_one_pre_t []for w_prime_index w_prime in enumerate top_words[1 ] for w_star in top_words[ w_prime_index + 1 ] s_one_pre_t append w_prime w_star s_one_pre append s_one_pre_t return s_one_pre
62
python-test-6172
python
Where does this function perform s_one_pre segmentation ?
on a list of topics
def s one pre topics s one pre []for top words in topics s one pre t []for w prime index w prime in enumerate top words[ 1 ] for w star in top words[ w prime index + 1 ] s one pre t append w prime w star s one pre append s one pre t return s one pre
def s_one_pre topics s_one_pre []for top_words in topics s_one_pre_t []for w_prime_index w_prime in enumerate top_words[1 ] for w_star in top_words[ w_prime_index + 1 ] s_one_pre_t append w_prime w_star s_one_pre append s_one_pre_t return s_one_pre
62
python-test-6179
python
What does the code compute ?
the alpha confidence interval for the selected quantiles of the data
def mquantiles cimj data prob [0 25 0 5 0 75 ] alpha 0 05 axis None alpha min alpha 1 - alpha z norm ppf 1 - alpha / 2 0 xq mstats mquantiles data prob alphap 0 betap 0 axis axis smj mjci data prob axis axis return xq - z * smj xq + z * smj
def mquantiles_cimj data prob [0 25 0 5 0 75] alpha 0 05 axis None alpha min alpha 1 - alpha z norm ppf 1 - alpha / 2 0 xq mstats mquantiles data prob alphap 0 betap 0 axis axis smj mjci data prob axis axis return xq - z * smj xq + z * smj
60
python-test-6180
python
When did all the theme reviewers do ?
since the great theme migration to amo up to when we started recording points
def run start date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION APPROVE reject '"action" %s' % rvw ACTION REJECT al Activity Log objects filter Q details contains approve Q details contains reject action amo LOG THEME REVIEW id created lte start date for chunk in chunked al 50 batch award points delay chu...
def run start_date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION_APPROVE reject '"action" %s' % rvw ACTION_REJECT al ActivityLog objects filter Q _details__contains approve Q _details__contains reject action amo LOG THEME_REVIEW id created__lte start_date for chunk in chunked al 50 _batch_award_points dela...
57
python-test-6181
python
What awards for all the theme reviewers done since the great theme migration to amo up to when we started recording points retroactively ?
theme reviewer points
def run start date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION APPROVE reject '"action" %s' % rvw ACTION REJECT al Activity Log objects filter Q details contains approve Q details contains reject action amo LOG THEME REVIEW id created lte start date for chunk in chunked al 50 batch award points delay chu...
def run start_date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION_APPROVE reject '"action" %s' % rvw ACTION_REJECT al ActivityLog objects filter Q _details__contains approve Q _details__contains reject action amo LOG THEME_REVIEW id created__lte start_date for chunk in chunked al 50 _batch_award_points dela...
57
python-test-6182
python
What do theme reviewer points award retroactively ?
for all the theme reviewers done since the great theme migration to amo up to when we started recording points
def run start date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION APPROVE reject '"action" %s' % rvw ACTION REJECT al Activity Log objects filter Q details contains approve Q details contains reject action amo LOG THEME REVIEW id created lte start date for chunk in chunked al 50 batch award points delay chu...
def run start_date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION_APPROVE reject '"action" %s' % rvw ACTION_REJECT al ActivityLog objects filter Q _details__contains approve Q _details__contains reject action amo LOG THEME_REVIEW id created__lte start_date for chunk in chunked al 50 _batch_award_points dela...
57
python-test-6183
python
How do theme reviewer points award for all the theme reviewers done since the great theme migration to amo up to when we started recording points ?
retroactively
def run start date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION APPROVE reject '"action" %s' % rvw ACTION REJECT al Activity Log objects filter Q details contains approve Q details contains reject action amo LOG THEME REVIEW id created lte start date for chunk in chunked al 50 batch award points delay chu...
def run start_date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION_APPROVE reject '"action" %s' % rvw ACTION_REJECT al ActivityLog objects filter Q _details__contains approve Q _details__contains reject action amo LOG THEME_REVIEW id created__lte start_date for chunk in chunked al 50 _batch_award_points dela...
57
python-test-6184
python
What did we start when ?
recording points
def run start date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION APPROVE reject '"action" %s' % rvw ACTION REJECT al Activity Log objects filter Q details contains approve Q details contains reject action amo LOG THEME REVIEW id created lte start date for chunk in chunked al 50 batch award points delay chu...
def run start_date datetime date 2013 8 27 approve '"action" %s' % rvw ACTION_APPROVE reject '"action" %s' % rvw ACTION_REJECT al ActivityLog objects filter Q _details__contains approve Q _details__contains reject action amo LOG THEME_REVIEW id created__lte start_date for chunk in chunked al 50 _batch_award_points dela...
57
python-test-6186
python
What does the code create ?
a network acl entry
def create network acl entry network acl id None rule number None protocol None rule action None cidr block None egress None network acl name None icmp code None icmp type None port range from None port range to None region None key None keyid None profile None kwargs locals return create network acl entry **kwargs
def create_network_acl_entry network_acl_id None rule_number None protocol None rule_action None cidr_block None egress None network_acl_name None icmp_code None icmp_type None port_range_from None port_range_to None region None key None keyid None profile None kwargs locals return _create_network_acl_entry **kwargs
56
python-test-6187
python
What does the code make ?
all the properties we know about in this node absolute
def Absolute Node node if node attributes for name value in node attributes items if name in [' Inherited Property Sheets' ' Relative Path' ' Additional Include Directories' ' Intermediate Directory' ' Output Directory' ' Additional Library Directories'] path list value split ' ' new list Fix Filenames path list os pat...
def AbsoluteNode node if node attributes for name value in node attributes items if name in ['InheritedPropertySheets' 'RelativePath' 'AdditionalIncludeDirectories' 'IntermediateDirectory' 'OutputDirectory' 'AdditionalLibraryDirectories'] path_list value split ' ' new_list FixFilenames path_list os path dirname ARGUMEN...
72
python-test-6188
python
Where do we know about ?
in this node absolute
def Absolute Node node if node attributes for name value in node attributes items if name in [' Inherited Property Sheets' ' Relative Path' ' Additional Include Directories' ' Intermediate Directory' ' Output Directory' ' Additional Library Directories'] path list value split ' ' new list Fix Filenames path list os pat...
def AbsoluteNode node if node attributes for name value in node attributes items if name in ['InheritedPropertySheets' 'RelativePath' 'AdditionalIncludeDirectories' 'IntermediateDirectory' 'OutputDirectory' 'AdditionalLibraryDirectories'] path_list value split ' ' new_list FixFilenames path_list os path dirname ARGUMEN...
72
python-test-6190
python
What does the code ensure ?
that diskcache
def test cache metadata config stub tmpdir config stub data {'storage' {'cache-size' 1024 } 'general' {'private-browsing' False}}url 'http //qutebrowser org'metadata Q Network Cache Meta Data metadata set Url Q Url url assert metadata is Valid disk cache cache Disk Cache str tmpdir device disk cache prepare metadata de...
def test_cache_metadata config_stub tmpdir config_stub data {'storage' {'cache-size' 1024} 'general' {'private-browsing' False}}url 'http //qutebrowser org'metadata QNetworkCacheMetaData metadata setUrl QUrl url assert metadata isValid disk_cache cache DiskCache str tmpdir device disk_cache prepare metadata device writ...
63
python-test-6193
python
What will this create ?
the welcome forum with a welcome topic
def create welcome forum if User query count < 1 return Falseuser User query filter by id 1 first category Category title u' My Category' position 1 category save forum Forum title u' Welcome' description u' Yourfirstforum' category id category id forum save topic Topic title u' Welcome ' post Post content u' Havefunwi...
def create_welcome_forum if User query count < 1 return Falseuser User query filter_by id 1 first category Category title u'MyCategory' position 1 category save forum Forum title u'Welcome' description u'Yourfirstforum' category_id category id forum save topic Topic title u'Welcome ' post Post content u'Havefunwithyour...
68
python-test-6198
python
What does the code ensure ?
a user is present
def present name profile 'github' **kwargs ret {'name' name 'changes' {} 'result' None 'comment' ''}target salt ['github get user'] name profile profile **kwargs if not target ret['result'] Falseret['comment'] ' Couldntfinduser{ 0 }' format name elif isinstance target bool and target ret['comment'] ' User{ 0 }isalready...
def present name profile 'github' **kwargs ret {'name' name 'changes' {} 'result' None 'comment' ''}target __salt__['github get_user'] name profile profile **kwargs if not target ret['result'] Falseret['comment'] 'Couldntfinduser{0}' format name elif isinstance target bool and target ret['comment'] 'User{0}isalreadyint...
118
python-test-6201
python
What does the code provide by attaching labels to the right end of each line ?
a legend for line charts
def Inline Legend chart show Falselabels []label positions []for series in chart data if series label is None labels append '' else labels append series label show Truelabel positions append series data[ -1 ] if show chart right min chart left minchart right max chart left maxchart right labels labelschart right label ...
def InlineLegend chart show Falselabels []label_positions []for series in chart data if series label is None labels append '' else labels append series label show Truelabel_positions append series data[ -1 ] if show chart right min chart left minchart right max chart left maxchart right labels labelschart right label_p...
58
python-test-6202
python
How does the code provide a legend for line charts ?
by attaching labels to the right end of each line
def Inline Legend chart show Falselabels []label positions []for series in chart data if series label is None labels append '' else labels append series label show Truelabel positions append series data[ -1 ] if show chart right min chart left minchart right max chart left maxchart right labels labelschart right label ...
def InlineLegend chart show Falselabels []label_positions []for series in chart data if series label is None labels append '' else labels append series label show Truelabel_positions append series data[ -1 ] if show chart right min chart left minchart right max chart left maxchart right labels labelschart right label_p...
58
python-test-6204
python
For what purpose do ip allocation pools create ?
for a specified subnet
def generate pools cidr gateway ip net netaddr IP Network cidr ip version net versionfirst netaddr IP Address net first ip version last netaddr IP Address net last ip version if first last return [netaddr IP Range first last ]first ip first + 1 last ip last - ip version 4 if first ip > last ip return []ipset netaddr IP...
def generate_pools cidr gateway_ip net netaddr IPNetwork cidr ip_version net versionfirst netaddr IPAddress net first ip_version last netaddr IPAddress net last ip_version if first last return [netaddr IPRange first last ]first_ip first + 1 last_ip last - ip_version 4 if first_ip > last_ip return []ipset netaddr IPSet ...
86
python-test-6205
python
What defines a subnets allocation pools as a list of iprange objects for defining the pool range ?
the neutron api
def generate pools cidr gateway ip net netaddr IP Network cidr ip version net versionfirst netaddr IP Address net first ip version last netaddr IP Address net last ip version if first last return [netaddr IP Range first last ]first ip first + 1 last ip last - ip version 4 if first ip > last ip return []ipset netaddr IP...
def generate_pools cidr gateway_ip net netaddr IPNetwork cidr ip_version net versionfirst netaddr IPAddress net first ip_version last netaddr IPAddress net last ip_version if first last return [netaddr IPRange first last ]first_ip first + 1 last_ip last - ip_version 4 if first_ip > last_ip return []ipset netaddr IPSet ...
86
python-test-6206
python
What does the neutron api define as a list of iprange objects for defining the pool range ?
a subnets allocation pools
def generate pools cidr gateway ip net netaddr IP Network cidr ip version net versionfirst netaddr IP Address net first ip version last netaddr IP Address net last ip version if first last return [netaddr IP Range first last ]first ip first + 1 last ip last - ip version 4 if first ip > last ip return []ipset netaddr IP...
def generate_pools cidr gateway_ip net netaddr IPNetwork cidr ip_version net versionfirst netaddr IPAddress net first ip_version last netaddr IPAddress net last ip_version if first last return [netaddr IPRange first last ]first_ip first + 1 last_ip last - ip_version 4 if first_ip > last_ip return []ipset netaddr IPSet ...
86
python-test-6212
python
What does the code calculate ?
the 0 order modified bessel function of the first kind
def i0 x return tt switch tt lt x 5 1 + x ** 2 / 4 + x ** 4 / 64 + x ** 6 / 2304 + x ** 8 / 147456 + x ** 10 / 14745600 + x ** 12 / 2123366400 np e ** x / 2 * np pi * x ** 0 5 * 1 + 1 / 8 * x + 9 / 128 * x ** 2 + 225 / 3072 * x ** 3 + 11025 / 98304 * x ** 4
def i0 x return tt switch tt lt x 5 1 + x ** 2 / 4 + x ** 4 / 64 + x ** 6 / 2304 + x ** 8 / 147456 + x ** 10 / 14745600 + x ** 12 / 2123366400 np e ** x / 2 * np pi * x ** 0 5 * 1 + 1 / 8 * x + 9 / 128 * x ** 2 + 225 / 3072 * x ** 3 + 11025 / 98304 * x ** 4
93
python-test-6214
python
What does the code generate ?
a random probable prime
def generate probable prime **kwargs exact bits kwargs pop 'exact bits' None randfunc kwargs pop 'randfunc' None prime filter kwargs pop 'prime filter' lambda x True if kwargs print ' Unknownparameters ' kwargs keys if exact bits is None raise Value Error ' Missingexact bitsparameter' if exact bits < 160 raise Value Er...
def generate_probable_prime **kwargs exact_bits kwargs pop 'exact_bits' None randfunc kwargs pop 'randfunc' None prime_filter kwargs pop 'prime_filter' lambda x True if kwargs print 'Unknownparameters ' kwargs keys if exact_bits is None raise ValueError 'Missingexact_bitsparameter' if exact_bits < 160 raise ValueError ...
91
python-test-6219
python
What does the code update ?
the global list of error - suppressions
def Parse Nolint Suppressions filename raw line linenum error matched RE SUPPRESSION search raw line if matched category matched group 1 if category in None ' * ' error suppressions setdefault None set add linenum elif category startswith ' ' and category endswith ' ' category category[ 1 -1 ]if category in ERROR CATEG...
def ParseNolintSuppressions filename raw_line linenum error matched _RE_SUPPRESSION search raw_line if matched category matched group 1 if category in None ' * ' _error_suppressions setdefault None set add linenum elif category startswith ' ' and category endswith ' ' category category[1 -1 ]if category in _ERROR_CATEG...
74
python-test-6222
python
Where do python code execute ?
in the most recent stack frame
def evalcode python executor code input type global dict gdb parse and eval ' Py Eval Get Globals ' local dict gdb parse and eval ' Py Eval Get Locals ' if pointervalue global dict 0 or pointervalue local dict 0 raise gdb Gdb Error ' Unabletofindthelocalsorglobalsofthemostrecent Pythonfunction relativetotheselectedfram...
def _evalcode_python executor code input_type global_dict gdb parse_and_eval 'PyEval_GetGlobals ' local_dict gdb parse_and_eval 'PyEval_GetLocals ' if pointervalue global_dict 0 or pointervalue local_dict 0 raise gdb GdbError 'UnabletofindthelocalsorglobalsofthemostrecentPythonfunction relativetotheselectedframe ' retu...
60
python-test-6223
python
What did a bug in putmask cause ?
erroneous mapping of 1
def test colormap endian cmap cm get cmap u'jet' a [ -0 5 0 0 5 1 1 5 np nan]for dt in [u'f 2 ' u'f 4 ' u'f 8 '] anative np ma masked invalid np array a dtype dt aforeign anative byteswap newbyteorder assert array equal cmap anative cmap aforeign
def test_colormap_endian cmap cm get_cmap u'jet' a [ -0 5 0 0 5 1 1 5 np nan]for dt in [u'f2' u'f4' u'f8'] anative np ma masked_invalid np array a dtype dt aforeign anative byteswap newbyteorder assert_array_equal cmap anative cmap aforeign
53
python-test-6224
python
What caused erroneous mapping of 1 ?
a bug in putmask
def test colormap endian cmap cm get cmap u'jet' a [ -0 5 0 0 5 1 1 5 np nan]for dt in [u'f 2 ' u'f 4 ' u'f 8 '] anative np ma masked invalid np array a dtype dt aforeign anative byteswap newbyteorder assert array equal cmap anative cmap aforeign
def test_colormap_endian cmap cm get_cmap u'jet' a [ -0 5 0 0 5 1 1 5 np nan]for dt in [u'f2' u'f4' u'f8'] anative np ma masked_invalid np array a dtype dt aforeign anative byteswap newbyteorder assert_array_equal cmap anative cmap aforeign
53
python-test-6231
python
What does the code make ?
a lowercase string with capitals
def nice case line l line lower s ''i 0next Cap 1while i < len l c l[i]if c > 'a' and c < 'z' and next Cap c c upper next Cap 0elif c '' or c ' ' or c ' ' or c ' ' or c ' ' or c ' DCTB ' or c '-' or c ' ' next Cap 1s + ci + 1return s
def _nice_case line l line lower s ''i 0nextCap 1while i < len l c l[i]if c > 'a' and c < 'z' and nextCap c c upper nextCap 0elif c '' or c ' ' or c ' ' or c ' ' or c ' ' or c ' DCTB ' or c '-' or c '_' nextCap 1s + ci + 1return s
72
python-test-6232
python
What will checks that lets encrypt consider ?
domain to be valid
def enforce le validity domain domain enforce domain sanity domain if not re match '^[A- Za-z 0 - 9 -]*$' domain raise errors Configuration Error '{ 0 }containsaninvalidcharacter Validcharactersare A-Z a-z 0- 9 and- ' format domain labels domain split ' ' if len labels < 2 raise errors Configuration Error '{ 0 }needsat...
def enforce_le_validity domain domain enforce_domain_sanity domain if not re match '^[A-Za-z0-9 -]*$' domain raise errors ConfigurationError '{0}containsaninvalidcharacter ValidcharactersareA-Z a-z 0-9 and- ' format domain labels domain split ' ' if len labels < 2 raise errors ConfigurationError '{0}needsatleasttwolabe...
94
python-test-6233
python
What will consider domain to be valid ?
checks that lets encrypt
def enforce le validity domain domain enforce domain sanity domain if not re match '^[A- Za-z 0 - 9 -]*$' domain raise errors Configuration Error '{ 0 }containsaninvalidcharacter Validcharactersare A-Z a-z 0- 9 and- ' format domain labels domain split ' ' if len labels < 2 raise errors Configuration Error '{ 0 }needsat...
def enforce_le_validity domain domain enforce_domain_sanity domain if not re match '^[A-Za-z0-9 -]*$' domain raise errors ConfigurationError '{0}containsaninvalidcharacter ValidcharactersareA-Z a-z 0-9 and- ' format domain labels domain split ' ' if len labels < 2 raise errors ConfigurationError '{0}needsatleasttwolabe...
94
python-test-6241
python
What does the code select ?
the * k * individuals among the input * individuals *
def sel Stochastic Universal Sampling individuals k s inds sorted individuals key attrgetter 'fitness' reverse True sum fits sum ind fitness values[ 0 ] for ind in individuals distance sum fits / float k start random uniform 0 distance points [ start + i * distance for i in xrange k ]chosen []for p in points i 0sum s i...
def selStochasticUniversalSampling individuals k s_inds sorted individuals key attrgetter 'fitness' reverse True sum_fits sum ind fitness values[0] for ind in individuals distance sum_fits / float k start random uniform 0 distance points [ start + i * distance for i in xrange k ]chosen []for p in points i 0sum_ s_inds[...
82
python-test-6249
python
What does the code instantiate ?
a placeholder tensor
def placeholder shape None ndim None dtype None sparse False name None if dtype is None dtype floatx if not shape if ndim shape tuple [ None for in range ndim ] if sparse x tf sparse placeholder dtype name name x dims len shape else x tf placeholder dtype shape shape name name x keras shape shapex uses learning phase F...
def placeholder shape None ndim None dtype None sparse False name None if dtype is None dtype floatx if not shape if ndim shape tuple [None for _ in range ndim ] if sparse x tf sparse_placeholder dtype name name x _dims len shape else x tf placeholder dtype shape shape name name x _keras_shape shapex _uses_learning_pha...
63
python-test-6252
python
How did the code set editorstack ?
with codeeditor containing some python code
def setup editor qtbot text 'a 1\nprint a \n\nx 2'editor Stack Editor Stack None [] editor Stack set introspector Mock editor Stack set find widget Mock editor Stack set io actions Mock Mock Mock Mock finfo editor Stack new 'foo py' 'utf- 8 ' text qtbot add Widget editor Stack return editor Stack finfo editor
def setup_editor qtbot text 'a 1\nprint a \n\nx 2'editorStack EditorStack None [] editorStack set_introspector Mock editorStack set_find_widget Mock editorStack set_io_actions Mock Mock Mock Mock finfo editorStack new 'foo py' 'utf-8' text qtbot addWidget editorStack return editorStack finfo editor
55
python-test-6253
python
What do codeeditor contain ?
some python code
def setup editor qtbot text 'a 1\nprint a \n\nx 2'editor Stack Editor Stack None [] editor Stack set introspector Mock editor Stack set find widget Mock editor Stack set io actions Mock Mock Mock Mock finfo editor Stack new 'foo py' 'utf- 8 ' text qtbot add Widget editor Stack return editor Stack finfo editor
def setup_editor qtbot text 'a 1\nprint a \n\nx 2'editorStack EditorStack None [] editorStack set_introspector Mock editorStack set_find_widget Mock editorStack set_io_actions Mock Mock Mock Mock finfo editorStack new 'foo py' 'utf-8' text qtbot addWidget editorStack return editorStack finfo editor
55
python-test-6254
python
What is containing some python code ?
codeeditor
def setup editor qtbot text 'a 1\nprint a \n\nx 2'editor Stack Editor Stack None [] editor Stack set introspector Mock editor Stack set find widget Mock editor Stack set io actions Mock Mock Mock Mock finfo editor Stack new 'foo py' 'utf- 8 ' text qtbot add Widget editor Stack return editor Stack finfo editor
def setup_editor qtbot text 'a 1\nprint a \n\nx 2'editorStack EditorStack None [] editorStack set_introspector Mock editorStack set_find_widget Mock editorStack set_io_actions Mock Mock Mock Mock finfo editorStack new 'foo py' 'utf-8' text qtbot addWidget editorStack return editorStack finfo editor
55
python-test-6255
python
What did the code set with codeeditor containing some python code ?
editorstack
def setup editor qtbot text 'a 1\nprint a \n\nx 2'editor Stack Editor Stack None [] editor Stack set introspector Mock editor Stack set find widget Mock editor Stack set io actions Mock Mock Mock Mock finfo editor Stack new 'foo py' 'utf- 8 ' text qtbot add Widget editor Stack return editor Stack finfo editor
def setup_editor qtbot text 'a 1\nprint a \n\nx 2'editorStack EditorStack None [] editorStack set_introspector Mock editorStack set_find_widget Mock editorStack set_io_actions Mock Mock Mock Mock finfo editorStack new 'foo py' 'utf-8' text qtbot addWidget editorStack return editorStack finfo editor
55
python-test-6264
python
What should appear in stderr ?
an exception thrown
def test cp 12403 super Console Send Keys 'output Redirect Start{ }{ }{ENTER}' super Console Send Keys 'raise Exception{ }" Somestringexception"{ }{ENTER}' expected [' Traceback mostrecentcalllast ' ' File"<stdin>" line 1 in<module>' ' Exception Somestringexception' '']super Console Send Keys 'output Redirect Stop{ }{ ...
def test_cp12403 superConsole SendKeys 'outputRedirectStart{ }{ }{ENTER}' superConsole SendKeys 'raiseException{ }"Somestringexception"{ }{ENTER}' expected ['Traceback mostrecentcalllast ' 'File"<stdin>" line1 in<module>' 'Exception Somestringexception' '']superConsole SendKeys 'outputRedirectStop{ }{ }{ENTER}' AreEqua...
77
python-test-6265
python
Where should an exception thrown appear ?
in stderr
def test cp 12403 super Console Send Keys 'output Redirect Start{ }{ }{ENTER}' super Console Send Keys 'raise Exception{ }" Somestringexception"{ }{ENTER}' expected [' Traceback mostrecentcalllast ' ' File"<stdin>" line 1 in<module>' ' Exception Somestringexception' '']super Console Send Keys 'output Redirect Stop{ }{ ...
def test_cp12403 superConsole SendKeys 'outputRedirectStart{ }{ }{ENTER}' superConsole SendKeys 'raiseException{ }"Somestringexception"{ }{ENTER}' expected ['Traceback mostrecentcalllast ' 'File"<stdin>" line1 in<module>' 'Exception Somestringexception' '']superConsole SendKeys 'outputRedirectStop{ }{ }{ENTER}' AreEqua...
77
python-test-6268
python
What computes within a job ?
log probabilities
def parallel predict log proba estimators estimators features X n classes n samples X shape[ 0 ]log proba np empty n samples n classes log proba fill - np inf all classes np arange n classes dtype np int for estimator features in zip estimators estimators features log proba estimator estimator predict log proba X[ feat...
def _parallel_predict_log_proba estimators estimators_features X n_classes n_samples X shape[0]log_proba np empty n_samples n_classes log_proba fill - np inf all_classes np arange n_classes dtype np int for estimator features in zip estimators estimators_features log_proba_estimator estimator predict_log_proba X[ featu...
115
python-test-6269
python
What did private function use ?
to compute log probabilities within a job
def parallel predict log proba estimators estimators features X n classes n samples X shape[ 0 ]log proba np empty n samples n classes log proba fill - np inf all classes np arange n classes dtype np int for estimator features in zip estimators estimators features log proba estimator estimator predict log proba X[ feat...
def _parallel_predict_log_proba estimators estimators_features X n_classes n_samples X shape[0]log_proba np empty n_samples n_classes log_proba fill - np inf all_classes np arange n_classes dtype np int for estimator features in zip estimators estimators_features log_proba_estimator estimator predict_log_proba X[ featu...
115
python-test-6270
python
What does the code verify ?
the actual censure keypoints and their corresponding scale with the expected values for star filter
def test keypoints censure moon image star detector CENSURE mode 'star' detector detect rescale img 0 25 expected keypoints np array [[ 23 27 ] [29 89 ] [30 86 ] [107 59 ] [109 64 ] [111 67 ] [113 70 ]] expected scales np array [3 2 4 2 5 3 2] assert array equal expected keypoints detector keypoints assert array equal ...
def test_keypoints_censure_moon_image_star detector CENSURE mode 'star' detector detect rescale img 0 25 expected_keypoints np array [[23 27] [29 89] [30 86] [107 59] [109 64] [111 67] [113 70]] expected_scales np array [3 2 4 2 5 3 2] assert_array_equal expected_keypoints detector keypoints assert_array_equal expected...
68
python-test-6283
python
What do helper send ?
an ec2_compatible error
def ec 2 error req request id code message LOG error '% code s % message s' % locals resp webob Response resp status 400 resp headers[' Content- Type'] 'text/xml'resp body str '<?xmlversion "1 0"?>\n< Response>< Errors>< Error>< Code>%s</ Code>< Message>%s</ Message></ Error></ Errors>< Request ID>%s</ Request ID></ Re...
def ec2_error req request_id code message LOG error _ '% code s % message s' % locals resp webob Response resp status 400resp headers['Content-Type'] 'text/xml'resp body str '<?xmlversion "1 0"?>\n<Response><Errors><Error><Code>%s</Code><Message>%s</Message></Error></Errors><RequestID>%s</RequestID></Response>' % utils...
74
python-test-6291
python
What does the code make ?
a summary for the report
def build summary layout level 1 assert level > 0 level - 1summary List klass u'summary' for child in layout children if not isinstance child Section continuelabel layout title child if not label and not child id continueif not child id child id label replace '' '-' node Link u'#' + child id label label or child id if ...
def build_summary layout level 1 assert level > 0 level - 1summary List klass u'summary' for child in layout children if not isinstance child Section continuelabel layout_title child if not label and not child id continueif not child id child id label replace '' '-' node Link u'#' + child id label label or child id if ...
85
python-test-6295
python
How do feature file names collect ?
by processing list of paths
def collect feature locations paths strict True locations []for path in paths if os path isdir path for dirpath dirnames filenames in os walk path dirnames sort for filename in sorted filenames if filename endswith ' feature' location File Location os path join dirpath filename locations append location elif path start...
def collect_feature_locations paths strict True locations []for path in paths if os path isdir path for dirpath dirnames filenames in os walk path dirnames sort for filename in sorted filenames if filename endswith ' feature' location FileLocation os path join dirpath filename locations append location elif path starts...
98
python-test-6297
python
What contains the tail_avg ?
the bin
def histogram bins timeseries series scipy array [x[ 1 ] for x in timeseries] t tail avg timeseries h np histogram series bins 15 bins h[ 1 ]for index bin size in enumerate h[ 0 ] if bin size < 20 if index 0 if t < bins[ 0 ] return Trueelif t > bins[index] and t < bins[ index + 1 ] return Truereturn False
def histogram_bins timeseries series scipy array [x[1] for x in timeseries] t tail_avg timeseries h np histogram series bins 15 bins h[1]for index bin_size in enumerate h[0] if bin_size < 20 if index 0 if t < bins[0] return Trueelif t > bins[index] and t < bins[ index + 1 ] return Truereturn False
66
python-test-6298
python
What does the bin contain ?
the tail_avg
def histogram bins timeseries series scipy array [x[ 1 ] for x in timeseries] t tail avg timeseries h np histogram series bins 15 bins h[ 1 ]for index bin size in enumerate h[ 0 ] if bin size < 20 if index 0 if t < bins[ 0 ] return Trueelif t > bins[index] and t < bins[ index + 1 ] return Truereturn False
def histogram_bins timeseries series scipy array [x[1] for x in timeseries] t tail_avg timeseries h np histogram series bins 15 bins h[1]for index bin_size in enumerate h[0] if bin_size < 20 if index 0 if t < bins[0] return Trueelif t > bins[index] and t < bins[ index + 1 ] return Truereturn False
66
python-test-6299
python
What does the code do ?
a health check on solr
def ping host None core name None ret get return dict if get none or value core name is None and check for cores success Truefor name in opts ['solr cores'] resp get admin info 'ping' host host core name name if resp['success'] data {name {'status' resp['data']['status']}}else success Falsedata {name {'status' None}}re...
def ping host None core_name None ret _get_return_dict if _get_none_or_value core_name is None and _check_for_cores success Truefor name in __opts__['solr cores'] resp _get_admin_info 'ping' host host core_name name if resp['success'] data {name {'status' resp['data']['status']}}else success Falsedata {name {'status' N...
74
python-test-6310
python
What does the code require ?
a ppa _ package source
def ppa name auto accept True keyserver None assert name startswith 'ppa ' user repo name[ 4 ] split '/' 2 release float distrib release if release > 12 04 repo repo replace ' ' ' ' auto accept '--yes' if auto accept else '' else auto accept ''if not isinstance keyserver basestring and keyserver keyserver keyserver[ 0 ...
def ppa name auto_accept True keyserver None assert name startswith 'ppa ' user repo name[4 ] split '/' 2 release float distrib_release if release > 12 04 repo repo replace ' ' '_' auto_accept '--yes' if auto_accept else '' else auto_accept ''if not isinstance keyserver basestring and keyserver keyserver keyserver[0]if...
114
python-test-6311
python
What does the code remove from the list of featured activity references ?
the specified activity reference
def remove featured activity activity type activity id featured references get featured activity references activity reference found Falsenew activity references []for reference in featured references if reference type activity type or reference id activity id new activity references append reference else activity refe...
def remove_featured_activity activity_type activity_id featured_references get_featured_activity_references activity_reference_found Falsenew_activity_references []for reference in featured_references if reference type activity_type or reference id activity_id new_activity_references append reference else activity_refe...
65
python-test-6323
python
Where do each test visit with c{visitor } ?
in c{suite
def suite Visit suite visitor warnings warn ' Testvisitorsdeprecatedin Twisted 8 0' category Deprecation Warning for case in suite tests visit getattr case 'visit' None if visit is not None visit visitor elif isinstance case pyunit Test Case case itrial I Test Case case case visit visitor elif isinstance case pyunit Te...
def suiteVisit suite visitor warnings warn 'TestvisitorsdeprecatedinTwisted8 0' category DeprecationWarning for case in suite _tests visit getattr case 'visit' None if visit is not None visit visitor elif isinstance case pyunit TestCase case itrial ITestCase case case visit visitor elif isinstance case pyunit TestSuite...
61
python-test-6324
python
How do each test visit in c{suite } ?
with c{visitor
def suite Visit suite visitor warnings warn ' Testvisitorsdeprecatedin Twisted 8 0' category Deprecation Warning for case in suite tests visit getattr case 'visit' None if visit is not None visit visitor elif isinstance case pyunit Test Case case itrial I Test Case case case visit visitor elif isinstance case pyunit Te...
def suiteVisit suite visitor warnings warn 'TestvisitorsdeprecatedinTwisted8 0' category DeprecationWarning for case in suite _tests visit getattr case 'visit' None if visit is not None visit visitor elif isinstance case pyunit TestCase case itrial ITestCase case case visit visitor elif isinstance case pyunit TestSuite...
61
python-test-6326
python
What can you access ?
a message by i d in our apis that either : ( 1 ) you received or have previously accessed via starring
def access message user profile message id try message Message objects select related get id message id except Message Does Not Exist raise Jsonable Error ' Invalidmessage s ' try user message User Message objects select related get user profile user profile message message except User Message Does Not Exist user messa...
def access_message user_profile message_id try message Message objects select_related get id message_id except Message DoesNotExist raise JsonableError _ 'Invalidmessage s ' try user_message UserMessage objects select_related get user_profile user_profile message message except UserMessage DoesNotExist user_message Non...
108
python-test-6327
python
How have you accessed a message previously ?
via starring
def access message user profile message id try message Message objects select related get id message id except Message Does Not Exist raise Jsonable Error ' Invalidmessage s ' try user message User Message objects select related get user profile user profile message message except User Message Does Not Exist user messa...
def access_message user_profile message_id try message Message objects select_related get id message_id except Message DoesNotExist raise JsonableError _ 'Invalidmessage s ' try user_message UserMessage objects select_related get user_profile user_profile message message except UserMessage DoesNotExist user_message Non...
108
python-test-6329
python
What can the string representation of an angle be used ?
to create a new valid angle
def test angle format roundtripping a1 Angle 0 unit u radian a2 Angle 10 unit u degree a3 Angle 0 543 unit u degree a4 Angle u' 1 d 2 m 3 4s' assert Angle str a1 degree a1 degree assert Angle str a2 degree a2 degree assert Angle str a3 degree a3 degree assert Angle str a4 degree a4 degree ra Longitude u' 1 h 2 m 3 4s' ...
def test_angle_format_roundtripping a1 Angle 0 unit u radian a2 Angle 10 unit u degree a3 Angle 0 543 unit u degree a4 Angle u'1d2m3 4s' assert Angle str a1 degree a1 degree assert Angle str a2 degree a2 degree assert Angle str a3 degree a3 degree assert Angle str a4 degree a4 degree ra Longitude u'1h2m3 4s' dec Latitu...
95
python-test-6330
python
What can be used to create a new valid angle ?
the string representation of an angle
def test angle format roundtripping a1 Angle 0 unit u radian a2 Angle 10 unit u degree a3 Angle 0 543 unit u degree a4 Angle u' 1 d 2 m 3 4s' assert Angle str a1 degree a1 degree assert Angle str a2 degree a2 degree assert Angle str a3 degree a3 degree assert Angle str a4 degree a4 degree ra Longitude u' 1 h 2 m 3 4s' ...
def test_angle_format_roundtripping a1 Angle 0 unit u radian a2 Angle 10 unit u degree a3 Angle 0 543 unit u degree a4 Angle u'1d2m3 4s' assert Angle str a1 degree a1 degree assert Angle str a2 degree a2 degree assert Angle str a3 degree a3 degree assert Angle str a4 degree a4 degree ra Longitude u'1h2m3 4s' dec Latitu...
95
python-test-6336
python
What does the code get if filesystemid is specified filesystemid - i d of the file system to retrieve properties returns - list of all elastic file system properties cli example ?
all efs properties or a specific instance property
def get file systems filesystemid None keyid None key None profile None region None **kwargs result Noneclient get conn key key keyid keyid profile profile region region if filesystemid response client describe file systems File System Id filesystemid result response[' File Systems']else response client describe file s...
def get_file_systems filesystemid None keyid None key None profile None region None **kwargs result Noneclient _get_conn key key keyid keyid profile profile region region if filesystemid response client describe_file_systems FileSystemId filesystemid result response['FileSystems']else response client describe_file_syst...
72
python-test-6339
python
What can that be used ?
to call configure snapshot = get_configuration ( ) configure
def get configuration root get Logger name levels [ '' logging get Level Name root level ]name levels extend name logging get Level Name logger level for name logger in root manager logger Dict items if hasattr logger 'level' config string ' ' join '%s %s' % x for x in name levels return dict config string config strin...
def get_configuration root getLogger name_levels [ '' logging getLevelName root level ]name_levels extend name logging getLevelName logger level for name logger in root manager loggerDict items if hasattr logger 'level' config_string ' ' join '%s %s' % x for x in name_levels return dict config_string config_string log_...
66
python-test-6340
python
What does the code get ?
a configuration that can be used to call configure snapshot = get_configuration ( ) configure
def get configuration root get Logger name levels [ '' logging get Level Name root level ]name levels extend name logging get Level Name logger level for name logger in root manager logger Dict items if hasattr logger 'level' config string ' ' join '%s %s' % x for x in name levels return dict config string config strin...
def get_configuration root getLogger name_levels [ '' logging getLevelName root level ]name_levels extend name logging getLevelName logger level for name logger in root manager loggerDict items if hasattr logger 'level' config_string ' ' join '%s %s' % x for x in name_levels return dict config_string config_string log_...
66
python-test-6344
python
For what purpose did by the servicetester call the code ?
in order to test build_archive service api call
def Test Build Archive tester user cookie user id device id tester Get Ids From Cookie user cookie request dict {'email' 'user 1 @emailscrubbed com'}actual dict tester Send Request 'build archive' user cookie request dict tester Compare Response Dicts 'build archive' user id request dict {} actual dict return actual di...
def _TestBuildArchive tester user_cookie user_id device_id tester GetIdsFromCookie user_cookie request_dict {'email' 'user1@emailscrubbed com'}actual_dict tester SendRequest 'build_archive' user_cookie request_dict tester _CompareResponseDicts 'build_archive' user_id request_dict {} actual_dict return actual_dict
51
python-test-6346
python
What does the code make ?
a trivial single - dispatch generic function
def simplegeneric func registry {}def wrapper *args **kw ob args[ 0 ]try cls ob class except Attribute Error cls type ob try mro cls mro except Attribute Error try class cls cls object passmro cls mro [1 ]except Type Error mro object for t in mro if t in registry return registry[t] *args **kw else return func *args **k...
def simplegeneric func registry {}def wrapper *args **kw ob args[0]try cls ob __class__except AttributeError cls type ob try mro cls __mro__except AttributeError try class cls cls object passmro cls __mro__[1 ]except TypeError mro object for t in mro if t in registry return registry[t] *args **kw else return func *args...
98
python-test-6349
python
What do we nt use ?
the argmax
@register uncanonicalize@gof local optimizer [T Max And Argmax] def local max and argmax node if isinstance node op T Max And Argmax axis node op get params node if len node outputs[ 1 ] clients 0 new CA Reduce scal maximum axis node inputs[ 0 ] return [new None]if len node outputs[ 0 ] clients 0 return [ None T argmax...
@register_uncanonicalize@gof local_optimizer [T MaxAndArgmax] def local_max_and_argmax node if isinstance node op T MaxAndArgmax axis node op get_params node if len node outputs[1] clients 0 new CAReduce scal maximum axis node inputs[0] return [new None]if len node outputs[0] clients 0 return [None T _argmax node input...
67
python-test-6350
python
Do we use the argmax ?
No
@register uncanonicalize@gof local optimizer [T Max And Argmax] def local max and argmax node if isinstance node op T Max And Argmax axis node op get params node if len node outputs[ 1 ] clients 0 new CA Reduce scal maximum axis node inputs[ 0 ] return [new None]if len node outputs[ 0 ] clients 0 return [ None T argmax...
@register_uncanonicalize@gof local_optimizer [T MaxAndArgmax] def local_max_and_argmax node if isinstance node op T MaxAndArgmax axis node op get_params node if len node outputs[1] clients 0 new CAReduce scal maximum axis node inputs[0] return [new None]if len node outputs[0] clients 0 return [None T _argmax node input...
67
python-test-6351
python
What do an iterator return ?
platerecords
def parse handle format if not isinstance format basestring raise Type Error ' Needastringforthefileformat lowercase ' if not format raise Value Error ' Formatrequired lowercasestring ' if format format lower raise Value Error " Formatstring'%s'shouldbelowercase" % format with as handle handle 'r U' as fp if format in ...
def parse handle format if not isinstance format basestring raise TypeError 'Needastringforthefileformat lowercase ' if not format raise ValueError 'Formatrequired lowercasestring ' if format format lower raise ValueError "Formatstring'%s'shouldbelowercase" % format with as_handle handle 'rU' as fp if format in _Format...
73
python-test-6355
python
How is a service discovered ?
via dnsservicebrowse ( ) and dnsserviceresolve ( ) calls
def DNS Service Register flags 0 interface Index kDNS Service Interface Index Any name None regtype NO DEFAULT domain None host None port NO DEFAULT txt Record '' call Back None NO DEFAULT check regtype NO DEFAULT check port port socket htons port if not txt Record txt Len txt Record 1 '\x 00 ' else txt Len txt Record ...
def DNSServiceRegister flags 0 interfaceIndex kDNSServiceInterfaceIndexAny name None regtype _NO_DEFAULT domain None host None port _NO_DEFAULT txtRecord '' callBack None _NO_DEFAULT check regtype _NO_DEFAULT check port port socket htons port if not txtRecord txtLen txtRecord 1 '\x00' else txtLen txtRecord _string_to_l...
137
python-test-6356
python
How do all members list ?
without mfa turned on
def list members without mfa profile 'github' ignore cache False key 'github {0 } non mfa users' format get config value profile 'org name' if key not in context or ignore cache client get client profile organization client get organization get config value profile 'org name' filter key 'filter'if hasattr github Team T...
def list_members_without_mfa profile 'github' ignore_cache False key 'github {0} non_mfa_users' format _get_config_value profile 'org_name' if key not in __context__ or ignore_cache client _get_client profile organization client get_organization _get_config_value profile 'org_name' filter_key 'filter'if hasattr github ...
77
python-test-6358
python
What does the code get from the " code " ?
an access token
def get access token from code code redirect uri app id app secret args {'code' code 'redirect uri' redirect uri 'client id' app id 'client secret' app secret}response urllib urlopen 'https //graph facebook com/oauth/access token' + '?' + urllib urlencode args read query str parse qs response if 'access token' in query...
def get_access_token_from_code code redirect_uri app_id app_secret args {'code' code 'redirect_uri' redirect_uri 'client_id' app_id 'client_secret' app_secret}response urllib urlopen 'https //graph facebook com/oauth/access_token' + '?' + urllib urlencode args read query_str parse_qs response if 'access_token' in query...
80
python-test-6365
python
Where do incremental mean and variance along an axix compute ?
on a csr or csc matrix
def incr mean variance axis X axis last mean last var last n raise error wrong axis axis if isinstance X sp csr matrix if axis 0 return incr mean var axis 0 X last mean last mean last var last var last n last n else return incr mean var axis 0 X T last mean last mean last var last var last n last n elif isinstance X sp...
def incr_mean_variance_axis X axis last_mean last_var last_n _raise_error_wrong_axis axis if isinstance X sp csr_matrix if axis 0 return _incr_mean_var_axis0 X last_mean last_mean last_var last_var last_n last_n else return _incr_mean_var_axis0 X T last_mean last_mean last_var last_var last_n last_n elif isinstance X s...
120
python-test-6366
python
What computes on a csr or csc matrix ?
incremental mean and variance along an axix
def incr mean variance axis X axis last mean last var last n raise error wrong axis axis if isinstance X sp csr matrix if axis 0 return incr mean var axis 0 X last mean last mean last var last var last n last n else return incr mean var axis 0 X T last mean last mean last var last var last n last n elif isinstance X sp...
def incr_mean_variance_axis X axis last_mean last_var last_n _raise_error_wrong_axis axis if isinstance X sp csr_matrix if axis 0 return _incr_mean_var_axis0 X last_mean last_mean last_var last_var last_n last_n else return _incr_mean_var_axis0 X T last_mean last_mean last_var last_var last_n last_n elif isinstance X s...
120
python-test-6367
python
What does the code get ?
user data
def get user data userid profile 'grafana' if isinstance profile string types profile salt ['config option'] profile response requests get '{ 0 }/api/users/{ 1 }' format profile['grafana url'] userid auth get auth profile headers get headers profile timeout profile get 'grafana timeout' 3 if response status code > 400 ...
def get_user_data userid profile 'grafana' if isinstance profile string_types profile __salt__['config option'] profile response requests get '{0}/api/users/{1}' format profile['grafana_url'] userid auth _get_auth profile headers _get_headers profile timeout profile get 'grafana_timeout' 3 if response status_code > 400...
56
python-test-6368
python
What does the code clean ?
a sff file
def cleanup sff flowgrams header outhandle None outdir '/tmp' min length 150 max length 400 clean filename ''if not outhandle fd clean filename mkstemp dir outdir prefix 'cleanup sff' suffix ' sff txt' close fd outhandle open clean filename 'w' l filter sff file flowgrams header [ lambda f within length f min length ma...
def cleanup_sff flowgrams header outhandle None outdir '/tmp' min_length 150 max_length 400 clean_filename ''if not outhandle fd clean_filename mkstemp dir outdir prefix 'cleanup_sff' suffix ' sff txt' close fd outhandle open clean_filename 'w' l filter_sff_file flowgrams header [ lambda f within_length f min_length ma...
68