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-1952
python
What does the code allocate to that container ?
the list " cpus " of cpus
def create container with mbytes and specific cpus name mbytes cpus None root SUPER ROOT io {} move in True timeout 0 need mem containers if not container exists root raise error Autotest Error ' Parentcontainer"%s"doesnotexist' % root if cpus is None cpus get cpus root else cpus set cpus if not cpus raise error Autote...
def create_container_with_mbytes_and_specific_cpus name mbytes cpus None root SUPER_ROOT io {} move_in True timeout 0 need_mem_containers if not container_exists root raise error AutotestError 'Parentcontainer"%s"doesnotexist' % root if cpus is None cpus get_cpus root else cpus set cpus if not cpus raise error Autotest...
101
python-test-1953
python
How d the code get a repository_review from the database ?
via repository i d
def get review by repository id changeset revision user id app repository id changeset revision user id sa session app model context currentreturn sa session query app model Repository Review filter and app model Repository Review repository id app security decode id repository id app model Repository Review changeset ...
def get_review_by_repository_id_changeset_revision_user_id app repository_id changeset_revision user_id sa_session app model context currentreturn sa_session query app model RepositoryReview filter and_ app model RepositoryReview repository_id app security decode_id repository_id app model RepositoryReview changeset_re...
65
python-test-1956
python
What does the code filter ?
the data based on those fields
def marshal data fields envelope None def make cls if isinstance cls type return cls return clsif isinstance data list tuple return Ordered Dict [ envelope [marshal d fields for d in data] ] if envelope else [marshal d fields for d in data] items k marshal data v if isinstance v dict else make v output k data for k v i...
def marshal data fields envelope None def make cls if isinstance cls type return cls return clsif isinstance data list tuple return OrderedDict [ envelope [marshal d fields for d in data] ] if envelope else [marshal d fields for d in data] items k marshal data v if isinstance v dict else make v output k data for k v in...
80
python-test-1957
python
What does the code take ?
raw data and a dict of fields to output
def marshal data fields envelope None def make cls if isinstance cls type return cls return clsif isinstance data list tuple return Ordered Dict [ envelope [marshal d fields for d in data] ] if envelope else [marshal d fields for d in data] items k marshal data v if isinstance v dict else make v output k data for k v i...
def marshal data fields envelope None def make cls if isinstance cls type return cls return clsif isinstance data list tuple return OrderedDict [ envelope [marshal d fields for d in data] ] if envelope else [marshal d fields for d in data] items k marshal data v if isinstance v dict else make v output k data for k v in...
80
python-test-1959
python
When do the meta data update ?
when cache is not activated
def test cache deactivated update metadata config stub tmpdir config stub data {'storage' {'cache-size' 1024 } 'general' {'private-browsing' True}}url 'http //qutebrowser org'disk cache cache Disk Cache str tmpdir metadata Q Network Cache Meta Data metadata set Url Q Url url assert metadata is Valid assert disk cache u...
def test_cache_deactivated_update_metadata config_stub tmpdir config_stub data {'storage' {'cache-size' 1024} 'general' {'private-browsing' True}}url 'http //qutebrowser org'disk_cache cache DiskCache str tmpdir metadata QNetworkCacheMetaData metadata setUrl QUrl url assert metadata isValid assert disk_cache updateMeta...
53
python-test-1960
python
Where does the code create a nvp logical router ?
on the specified cluster
def create lrouter cluster tenant id display name nexthop tags [{'tag' tenant id 'scope' 'os tid'}]display name check and truncate name display name lrouter obj {'display name' display name 'tags' tags 'routing config' {'default route next hop' {'gateway ip address' nexthop 'type' ' Router Next Hop'} 'type' ' Single De...
def create_lrouter cluster tenant_id display_name nexthop tags [{'tag' tenant_id 'scope' 'os_tid'}]display_name _check_and_truncate_name display_name lrouter_obj {'display_name' display_name 'tags' tags 'routing_config' {'default_route_next_hop' {'gateway_ip_address' nexthop 'type' 'RouterNextHop'} 'type' 'SingleDefaul...
95
python-test-1961
python
What does the code create on the specified cluster ?
a nvp logical router
def create lrouter cluster tenant id display name nexthop tags [{'tag' tenant id 'scope' 'os tid'}]display name check and truncate name display name lrouter obj {'display name' display name 'tags' tags 'routing config' {'default route next hop' {'gateway ip address' nexthop 'type' ' Router Next Hop'} 'type' ' Single De...
def create_lrouter cluster tenant_id display_name nexthop tags [{'tag' tenant_id 'scope' 'os_tid'}]display_name _check_and_truncate_name display_name lrouter_obj {'display_name' display_name 'tags' tags 'routing_config' {'default_route_next_hop' {'gateway_ip_address' nexthop 'type' 'RouterNextHop'} 'type' 'SingleDefaul...
95
python-test-1964
python
What does the code add ?
the given fake facilities
def generate fake facilities names ' Wilson Elementary' facilities []for name in names found facilities Facility objects filter name name if found facilities facility found facilities[ 0 ]logging info " Retrievedfacility'%s'" % name else facility Facility name name facility save logging info " Createdfacility'%s'" % na...
def generate_fake_facilities names 'WilsonElementary' facilities []for name in names found_facilities Facility objects filter name name if found_facilities facility found_facilities[0]logging info "Retrievedfacility'%s'" % name else facility Facility name name facility save logging info "Createdfacility'%s'" % name fac...
51
python-test-1971
python
What does the code generate ?
the description of a l{klein } route
def format Route Body data schema store base Substitutions {u'DOMAIN' u'example com' u'NODE 0' u'cf 0 f 0346 - 17 b 2 - 4812 -beca- 1434997 d 6 c 3 f' u'NODE 1' u' 7 ec 3 c 4 eb- 6 b 1 c- 43 da- 8015 -a 163 f 7 d 15244 '}for line in data['description'] yield line if 'input' in data for line in format Actual Schema data...
def _formatRouteBody data schema_store baseSubstitutions {u'DOMAIN' u'example com' u'NODE_0' u'cf0f0346-17b2-4812-beca-1434997d6c3f' u'NODE_1' u'7ec3c4eb-6b1c-43da-8015-a163f7d15244'}for line in data['description'] yield line if 'input' in data for line in _formatActualSchema data['input_schema'] '+RequestJSONSchema' s...
142
python-test-1973
python
How do image adjustments apply ?
one by one
def apply adjustments rgba adjustments if not adjustments return rgbafor adjustment in adjustments name args adjustment[ 0 ] adjustment[ 1 ] if name 'threshold' rgba apply threshold adjustment rgba *args elif name 'curves' rgba apply curves adjustment rgba *args elif name 'curves 2 ' rgba apply curves 2 adjustment rgba...
def apply_adjustments rgba adjustments if not adjustments return rgbafor adjustment in adjustments name args adjustment[0] adjustment[1 ] if name 'threshold' rgba apply_threshold_adjustment rgba *args elif name 'curves' rgba apply_curves_adjustment rgba *args elif name 'curves2' rgba apply_curves2_adjustment rgba *args...
64
python-test-1975
python
What do file download if it does not already exist ?
to filename fname
def verify Third Party File url checksum fname name os path basename fname if os path exists fname print ' Usinglocalcopyof%s' % name else print ' Didnotfindlocalcopyof%s' % name print ' Downloading%s' % name download URL url fname print ' Archivefor%sstoredas%s' % name fname if os system 'MD 5 $ opensslmd 5 %s test"${...
def verifyThirdPartyFile url checksum fname name os path basename fname if os path exists fname print 'Usinglocalcopyof%s' % name else print 'Didnotfindlocalcopyof%s' % name print 'Downloading%s' % name downloadURL url fname print 'Archivefor%sstoredas%s' % name fname if os system 'MD5 $ opensslmd5%s test"${MD5##* }" "...
69
python-test-1978
python
What does the code reduce ?
the complex valued equation f(x ) = y
def invert f x y x domain S Complexes x sympify x if not x is Symbol raise Value Error 'xmustbeasymbol' f x sympify f x if not f x has x raise Value Error " Inverseofconstantfunctiondoesn'texist" y sympify y if y has x raise Value Error 'yshouldbeindependentofx' if domain is subset S Reals x s invert real f x Finite Se...
def _invert f_x y x domain S Complexes x sympify x if not x is_Symbol raise ValueError 'xmustbeasymbol' f_x sympify f_x if not f_x has x raise ValueError "Inverseofconstantfunctiondoesn'texist" y sympify y if y has x raise ValueError 'yshouldbeindependentofx' if domain is_subset S Reals x s _invert_real f_x FiniteSet y...
87
python-test-1981
python
What does helper method create ?
a cluster with up and down services
def create populated cluster ctxt num services num down svcs 0 **values up time timeutils utcnow down time up time - datetime timedelta seconds CONF service down time + 1 cluster create cluster ctxt **values svcs [db service create ctxt {'cluster name' cluster name 'host' 'host' + str i 'updated at' down time if i < nu...
def create_populated_cluster ctxt num_services num_down_svcs 0 **values up_time timeutils utcnow down_time up_time - datetime timedelta seconds CONF service_down_time + 1 cluster create_cluster ctxt **values svcs [db service_create ctxt {'cluster_name' cluster name 'host' 'host' + str i 'updated_at' down_time if i < nu...
72
python-test-1985
python
What does the code check ?
a symbolic mathematical expression using sympy
def symmath check simple expect ans adict {} symtab None extra options None options {' MATRIX ' False ' ABC ' False ' LOWER ' False}if extra options options update extra options for op in options if op in expect expect expect replace op '' options[op] Trueexpect expect replace ' OR ' ' or ' if options[' LOWER '] expect...
def symmath_check_simple expect ans adict {} symtab None extra_options None options {'__MATRIX__' False '__ABC__' False '__LOWER__' False}if extra_options options update extra_options for op in options if op in expect expect expect replace op '' options[op] Trueexpect expect replace '__OR__' '__or__' if options['__LOWE...
100
python-test-1986
python
What is using sympy ?
a symbolic mathematical expression
def symmath check simple expect ans adict {} symtab None extra options None options {' MATRIX ' False ' ABC ' False ' LOWER ' False}if extra options options update extra options for op in options if op in expect expect expect replace op '' options[op] Trueexpect expect replace ' OR ' ' or ' if options[' LOWER '] expect...
def symmath_check_simple expect ans adict {} symtab None extra_options None options {'__MATRIX__' False '__ABC__' False '__LOWER__' False}if extra_options options update extra_options for op in options if op in expect expect expect replace op '' options[op] Trueexpect expect replace '__OR__' '__or__' if options['__LOWE...
100
python-test-1988
python
What does the code find in file system ?
control files
def get tests from fs parent dir control pattern add noncompliant False tests {}profilers Falseif 'client/profilers' in parent dir profilers Truefor dir in [parent dir] files recursive walk dir control pattern for file in files if ' init py' in file or ' svn' in file continueif not profilers if not add noncompliant try...
def get_tests_from_fs parent_dir control_pattern add_noncompliant False tests {}profilers Falseif 'client/profilers' in parent_dir profilers Truefor dir in [parent_dir] files recursive_walk dir control_pattern for file in files if '__init__ py' in file or ' svn' in file continueif not profilers if not add_noncompliant ...
108
python-test-1989
python
Where does the code find control files ?
in file system
def get tests from fs parent dir control pattern add noncompliant False tests {}profilers Falseif 'client/profilers' in parent dir profilers Truefor dir in [parent dir] files recursive walk dir control pattern for file in files if ' init py' in file or ' svn' in file continueif not profilers if not add noncompliant try...
def get_tests_from_fs parent_dir control_pattern add_noncompliant False tests {}profilers Falseif 'client/profilers' in parent_dir profilers Truefor dir in [parent_dir] files recursive_walk dir control_pattern for file in files if '__init__ py' in file or ' svn' in file continueif not profilers if not add_noncompliant ...
108
python-test-1991
python
What does the code compute ?
the contribution of the string at * index * in the match set
def match Set Contribution match set target set index contribution 0 0for t in target set match - float 'inf' id -1 for i m in enumerate match set v match Strength m t if v > match match vid iif id index contribution + matchreturn contribution / len target set
def matchSetContribution match_set target_set index contribution 0 0for t in target_set match - float 'inf' id -1 for i m in enumerate match_set v matchStrength m t if v > match match vid iif id index contribution + matchreturn contribution / len target_set
51
python-test-1993
python
How did an equivalent qt css gradient fragment return ?
qlineargradient
def css gradient gradient stop final Stop gradient start gradient final Stop x1 y1 x2 y2 stop x stop y final Stop x final Stop y stops gradient stops stops '\n' join 'stop {0 f}{ 1 }' format stop color name for stop color in stops return 'qlineargradient \nx 1 {x 1 } y1 {y 1 } x2 {x 1 } y2 {y 2 } \n{stops} ' format x1 ...
def css_gradient gradient stop finalStop gradient start gradient finalStop x1 y1 x2 y2 stop x stop y finalStop x finalStop y stops gradient stops stops '\n' join 'stop {0 f}{1}' format stop color name for stop color in stops return 'qlineargradient \nx1 {x1} y1 {y1} x2 {x1} y2 {y2} \n{stops} ' format x1 x1 y1 y1 x2 x2 ...
78
python-test-1995
python
What are rolled in the delta response ?
multiple revisions of the same object
def test events are condensed api client message ts int time time + 22 cursor get cursor api client ts message id api client get data '/messages/' [0 ]['id']message path '/messages/{}' format message id api client put data message path {'unread' True} api client put data message path {'unread' False} api client put dat...
def test_events_are_condensed api_client message ts int time time + 22 cursor get_cursor api_client ts message_id api_client get_data '/messages/' [0]['id']message_path '/messages/{}' format message_id api_client put_data message_path {'unread' True} api_client put_data message_path {'unread' False} api_client put_data...
99
python-test-1996
python
Where are multiple revisions of the same object rolled ?
in the delta response
def test events are condensed api client message ts int time time + 22 cursor get cursor api client ts message id api client get data '/messages/' [0 ]['id']message path '/messages/{}' format message id api client put data message path {'unread' True} api client put data message path {'unread' False} api client put dat...
def test_events_are_condensed api_client message ts int time time + 22 cursor get_cursor api_client ts message_id api_client get_data '/messages/' [0]['id']message_path '/messages/{}' format message_id api_client put_data message_path {'unread' True} api_client put_data message_path {'unread' False} api_client put_data...
99
python-test-1998
python
Who is asking them ?
what did they work on today
def trigger emails settings frappe get doc u' Daily Work Summary Settings' for d in settings companies if frappe utils nowtime split u' ' [0 ] d send emails at split u' ' [0 ] emails get employee emails d company if emails daily work summary frappe get doc dict doctype u' Daily Work Summary' company d company insert da...
def trigger_emails settings frappe get_doc u'DailyWorkSummarySettings' for d in settings companies if frappe utils nowtime split u' ' [0] d send_emails_at split u' ' [0] emails get_employee_emails d company if emails daily_work_summary frappe get_doc dict doctype u'DailyWorkSummary' company d company insert daily_work_...
66
python-test-1999
python
When do emails send to employees of the enabled companies asking them what did they work on today ?
at the give hour
def trigger emails settings frappe get doc u' Daily Work Summary Settings' for d in settings companies if frappe utils nowtime split u' ' [0 ] d send emails at split u' ' [0 ] emails get employee emails d company if emails daily work summary frappe get doc dict doctype u' Daily Work Summary' company d company insert da...
def trigger_emails settings frappe get_doc u'DailyWorkSummarySettings' for d in settings companies if frappe utils nowtime split u' ' [0] d send_emails_at split u' ' [0] emails get_employee_emails d company if emails daily_work_summary frappe get_doc dict doctype u'DailyWorkSummary' company d company insert daily_work_...
66
python-test-2001
python
What do we want ?
to generate a requirements
@only cidef generate requirements txt failed deps req file file REQUIREMENTS TXT 'w' if failed deps for pkg in failed deps if pkg is git req file write '%s\n' % pkg git src else req file write '%s %s\n' % pkg package name pkg package version req file close return REQUIREMENTS TXT
@only_cidef generate_requirements_txt failed_deps req_file file REQUIREMENTS_TXT 'w' if failed_deps for pkg in failed_deps if pkg is_git req_file write '%s\n' % pkg git_src else req_file write '%s %s\n' % pkg package_name pkg package_version req_file close return REQUIREMENTS_TXT
52
python-test-2002
python
What did the code put to local cache ?
our response object
def put response to local cache url our resp without content False if parse method 'GET' or our resp status code 200 returndbgprint ' Putting Cache ' url 'without content ' without content if without content our resp copy copy our resp our resp response Noneobj size 0else our resp our respobj size len parse remote resp...
def put_response_to_local_cache url _our_resp without_content False if parse method 'GET' or _our_resp status_code 200 returndbgprint 'PuttingCache ' url 'without_content ' without_content if without_content our_resp copy copy _our_resp our_resp response Noneobj_size 0else our_resp _our_respobj_size len parse remote_re...
100
python-test-2005
python
How are keyhints shown ?
based on a prefix
def test suggestions keyhint key config stub key config stub set bindings for 'normal' Ordered Dict [ 'aa' 'cmd-aa' 'ab' 'cmd-ab' 'aba' 'cmd-aba' 'abb' 'cmd-abb' 'xd' 'cmd-xd' 'xe' 'cmd-xe' ] keyhint update keyhint 'normal' 'a' assert keyhint text expected text 'a' 'yellow' 'a' 'cmd-aa' 'a' 'yellow' 'b' 'cmd-ab' 'a' 'y...
def test_suggestions keyhint key_config_stub key_config_stub set_bindings_for 'normal' OrderedDict [ 'aa' 'cmd-aa' 'ab' 'cmd-ab' 'aba' 'cmd-aba' 'abb' 'cmd-abb' 'xd' 'cmd-xd' 'xe' 'cmd-xe' ] keyhint update_keyhint 'normal' 'a' assert keyhint text expected_text 'a' 'yellow' 'a' 'cmd-aa' 'a' 'yellow' 'b' 'cmd-ab' 'a' 'ye...
56
python-test-2012
python
What does the code extract ?
the hash sum
def get source sum source hash file path saltenv ret dict schemes u'salt' u'http' u'https' u'ftp' u'swift' u's 3 ' u'file' invalid hash msg u" Sourcehash'{ 0 }'formatisinvalid Itmustbeintheformat<hashtype> <hash>" format source hash source hash str source hash source hash scheme urlparse source hash schemeif source has...
def _get_source_sum source_hash file_path saltenv ret dict schemes u'salt' u'http' u'https' u'ftp' u'swift' u's3' u'file' invalid_hash_msg u"Sourcehash'{0}'formatisinvalid Itmustbeintheformat<hashtype> <hash>" format source_hash source_hash str source_hash source_hash_scheme _urlparse source_hash schemeif source_hash_s...
145
python-test-2014
python
Where does the code rewrite an exception if needed ?
in an event
def rewrite exception data exc data data get 'sentry interfaces Exception' if not exc data return Falserv Falsefor exc in exc data['values'] for processor in six itervalues error processors try if processor try process exc rv Truebreakexcept Exception as e logger error ' Failedtorunprocessor"%s" %s' processor vendor e ...
def rewrite_exception data exc_data data get 'sentry interfaces Exception' if not exc_data return Falserv Falsefor exc in exc_data['values'] for processor in six itervalues error_processors try if processor try_process exc rv Truebreakexcept Exception as e logger error 'Failedtorunprocessor"%s" %s' processor vendor e e...
53
python-test-2017
python
What does the code convert to an mne struct ?
a set of coils
def compute mne loc coil loc loc np zeros 12 if np linalg norm coil loc['inner coil'] 0 and np linalg norm coil loc['outer coil'] 0 return locloc[ 0 3] coil loc['inner coil'] / 39 370078 z axis coil loc['outer coil'] - coil loc['inner coil'] R rotation 3 d align z axis z axis loc[ 3 13 ] R T reshape 9 return loc
def _compute_mne_loc coil_loc loc np zeros 12 if np linalg norm coil_loc['inner_coil'] 0 and np linalg norm coil_loc['outer_coil'] 0 return locloc[0 3] coil_loc['inner_coil'] / 39 370078 z_axis coil_loc['outer_coil'] - coil_loc['inner_coil'] R rotation3d_align_z_axis z_axis loc[3 13] R T reshape 9 return loc
64
python-test-2024
python
How do new cameras create ?
using a string name
def make camera cam type *args **kwargs cam types { None Base Camera}for cam Type in Base Camera Pan Zoom Camera Perspective Camera Turntable Camera Fly Camera Arcball Camera cam types[cam Type name [ -6 ] lower ] cam Typetry return cam types[cam type] *args **kwargs except Key Error raise Key Error ' Unknowncameratype...
def make_camera cam_type *args **kwargs cam_types {None BaseCamera}for camType in BaseCamera PanZoomCamera PerspectiveCamera TurntableCamera FlyCamera ArcballCamera cam_types[camType __name__[ -6 ] lower ] camTypetry return cam_types[cam_type] *args **kwargs except KeyError raise KeyError 'Unknowncameratype"%s" Options...
62
python-test-2025
python
What is using a string name ?
new cameras
def make camera cam type *args **kwargs cam types { None Base Camera}for cam Type in Base Camera Pan Zoom Camera Perspective Camera Turntable Camera Fly Camera Arcball Camera cam types[cam Type name [ -6 ] lower ] cam Typetry return cam types[cam type] *args **kwargs except Key Error raise Key Error ' Unknowncameratype...
def make_camera cam_type *args **kwargs cam_types {None BaseCamera}for camType in BaseCamera PanZoomCamera PerspectiveCamera TurntableCamera FlyCamera ArcballCamera cam_types[camType __name__[ -6 ] lower ] camTypetry return cam_types[cam_type] *args **kwargs except KeyError raise KeyError 'Unknowncameratype"%s" Options...
62
python-test-2026
python
What do new cameras use ?
a string name
def make camera cam type *args **kwargs cam types { None Base Camera}for cam Type in Base Camera Pan Zoom Camera Perspective Camera Turntable Camera Fly Camera Arcball Camera cam types[cam Type name [ -6 ] lower ] cam Typetry return cam types[cam type] *args **kwargs except Key Error raise Key Error ' Unknowncameratype...
def make_camera cam_type *args **kwargs cam_types {None BaseCamera}for camType in BaseCamera PanZoomCamera PerspectiveCamera TurntableCamera FlyCamera ArcballCamera cam_types[camType __name__[ -6 ] lower ] camTypetry return cam_types[cam_type] *args **kwargs except KeyError raise KeyError 'Unknowncameratype"%s" Options...
62
python-test-2028
python
What do we store in shared variables the reason ?
our dataset
def shared dataset data xy borrow True data x data y data xyshared x theano shared np asarray data x dtype theano config float X borrow borrow shared y theano shared np asarray data y dtype theano config float X borrow borrow return shared x T cast shared y 'int 32 '
def shared_dataset data_xy borrow True data_x data_y data_xyshared_x theano shared np asarray data_x dtype theano config floatX borrow borrow shared_y theano shared np asarray data_y dtype theano config floatX borrow borrow return shared_x T cast shared_y 'int32'
52
python-test-2029
python
What copys it into the gpu memory ?
theano
def shared dataset data xy borrow True data x data y data xyshared x theano shared np asarray data x dtype theano config float X borrow borrow shared y theano shared np asarray data y dtype theano config float X borrow borrow return shared x T cast shared y 'int 32 '
def shared_dataset data_xy borrow True data_x data_y data_xyshared_x theano shared np asarray data_x dtype theano config floatX borrow borrow shared_y theano shared np asarray data_y dtype theano config floatX borrow borrow return shared_x T cast shared_y 'int32'
52
python-test-2030
python
What is to allow theano to copy it into the gpu memory ?
the reason we store our dataset in shared variables
def shared dataset data xy borrow True data x data y data xyshared x theano shared np asarray data x dtype theano config float X borrow borrow shared y theano shared np asarray data y dtype theano config float X borrow borrow return shared x T cast shared y 'int 32 '
def shared_dataset data_xy borrow True data_x data_y data_xyshared_x theano shared np asarray data_x dtype theano config floatX borrow borrow shared_y theano shared np asarray data_y dtype theano config floatX borrow borrow return shared_x T cast shared_y 'int32'
52
python-test-2031
python
What does the reason we store our dataset in shared variables be ?
to allow theano to copy it into the gpu memory
def shared dataset data xy borrow True data x data y data xyshared x theano shared np asarray data x dtype theano config float X borrow borrow shared y theano shared np asarray data y dtype theano config float X borrow borrow return shared x T cast shared y 'int 32 '
def shared_dataset data_xy borrow True data_x data_y data_xyshared_x theano shared np asarray data_x dtype theano config floatX borrow borrow shared_y theano shared np asarray data_y dtype theano config floatX borrow borrow return shared_x T cast shared_y 'int32'
52
python-test-2032
python
What do a compass file contain ?
one compass record
def read handle record Nonetry line next handle record Record read names record line line next handle read threshold record line line next handle read lengths record line line next handle read profilewidth record line line next handle read scores record line except Stop Iteration if not record raise Value Error ' Norec...
def read handle record Nonetry line next handle record Record __read_names record line line next handle __read_threshold record line line next handle __read_lengths record line line next handle __read_profilewidth record line line next handle __read_scores record line except StopIteration if not record raise ValueError...
102
python-test-2033
python
What is containing one compass record ?
a compass file
def read handle record Nonetry line next handle record Record read names record line line next handle read threshold record line line next handle read lengths record line line next handle read profilewidth record line line next handle read scores record line except Stop Iteration if not record raise Value Error ' Norec...
def read handle record Nonetry line next handle record Record __read_names record line line next handle __read_threshold record line line next handle __read_lengths record line line next handle __read_profilewidth record line line next handle __read_scores record line except StopIteration if not record raise ValueError...
102
python-test-2037
python
What does the code return ?
the name of the type of the given property value
def Property Type Name value if value class in PROPERTY MEANINGS meaning PROPERTY MEANINGS[value class ]name entity pb Property Meaning NAMES[meaning]return name lower replace ' ' ' ' elif isinstance value basestring return 'string'elif isinstance value users User return 'user'elif isinstance value long return 'int'eli...
def PropertyTypeName value if value __class__ in _PROPERTY_MEANINGS meaning _PROPERTY_MEANINGS[value __class__]name entity_pb Property _Meaning_NAMES[meaning]return name lower replace '_' ' ' elif isinstance value basestring return 'string'elif isinstance value users User return 'user'elif isinstance value long return ...
54
python-test-2043
python
Where did object ids see ?
in a structure
def Collect Object I Ds ids obj if id obj in ids returnids add id obj if isinstance obj list tuple set frozenset for e in obj Collect Object I Ds ids e elif isinstance obj dict for k v in obj items Collect Object I Ds ids k Collect Object I Ds ids v return len ids
def CollectObjectIDs ids obj if id obj in ids returnids add id obj if isinstance obj list tuple set frozenset for e in obj CollectObjectIDs ids e elif isinstance obj dict for k v in obj items CollectObjectIDs ids k CollectObjectIDs ids v return len ids
58
python-test-2044
python
What seen in a structure ?
object ids
def Collect Object I Ds ids obj if id obj in ids returnids add id obj if isinstance obj list tuple set frozenset for e in obj Collect Object I Ds ids e elif isinstance obj dict for k v in obj items Collect Object I Ds ids k Collect Object I Ds ids v return len ids
def CollectObjectIDs ids obj if id obj in ids returnids add id obj if isinstance obj list tuple set frozenset for e in obj CollectObjectIDs ids e elif isinstance obj dict for k v in obj items CollectObjectIDs ids k CollectObjectIDs ids v return len ids
58
python-test-2045
python
What does the code compute ?
the number of patches that will be extracted in an image
def compute n patches i h i w p h p w max patches None n h i h - p h + 1 n w i w - p w + 1 all patches n h * n w if max patches if isinstance max patches numbers Integral and max patches < all patches return max patcheselif isinstance max patches numbers Real and 0 < max patches < 1 return int max patches * all patches...
def _compute_n_patches i_h i_w p_h p_w max_patches None n_h i_h - p_h + 1 n_w i_w - p_w + 1 all_patches n_h * n_w if max_patches if isinstance max_patches numbers Integral and max_patches < all_patches return max_patcheselif isinstance max_patches numbers Real and 0 < max_patches < 1 return int max_patches * all_patche...
92
python-test-2047
python
For what purpose did role require ?
to access a resource - used by gis for map layer permissions management
def s3 role required T current Tgtable current auth settings table grouprepresent S3 Represent lookup 'auth group' fields ['role'] f S3 Reusable Field 'role required' gtable sortby 'role' requires IS EMPTY OR IS ONE OF current db 'auth group id' represent zero T ' Public' represent represent label T ' Role Required' co...
def s3_role_required T current Tgtable current auth settings table_grouprepresent S3Represent lookup 'auth_group' fields ['role'] f S3ReusableField 'role_required' gtable sortby 'role' requires IS_EMPTY_OR IS_ONE_OF current db 'auth_group id' represent zero T 'Public' represent represent label T 'RoleRequired' comment ...
72
python-test-2048
python
What does the code retrieve from the catalog service ?
all program types
def get program types user None catalog integration Catalog Integration current if catalog integration enabled user get service user user catalog integration service username if not user return []api create catalog api client user catalog integration cache key '{base} program types' format base catalog integration CACH...
def get_program_types user None catalog_integration CatalogIntegration current if catalog_integration enabled user _get_service_user user catalog_integration service_username if not user return []api create_catalog_api_client user catalog_integration cache_key '{base} program_types' format base catalog_integration CACH...
74
python-test-2049
python
What does the code throttle ?
the rate at which occurrences of some event can occur
def Throttle Rate throttle dict max count time period now Get Current Timestamp if not throttle dict or now > throttle dict['start time'] + time period throttle dict {'start time' now 'count' 0}else throttle dict {'start time' throttle dict['start time'] 'count' throttle dict['count']}if throttle dict['count'] > max co...
def ThrottleRate throttle_dict max_count time_period now GetCurrentTimestamp if not throttle_dict or now > throttle_dict['start_time'] + time_period throttle_dict {'start_time' now 'count' 0}else throttle_dict {'start_time' throttle_dict['start_time'] 'count' throttle_dict['count']}if throttle_dict['count'] > max_count...
59
python-test-2050
python
How do environments start ?
without errors
@pytest mark parametrize 'env id' test envs def test smoke env id gym undo logger setup logging get Logger set Level logging INFO env gym make env id env wrappers Unvectorize env if os environ get 'FORCE LATEST UNIVERSE DOCKER RUNTIMES' configure with latest docker runtime tag env else env configure remotes 1 env reset...
@pytest mark parametrize 'env_id' test_envs def test_smoke env_id gym undo_logger_setup logging getLogger setLevel logging INFO env gym make env_id env wrappers Unvectorize env if os environ get 'FORCE_LATEST_UNIVERSE_DOCKER_RUNTIMES' configure_with_latest_docker_runtime_tag env else env configure remotes 1 env reset _...
62
python-test-2051
python
What can we extract ?
rewards and observations
@pytest mark parametrize 'env id' test envs def test smoke env id gym undo logger setup logging get Logger set Level logging INFO env gym make env id env wrappers Unvectorize env if os environ get 'FORCE LATEST UNIVERSE DOCKER RUNTIMES' configure with latest docker runtime tag env else env configure remotes 1 env reset...
@pytest mark parametrize 'env_id' test_envs def test_smoke env_id gym undo_logger_setup logging getLogger setLevel logging INFO env gym make env_id env wrappers Unvectorize env if os environ get 'FORCE_LATEST_UNIVERSE_DOCKER_RUNTIMES' configure_with_latest_docker_runtime_tag env else env configure remotes 1 env reset _...
62
python-test-2057
python
What do a string represent ?
bool value
def parse Bool Value value fail on errors True preserve none False if not isinstance value string type if preserve none and value is None return valuereturn bool value elif preserve none and value lower u'none' return Noneelif value lower in u'true' u'yes' u'y' u'on' u' 1 ' return Trueelif value lower in u'false' u'no'...
def parseBoolValue value fail_on_errors True preserve_none False if not isinstance value string_type if preserve_none and value is None return valuereturn bool value elif preserve_none and value lower u'none' return Noneelif value lower in u'true' u'yes' u'y' u'on' u'1' return Trueelif value lower in u'false' u'no' u'n...
74
python-test-2059
python
When did any quota adjustment require ?
at a particular point in the resize cycle
def resize quota delta context new flavor old flavor sense compare def quota delta resource return sense * new flavor[resource] - old flavor[resource] deltas {}if compare * quota delta 'vcpus' > 0 deltas['cores'] quota delta 'vcpus' if compare * quota delta 'memory mb' > 0 deltas['ram'] quota delta 'memory mb' return d...
def resize_quota_delta context new_flavor old_flavor sense compare def _quota_delta resource return sense * new_flavor[resource] - old_flavor[resource] deltas {}if compare * _quota_delta 'vcpus' > 0 deltas['cores'] _quota_delta 'vcpus' if compare * _quota_delta 'memory_mb' > 0 deltas['ram'] _quota_delta 'memory_mb' ret...
52
python-test-2066
python
What does the code create ?
a cloudtrail digesttraverser and its object graph
def create digest traverser cloudtrail client s3 client provider trail arn trail source region None on invalid None on gap None on missing None bucket None prefix None assert cloudtrail arn is valid trail arn account id get account id from arn trail arn if bucket is None trail info get trail by arn cloudtrail client tr...
def create_digest_traverser cloudtrail_client s3_client_provider trail_arn trail_source_region None on_invalid None on_gap None on_missing None bucket None prefix None assert_cloudtrail_arn_is_valid trail_arn account_id get_account_id_from_arn trail_arn if bucket is None trail_info get_trail_by_arn cloudtrail_client tr...
157
python-test-2070
python
What allow filters and ascending - orders on _ _ key _ _ only ?
queries
def Parse Key Filtered Query filters orders remaining filters []key range Value Range key prop datastore types KEY SPECIAL PROPERT Yfor f in filters op f op if not f property size 1 and f property 0 name key prop and not op datastore pb Query Filter IN or op datastore pb Query Filter EXISTS remaining filters append f c...
def ParseKeyFilteredQuery filters orders remaining_filters []key_range ValueRange key_prop datastore_types KEY_SPECIAL_PROPERTYfor f in filters op f op if not f property_size 1 and f property 0 name key_prop and not op datastore_pb Query_Filter IN or op datastore_pb Query_Filter EXISTS remaining_filters append f contin...
137
python-test-2071
python
What do queries allow only ?
filters and ascending - orders on _ _ key _ _
def Parse Key Filtered Query filters orders remaining filters []key range Value Range key prop datastore types KEY SPECIAL PROPERT Yfor f in filters op f op if not f property size 1 and f property 0 name key prop and not op datastore pb Query Filter IN or op datastore pb Query Filter EXISTS remaining filters append f c...
def ParseKeyFilteredQuery filters orders remaining_filters []key_range ValueRange key_prop datastore_types KEY_SPECIAL_PROPERTYfor f in filters op f op if not f property_size 1 and f property 0 name key_prop and not op datastore_pb Query_Filter IN or op datastore_pb Query_Filter EXISTS remaining_filters append f contin...
137
python-test-2072
python
What does the code get ?
the info structure for an object
def get object info env app path None swift source None version account container obj split path path or env['PATH INFO'] 4 4 True info get object info app env account container obj swift source swift source if info info deepcopy info else info headers to object info {} 0 for field in 'length' if info get field is None...
def get_object_info env app path None swift_source None version account container obj split_path path or env['PATH_INFO'] 4 4 True info _get_object_info app env account container obj swift_source swift_source if info info deepcopy info else info headers_to_object_info {} 0 for field in 'length' if info get field is Non...
67
python-test-2073
python
What do a modelform contain ?
form fields for the given model
def modelform factory model form Model Form fields None exclude None formfield callback None widgets None attrs {u'model' model}if fields is not None attrs[u'fields'] fieldsif exclude is not None attrs[u'exclude'] excludeif widgets is not None attrs[u'widgets'] widgetsparent object if hasattr form u' Meta' parent form ...
def modelform_factory model form ModelForm fields None exclude None formfield_callback None widgets None attrs {u'model' model}if fields is not None attrs[u'fields'] fieldsif exclude is not None attrs[u'exclude'] excludeif widgets is not None attrs[u'widgets'] widgetsparent object if hasattr form u'Meta' parent form Me...
80
python-test-2074
python
What is containing form fields for the given model ?
a modelform
def modelform factory model form Model Form fields None exclude None formfield callback None widgets None attrs {u'model' model}if fields is not None attrs[u'fields'] fieldsif exclude is not None attrs[u'exclude'] excludeif widgets is not None attrs[u'widgets'] widgetsparent object if hasattr form u' Meta' parent form ...
def modelform_factory model form ModelForm fields None exclude None formfield_callback None widgets None attrs {u'model' model}if fields is not None attrs[u'fields'] fieldsif exclude is not None attrs[u'exclude'] excludeif widgets is not None attrs[u'widgets'] widgetsparent object if hasattr form u'Meta' parent form Me...
80
python-test-2075
python
What does the code create ?
a new record object
def Record name object import gencacheobject gencache Ensure Dispatch object module sys modules[object class module ]package gencache Get Module For Typelib module CLSID module LCID module Major Version module Minor Version try struct guid package Record Map[name]except Key Error raise Value Error " Thestructure'%s'isn...
def Record name object import gencacheobject gencache EnsureDispatch object module sys modules[object __class__ __module__]package gencache GetModuleForTypelib module CLSID module LCID module MajorVersion module MinorVersion try struct_guid package RecordMap[name]except KeyError raise ValueError "Thestructure'%s'isnotd...
65
python-test-2077
python
What does the code show in a dialog ?
a wall of text
def text dialog text title parent qtutils active window label Qt Widgets Q Label parent label set Font qtutils diff font label set Text text label set Text Interaction Flags Qt No Text Interaction widget Qt Widgets Q Dialog parent widget set Window Modality Qt Window Modal widget set Window Title title layout qtutils h...
def text_dialog text title parent qtutils active_window label QtWidgets QLabel parent label setFont qtutils diff_font label setText text label setTextInteractionFlags Qt NoTextInteraction widget QtWidgets QDialog parent widget setWindowModality Qt WindowModal widget setWindowTitle title layout qtutils hbox defs margin ...
86
python-test-2078
python
Where does the code show a wall of text ?
in a dialog
def text dialog text title parent qtutils active window label Qt Widgets Q Label parent label set Font qtutils diff font label set Text text label set Text Interaction Flags Qt No Text Interaction widget Qt Widgets Q Dialog parent widget set Window Modality Qt Window Modal widget set Window Title title layout qtutils h...
def text_dialog text title parent qtutils active_window label QtWidgets QLabel parent label setFont qtutils diff_font label setText text label setTextInteractionFlags Qt NoTextInteraction widget QtWidgets QDialog parent widget setWindowModality Qt WindowModal widget setWindowTitle title layout qtutils hbox defs margin ...
86
python-test-2081
python
How do a string split ?
via shelllexer
def split s keep False lexer Shell Lexer s lexer keep keeptokens list lexer if not tokens return []out []spaces ''log shlexer vdebug '{ r}->{ r}' format s tokens for t in tokens if t isspace spaces + telse out append spaces + t spaces ''if spaces out append spaces return out
def split s keep False lexer ShellLexer s lexer keep keeptokens list lexer if not tokens return []out []spaces ''log shlexer vdebug '{ r}->{ r}' format s tokens for t in tokens if t isspace spaces + telse out append spaces + t spaces ''if spaces out append spaces return out
52
python-test-2082
python
What does custom event loop implementation use to respect active flag ?
poll instead of loop
def loop active timeout None use poll False err Count 0if timeout is None timeout Utils DEFAULT SLEEP TIM Epoll asyncore pollif use poll and asyncore poll 2 and hasattr asyncore select 'poll' log Sys debug ' Serverlistener select usespoll' timeout float timeout / 1000 poll asyncore poll 2 while active try poll timeout ...
def loop active timeout None use_poll False errCount 0if timeout is None timeout Utils DEFAULT_SLEEP_TIMEpoll asyncore pollif use_poll and asyncore poll2 and hasattr asyncore select 'poll' logSys debug 'Serverlistener select usespoll' timeout float timeout / 1000 poll asyncore poll2while active try poll timeout if errC...
115
python-test-2083
python
What does custom event loop implementation use poll instead of loop ?
to respect active flag
def loop active timeout None use poll False err Count 0if timeout is None timeout Utils DEFAULT SLEEP TIM Epoll asyncore pollif use poll and asyncore poll 2 and hasattr asyncore select 'poll' log Sys debug ' Serverlistener select usespoll' timeout float timeout / 1000 poll asyncore poll 2 while active try poll timeout ...
def loop active timeout None use_poll False errCount 0if timeout is None timeout Utils DEFAULT_SLEEP_TIMEpoll asyncore pollif use_poll and asyncore poll2 and hasattr asyncore select 'poll' logSys debug 'Serverlistener select usespoll' timeout float timeout / 1000 poll asyncore poll2while active try poll timeout if errC...
115
python-test-2096
python
How does a style object return ?
with the django color scheme
def color style if not supports color style no style else DJANGO COLORS os environ get 'DJANGO COLORS' '' color settings termcolors parse color setting DJANGO COLORS if color settings class dummy passstyle dummy for role in termcolors PALETTES[termcolors NOCOLOR PALETTE] format color settings get role {} setattr style ...
def color_style if not supports_color style no_style else DJANGO_COLORS os environ get 'DJANGO_COLORS' '' color_settings termcolors parse_color_setting DJANGO_COLORS if color_settings class dummy passstyle dummy for role in termcolors PALETTES[termcolors NOCOLOR_PALETTE] format color_settings get role {} setattr style ...
65
python-test-2101
python
What does the code calculate ?
the widely available information criterion
def waic trace model None n eff False pointwise False model modelcontext model log py log post trace trace model lppd i logsumexp log py axis 0 b 1 0 / log py shape[ 0 ] vars lpd np var log py axis 0 if np any vars lpd > 0 4 warnings warn ' Foroneormoresamplestheposteriorvarianceofthe\nlogpredictivedensitiesexceeds 0 4...
def waic trace model None n_eff False pointwise False model modelcontext model log_py log_post_trace trace model lppd_i logsumexp log_py axis 0 b 1 0 / log_py shape[0] vars_lpd np var log_py axis 0 if np any vars_lpd > 0 4 warnings warn 'Foroneormoresamplestheposteriorvarianceofthe\nlogpredictivedensitiesexceeds0 4 Thi...
122
python-test-2102
python
What does the code get ?
metadata for a single file
def get meta module cf container src dest c get container module cf container objs Noneif src and dest module fail json msg ' Error ambiguousinstructions filestobedeletedhavebeenspecifiedonbothsrcanddestargs' elif dest objs destelse objs srcif objs objs objs split ' ' objs map str strip objs else objs c get object name...
def get_meta module cf container src dest c _get_container module cf container objs Noneif src and dest module fail_json msg 'Error ambiguousinstructions filestobedeletedhavebeenspecifiedonbothsrcanddestargs' elif dest objs destelse objs srcif objs objs objs split ' ' objs map str strip objs else objs c get_object_name...
109
python-test-2104
python
How do instance method call ?
via async
def test basic call on method registering without decorator coroutine class API object def init self hug call self hello world method @asyncio coroutinedef hello world method self return ' Hello World 'api instance API assert loop run until complete api instance hello world method ' Hello World ' assert hug test get ap...
def test_basic_call_on_method_registering_without_decorator_coroutine class API object def __init__ self hug call self hello_world_method @asyncio coroutinedef hello_world_method self return 'HelloWorld 'api_instance API assert loop run_until_complete api_instance hello_world_method 'HelloWorld ' assert hug test get ap...
62
python-test-2105
python
What has problems ?
each section
def get array section has problem course id course modulestore get course course id depth 4 b section has problem [ False] * len course get children i 0for section in course get children for subsection in section get children for unit in subsection get children for child in unit get children if child location category ...
def get_array_section_has_problem course_id course modulestore get_course course_id depth 4 b_section_has_problem [False] * len course get_children i 0for section in course get_children for subsection in section get_children for unit in subsection get_children for child in unit get_children if child location category '...
78
python-test-2109
python
What does the code remove ?
all actions from the task
def clear actions name location '\\' if name not in list tasks location return '{ 0 }notfoundin{ 1 }' format name location pythoncom Co Initialize task service win 32 com client Dispatch ' Schedule Service' task service Connect task folder task service Get Folder location task definition task folder Get Task name Defin...
def _clear_actions name location '\\' if name not in list_tasks location return '{0}notfoundin{1}' format name location pythoncom CoInitialize task_service win32com client Dispatch 'Schedule Service' task_service Connect task_folder task_service GetFolder location task_definition task_folder GetTask name Definitionacti...
87
python-test-2112
python
What does the code generate ?
the binary partition of n
def binary partitions n from math import ceil logpow int 2 ** ceil log n 2 sum 0partition []while pow if sum + pow < n partition append pow sum + powpow >> 1last num len partition - 1 - n & 1 while last num > 0 yield partition if partition[last num] 2 partition[last num] 1partition append 1 last num - 1continuepartitio...
def binary_partitions n from math import ceil logpow int 2 ** ceil log n 2 sum 0partition []while pow if sum + pow < n partition append pow sum + powpow >> 1last_num len partition - 1 - n & 1 while last_num > 0 yield partition if partition[last_num] 2 partition[last_num] 1partition append 1 last_num - 1continuepartitio...
113
python-test-2115
python
What does this function tell how it should extract the tlvs from the payload ?
the packetlistfield
def PPI Guess Payload Class p **kargs if len p > 4 t pfh len struct unpack '<HH' p[ 4] cls get PPI Type t 'default' pfh len + 4out cls p[ pfh len] **kargs if out payload out payload conf raw layer out payload load if len p > pfh len out payload payload conf padding layer p[pfh len ] elif len p > pfh len out payload con...
def _PPIGuessPayloadClass p **kargs if len p > 4 t pfh_len struct unpack '<HH' p[ 4] cls getPPIType t 'default' pfh_len + 4out cls p[ pfh_len] **kargs if out payload out payload conf raw_layer out payload load if len p > pfh_len out payload payload conf padding_layer p[pfh_len ] elif len p > pfh_len out payload conf pa...
84
python-test-2116
python
What should it extract from the payload how ?
the tlvs
def PPI Guess Payload Class p **kargs if len p > 4 t pfh len struct unpack '<HH' p[ 4] cls get PPI Type t 'default' pfh len + 4out cls p[ pfh len] **kargs if out payload out payload conf raw layer out payload load if len p > pfh len out payload payload conf padding layer p[pfh len ] elif len p > pfh len out payload con...
def _PPIGuessPayloadClass p **kargs if len p > 4 t pfh_len struct unpack '<HH' p[ 4] cls getPPIType t 'default' pfh_len + 4out cls p[ pfh_len] **kargs if out payload out payload conf raw_layer out payload load if len p > pfh_len out payload payload conf padding_layer p[pfh_len ] elif len p > pfh_len out payload conf pa...
84
python-test-2120
python
What does the code delete ?
an autoscale group
def delete name force False region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile try conn delete auto scaling group name force msg ' Deletedautoscalegroup{ 0 } ' format name log info msg return Trueexcept boto exception Boto Server Error as e log debug e msg ' Fai...
def delete name force False region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile try conn delete_auto_scaling_group name force msg 'Deletedautoscalegroup{0} ' format name log info msg return Trueexcept boto exception BotoServerError as e log debug e msg 'Failedto...
67
python-test-2122
python
What do formats check ?
highlights
def fmt highlights raw value value unit if unit is None return valuehighlights highlight string raw value unit start search 0for highlight in highlights htext escape force text highlight[ 2 ] find highlight value find htext start search if find highlight > 0 newpart HL CHECK format htext next part value[ find highlight...
def fmt_highlights raw_value value unit if unit is None return valuehighlights highlight_string raw_value unit start_search 0for highlight in highlights htext escape force_text highlight[2] find_highlight value find htext start_search if find_highlight > 0 newpart HL_CHECK format htext next_part value[ find_highlight +...
74
python-test-2124
python
What does the code compute ?
the of * val * divided by the constant positive * divisor *
def divmod by constant builder val divisor assert divisor > 0 divisor val type divisor one val type 1 quot alloca once builder val type with builder if else is neg int builder val as if neg if pos with if pos quot val builder sdiv val divisor builder store quot val quot with if neg val plus one builder add val one quot...
def divmod_by_constant builder val divisor assert divisor > 0 divisor val type divisor one val type 1 quot alloca_once builder val type with builder if_else is_neg_int builder val as if_neg if_pos with if_pos quot_val builder sdiv val divisor builder store quot_val quot with if_neg val_plus_one builder add val one quot...
99
python-test-2125
python
What does the code attach to each object of the queryset ?
a json issue custom attributes representation
def attach issue custom attributes queryset as field 'issue custom attributes attr' model queryset modelsql '\n SELEC Tjson agg \nrow to json custom attributes issuecustomattribute \n ORDERB Ycustom attributes issuecustomattribute order\n \n FRO Mcustom attributes issuecustomattribute\n WHER Ecustom attributes issuecus...
def attach_issue_custom_attributes queryset as_field 'issue_custom_attributes_attr' model queryset modelsql '\nSELECTjson_agg \nrow_to_json custom_attributes_issuecustomattribute \nORDERBYcustom_attributes_issuecustomattribute order\n \nFROMcustom_attributes_issuecustomattribute\nWHEREcustom_attributes_issuecustomattri...
60
python-test-2126
python
Where do shortest path lengths and predecessors compute ?
on shortest paths
def bellman ford predecessor and distance G source target None cutoff None weight 'weight' if source not in G raise nx Node Not Found ' Node%sisnotfoundinthegraph' % source weight weight function G weight if any weight u v d < 0 for u v d in G selfloop edges data True raise nx Network X Unbounded ' Negativecostcycledet...
def bellman_ford_predecessor_and_distance G source target None cutoff None weight 'weight' if source not in G raise nx NodeNotFound 'Node%sisnotfoundinthegraph' % source weight _weight_function G weight if any weight u v d < 0 for u v d in G selfloop_edges data True raise nx NetworkXUnbounded 'Negativecostcycledetected...
91
python-test-2127
python
What computes on shortest paths ?
shortest path lengths and predecessors
def bellman ford predecessor and distance G source target None cutoff None weight 'weight' if source not in G raise nx Node Not Found ' Node%sisnotfoundinthegraph' % source weight weight function G weight if any weight u v d < 0 for u v d in G selfloop edges data True raise nx Network X Unbounded ' Negativecostcycledet...
def bellman_ford_predecessor_and_distance G source target None cutoff None weight 'weight' if source not in G raise nx NodeNotFound 'Node%sisnotfoundinthegraph' % source weight _weight_function G weight if any weight u v d < 0 for u v d in G selfloop_edges data True raise nx NetworkXUnbounded 'Negativecostcycledetected...
91
python-test-2128
python
How do command save ?
with no playlist name
@command 'save' def save last if g last opened open save view 'save' g last opened else saveas ''if g model saveas g model[ 0 ] title[ 18 ] strip saveas re sub '[^-\\w]' '-' saveas re UNICODE post 0while g userpl get saveas post + 1saveas g model[ 0 ] title[ 18 ] strip + '-' + str post saveas saveas lstrip '0123456789 ...
@command 'save' def save_last if g last_opened open_save_view 'save' g last_opened else saveas ''if g model saveas g model[0] title[ 18] strip saveas re sub '[^-\\w]' '-' saveas re UNICODE post 0while g userpl get saveas post + 1saveas g model[0] title[ 18] strip + '-' + str post saveas saveas lstrip '0123456789' open_...
70
python-test-2134
python
What does the code setup ?
the plex sensor
def setup platform hass config add devices discovery info None name config get CONF NAME plex user config get CONF USERNAME plex password config get CONF PASSWORD plex server config get CONF SERVER plex host config get CONF HOST plex port config get CONF PORT plex url 'http //{} {}' format plex host plex port add devic...
def setup_platform hass config add_devices discovery_info None name config get CONF_NAME plex_user config get CONF_USERNAME plex_password config get CONF_PASSWORD plex_server config get CONF_SERVER plex_host config get CONF_HOST plex_port config get CONF_PORT plex_url 'http //{} {}' format plex_host plex_port add_devic...
70
python-test-2142
python
Where does the reader ignore whitespace ?
at the end of fields
@pytest mark parametrize 'parallel' [ True False] def test rstrip whitespace parallel read basic text '1 2 DCTB 3\n A DCTB B C DCTB DCTB \n DCTB a b c\n'table read basic text delimiter ' ' parallel parallel expected Table [['A' 'a'] ['B' 'b'] ['C' 'c']] names '1 ' '2 ' '3 ' assert table equal table expected
@pytest mark parametrize 'parallel' [True False] def test_rstrip_whitespace parallel read_basic text '1 2 DCTB 3\nA DCTB B C DCTB DCTB \n DCTB a b c\n'table read_basic text delimiter ' ' parallel parallel expected Table [['A' 'a'] ['B' 'b'] ['C' 'c']] names '1' '2' '3' assert_table_equal table expected
58
python-test-2143
python
Why are services not are available ?
because of a missing feature
def filter services services filtered services services[ ]for service name in services mod import 'services ' + service name globals globals locals locals fromlist [' Service'] level -1 service mod Serviceif service required features is not None and bs 4 builder registry lookup *service required features is None logger...
def filter_services services filtered_services services[ ]for service_name in services mod __import__ 'services ' + service_name globals globals locals locals fromlist ['Service'] level -1 service mod Serviceif service required_features is not None and bs4 builder_registry lookup *service required_features is None logg...
68
python-test-2147
python
What does this return ?
a dict with a set of tasks for all of the other workers
def get external workers worker worker that blocked task collections defaultdict set get work response history worker get work response historyfor get work response in get work response history if get work response['task id'] is None for running task in get work response['running tasks'] other worker id running task['w...
def _get_external_workers worker worker_that_blocked_task collections defaultdict set get_work_response_history worker _get_work_response_historyfor get_work_response in get_work_response_history if get_work_response['task_id'] is None for running_task in get_work_response['running_tasks'] other_worker_id running_task[...
86
python-test-2153
python
What does the code ingest ?
the data for the given bundle
@main command @click option '-b' '--bundle' default 'quantopian-quandl' metavar 'BUNDLE-NAME' show default True help ' Thedatabundletoingest ' @click option '--assets-version' type int multiple True help ' Versionoftheassetsdbtowhichtodowngrade ' @click option '--show-progress/--no-show-progress' default True help ' Pr...
@main command @click option '-b' '--bundle' default 'quantopian-quandl' metavar 'BUNDLE-NAME' show_default True help 'Thedatabundletoingest ' @click option '--assets-version' type int multiple True help 'Versionoftheassetsdbtowhichtodowngrade ' @click option '--show-progress/--no-show-progress' default True help 'Print...
57
python-test-2155
python
What does the code create ?
a thumbnail with a geoserver request
def create gs thumbnail layer overwrite False params {'layers' layer typename encode 'utf- 8 ' 'format' 'image/png 8 ' 'width' 200 'height' 150 'TIME' '- 99999999999 - 01 - 01 T 00 00 00 0Z/ 99999999999 - 01 - 01 T 00 00 00 0Z'}if None not in layer bbox params['bbox'] layer bbox stringp '&' join '%s %s' % item for item...
def create_gs_thumbnail layer overwrite False params {'layers' layer typename encode 'utf-8' 'format' 'image/png8' 'width' 200 'height' 150 'TIME' '-99999999999-01-01T00 00 00 0Z/99999999999-01-01T00 00 00 0Z'}if None not in layer bbox params['bbox'] layer bbox_stringp '&' join '%s %s' % item for item in params items t...
103
python-test-2158
python
What does a helper function implement ?
the commonality between the complex
def single spectrum helper x mode Fs None window None pad to None sides None if mode is None or mode u'psd' or mode u'default' raise Value Error u' single spectrum helperdoesnotworkwith%smode' % mode if pad to is None pad to len x spec freqs spectral helper x x y None NFFT len x Fs Fs detrend func detrend none window w...
def _single_spectrum_helper x mode Fs None window None pad_to None sides None if mode is None or mode u'psd' or mode u'default' raise ValueError u'_single_spectrum_helperdoesnotworkwith%smode' % mode if pad_to is None pad_to len x spec freqs _ _spectral_helper x x y None NFFT len x Fs Fs detrend_func detrend_none windo...
96
python-test-2163
python
What does the code save to memcache ?
all traces
def end recording status firepython set extension data None if firepython set extension data is not None warnings warn ' Firepythonisnolongersupported' rec recorder proxy get for current request recorder proxy clear for current request if config DEBUG logging debug ' Clearedrecorder' if rec is not None try rec record h...
def end_recording status firepython_set_extension_data None if firepython_set_extension_data is not None warnings warn 'Firepythonisnolongersupported' rec recorder_proxy get_for_current_request recorder_proxy clear_for_current_request if config DEBUG logging debug 'Clearedrecorder' if rec is not None try rec record_htt...
63
python-test-2164
python
What does the code record ?
rpc traces
def end recording status firepython set extension data None if firepython set extension data is not None warnings warn ' Firepythonisnolongersupported' rec recorder proxy get for current request recorder proxy clear for current request if config DEBUG logging debug ' Clearedrecorder' if rec is not None try rec record h...
def end_recording status firepython_set_extension_data None if firepython_set_extension_data is not None warnings warn 'Firepythonisnolongersupported' rec recorder_proxy get_for_current_request recorder_proxy clear_for_current_request if config DEBUG logging debug 'Clearedrecorder' if rec is not None try rec record_htt...
63
python-test-2165
python
What does the code stop ?
recording rpc traces
def end recording status firepython set extension data None if firepython set extension data is not None warnings warn ' Firepythonisnolongersupported' rec recorder proxy get for current request recorder proxy clear for current request if config DEBUG logging debug ' Clearedrecorder' if rec is not None try rec record h...
def end_recording status firepython_set_extension_data None if firepython_set_extension_data is not None warnings warn 'Firepythonisnolongersupported' rec recorder_proxy get_for_current_request recorder_proxy clear_for_current_request if config DEBUG logging debug 'Clearedrecorder' if rec is not None try rec record_htt...
63
python-test-2166
python
For what purpose do the static file cache destroy atomically ?
for a certain path
def clear static cache path fully qualified path os path join django conf settings WEB ROOT path try new temp path tempfile mkdtemp dir django conf settings WEB ROOT + '/' except OS Error as e if e errno 28 shutil rmtree fully qualified path returntry os rename fully qualified path os path join new temp path 'old' exce...
def clear_static_cache path fully_qualified_path os path join django conf settings WEB_ROOT path try new_temp_path tempfile mkdtemp dir django conf settings WEB_ROOT + '/' except OSError as e if e errno 28 shutil rmtree fully_qualified_path returntry os rename fully_qualified_path os path join new_temp_path 'old' excep...
73
python-test-2167
python
What does the code build ?
the html and pdf docs
@taskdef build docs with cd '/home/vagrant/repos/sympy' run 'mkdir-pdist' venv '/home/vagrant/docs-virtualenv'make virtualenv venv dependencies ['sphinx 1 1 3' 'numpy' 'mpmath'] with virtualenv venv with cd '/home/vagrant/repos/sympy/doc' run 'makeclean' run 'makehtml-errors' run 'makeman' with cd '/home/vagrant/repos/...
@taskdef build_docs with cd '/home/vagrant/repos/sympy' run 'mkdir-pdist' venv '/home/vagrant/docs-virtualenv'make_virtualenv venv dependencies ['sphinx 1 1 3' 'numpy' 'mpmath'] with virtualenv venv with cd '/home/vagrant/repos/sympy/doc' run 'makeclean' run 'makehtml-errors' run 'makeman' with cd '/home/vagrant/repos/...
72
python-test-2168
python
Where did the code store ?
in common_site_config
def use wildcard certificate bench path ret from bench config common site config import get configconfig get config bench path bench path wildcard config get 'wildcard' if not wildcard returndomain wildcard['domain']ssl certificate wildcard['ssl certificate']ssl certificate key wildcard['ssl certificate key']if domain ...
def use_wildcard_certificate bench_path ret from bench config common_site_config import get_configconfig get_config bench_path bench_path wildcard config get 'wildcard' if not wildcard returndomain wildcard['domain']ssl_certificate wildcard['ssl_certificate']ssl_certificate_key wildcard['ssl_certificate_key']if domain ...
79
python-test-2169
python
What does the code simplify ?
a multiplication tree
def simplify mul tree neg inputs treeif isinstance inputs list s inputs []for s i in imap simplify mul inputs if s i[ 1 ] is None neg ^ s i[ 0 ]else s inputs append s i if not s inputs rval [neg None]elif len s inputs 1 s inputs[ 0 ][ 0 ] ^ negrval s inputs[ 0 ]else rval [neg s inputs]else rval treereturn rval
def simplify_mul tree neg inputs treeif isinstance inputs list s_inputs []for s_i in imap simplify_mul inputs if s_i[1] is None neg ^ s_i[0]else s_inputs append s_i if not s_inputs rval [neg None]elif len s_inputs 1 s_inputs[0][0] ^ negrval s_inputs[0]else rval [neg s_inputs]else rval treereturn rval
68
python-test-2170
python
For what purpose does an interactive shell start ?
so that the user can inspect errors
def start interactive mode result debuggers result debuggersdescrs result error descrs + result fail descrs if len debuggers 1 debuggers[ 0 ] start else while True testindex 0print ' Chooseatesttodebug ' print '\n' join [ ' DCTB %s %s' % i descr for i descr in enumerate descrs ] print " Type'exit' or^D toquit" print tr...
def start_interactive_mode result debuggers result debuggersdescrs result error_descrs + result fail_descrs if len debuggers 1 debuggers[0] start else while True testindex 0print 'Chooseatesttodebug ' print '\n' join [ ' DCTB %s %s' % i descr for i _ descr in enumerate descrs ] print "Type'exit' or^D toquit" print try ...
95
python-test-2171
python
For what purpose does domain set ?
to use namecheap default dns servers
def set default sld tld opts salt utils namecheap get opts 'namecheap domains dns set Default' opts['SLD'] sldopts['TLD'] tldresponse xml salt utils namecheap post request opts if response xml is None return Falsednsresult response xml get Elements By Tag Name ' Domain DNS Set Default Result' [0 ]return salt utils name...
def set_default sld tld opts salt utils namecheap get_opts 'namecheap domains dns setDefault' opts['SLD'] sldopts['TLD'] tldresponse_xml salt utils namecheap post_request opts if response_xml is None return Falsednsresult response_xml getElementsByTagName 'DomainDNSSetDefaultResult' [0]return salt utils namecheap strin...
59
python-test-2174
python
What does the code determine ?
nonstandard properties of an input image
def get image properties image immin immax np min image np max image imtype image dtype typetry lo hi dtypes dtype range[imtype]except Key Error lo hi immin immax signed immin < 0 out of range float np issubdtype image dtype np float and immin < lo or immax > hi low data range immin immax and is low contrast image unsu...
def _get_image_properties image immin immax np min image np max image imtype image dtype typetry lo hi dtypes dtype_range[imtype]except KeyError lo hi immin immax signed immin < 0 out_of_range_float np issubdtype image dtype np float and immin < lo or immax > hi low_data_range immin immax and is_low_contrast image unsu...
82
python-test-2185
python
What does the code setup ?
the demo climate devices
def setup platform hass config add devices discovery info None add devices [ Demo Climate ' Heat Pump' 68 TEMP FAHRENHEIT None 77 ' Auto Low' None None ' Auto' 'heat' None None None Demo Climate ' Hvac' 21 TEMP CELSIUS True 22 ' On High' 67 54 ' Off' 'cool' False None None Demo Climate ' Ecobee' None TEMP CELSIUS None ...
def setup_platform hass config add_devices discovery_info None add_devices [DemoClimate 'HeatPump' 68 TEMP_FAHRENHEIT None 77 'AutoLow' None None 'Auto' 'heat' None None None DemoClimate 'Hvac' 21 TEMP_CELSIUS True 22 'OnHigh' 67 54 'Off' 'cool' False None None DemoClimate 'Ecobee' None TEMP_CELSIUS None 23 'AutoLow' N...
75
python-test-2193
python
What does the code get ?
the entire accountpolicy
def get account policy name cmd 'pwpolicy-u{ 0 }-getpolicy' format name try ret salt utils mac utils execute return result cmd except Command Execution Error as exc if ' Error user<{ 0 }>notfound' format name in exc strerror raise Command Execution Error ' Usernotfound {0 }' format name raise Command Execution Error ' ...
def _get_account_policy name cmd 'pwpolicy-u{0}-getpolicy' format name try ret salt utils mac_utils execute_return_result cmd except CommandExecutionError as exc if 'Error user<{0}>notfound' format name in exc strerror raise CommandExecutionError 'Usernotfound {0}' format name raise CommandExecutionError 'Unknownerror ...
96
python-test-2197
python
Why does the code save it as a global ?
since this is configured in settings and should not change from request to request
def get default role request global DEFAULT ROL Edefault getattr settings 'OPENSTACK KEYSTONE DEFAULT ROLE' None if default and DEFAULT ROLE is None try roles keystoneclient request admin True roles list except roles []exceptions handle request for role in roles if role id default or role name default DEFAULT ROLE role...
def get_default_role request global DEFAULT_ROLEdefault getattr settings 'OPENSTACK_KEYSTONE_DEFAULT_ROLE' None if default and DEFAULT_ROLE is None try roles keystoneclient request admin True roles list except roles []exceptions handle request for role in roles if role id default or role name default DEFAULT_ROLE roleb...
53
python-test-2198
python
What will a callback function return ?
a comment containing the given data plus necessary dummy data
def get comment callback comment data thread id parent id def callback request uri headers '\n Simulatethecommentcreationorupdateendpointasdescribedabove \n'response data make minimal cs comment comment data response data['thread id'] thread idresponse data['parent id'] parent idfor key val list in request parsed body ...
def _get_comment_callback comment_data thread_id parent_id def callback request _uri headers '\nSimulatethecommentcreationorupdateendpointasdescribedabove \n'response_data make_minimal_cs_comment comment_data response_data['thread_id'] thread_idresponse_data['parent_id'] parent_idfor key val_list in request parsed_body...
71
python-test-2199
python
What does the code get ?
a callback function that will return a comment containing the given data plus necessary dummy data
def get comment callback comment data thread id parent id def callback request uri headers '\n Simulatethecommentcreationorupdateendpointasdescribedabove \n'response data make minimal cs comment comment data response data['thread id'] thread idresponse data['parent id'] parent idfor key val list in request parsed body ...
def _get_comment_callback comment_data thread_id parent_id def callback request _uri headers '\nSimulatethecommentcreationorupdateendpointasdescribedabove \n'response_data make_minimal_cs_comment comment_data response_data['thread_id'] thread_idresponse_data['parent_id'] parent_idfor key val_list in request parsed_body...
71
python-test-2202
python
How did time specify ?
in a variety of forms
def time to epoch t if isinstance t int return telif isinstance t tuple or isinstance t time struct time return int time mktime t elif hasattr t 'timetuple' return int time mktime t timetuple elif hasattr t 'strftime' return int t strftime '%s' elif isinstance t str or isinstance t unicode try if t startswith '+' retur...
def time_to_epoch t if isinstance t int return telif isinstance t tuple or isinstance t time struct_time return int time mktime t elif hasattr t 'timetuple' return int time mktime t timetuple elif hasattr t 'strftime' return int t strftime '%s' elif isinstance t str or isinstance t unicode try if t startswith '+' retur...
104