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-5845
python
What does the code take ?
a list of tags that is a comma - separated string
def tag string convert key data errors context if isinstance data[key] basestring tags [tag strip for tag in data[key] split ' ' if tag strip ]else tags data[key]current index max [int k[ 1 ] for k in data keys if len k 3 and k[ 0 ] 'tags' ] + [ -1 ] for num tag in zip count current index + 1 tags data[ 'tags' num 'nam...
def tag_string_convert key data errors context if isinstance data[key] basestring tags [tag strip for tag in data[key] split ' ' if tag strip ]else tags data[key]current_index max [int k[1] for k in data keys if len k 3 and k[0] 'tags' ] + [ -1 ] for num tag in zip count current_index + 1 tags data[ 'tags' num 'name' ]...
83
python-test-5846
python
What does the code get ?
a list of module files for a filename
def get Files For Name name if not os path exists name if contains Any name '*?[]' files glob glob name list []for file in files list extend get Files For Name file return listname get modpkg path name if not name return []if os path isdir name list []os path walk name visit pyfiles list return listelif os path exists ...
def getFilesForName name if not os path exists name if containsAny name '*?[]' files glob glob name list []for file in files list extend getFilesForName file return listname _get_modpkg_path name if not name return []if os path isdir name list []os path walk name _visit_pyfiles list return listelif os path exists name ...
65
python-test-5847
python
Where do querystring persist ?
in pagination links
@register inclusion tag u'includes/pagination html' takes context True def pagination for context current page page var u'page' exclude vars u'' querystring context[u'request'] GET copy exclude vars [v for v in exclude vars split u' ' if v] + [page var] for exclude var in exclude vars if exclude var in querystring del ...
@register inclusion_tag u'includes/pagination html' takes_context True def pagination_for context current_page page_var u'page' exclude_vars u'' querystring context[u'request'] GET copy exclude_vars [v for v in exclude_vars split u' ' if v] + [page_var] for exclude_var in exclude_vars if exclude_var in querystring del ...
67
python-test-5848
python
What is persisting in pagination links ?
querystring
@register inclusion tag u'includes/pagination html' takes context True def pagination for context current page page var u'page' exclude vars u'' querystring context[u'request'] GET copy exclude vars [v for v in exclude vars split u' ' if v] + [page var] for exclude var in exclude vars if exclude var in querystring del ...
@register inclusion_tag u'includes/pagination html' takes_context True def pagination_for context current_page page_var u'page' exclude_vars u'' querystring context[u'request'] GET copy exclude_vars [v for v in exclude_vars split u' ' if v] + [page_var] for exclude_var in exclude_vars if exclude_var in querystring del ...
67
python-test-5852
python
What did the code set ?
the insteon local light platform
def setup platform hass config add devices discovery info None insteonhub hass data['insteon local']conf lights config from file hass config path INSTEON LOCAL LIGHTS CONF if len conf lights for device id in conf lights setup light device id conf lights[device id] insteonhub hass add devices linked insteonhub get linke...
def setup_platform hass config add_devices discovery_info None insteonhub hass data['insteon_local']conf_lights config_from_file hass config path INSTEON_LOCAL_LIGHTS_CONF if len conf_lights for device_id in conf_lights setup_light device_id conf_lights[device_id] insteonhub hass add_devices linked insteonhub get_linke...
83
python-test-5853
python
What does the code add ?
remaining sequences
def finish backtrace sequence A sequence B ali seq A ali seq B row col gap char if row ali seq A + sequence A[ row - 1 -1 ]if col ali seq B + sequence B[ col - 1 -1 ]if row > col ali seq B + gap char * len ali seq A - len ali seq B elif col > row ali seq A + gap char * len ali seq B - len ali seq A return ali seq A ali...
def _finish_backtrace sequenceA sequenceB ali_seqA ali_seqB row col gap_char if row ali_seqA + sequenceA[ row - 1 -1 ]if col ali_seqB + sequenceB[ col - 1 -1 ]if row > col ali_seqB + gap_char * len ali_seqA - len ali_seqB elif col > row ali_seqA + gap_char * len ali_seqB - len ali_seqA return ali_seqA ali_seqB
88
python-test-5854
python
What specified in my_ips and my_port respectively ?
the ip addresses
def is local device my ips my port dev ip dev port candidate ips []if not is valid ip dev ip and is valid hostname dev ip try addrinfo socket getaddrinfo dev ip dev port for addr in addrinfo family addr[ 0 ]dev ip addr[ 4 ][ 0 ]if family socket AF INET 6 dev ip expand ipv 6 dev ip candidate ips append dev ip except soc...
def is_local_device my_ips my_port dev_ip dev_port candidate_ips []if not is_valid_ip dev_ip and is_valid_hostname dev_ip try addrinfo socket getaddrinfo dev_ip dev_port for addr in addrinfo family addr[0]dev_ip addr[4][0]if family socket AF_INET6 dev_ip expand_ipv6 dev_ip candidate_ips append dev_ip except socket gaie...
113
python-test-5855
python
Where did the ip addresses specify ?
in my_ips and my_port respectively
def is local device my ips my port dev ip dev port candidate ips []if not is valid ip dev ip and is valid hostname dev ip try addrinfo socket getaddrinfo dev ip dev port for addr in addrinfo family addr[ 0 ]dev ip addr[ 4 ][ 0 ]if family socket AF INET 6 dev ip expand ipv 6 dev ip candidate ips append dev ip except soc...
def is_local_device my_ips my_port dev_ip dev_port candidate_ips []if not is_valid_ip dev_ip and is_valid_hostname dev_ip try addrinfo socket getaddrinfo dev_ip dev_port for addr in addrinfo family addr[0]dev_ip addr[4][0]if family socket AF_INET6 dev_ip expand_ipv6 dev_ip candidate_ips append dev_ip except socket gaie...
113
python-test-5859
python
What does the code show ?
a users timeline
@app route '/' def timeline if not g user return redirect url for 'public timeline' return render template 'timeline html' messages query db '\nselectmessage * user *frommessage user\nwheremessage author id user user idand \nuser user id ?or\nuser user idin selectwhom idfromfollower\nwherewho id ? \norderbymessage pub ...
@app route '/' def timeline if not g user return redirect url_for 'public_timeline' return render_template 'timeline html' messages query_db '\nselectmessage * user *frommessage user\nwheremessage author_id user user_idand \nuser user_id ?or\nuser user_idin selectwhom_idfromfollower\nwherewho_id ? \norderbymessage pub_...
52
python-test-5875
python
How does the code abort the current request immediately ?
by returning an http exception
def abort status code None detail '' headers None comment None if status code 403 for item in p Plugin Implementations p I Authenticator result item abort status code detail headers comment status code detail headers comment resultif detail and status code 503 h flash error detail detail detail encode 'utf 8 ' return a...
def abort status_code None detail '' headers None comment None if status_code 403 for item in p PluginImplementations p IAuthenticator result item abort status_code detail headers comment status_code detail headers comment resultif detail and status_code 503 h flash_error detail detail detail encode 'utf8' return _abor...
65
python-test-5894
python
What does the code make ?
the virtual env at revision active
@taskdef virtualenv activate requirements revision None assert not is old env ' Activeenvironmentisold-style directory notsymlink Manualinterventionrequired 'req rev requirements revision or latest requirements revision assert virtualenv verify req rev ' Desiredenvrevision%sinvalid cannotbemadeactive' % req rev env dir...
@taskdef virtualenv_activate requirements_revision None assert not is_old_env 'Activeenvironmentisold-style directory notsymlink Manualinterventionrequired 'req_rev requirements_revision or latest_requirements_revision assert virtualenv_verify req_rev 'Desiredenvrevision%sinvalid cannotbemadeactive' % req_rev env_dir '...
69
python-test-5895
python
What does the code get ?
the course descriptor
def get course course key user try course get course with access user 'load' course key check if enrolled True except Http 404 raise Course Not Found Error ' Coursenotfound ' if not any [ tab type 'discussion' and tab is enabled course user for tab in course tabs] raise Discussion Disabled Error ' Discussionisdisabledf...
def _get_course course_key user try course get_course_with_access user 'load' course_key check_if_enrolled True except Http404 raise CourseNotFoundError 'Coursenotfound ' if not any [ tab type 'discussion' and tab is_enabled course user for tab in course tabs] raise DiscussionDisabledError 'Discussionisdisabledfortheco...
58
python-test-5903
python
How does an option within a select choose ?
by text
def select option by text select browser query option text def select option query value ' Getthefirstselectelementthatmatchesthequeryandselectthedesiredvalue 'try select Select query first results[ 0 ] select select by visible text value return Trueexcept Stale Element Reference Exception return Falsemsg ' Selectedopt...
def select_option_by_text select_browser_query option_text def select_option query value 'Getthefirstselectelementthatmatchesthequeryandselectthedesiredvalue 'try select Select query first results[0] select select_by_visible_text value return Trueexcept StaleElementReferenceException return Falsemsg 'Selectedoption{}' ...
56
python-test-5905
python
What does the code get ?
the abridged settings from the gcode text
def get Abridged Settings gcode Text abridged Settings []lines archive get Text Lines gcode Text settings Start Falsefor line in lines split Line gcodec get Split Line Before Bracket Semicolon line first Word gcodec get First Word split Line if first Word ' <setting>' and settings Start if len split Line > 4 abridged S...
def getAbridgedSettings gcodeText abridgedSettings []lines archive getTextLines gcodeText settingsStart Falsefor line in lines splitLine gcodec getSplitLineBeforeBracketSemicolon line firstWord gcodec getFirstWord splitLine if firstWord ' <setting>' and settingsStart if len splitLine > 4 abridgedSettings append Abridge...
78
python-test-5907
python
Do we set the src / dst ?
No
def test resize icon poorly somepic get image path 'mozilla png' src tempfile Named Temporary File mode 'r+w+b' suffix ' png' delete False dir settings TMP PATH shutil copyfile somepic src name src image Image open src name assert src image size 339 128 resize icon src name src name locally True src image Image open sr...
def test_resize_icon_poorly somepic get_image_path 'mozilla png' src tempfile NamedTemporaryFile mode 'r+w+b' suffix ' png' delete False dir settings TMP_PATH shutil copyfile somepic src name src_image Image open src name assert src_image size 339 128 resize_icon src name src name locally True src_image Image open src ...
64
python-test-5908
python
What do we attempt ?
to set the src / dst
def test resize icon poorly somepic get image path 'mozilla png' src tempfile Named Temporary File mode 'r+w+b' suffix ' png' delete False dir settings TMP PATH shutil copyfile somepic src name src image Image open src name assert src image size 339 128 resize icon src name src name locally True src image Image open sr...
def test_resize_icon_poorly somepic get_image_path 'mozilla png' src tempfile NamedTemporaryFile mode 'r+w+b' suffix ' png' delete False dir settings TMP_PATH shutil copyfile somepic src name src_image Image open src name assert src_image size 339 128 resize_icon src name src name locally True src_image Image open src ...
64
python-test-5909
python
What does jclouds provide on most of the currently usable cloud infrastructures ?
slave launching
def jclouds registry xml parent data if 'instances' in data build Wrapper XML Sub Element xml parent 'jenkins plugins jclouds compute J Clouds Build Wrapper' instances XML Sub Element build Wrapper 'instances To Run' for foo in data['instances'] for template params in foo items instance XML Sub Element instances 'jenki...
def jclouds registry xml_parent data if 'instances' in data buildWrapper XML SubElement xml_parent 'jenkins plugins jclouds compute JCloudsBuildWrapper' instances XML SubElement buildWrapper 'instancesToRun' for foo in data['instances'] for template params in foo items instance XML SubElement instances 'jenkins plugins...
118
python-test-5910
python
What does jclouds use jclouds ?
to provide slave launching on most of the currently usable cloud infrastructures
def jclouds registry xml parent data if 'instances' in data build Wrapper XML Sub Element xml parent 'jenkins plugins jclouds compute J Clouds Build Wrapper' instances XML Sub Element build Wrapper 'instances To Run' for foo in data['instances'] for template params in foo items instance XML Sub Element instances 'jenki...
def jclouds registry xml_parent data if 'instances' in data buildWrapper XML SubElement xml_parent 'jenkins plugins jclouds compute JCloudsBuildWrapper' instances XML SubElement buildWrapper 'instancesToRun' for foo in data['instances'] for template params in foo items instance XML SubElement instances 'jenkins plugins...
118
python-test-5911
python
Where does jclouds provide slave launching ?
on most of the currently usable cloud infrastructures
def jclouds registry xml parent data if 'instances' in data build Wrapper XML Sub Element xml parent 'jenkins plugins jclouds compute J Clouds Build Wrapper' instances XML Sub Element build Wrapper 'instances To Run' for foo in data['instances'] for template params in foo items instance XML Sub Element instances 'jenki...
def jclouds registry xml_parent data if 'instances' in data buildWrapper XML SubElement xml_parent 'jenkins plugins jclouds compute JCloudsBuildWrapper' instances XML SubElement buildWrapper 'instancesToRun' for foo in data['instances'] for template params in foo items instance XML SubElement instances 'jenkins plugins...
118
python-test-5912
python
What does the code ensure ?
that data and mask are compatabile and add missing values
def matrix mask data mask if mask is None mask np zeros data shape np bool if isinstance mask np ndarray if mask shape data shape raise Value Error ' Maskmusthavethesameshapeasdata ' mask pd Data Frame mask index data index columns data columns dtype np bool elif isinstance mask pd Data Frame if not mask index equals d...
def _matrix_mask data mask if mask is None mask np zeros data shape np bool if isinstance mask np ndarray if mask shape data shape raise ValueError 'Maskmusthavethesameshapeasdata ' mask pd DataFrame mask index data index columns data columns dtype np bool elif isinstance mask pd DataFrame if not mask index equals data...
79
python-test-5913
python
What does the code add ?
missing values
def matrix mask data mask if mask is None mask np zeros data shape np bool if isinstance mask np ndarray if mask shape data shape raise Value Error ' Maskmusthavethesameshapeasdata ' mask pd Data Frame mask index data index columns data columns dtype np bool elif isinstance mask pd Data Frame if not mask index equals d...
def _matrix_mask data mask if mask is None mask np zeros data shape np bool if isinstance mask np ndarray if mask shape data shape raise ValueError 'Maskmusthavethesameshapeasdata ' mask pd DataFrame mask index data index columns data columns dtype np bool elif isinstance mask pd DataFrame if not mask index equals data...
79
python-test-5918
python
What does the code update to the given image url ?
the user profiles image
def update image facebook id image url image name 'fb image %s jpg' % facebook id image temp Named Temporary File try image response urllib 2 urlopen image url except Attribute Error image response urllib request urlopen image url image content image response read image temp write image content http message image respo...
def _update_image facebook_id image_url image_name 'fb_image_%s jpg' % facebook_id image_temp NamedTemporaryFile try image_response urllib2 urlopen image_url except AttributeError image_response urllib request urlopen image_url image_content image_response read image_temp write image_content http_message image_response...
110
python-test-5922
python
Till when do a resource query ?
until a successful response
def wait for successful query url wait for 300 **kwargs starttime time time while True caught exception Noneresult Nonetry result query url url **kwargs if not result get ' Error' and not result get 'error' return resultexcept Exception as exc caught exception excif time time > starttime + wait for if not result and ca...
def wait_for_successful_query url wait_for 300 **kwargs starttime time time while True caught_exception Noneresult Nonetry result query url url **kwargs if not result get 'Error' and not result get 'error' return resultexcept Exception as exc caught_exception excif time time > starttime + wait_for if not result and cau...
60
python-test-5924
python
What do tests serialize in a simple migration ?
translated field
def test translated field supports migration fields {'charfield' Translated Field }migration type str ' Migration' migrations Migration {'operations' [migrations Create Model name ' My Model' fields tuple fields items bases models Model ]} writer Migration Writer migration output writer as string result safe exec outpu...
def test_translated_field_supports_migration fields {'charfield' TranslatedField }migration type str 'Migration' migrations Migration {'operations' [migrations CreateModel name 'MyModel' fields tuple fields items bases models Model ]} writer MigrationWriter migration output writer as_string result safe_exec output glob...
52
python-test-5925
python
How do weights transfer ?
by copying matching parameters
def transplant new net net suffix '' for p in net params p new p + suffix if p new not in new net params print 'dropping' pcontinuefor i in range len net params[p] if i > len new net params[p new] - 1 print 'dropping' p ibreakif net params[p][i] data shape new net params[p new][i] data shape print 'coercing' p i 'from'...
def transplant new_net net suffix '' for p in net params p_new p + suffix if p_new not in new_net params print 'dropping' pcontinuefor i in range len net params[p] if i > len new_net params[p_new] - 1 print 'dropping' p ibreakif net params[p][i] data shape new_net params[p_new][i] data shape print 'coercing' p i 'from'...
90
python-test-5926
python
What does the code given ?
a liveaction
def get trace db by live action liveaction trace db Nonecreated Falsetrace context liveaction context get TRACE CONTEXT None if trace context trace context get valid trace context trace context trace db get trace trace context trace context ignore trace tag True if not trace db trace db Trace DB trace tag trace context...
def get_trace_db_by_live_action liveaction trace_db Nonecreated Falsetrace_context liveaction context get TRACE_CONTEXT None if trace_context trace_context _get_valid_trace_context trace_context trace_db get_trace trace_context trace_context ignore_trace_tag True if not trace_db trace_db TraceDB trace_tag trace_context...
168
python-test-5928
python
What is constructing in ?
a standard tooltip for the node
def Node Item tool Tip Helper node links in [] links out [] desc node widget descriptionchannel fmt '<li>{ 0 }</li>'title fmt '<b>{title}</b><hr/>'title title fmt format title escape node title inputs list fmt ' Inputs <ul>{inputs}</ul><hr/>'outputs list fmt ' Outputs <ul>{outputs}</ul>'if desc inputs inputs [channel f...
def NodeItem_toolTipHelper node links_in [] links_out [] desc node widget_descriptionchannel_fmt '<li>{0}</li>'title_fmt '<b>{title}</b><hr/>'title title_fmt format title escape node title inputs_list_fmt 'Inputs <ul>{inputs}</ul><hr/>'outputs_list_fmt 'Outputs <ul>{outputs}</ul>'if desc inputs inputs [channel_fmt form...
109
python-test-5929
python
What does the code remove ?
empty or unwanted headers
def fix headers soup data header rows soup find all 'th' for t in header rows if ' Version ' in t text if t next sibling text '$ Revision$' t parent extract if t next sibling text '' t parent extract if ' Last- Modified ' in t text if '$ Date$' in t next sibling text t parent extract if t next sibling text '' t parent ...
def fix_headers soup data header_rows soup find_all 'th' for t in header_rows if 'Version ' in t text if t next_sibling text '$Revision$' t parent extract if t next_sibling text '' t parent extract if 'Last-Modified ' in t text if '$Date$' in t next_sibling text t parent extract if t next_sibling text '' t parent extra...
110
python-test-5930
python
What does the code find ?
our title
def fix headers soup data header rows soup find all 'th' for t in header rows if ' Version ' in t text if t next sibling text '$ Revision$' t parent extract if t next sibling text '' t parent extract if ' Last- Modified ' in t text if '$ Date$' in t next sibling text t parent extract if t next sibling text '' t parent ...
def fix_headers soup data header_rows soup find_all 'th' for t in header_rows if 'Version ' in t text if t next_sibling text '$Revision$' t parent extract if t next_sibling text '' t parent extract if 'Last-Modified ' in t text if '$Date$' in t next_sibling text t parent extract if t next_sibling text '' t parent extra...
110
python-test-5937
python
What does the code get ?
admin state and description of a svi interface
def get manual interface attributes interface module if get interface type interface 'svi' command 'showinterface' + interface try body execute modified show for cli text command module [0 ]except Index Error Shell Error return Nonecommand list body split '\n' desc Noneadmin state 'up'for each in command list if ' Desc...
def get_manual_interface_attributes interface module if get_interface_type interface 'svi' command 'showinterface' + interface try body execute_modified_show_for_cli_text command module [0]except IndexError ShellError return Nonecommand_list body split '\n' desc Noneadmin_state 'up'for each in command_list if 'Descript...
87
python-test-5939
python
How do a specific course certificate signatory manipulate ?
via its internal identifier
@login required@ensure csrf cookie@require http methods 'POST' 'PUT' 'DELETE' def signatory detail handler request course key string certificate id signatory id course key Course Key from string course key string store modulestore with store bulk operations course key course get course and check access course key reque...
@login_required@ensure_csrf_cookie@require_http_methods 'POST' 'PUT' 'DELETE' def signatory_detail_handler request course_key_string certificate_id signatory_id course_key CourseKey from_string course_key_string store modulestore with store bulk_operations course_key course _get_course_and_check_access course_key reque...
110
python-test-5941
python
What does the mod_aggregate function look ?
all rules in the available low chunks
def mod aggregate low chunks running rules []agg enabled ['append' 'insert']if low get 'fun' not in agg enabled return lowfor chunk in chunks tag salt utils gen state tag chunk if tag in running continueif chunk get 'state' 'iptables' if ' agg ' in chunk continueif chunk get 'fun' low get 'fun' continueif chunk not in ...
def mod_aggregate low chunks running rules []agg_enabled ['append' 'insert']if low get 'fun' not in agg_enabled return lowfor chunk in chunks tag salt utils gen_state_tag chunk if tag in running continueif chunk get 'state' 'iptables' if '__agg__' in chunk continueif chunk get 'fun' low get 'fun' continueif chunk not i...
76
python-test-5945
python
What does the code convert to a template ?
a simple " shorthand " python value
def as template value if isinstance value Template return valueelif isinstance value collections Mapping return Mapping Template value elif value is int return Integer elif isinstance value int return Integer value elif isinstance value type and issubclass value BASESTRING return String elif isinstance value BASESTRING...
def as_template value if isinstance value Template return valueelif isinstance value collections Mapping return MappingTemplate value elif value is int return Integer elif isinstance value int return Integer value elif isinstance value type and issubclass value BASESTRING return String elif isinstance value BASESTRING ...
95
python-test-5946
python
What does the code take if a string that is already a dns name in dns format is passed as input ?
a list of dns names or a single dns name
def names 2 dnsrepr x if type x is str if x and x[ -1 ] '\x 00 ' return xx [x]res []for n in x termin '\x 00 'if n count ' ' 0 termin + '\x 00 'n '' join map lambda y chr len y + y n split ' ' + termin res append n return '' join res
def names2dnsrepr x if type x is str if x and x[ -1 ] '\x00' return xx [x]res []for n in x termin '\x00'if n count ' ' 0 termin + '\x00'n '' join map lambda y chr len y + y n split ' ' + termin res append n return '' join res
63
python-test-5947
python
How does the code encode it if a string that is already a dns name in dns format is passed ?
in dns format
def names 2 dnsrepr x if type x is str if x and x[ -1 ] '\x 00 ' return xx [x]res []for n in x termin '\x 00 'if n count ' ' 0 termin + '\x 00 'n '' join map lambda y chr len y + y n split ' ' + termin res append n return '' join res
def names2dnsrepr x if type x is str if x and x[ -1 ] '\x00' return xx [x]res []for n in x termin '\x00'if n count ' ' 0 termin + '\x00'n '' join map lambda y chr len y + y n split ' ' + termin res append n return '' join res
63
python-test-5950
python
What does the code add ?
a junction to the _ current_statement
def add junction item type channels expand one key dictionary item junction Unnamed Statement type 'junction' for item in channels type value expand one key dictionary item channel Unnamed Statement type 'channel' for val in value if is reference val add reference val channel elif is inline definition val add inline de...
def _add_junction item type_ channels _expand_one_key_dictionary item junction UnnamedStatement type 'junction' for item in channels type_ value _expand_one_key_dictionary item channel UnnamedStatement type 'channel' for val in value if _is_reference val _add_reference val channel elif _is_inline_definition val _add_in...
63
python-test-5954
python
What does the code take ?
a soundcloud url
def get with url url try params {'url' url 'client id' api key}request requests get API BASE format 'resolve' params params request raise for status except requests exceptions HTTP Error requests exceptions Connection Error as e raise API Error '{}' format e json request json if not json return Noneelse return json
def get_with_url url try params {'url' url 'client_id' api_key}request requests get API_BASE format 'resolve' params params request raise_for_status except requests exceptions HTTPError requests exceptions ConnectionError as e raise APIError '{}' format e json request json if not json return Noneelse return json
52
python-test-5955
python
What does the code perform ?
a ll operation
def ll op left right if len left > 0 ll gate left[ 0 ]ll gate is unitary is scalar matrix Dagger ll gate ll gate get min qubits ll gate True if len left > 0 and ll gate is unitary new left left[ 1 len left ]new right Dagger ll gate + right return new left new right return None
def ll_op left right if len left > 0 ll_gate left[0]ll_gate_is_unitary is_scalar_matrix Dagger ll_gate ll_gate _get_min_qubits ll_gate True if len left > 0 and ll_gate_is_unitary new_left left[1 len left ]new_right Dagger ll_gate + right return new_left new_right return None
62
python-test-5957
python
What does a context manager set for a test ?
the correct keyczar environment
@contextmanagerdef keys purpose mode None orig setting dir getattr settings 'ENCRYPTED FIELD KEYS DIR' None orig setting mode getattr settings 'ENCRYPTED FIELD MODE' None try if mode settings ENCRYPTED FIELD MODE modeif purpose keyinfo DECRYPT AND ENCRYPT settings ENCRYPTED FIELD KEYS DIR KEY LOCS['DECRYPT AND ENCRYPT'...
@contextmanagerdef keys purpose mode None orig_setting_dir getattr settings 'ENCRYPTED_FIELD_KEYS_DIR' None orig_setting_mode getattr settings 'ENCRYPTED_FIELD_MODE' None try if mode settings ENCRYPTED_FIELD_MODE modeif purpose keyinfo DECRYPT_AND_ENCRYPT settings ENCRYPTED_FIELD_KEYS_DIR KEY_LOCS['DECRYPT_AND_ENCRYPT'...
99
python-test-5958
python
What does the code return ?
a dict with information about schemas in a database
def schema get dbname name db user None db password None db host None db port None all schemas schema list dbname db user db user db host db host db port db port db password db password try return all schemas get name None except Attribute Error log error ' Couldnotretrieve Postgresschema Is Postgresrunning?' return Fa...
def schema_get dbname name db_user None db_password None db_host None db_port None all_schemas schema_list dbname db_user db_user db_host db_host db_port db_port db_password db_password try return all_schemas get name None except AttributeError log error 'CouldnotretrievePostgresschema IsPostgresrunning?' return False
57
python-test-5961
python
How is the path intersecting ?
by checking line intersection
def is Added Point On Path Intersecting Path begin path point point Index segment point - begin segment Length abs segment if segment Length < 0 0 return Falsenormalized Segment segment / segment Length segment Y Mirror complex normalized Segment real - normalized Segment imag point Rotated segment Y Mirror * point beg...
def isAddedPointOnPathIntersectingPath begin path point pointIndex segment point - begin segmentLength abs segment if segmentLength < 0 0 return FalsenormalizedSegment segment / segmentLength segmentYMirror complex normalizedSegment real - normalizedSegment imag pointRotated segmentYMirror * point beginRotated segmentY...
116
python-test-5963
python
What does function handle ?
a email confirmation request
def confirm email token expired invalid user confirm email token status token if not user or invalid invalid Truedo flash *get message 'INVALID CONFIRMATION TOKEN' if expired send confirmation instructions user do flash *get message 'CONFIRMATION EXPIRED' email user email within security confirm email within if invalid...
def confirm_email token expired invalid user confirm_email_token_status token if not user or invalid invalid Truedo_flash *get_message 'INVALID_CONFIRMATION_TOKEN' if expired send_confirmation_instructions user do_flash *get_message 'CONFIRMATION_EXPIRED' email user email within _security confirm_email_within if invali...
104
python-test-5968
python
Where did points give ?
in eval_points
def Lop f wrt eval points consider constant None disconnected inputs 'raise' if type eval points not in list tuple eval points [eval points]using list isinstance wrt list using tuple isinstance wrt tuple if not isinstance f list tuple f [f]f list f grads list eval points if not isinstance wrt list tuple wrt [wrt]assert...
def Lop f wrt eval_points consider_constant None disconnected_inputs 'raise' if type eval_points not in list tuple eval_points [eval_points]using_list isinstance wrt list using_tuple isinstance wrt tuple if not isinstance f list tuple f [f]f list f grads list eval_points if not isinstance wrt list tuple wrt [wrt]assert...
90
python-test-5969
python
What does the code compute ?
the l operation on f wrt to wrt evaluated at points given in eval_points
def Lop f wrt eval points consider constant None disconnected inputs 'raise' if type eval points not in list tuple eval points [eval points]using list isinstance wrt list using tuple isinstance wrt tuple if not isinstance f list tuple f [f]f list f grads list eval points if not isinstance wrt list tuple wrt [wrt]assert...
def Lop f wrt eval_points consider_constant None disconnected_inputs 'raise' if type eval_points not in list tuple eval_points [eval_points]using_list isinstance wrt list using_tuple isinstance wrt tuple if not isinstance f list tuple f [f]f list f grads list eval_points if not isinstance wrt list tuple wrt [wrt]assert...
90
python-test-5971
python
What does this call the windows in a unicode safe way ?
regenumkeyex function
def Enum Key key index regenumkeyex advapi 32 [' Reg Enum Key Ex W']regenumkeyex restype ctypes c longregenumkeyex argtypes [ctypes c void p ctypes wintypes DWORD ctypes c wchar p LPDWORD LPDWORD ctypes c wchar p LPDWORD ctypes POINTER File Time ]buf ctypes create unicode buffer 257 length ctypes wintypes DWORD 257 rc ...
def EnumKey key index regenumkeyex advapi32['RegEnumKeyExW']regenumkeyex restype ctypes c_longregenumkeyex argtypes [ctypes c_void_p ctypes wintypes DWORD ctypes c_wchar_p LPDWORD LPDWORD ctypes c_wchar_p LPDWORD ctypes POINTER FileTime ]buf ctypes create_unicode_buffer 257 length ctypes wintypes DWORD 257 rc regenumke...
96
python-test-5973
python
What does the code make ?
a table with the columns in mixin_cols
def test make table table types mixin cols t table types Table mixin cols check mixin type t t['m'] mixin cols['m'] cols list mixin cols values t table types Table cols names 'i' 'a' 'b' 'm' check mixin type t t['m'] mixin cols['m'] t table types Table cols check mixin type t t['col 3 '] mixin cols['m']
def test_make_table table_types mixin_cols t table_types Table mixin_cols check_mixin_type t t['m'] mixin_cols['m'] cols list mixin_cols values t table_types Table cols names 'i' 'a' 'b' 'm' check_mixin_type t t['m'] mixin_cols['m'] t table_types Table cols check_mixin_type t t['col3'] mixin_cols['m']
57
python-test-5975
python
What does this function calculate ?
the log - conditional - probability measure which is used by coherence measures such as u_mass
def log conditional probability segmented topics per topic postings num docs m lc []for s i in segmented topics for w prime w star in s i w prime docs per topic postings[w prime]w star docs per topic postings[w star]co docs w prime docs intersection w star docs if w star docs m lc i np log len co docs / float num docs ...
def log_conditional_probability segmented_topics per_topic_postings num_docs m_lc []for s_i in segmented_topics for w_prime w_star in s_i w_prime_docs per_topic_postings[w_prime]w_star_docs per_topic_postings[w_star]co_docs w_prime_docs intersection w_star_docs if w_star_docs m_lc_i np log len co_docs / float num_docs ...
89
python-test-5976
python
What does the code process using pygments ?
the contained block
@environmentfilterdef syntax env value lexer None filename None try import pygmentsfrom pygments import lexersfrom pygments import formattersexcept Import Error logger error u'pygmentslibraryisrequiredtousesyntaxhighlightingtags ' raise Template Error ' Cannotloadpygments' pyg lexers get lexer by name lexer if lexer el...
@environmentfilterdef syntax env value lexer None filename None try import pygmentsfrom pygments import lexersfrom pygments import formattersexcept ImportError logger error u'pygmentslibraryisrequiredtousesyntaxhighlightingtags ' raise TemplateError 'Cannotloadpygments' pyg lexers get_lexer_by_name lexer if lexer else ...
110
python-test-5977
python
How does the code process the contained block ?
using pygments
@environmentfilterdef syntax env value lexer None filename None try import pygmentsfrom pygments import lexersfrom pygments import formattersexcept Import Error logger error u'pygmentslibraryisrequiredtousesyntaxhighlightingtags ' raise Template Error ' Cannotloadpygments' pyg lexers get lexer by name lexer if lexer el...
@environmentfilterdef syntax env value lexer None filename None try import pygmentsfrom pygments import lexersfrom pygments import formattersexcept ImportError logger error u'pygmentslibraryisrequiredtousesyntaxhighlightingtags ' raise TemplateError 'Cannotloadpygments' pyg lexers get_lexer_by_name lexer if lexer else ...
110
python-test-5980
python
What does the code remove ?
unnecessary closing point of polygon points attribute
def clean Polygon elem options global num Points Removed From Polygonpts parse List Of Points elem get Attribute 'points' N len pts / 2 if N > 2 startx starty pts[ 2] endx endy pts[ -2 ]if startx endx and starty endy del pts[ -2 ]num Points Removed From Polygon + 1elem set Attribute 'points' scour Coordinates pts optio...
def cleanPolygon elem options global numPointsRemovedFromPolygonpts parseListOfPoints elem getAttribute 'points' N len pts / 2 if N > 2 startx starty pts[ 2] endx endy pts[ -2 ]if startx endx and starty endy del pts[ -2 ]numPointsRemovedFromPolygon + 1elem setAttribute 'points' scourCoordinates pts options True
60
python-test-5982
python
What does the code generate ?
a sequence of all
def Get Java Jars target list target dicts toplevel dir for target name in target list target target dicts[target name]for action in target get 'actions' [] for input in action['inputs'] if os path splitext input [1 ] ' jar' and not input startswith '$' if os path isabs input yield input else yield os path join os path...
def GetJavaJars target_list target_dicts toplevel_dir for target_name in target_list target target_dicts[target_name]for action in target get 'actions' [] for input_ in action['inputs'] if os path splitext input_ [1] ' jar' and not input_ startswith '$' if os path isabs input_ yield input_ else yield os path join os pa...
62
python-test-5984
python
How do the worker activate ?
worker_activate
def send command cmd worker lbn target profile 'default' tgt type 'glob' ret {'code' False 'msg' 'OK' 'minions' []}func 'modjk {0 }' format cmd args [worker lbn profile]response salt ['publish publish'] target func args tgt type errors []minions []for minion in response minions append minion if not response[minion] err...
def _send_command cmd worker lbn target profile 'default' tgt_type 'glob' ret {'code' False 'msg' 'OK' 'minions' []}func 'modjk {0}' format cmd args [worker lbn profile]response __salt__['publish publish'] target func args tgt_type errors []minions []for minion in response minions append minion if not response[minion] ...
76
python-test-5985
python
What do the minion need ?
to be able to publish the commands to the load balancer cmd
def send command cmd worker lbn target profile 'default' tgt type 'glob' ret {'code' False 'msg' 'OK' 'minions' []}func 'modjk {0 }' format cmd args [worker lbn profile]response salt ['publish publish'] target func args tgt type errors []minions []for minion in response minions append minion if not response[minion] err...
def _send_command cmd worker lbn target profile 'default' tgt_type 'glob' ret {'code' False 'msg' 'OK' 'minions' []}func 'modjk {0}' format cmd args [worker lbn profile]response __salt__['publish publish'] target func args tgt_type errors []minions []for minion in response minions append minion if not response[minion] ...
76
python-test-5987
python
How do the encoding of the file get ?
using the pep 0263 rules search
def get file encoding content encoding Nonetry lines to check content split u'\n' 2 for index in range 2 if len lines to check > index line encoding search coding line lines to check[index] if line encoding encoding line encodingbreakexcept Unicode Decode Error as error print errorif encoding is None encoding u'UTF- 8 ...
def get_file_encoding content encoding Nonetry lines_to_check content split u'\n' 2 for index in range 2 if len lines_to_check > index line_encoding _search_coding_line lines_to_check[index] if line_encoding encoding line_encodingbreakexcept UnicodeDecodeError as error print errorif encoding is None encoding u'UTF-8're...
55
python-test-5988
python
When do the pep 0263 rules search ?
the first or the second line of the file
def get file encoding content encoding Nonetry lines to check content split u'\n' 2 for index in range 2 if len lines to check > index line encoding search coding line lines to check[index] if line encoding encoding line encodingbreakexcept Unicode Decode Error as error print errorif encoding is None encoding u'UTF- 8 ...
def get_file_encoding content encoding Nonetry lines_to_check content split u'\n' 2 for index in range 2 if len lines_to_check > index line_encoding _search_coding_line lines_to_check[index] if line_encoding encoding line_encodingbreakexcept UnicodeDecodeError as error print errorif encoding is None encoding u'UTF-8're...
55
python-test-5991
python
Does a version of path exist on the filesystem ?
No
def unique path path if not os path exists syspath path return path base ext os path splitext path match re search '\\ \\d +$' base if match num int match group 1 base base[ match start ]else num 0while True num + 1new path '%s %i%s' % base num ext if not os path exists new path return new path
def unique_path path if not os path exists syspath path return path base ext os path splitext path match re search '\\ \\d +$' base if match num int match group 1 base base[ match start ]else num 0while True num + 1new_path '%s %i%s' % base num ext if not os path exists new_path return new_path
61
python-test-5992
python
What does not exist on the filesystem ?
a version of path
def unique path path if not os path exists syspath path return path base ext os path splitext path match re search '\\ \\d +$' base if match num int match group 1 base base[ match start ]else num 0while True num + 1new path '%s %i%s' % base num ext if not os path exists new path return new path
def unique_path path if not os path exists syspath path return path base ext os path splitext path match re search '\\ \\d +$' base if match num int match group 1 base base[ match start ]else num 0while True num + 1new_path '%s %i%s' % base num ext if not os path exists new_path return new_path
61
python-test-5993
python
Where does a version of path not exist ?
on the filesystem
def unique path path if not os path exists syspath path return path base ext os path splitext path match re search '\\ \\d +$' base if match num int match group 1 base base[ match start ]else num 0while True num + 1new path '%s %i%s' % base num ext if not os path exists new path return new path
def unique_path path if not os path exists syspath path return path base ext os path splitext path match re search '\\ \\d +$' base if match num int match group 1 base base[ match start ]else num 0while True num + 1new_path '%s %i%s' % base num ext if not os path exists new_path return new_path
61
python-test-5997
python
What did the code set ?
the named ports on a managed instance group
def update named ports mig named ports changed Falseexisting ports []new ports []if hasattr mig instance group 'named ports' existing ports sorted mig instance group named ports key lambda x x['name'] if named ports is not None new ports sorted named ports key lambda x x['name'] if existing ports new ports if mig insta...
def update_named_ports mig named_ports changed Falseexisting_ports []new_ports []if hasattr mig instance_group 'named_ports' existing_ports sorted mig instance_group named_ports key lambda x x['name'] if named_ports is not None new_ports sorted named_ports key lambda x x['name'] if existing_ports new_ports if mig insta...
63
python-test-6000
python
What does the code make ?
n samples related to each sample in an input otu table input : the constituents of an otu table * sample_ids : list * otu_ids : list * samples : iterable
def sim otu table sample ids otu ids samples otu metadata tree num replicates dissimilarity sample dicts []res sam names []for i sample info in enumerate samples sample vector sample info[ 0 ]for j in range num replicates sample dict {}for k in range len otu ids otu abundance sample vector[k]if otu abundance 0 continue...
def sim_otu_table sample_ids otu_ids samples otu_metadata tree num_replicates dissimilarity sample_dicts []res_sam_names []for i sample_info in enumerate samples sample_vector sample_info[0]for j in range num_replicates sample_dict {}for k in range len otu_ids otu_abundance sample_vector[k]if otu_abundance 0 continuene...
165
python-test-6003
python
For what purpose does both dump and add_to_dump call ?
to serialze several objects
def dump and add to dump object file parameters None to add None use cpickle False protocol DEFAULT PROTOCOL **kwargs dump object file parameters parameters use cpickle use cpickle protocol protocol **kwargs if to add is not None for name obj in six iteritems to add add to dump obj file name parameters parameters use c...
def dump_and_add_to_dump object_ file_ parameters None to_add None use_cpickle False protocol DEFAULT_PROTOCOL **kwargs dump object_ file_ parameters parameters use_cpickle use_cpickle protocol protocol **kwargs if to_add is not None for name obj in six iteritems to_add add_to_dump obj file_ name parameters parameters ...
61
python-test-6005
python
What does the code setup ?
the osram lightify lights
def setup platform hass config add devices discovery info None import lightifyhost config get CONF HOST if host try bridge lightify Lightify host except socket error as err msg ' Errorconnectingtobridge {}dueto {}' format host str err LOGGER exception msg return Falsesetup bridge bridge add devices else LOGGER error ' ...
def setup_platform hass config add_devices discovery_info None import lightifyhost config get CONF_HOST if host try bridge lightify Lightify host except socket error as err msg 'Errorconnectingtobridge {}dueto {}' format host str err _LOGGER exception msg return Falsesetup_bridge bridge add_devices else _LOGGER error '...
53
python-test-6011
python
What does nt use the uri notation ?
the backend configuration
def parse backend conf backend **kwargs conf settings CACHES get backend None if conf is not None args conf copy args update kwargs backend args pop 'BACKEND' location args pop 'LOCATION' '' return backend location args else try backend cls import by path backend except Improperly Configured as e raise Invalid Cache Ba...
def parse_backend_conf backend **kwargs conf settings CACHES get backend None if conf is not None args conf copy args update kwargs backend args pop 'BACKEND' location args pop 'LOCATION' '' return backend location args else try backend_cls import_by_path backend except ImproperlyConfigured as e raise InvalidCacheBacke...
69
python-test-6012
python
What does the backend configuration nt use ?
the uri notation
def parse backend conf backend **kwargs conf settings CACHES get backend None if conf is not None args conf copy args update kwargs backend args pop 'BACKEND' location args pop 'LOCATION' '' return backend location args else try backend cls import by path backend except Improperly Configured as e raise Invalid Cache Ba...
def parse_backend_conf backend **kwargs conf settings CACHES get backend None if conf is not None args conf copy args update kwargs backend args pop 'BACKEND' location args pop 'LOCATION' '' return backend location args else try backend_cls import_by_path backend except ImproperlyConfigured as e raise InvalidCacheBacke...
69
python-test-6013
python
Does the backend configuration use the uri notation ?
No
def parse backend conf backend **kwargs conf settings CACHES get backend None if conf is not None args conf copy args update kwargs backend args pop 'BACKEND' location args pop 'LOCATION' '' return backend location args else try backend cls import by path backend except Improperly Configured as e raise Invalid Cache Ba...
def parse_backend_conf backend **kwargs conf settings CACHES get backend None if conf is not None args conf copy args update kwargs backend args pop 'BACKEND' location args pop 'LOCATION' '' return backend location args else try backend_cls import_by_path backend except ImproperlyConfigured as e raise InvalidCacheBacke...
69
python-test-6020
python
What does the code run ?
the command configured
def top **kwargs if 'id' not in kwargs['opts'] return {}cmd '{ 0 }{ 1 }' format opts ['master tops']['ext nodes'] kwargs['opts']['id'] ndata yaml safe load subprocess Popen cmd shell True stdout subprocess PIPE communicate [0 ] if not ndata log info 'master topsext nodescalldidnotreturnanydata' ret {}if 'environment' i...
def top **kwargs if 'id' not in kwargs['opts'] return {}cmd '{0}{1}' format __opts__['master_tops']['ext_nodes'] kwargs['opts']['id'] ndata yaml safe_load subprocess Popen cmd shell True stdout subprocess PIPE communicate [0] if not ndata log info 'master_topsext_nodescalldidnotreturnanydata' ret {}if 'environment' in ...
79
python-test-6024
python
What set global_help_setup as 1 in common_site_config ?
a separate database
@click command u'setup-global-help' @click option u'--mariadb root password' def setup global help mariadb root password None from frappe installer import update site configfrappe local flags frappe dict frappe local flags in setup help Truefrappe local flags in install Truefrappe local lang u'en'frappe local conf frap...
@click command u'setup-global-help' @click option u'--mariadb_root_password' def setup_global_help mariadb_root_password None from frappe installer import update_site_configfrappe local flags frappe _dict frappe local flags in_setup_help Truefrappe local flags in_install Truefrappe local lang u'en'frappe local conf fra...
88
python-test-6025
python
What did a separate database set as 1 in common_site_config ?
global_help_setup
@click command u'setup-global-help' @click option u'--mariadb root password' def setup global help mariadb root password None from frappe installer import update site configfrappe local flags frappe dict frappe local flags in setup help Truefrappe local flags in install Truefrappe local lang u'en'frappe local conf frap...
@click command u'setup-global-help' @click option u'--mariadb_root_password' def setup_global_help mariadb_root_password None from frappe installer import update_site_configfrappe local flags frappe _dict frappe local flags in_setup_help Truefrappe local flags in_install Truefrappe local lang u'en'frappe local conf fra...
88
python-test-6029
python
In which direction do vehicle move ?
in direction based on specified velocity vectors and for the specified duration
def send ned velocity velocity x velocity y velocity z duration msg vehicle message factory set position target local ned encode 0 0 0 mavutil mavlink MAV FRAME LOCAL NED 4039 0 0 0 velocity x velocity y velocity z 0 0 0 0 0 for x in range 0 duration vehicle send mavlink msg time sleep 1
def send_ned_velocity velocity_x velocity_y velocity_z duration msg vehicle message_factory set_position_target_local_ned_encode 0 0 0 mavutil mavlink MAV_FRAME_LOCAL_NED 4039 0 0 0 velocity_x velocity_y velocity_z 0 0 0 0 0 for x in range 0 duration vehicle send_mavlink msg time sleep 1
58
python-test-6034
python
How does section search query ?
with query q across all documents and projects
@decorators api view ['GET'] @decorators permission classes permissions Allow Any @decorators renderer classes JSON Renderer def section search request query request GET get 'q' None if not query return Response {'error' ' Searchtermrequired Usethe"q"GE Targtosearch '} status status HTTP 400 BAD REQUEST project slug re...
@decorators api_view ['GET'] @decorators permission_classes permissions AllowAny @decorators renderer_classes JSONRenderer def section_search request query request GET get 'q' None if not query return Response {'error' 'Searchtermrequired Usethe"q"GETargtosearch '} status status HTTP_400_BAD_REQUEST project_slug reques...
96
python-test-6035
python
For what purpose do you perform the equivalent of a oc deploy --cancel ?
for the provided deployment config
def openshift deploy canceller registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Deploy Canceller' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'dep-cfg' 'dep Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' ...
def openshift_deploy_canceller registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftDeployCanceller' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'dep-cfg' 'depCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'ver...
59
python-test-6036
python
For what purpose did cleanup provide when the job completes ?
for any openshift deployments left running
def openshift deploy canceller registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Deploy Canceller' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'dep-cfg' 'dep Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' ...
def openshift_deploy_canceller registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftDeployCanceller' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'dep-cfg' 'depCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'ver...
59
python-test-6037
python
What do you perform for the provided deployment config ?
the equivalent of a oc deploy --cancel
def openshift deploy canceller registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Deploy Canceller' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'dep-cfg' 'dep Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' ...
def openshift_deploy_canceller registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftDeployCanceller' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'dep-cfg' 'depCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'ver...
59
python-test-6038
python
What left running when the job completes ?
any openshift deployments
def openshift deploy canceller registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Deploy Canceller' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'dep-cfg' 'dep Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' ...
def openshift_deploy_canceller registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftDeployCanceller' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'dep-cfg' 'depCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'ver...
59
python-test-6039
python
What will this step allow ?
you to perform the equivalent of a oc deploy --cancel for the provided deployment config
def openshift deploy canceller registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Deploy Canceller' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'dep-cfg' 'dep Cfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'auth Token' ...
def openshift_deploy_canceller registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftDeployCanceller' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'dep-cfg' 'depCfg' 'frontend' 'namespace' 'namespace' 'test' 'auth-token' 'authToken' '' 'ver...
59
python-test-6044
python
What is this device having ?
its own devices downloaded
@csrf exempt@gzip page@require sync session@api handle error with jsondef device download data session zone session client device get zone devicezones list Device Zone all objects filter zone zone device in data['devices'] devices [devicezone device for devicezone in devicezones]session models downloaded + len devices ...
@csrf_exempt@gzip_page@require_sync_session@api_handle_error_with_jsondef device_download data session zone session client_device get_zone devicezones list DeviceZone all_objects filter zone zone device__in data['devices'] devices [devicezone device for devicezone in devicezones]session models_downloaded + len devices ...
63
python-test-6047
python
What does this function map sqlalchemy types ?
to spyne types
def process item v rpc type Noneif isinstance v Column if isinstance v type sqlalchemy Enum if v type convert unicode rpc type primitive Unicode values v type enums else rpc type primitive String values v type enums elif v type in type map rpc type type map[v type]elif type v type in type map rpc type type map[type v t...
def _process_item v rpc_type Noneif isinstance v Column if isinstance v type sqlalchemy Enum if v type convert_unicode rpc_type primitive Unicode values v type enums else rpc_type primitive String values v type enums elif v type in _type_map rpc_type _type_map[v type]elif type v type in _type_map rpc_type _type_map[typ...
88
python-test-6048
python
What does this function map to spyne types ?
sqlalchemy types
def process item v rpc type Noneif isinstance v Column if isinstance v type sqlalchemy Enum if v type convert unicode rpc type primitive Unicode values v type enums else rpc type primitive String values v type enums elif v type in type map rpc type type map[v type]elif type v type in type map rpc type type map[type v t...
def _process_item v rpc_type Noneif isinstance v Column if isinstance v type sqlalchemy Enum if v type convert_unicode rpc_type primitive Unicode values v type enums else rpc_type primitive String values v type enums elif v type in _type_map rpc_type _type_map[v type]elif type v type in _type_map rpc_type _type_map[typ...
88
python-test-6053
python
What does the code add to the given fake facilities ?
the given fake facility groups
def generate fake facility groups names ' Class 4 E' ' Class 5 B' facilities None if not facilities facilities generate fake facilities facility groups []for facility in facilities for name in names found facility groups Facility Group objects filter facility facility name name if found facility groups facility group f...
def generate_fake_facility_groups names 'Class4E' 'Class5B' facilities None if not facilities facilities generate_fake_facilities facility_groups []for facility in facilities for name in names found_facility_groups FacilityGroup objects filter facility facility name name if found_facility_groups facility_group found_fa...
87
python-test-6054
python
How did the code give the code ?
with an " rrule "
def recurring component to events component rrule as str component get 'rrule' to ical recur rule rrule rrulestr rrule as str dtstart component decoded 'dtstart' recur set rrule rruleset recur set rrule recur rule if 'exdate' in component for exdate line in component decoded 'exdate' for exdate in exdate line dts recur...
def _recurring_component_to_events component rrule_as_str component get 'rrule' to_ical recur_rule rrule rrulestr rrule_as_str dtstart component decoded 'dtstart' recur_set rrule rruleset recur_set rrule recur_rule if 'exdate' in component for exdate_line in component decoded 'exdate' for exdate in exdate_line dts recu...
113
python-test-6056
python
What does the code ensure ?
beacon is absent
def absent name **kwargs ret {'name' name 'result' True 'changes' {} 'comment' []}current beacons salt ['beacons list'] return yaml False if name in current beacons if 'test' in opts and opts ['test'] kwargs['test'] Trueresult salt ['beacons delete'] name **kwargs ret['comment'] append result['comment'] else result sal...
def absent name **kwargs ret {'name' name 'result' True 'changes' {} 'comment' []}current_beacons __salt__['beacons list'] return_yaml False if name in current_beacons if 'test' in __opts__ and __opts__['test'] kwargs['test'] Trueresult __salt__['beacons delete'] name **kwargs ret['comment'] append result['comment'] el...
78
python-test-6059
python
What does the code check ?
a named value return a dictionary containing associations
def check named option opt value if isinstance value dict return valuevalues []for value in check csv option opt value if value find ' ' -1 values append value split ' ' 1 elif value find ' ' -1 values append value split ' ' 1 if values return dict values msg 'option%s invalidnamedvalue%r shouldbe<NAME> <VALUE>or<NAME>...
def check_named option opt value if isinstance value dict return valuevalues []for value in check_csv option opt value if value find ' ' -1 values append value split ' ' 1 elif value find ' ' -1 values append value split ' ' 1 if values return dict values msg 'option%s invalidnamedvalue%r shouldbe<NAME> <VALUE>or<NAME>...
64
python-test-6060
python
How do constrasting colors generate ?
by varying most significant bit of rgb first
def contrasting color generator def rgb to hex rgb return u'#% 02 x% 02 x% 02 x' % tuple rgb triples [ 1 0 0 0 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 1 ]n 1 << 7 so far [[ 0 0 0]]while True if n 0 yield u'# 000000 ' copy so far list so far for triple in triples for previous in copy so far rgb [ n * triple[i] + previous[i] for...
def contrasting_color_generator def rgb_to_hex rgb return u'#%02x%02x%02x' % tuple rgb triples [ 1 0 0 0 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 1 ]n 1 << 7 so_far [[0 0 0]]while True if n 0 yield u'#000000' copy_so_far list so_far for triple in triples for previous in copy_so_far rgb [ n * triple[i] + previous[i] for i in ran...
101
python-test-6069
python
What does a generator yield ?
-tuples of visited pages
def crawl links [] domains [] delay 20 0 parse HTML Link Parser parse sort FIFO method DEPTH **kwargs crawler Crawler links domains delay parse sort bind crawler 'visit' lambda crawler link source None setattr crawler 'crawled' link source while not crawler done crawler crawled None None crawler crawl method **kwargs y...
def crawl links [] domains [] delay 20 0 parse HTMLLinkParser parse sort FIFO method DEPTH **kwargs crawler Crawler links domains delay parse sort bind crawler 'visit' lambda crawler link source None setattr crawler 'crawled' link source while not crawler done crawler crawled None None crawler crawl method **kwargs yie...
54
python-test-6070
python
When does a copy of obj return ?
after parsing strings in it using params
def evaluate object obj params if isinstance obj basestring return parse string obj params elif isinstance obj list new list []for item in obj new list append evaluate object item params return new listelif isinstance obj dict new dict {}for key in obj new dict[key] evaluate object obj[key] params return new dictelse r...
def evaluate_object obj params if isinstance obj basestring return parse_string obj params elif isinstance obj list new_list []for item in obj new_list append evaluate_object item params return new_listelif isinstance obj dict new_dict {}for key in obj new_dict[key] evaluate_object obj[key] params return new_dictelse r...
56
python-test-6071
python
What does the code update ?
the specified app with the given configuration
def update app id config if 'id' not in config config['id'] idconfig pop 'version' None config pop 'fetch' None data json dumps config try response salt utils http query '{ 0 }/v 2 /apps/{ 1 }?force true' format base url id method 'PUT' decode type 'json' decode True data data header dict {' Content- Type' 'application...
def update_app id config if 'id' not in config config['id'] idconfig pop 'version' None config pop 'fetch' None data json dumps config try response salt utils http query '{0}/v2/apps/{1}?force true' format _base_url id method 'PUT' decode_type 'json' decode True data data header_dict {'Content-Type' 'application/json' ...
85
python-test-6074
python
What do file contain ?
python byte - code object code_object : code_object
def load module filename import magics marshalfp open filename 'rb' magic fp read 4 try version magics versions[magic]except Key Error raise Import Error ' Unknownmagicnumber%sin%s' % ord magic[ 0 ] + 256 * ord magic[ 1 ] filename if version '2 7' raise Import Error ' Thisisa Python%sfile Only Python 2 7filesaresupport...
def _load_module filename import magics marshalfp open filename 'rb' magic fp read 4 try version magics versions[magic]except KeyError raise ImportError 'Unknownmagicnumber%sin%s' % ord magic[0] + 256 * ord magic[1] filename if version '2 7' raise ImportError 'ThisisaPython%sfile OnlyPython2 7filesaresupported ' % vers...
67
python-test-6075
python
What does the code create a directed graph d from an undirected graph g ?
to compute flow based node connectivity
def build auxiliary node connectivity G directed G is directed mapping {}H nx Di Graph for i node in enumerate G mapping[node] iH add node '%d A' % i id node H add node '%d B' % i id node H add edge '%d A' % i '%d B' % i capacity 1 edges []for source target in G edges edges append '%s B' % mapping[source] '%s A' % mapp...
def build_auxiliary_node_connectivity G directed G is_directed mapping {}H nx DiGraph for i node in enumerate G mapping[node] iH add_node '%dA' % i id node H add_node '%dB' % i id node H add_edge '%dA' % i '%dB' % i capacity 1 edges []for source target in G edges edges append '%sB' % mapping[source] '%sA' % mapping[tar...
94
python-test-6076
python
What does the code create to compute flow based node connectivity ?
a directed graph d from an undirected graph g
def build auxiliary node connectivity G directed G is directed mapping {}H nx Di Graph for i node in enumerate G mapping[node] iH add node '%d A' % i id node H add node '%d B' % i id node H add edge '%d A' % i '%d B' % i capacity 1 edges []for source target in G edges edges append '%s B' % mapping[source] '%s A' % mapp...
def build_auxiliary_node_connectivity G directed G is_directed mapping {}H nx DiGraph for i node in enumerate G mapping[node] iH add_node '%dA' % i id node H add_node '%dB' % i id node H add_edge '%dA' % i '%dB' % i capacity 1 edges []for source target in G edges edges append '%sB' % mapping[source] '%sA' % mapping[tar...
94
python-test-6077
python
What does the code read ?
a dictionary of the current users tokens from the datastore
def load auth tokens user None if user is None user users get current user if user is None return {}pickled tokens memcache get 'gdata pickled tokens %s' % user if pickled tokens return pickle loads pickled tokens user tokens Token Collection all filter 'user ' user get if user tokens memcache set 'gdata pickled tokens...
def load_auth_tokens user None if user is None user users get_current_user if user is None return {}pickled_tokens memcache get 'gdata_pickled_tokens %s' % user if pickled_tokens return pickle loads pickled_tokens user_tokens TokenCollection all filter 'user ' user get if user_tokens memcache set 'gdata_pickled_tokens ...
72
python-test-6078
python
What do this method use ?
to send answers to callback queries sent from inline keyboards
def answer callback query token callback query id text None show alert None url None cache time None method url 'answer Callback Query'payload {'callback query id' callback query id}if text payload['text'] textif show alert payload['show alert'] show alertif url payload['url'] urlif cache time payload['cache time'] cac...
def answer_callback_query token callback_query_id text None show_alert None url None cache_time None method_url 'answerCallbackQuery'payload {'callback_query_id' callback_query_id}if text payload['text'] textif show_alert payload['show_alert'] show_alertif url payload['url'] urlif cache_time payload['cache_time'] cache...
56
python-test-6082
python
When be your build name updated ?
during the build process
def build name setter registry xml parent data build name setter XML Sub Element xml parent 'org jenkinsci plugins buildnameupdater Build Name Updater' mapping [ 'name' 'build Name' 'version txt' 'template' 'macro Template' '#${BUILD NUMBER}' 'file' 'from File' False 'macro' 'from Macro' False 'macro-first' 'macro Firs...
def build_name_setter registry xml_parent data build_name_setter XML SubElement xml_parent 'org jenkinsci plugins buildnameupdater BuildNameUpdater' mapping [ 'name' 'buildName' 'version txt' 'template' 'macroTemplate' '#${BUILD_NUMBER}' 'file' 'fromFile' False 'macro' 'fromMacro' False 'macro-first' 'macroFirst' False...
59
python-test-6083
python
What allows your build name to be updated during the build process ?
build name setter options
def build name setter registry xml parent data build name setter XML Sub Element xml parent 'org jenkinsci plugins buildnameupdater Build Name Updater' mapping [ 'name' 'build Name' 'version txt' 'template' 'macro Template' '#${BUILD NUMBER}' 'file' 'from File' False 'macro' 'from Macro' False 'macro-first' 'macro Firs...
def build_name_setter registry xml_parent data build_name_setter XML SubElement xml_parent 'org jenkinsci plugins buildnameupdater BuildNameUpdater' mapping [ 'name' 'buildName' 'version txt' 'template' 'macroTemplate' '#${BUILD_NUMBER}' 'file' 'fromFile' False 'macro' 'fromMacro' False 'macro-first' 'macroFirst' False...
59
python-test-6084
python
What does build name setter options allow ?
your build name to be updated during the build process
def build name setter registry xml parent data build name setter XML Sub Element xml parent 'org jenkinsci plugins buildnameupdater Build Name Updater' mapping [ 'name' 'build Name' 'version txt' 'template' 'macro Template' '#${BUILD NUMBER}' 'file' 'from File' False 'macro' 'from Macro' False 'macro-first' 'macro Firs...
def build_name_setter registry xml_parent data build_name_setter XML SubElement xml_parent 'org jenkinsci plugins buildnameupdater BuildNameUpdater' mapping [ 'name' 'buildName' 'version txt' 'template' 'macroTemplate' '#${BUILD_NUMBER}' 'file' 'fromFile' False 'macro' 'fromMacro' False 'macro-first' 'macroFirst' False...
59
python-test-6085
python
Where did the experiments describe ?
in the book
def run experiments shallow basic conv omit FC dbl conv activation fn sigmoid dbl conv relu expanded data n 100 expanded data n 300 expanded data n 1000 expanded data double fc n 100 expanded data double fc n 300 expanded data double fc n 1000 nets double fc dropout 0 5 0 5 0 5 5 error locations erroneous predictions e...
def run_experiments shallow basic_conv omit_FC dbl_conv activation_fn sigmoid dbl_conv_relu expanded_data n 100 expanded_data n 300 expanded_data n 1000 expanded_data_double_fc n 100 expanded_data_double_fc n 300 expanded_data_double_fc n 1000 nets double_fc_dropout 0 5 0 5 0 5 5 error_locations erroneous_predictions e...
107
python-test-6086
python
What does the code run ?
the experiments described in the book
def run experiments shallow basic conv omit FC dbl conv activation fn sigmoid dbl conv relu expanded data n 100 expanded data n 300 expanded data n 1000 expanded data double fc n 100 expanded data double fc n 300 expanded data double fc n 1000 nets double fc dropout 0 5 0 5 0 5 5 error locations erroneous predictions e...
def run_experiments shallow basic_conv omit_FC dbl_conv activation_fn sigmoid dbl_conv_relu expanded_data n 100 expanded_data n 300 expanded_data n 1000 expanded_data_double_fc n 100 expanded_data_double_fc n 300 expanded_data_double_fc n 1000 nets double_fc_dropout 0 5 0 5 0 5 5 error_locations erroneous_predictions e...
107
python-test-6087
python
What described in the book ?
the experiments
def run experiments shallow basic conv omit FC dbl conv activation fn sigmoid dbl conv relu expanded data n 100 expanded data n 300 expanded data n 1000 expanded data double fc n 100 expanded data double fc n 300 expanded data double fc n 1000 nets double fc dropout 0 5 0 5 0 5 5 error locations erroneous predictions e...
def run_experiments shallow basic_conv omit_FC dbl_conv activation_fn sigmoid dbl_conv_relu expanded_data n 100 expanded_data n 300 expanded_data n 1000 expanded_data_double_fc n 100 expanded_data_double_fc n 300 expanded_data_double_fc n 1000 nets double_fc_dropout 0 5 0 5 0 5 5 error_locations erroneous_predictions e...
107
python-test-6090
python
What does the code get on a given switch returns ?
all active interfaces
def get interfaces dict module command 'showinterfacestatus'try body execute show command command module [0 ]except Index Error body {}interfaces {'ethernet' [] 'svi' [] 'loopback' [] 'management' [] 'portchannel' [] 'nve' [] 'unknown' []}interface list body get 'TABLE interface' ['ROW interface']for index in interface...
def get_interfaces_dict module command 'showinterfacestatus'try body execute_show_command command module [0]except IndexError body {}interfaces {'ethernet' [] 'svi' [] 'loopback' [] 'management' [] 'portchannel' [] 'nve' [] 'unknown' []}interface_list body get 'TABLE_interface' ['ROW_interface']for index in interface_l...
57
python-test-6091
python
Where does the code get all active interfaces ?
on a given switch returns
def get interfaces dict module command 'showinterfacestatus'try body execute show command command module [0 ]except Index Error body {}interfaces {'ethernet' [] 'svi' [] 'loopback' [] 'management' [] 'portchannel' [] 'nve' [] 'unknown' []}interface list body get 'TABLE interface' ['ROW interface']for index in interface...
def get_interfaces_dict module command 'showinterfacestatus'try body execute_show_command command module [0]except IndexError body {}interfaces {'ethernet' [] 'svi' [] 'loopback' [] 'management' [] 'portchannel' [] 'nve' [] 'unknown' []}interface_list body get 'TABLE_interface' ['ROW_interface']for index in interface_l...
57
python-test-6092
python
Where does information on the vimeo video return ?
at <
@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