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-2940 | python | What is this method not supposed helper method ? | to be used directly | def salt cloud force ascii exc if not isinstance exc Unicode Encode Error Unicode Translate Error raise Type Error " Can'thandle{ 0 }" format exc unicode trans {u'\xa 0 ' u'' u'\u 2013 ' u'-'}if exc object[exc start exc end] in unicode trans return unicode trans[exc object[exc start exc end]] exc end raise exc | def _salt_cloud_force_ascii exc if not isinstance exc UnicodeEncodeError UnicodeTranslateError raise TypeError "Can'thandle{0}" format exc unicode_trans {u'\xa0' u'' u'\u2013' u'-'}if exc object[exc start exc end] in unicode_trans return unicode_trans[exc object[exc start exc end]] exc end raise exc | 54 |
python-test-2942 | python | What does the code parse ? | the iso 8601 standard that provides for timestamps like | def parse iso timestamp entry if not isinstance entry str str type raise Value Error 'parse iso timestamp inputmustbeastr gota%s' % type entry if ' ' in entry timestamp str microseconds entry split ' ' else timestamp str microseconds entry '000000 ' if len microseconds 6 or not microseconds isdigit raise Value Error "t... | def _parse_iso_timestamp entry if not isinstance entry str str_type raise ValueError 'parse_iso_timestamp inputmustbeastr gota%s' % type entry if ' ' in entry timestamp_str microseconds entry split ' ' else timestamp_str microseconds entry '000000' if len microseconds 6 or not microseconds isdigit raise ValueError "tim... | 91 |
python-test-2944 | python | What does the code ensure ? | we handle unicode strings correctly | def test ast unicode strings def compile string s hy s Hy String s hy s start line hy s end line 0hy s start column hy s end column 0code hy compile [hy s] u' main ' return code body[ 0 ] value sassert compile string u'test' u'test' assert compile string u'\u 03 b 1 \u 03 b 2 ' u'\u 03 b 1 \u 03 b 2 ' assert compile st... | def test_ast_unicode_strings def _compile_string s hy_s HyString s hy_s start_line hy_s end_line 0hy_s start_column hy_s end_column 0code hy_compile [hy_s] u'__main__' return code body[0] value sassert _compile_string u'test' u'test' assert _compile_string u'\u03b1\u03b2' u'\u03b1\u03b2' assert _compile_string u'\xc3\x... | 83 |
python-test-2945 | python | Applies the linear operator which organization ? | |a | def op abs tmul lin op value if lin op type is lo NEG result valueelif lin op type is lo MUL coeff mul lin op data {} True if np isscalar coeff result coeff * value else result coeff T * value elif lin op type is lo DIV divisor mul lin op data {} True result value / divisor elif lin op type is lo CONV result conv mul l... | def op_abs_tmul lin_op value if lin_op type is lo NEG result valueelif lin_op type is lo MUL coeff mul lin_op data {} True if np isscalar coeff result coeff * value else result coeff T * value elif lin_op type is lo DIV divisor mul lin_op data {} True result value / divisor elif lin_op type is lo CONV result conv_mul l... | 85 |
python-test-2946 | python | What does the code make ? | edge table where each sample is connected to the otus found in it | def make edge table bt data asarray [d for d in bt iter data axis 'observation' dense True ] oids asarray bt ids axis 'observation' header '# Sample DCTB OTU DCTB Abundance'lines [header]for sample in bt ids sample ind bt index sample 'sample' otu ids oids[data[ sample ind] nonzero [0 ]]otu abs data[ sample ind][data[ ... | def make_edge_table bt data asarray [d for d in bt iter_data axis 'observation' dense True ] oids asarray bt ids axis 'observation' header '#Sample DCTB OTU DCTB Abundance'lines [header]for sample in bt ids sample_ind bt index sample 'sample' otu_ids oids[data[ sample_ind] nonzero [0]]otu_abs data[ sample_ind][data[ sa... | 84 |
python-test-2947 | python | What found in it ? | the otus | def make edge table bt data asarray [d for d in bt iter data axis 'observation' dense True ] oids asarray bt ids axis 'observation' header '# Sample DCTB OTU DCTB Abundance'lines [header]for sample in bt ids sample ind bt index sample 'sample' otu ids oids[data[ sample ind] nonzero [0 ]]otu abs data[ sample ind][data[ ... | def make_edge_table bt data asarray [d for d in bt iter_data axis 'observation' dense True ] oids asarray bt ids axis 'observation' header '#Sample DCTB OTU DCTB Abundance'lines [header]for sample in bt ids sample_ind bt index sample 'sample' otu_ids oids[data[ sample_ind] nonzero [0]]otu_abs data[ sample_ind][data[ sa... | 84 |
python-test-2948 | python | What is connected to the otus found in it where ? | each sample | def make edge table bt data asarray [d for d in bt iter data axis 'observation' dense True ] oids asarray bt ids axis 'observation' header '# Sample DCTB OTU DCTB Abundance'lines [header]for sample in bt ids sample ind bt index sample 'sample' otu ids oids[data[ sample ind] nonzero [0 ]]otu abs data[ sample ind][data[ ... | def make_edge_table bt data asarray [d for d in bt iter_data axis 'observation' dense True ] oids asarray bt ids axis 'observation' header '#Sample DCTB OTU DCTB Abundance'lines [header]for sample in bt ids sample_ind bt index sample 'sample' otu_ids oids[data[ sample_ind] nonzero [0]]otu_abs data[ sample_ind][data[ sa... | 84 |
python-test-2954 | python | What does the code get from different sources ? | a valid template | def get template from request request obj None no current page False template Noneif len get cms setting 'TEMPLATES' 1 return get cms setting 'TEMPLATES' [0 ][ 0 ]if hasattr request 'POST' and 'template' in request POST template request POST['template']elif hasattr request 'GET' and 'template' in request GET template r... | def get_template_from_request request obj None no_current_page False template Noneif len get_cms_setting 'TEMPLATES' 1 return get_cms_setting 'TEMPLATES' [0][0]if hasattr request 'POST' and 'template' in request POST template request POST['template']elif hasattr request 'GET' and 'template' in request GET template requ... | 126 |
python-test-2956 | python | How did discretization function base ? | quantile | def qcut x q labels None retbins False precision 3 duplicates 'raise' x is series series index name x preprocess for cut x x dtype coerce to type x if is integer q quantiles np linspace 0 1 q + 1 else quantiles qbins algos quantile x quantiles fac bins bins to cuts x bins labels labels precision precision include lowes... | def qcut x q labels None retbins False precision 3 duplicates 'raise' x_is_series series_index name x _preprocess_for_cut x x dtype _coerce_to_type x if is_integer q quantiles np linspace 0 1 q + 1 else quantiles qbins algos quantile x quantiles fac bins _bins_to_cuts x bins labels labels precision precision include_lo... | 79 |
python-test-2957 | python | How do the container reboot ? | by sending a sigint to its init process | @ ensure existsdef reboot name kill False if sd version > 219 if state name 'running' ret machinectl 'reboot{ 0 }' format name else return start name else cmd 'systemctlstopsystemd-nspawn@{ 0 }' format name ret salt ['cmd run all'] cmd python shell False if ret['retcode'] 0 context ['retcode'] salt defaults exitcodes E... | @_ensure_existsdef reboot name kill False if _sd_version > 219 if state name 'running' ret _machinectl 'reboot{0}' format name else return start name else cmd 'systemctlstopsystemd-nspawn@{0}' format name ret __salt__['cmd run_all'] cmd python_shell False if ret['retcode'] 0 __context__['retcode'] salt defaults exitcod... | 82 |
python-test-2958 | python | What does helper method instantiate ? | the stimclient | def connect client trig queue t0 time time while time time - t0 < max wait and server is None or not server running time sleep 0 01 assert true server is not None and server running stim client Stim Client 'localhost' port 4218 t0 time time while time time - t0 < max wait and not have put in trigger time sleep 0 01 ass... | def _connect_client trig_queue t0 time time while time time - t0 < _max_wait and _server is None or not _server _running time sleep 0 01 assert_true _server is not None and _server _running stim_client StimClient 'localhost' port 4218 t0 time time while time time - t0 < _max_wait and not _have_put_in_trigger time sleep... | 81 |
python-test-2959 | python | What does the code get ? | monitor data of the instance | def list monitor data kwargs None call None if call 'function' raise Salt Cloud System Exit ' Thelist monitor datamustbecalledwith-for--function ' if not isinstance kwargs dict kwargs {}ret {}params {' Action' ' Get Monitor Data' ' Region Id' get location }if 'name' in kwargs params[' Instance Id'] kwargs['name']items ... | def list_monitor_data kwargs None call None if call 'function' raise SaltCloudSystemExit 'Thelist_monitor_datamustbecalledwith-for--function ' if not isinstance kwargs dict kwargs {}ret {}params {'Action' 'GetMonitorData' 'RegionId' get_location }if 'name' in kwargs params['InstanceId'] kwargs['name']items query params... | 77 |
python-test-2961 | python | Where is utility function ran once ? | on library import | def init once path os getenv 'LIBCLOUD DEBUG' if path mode 'a'from libcloud utils py 3 import PY 3 if path in ['/dev/stderr' '/dev/stdout'] and PY 3 mode 'w'fo codecs open path mode encoding 'utf 8 ' enable debug fo if have paramiko paramiko common logging basic Config level paramiko common DEBUG | def _init_once path os getenv 'LIBCLOUD_DEBUG' if path mode 'a'from libcloud utils py3 import PY3if path in ['/dev/stderr' '/dev/stdout'] and PY3 mode 'w'fo codecs open path mode encoding 'utf8' enable_debug fo if have_paramiko paramiko common logging basicConfig level paramiko common DEBUG | 52 |
python-test-2962 | python | What does the code build ? | a test suite of the above tests and extension doctests | def suite suite unittest Test Suite suite add Test unittest make Suite Test Markdown suite add Test unittest make Suite Test Block Parser suite add Test unittest make Suite Test Block Parser State suite add Test unittest make Suite Test Html Stash suite add Test unittest make Suite Test Ordered Dict for filename in os ... | def suite suite unittest TestSuite suite addTest unittest makeSuite TestMarkdown suite addTest unittest makeSuite TestBlockParser suite addTest unittest makeSuite TestBlockParserState suite addTest unittest makeSuite TestHtmlStash suite addTest unittest makeSuite TestOrderedDict for filename in os listdir 'markdown/ext... | 82 |
python-test-2964 | python | By how much did http response headers encode ? | usascii | def test http header encoding mocked socket mock Magic Mock mocked socket sendall mock Magic Mock mocked request mock Magic Mock response Response mocked request mocked socket None response headers append 'foo' u'h\xe 4 der' with pytest raises Unicode Encode Error response send headers tosend response default headers t... | def test_http_header_encoding mocked_socket mock MagicMock mocked_socket sendall mock MagicMock mocked_request mock MagicMock response Response mocked_request mocked_socket None response headers append 'foo' u'h\xe4der' with pytest raises UnicodeEncodeError response send_headers tosend response default_headers tosend e... | 84 |
python-test-2968 | python | For what purpose are csp policies specified ? | for script / style | def unsafe inline enabled response non report only policies retrieve csp policies response report only policies retrieve csp policies response True policies all merge policies dict non report only policies report only policies if len policies all > 0 for directive name in policies all if directive name lower CSP DIRECT... | def unsafe_inline_enabled response non_report_only_policies retrieve_csp_policies response report_only_policies retrieve_csp_policies response True policies_all merge_policies_dict non_report_only_policies report_only_policies if len policies_all > 0 for directive_name in policies_all if directive_name lower CSP_DIRECT... | 79 |
python-test-2969 | python | What will aggregate ora2 responses for a course into a ? | a celery task | @transaction non atomic requests@require POST@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' def export ora 2 data request course id course key Slash Separated Course Key from deprecated string course id try lms djangoapps instructor task api submit export ora 2... | @transaction non_atomic_requests@require_POST@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' def export_ora2_data request course_id course_key SlashSeparatedCourseKey from_deprecated_string course_id try lms djangoapps instructor_task api submit_export_ora2_data... | 90 |
python-test-2970 | python | What will a celery task aggregate ? | ora2 responses for a course into a | @transaction non atomic requests@require POST@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' def export ora 2 data request course id course key Slash Separated Course Key from deprecated string course id try lms djangoapps instructor task api submit export ora 2... | @transaction non_atomic_requests@require_POST@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' def export_ora2_data request course_id course_key SlashSeparatedCourseKey from_deprecated_string course_id try lms djangoapps instructor_task api submit_export_ora2_data... | 90 |
python-test-2972 | python | What does the code update by inserting all not found records by inserting all not found records ? | the data | @transaction atomicdef mass get or create model class base queryset id field default dict global defaults current instances list base queryset current ids set [unicode getattr c id field for c in current instances] given ids map unicode default dict keys new ids [g for g in given ids if g not in current ids ]prepared m... | @transaction atomicdef mass_get_or_create model_class base_queryset id_field default_dict global_defaults current_instances list base_queryset current_ids set [unicode getattr c id_field for c in current_instances] given_ids map unicode default_dict keys new_ids [g for g in given_ids if g not in current_ids ]prepared_m... | 114 |
python-test-2973 | python | Does the code delete records if not in the new data example usage ? | No | @transaction atomicdef mass get or create model class base queryset id field default dict global defaults current instances list base queryset current ids set [unicode getattr c id field for c in current instances] given ids map unicode default dict keys new ids [g for g in given ids if g not in current ids ]prepared m... | @transaction atomicdef mass_get_or_create model_class base_queryset id_field default_dict global_defaults current_instances list base_queryset current_ids set [unicode getattr c id_field for c in current_instances] given_ids map unicode default_dict keys new_ids [g for g in given_ids if g not in current_ids ]prepared_m... | 114 |
python-test-2974 | python | What does the code nt delete if not in the new data example usage ? | records | @transaction atomicdef mass get or create model class base queryset id field default dict global defaults current instances list base queryset current ids set [unicode getattr c id field for c in current instances] given ids map unicode default dict keys new ids [g for g in given ids if g not in current ids ]prepared m... | @transaction atomicdef mass_get_or_create model_class base_queryset id_field default_dict global_defaults current_instances list base_queryset current_ids set [unicode getattr c id_field for c in current_instances] given_ids map unicode default_dict keys new_ids [g for g in given_ids if g not in current_ids ]prepared_m... | 114 |
python-test-2975 | python | How does the code update the data ? | by inserting all not found records | @transaction atomicdef mass get or create model class base queryset id field default dict global defaults current instances list base queryset current ids set [unicode getattr c id field for c in current instances] given ids map unicode default dict keys new ids [g for g in given ids if g not in current ids ]prepared m... | @transaction atomicdef mass_get_or_create model_class base_queryset id_field default_dict global_defaults current_instances list base_queryset current_ids set [unicode getattr c id_field for c in current_instances] given_ids map unicode default_dict keys new_ids [g for g in given_ids if g not in current_ids ]prepared_m... | 114 |
python-test-2978 | python | What live the path ? | configuration and certificates | def context factory and credential path host port ca Certificate load PEM path child 'cluster crt' get Content node credential Node Credential from path path 'node' policy Control Service Policy ca certificate ca client credential node credential credential return TLS Context context factory policy creator For Netloc h... | def _context_factory_and_credential path host port ca Certificate loadPEM path child 'cluster crt' getContent node_credential NodeCredential from_path path 'node' policy ControlServicePolicy ca_certificate ca client_credential node_credential credential return _TLSContext context_factory policy creatorForNetloc host po... | 53 |
python-test-2979 | python | In which direction do a tls context factory load a tls context factory ? | from the path where configuration and certificates live | def context factory and credential path host port ca Certificate load PEM path child 'cluster crt' get Content node credential Node Credential from path path 'node' policy Control Service Policy ca certificate ca client credential node credential credential return TLS Context context factory policy creator For Netloc h... | def _context_factory_and_credential path host port ca Certificate loadPEM path child 'cluster crt' getContent node_credential NodeCredential from_path path 'node' policy ControlServicePolicy ca_certificate ca client_credential node_credential credential return _TLSContext context_factory policy creatorForNetloc host po... | 53 |
python-test-2980 | python | What has a user satisfied ? | which credit requirements | def credit course requirements course key student if not settings FEATURES get 'ENABLE CREDIT ELIGIBILITY' False and is credit course course key return Noneenrollment Course Enrollment get enrollment student course key if enrollment and enrollment mode not in REQUIREMENTS DISPLAY MODES return Nonenon eligible statuses ... | def _credit_course_requirements course_key student if not settings FEATURES get 'ENABLE_CREDIT_ELIGIBILITY' False and is_credit_course course_key return Noneenrollment CourseEnrollment get_enrollment student course_key if enrollment and enrollment mode not in REQUIREMENTS_DISPLAY_MODES return Nonenon_eligible_statuses ... | 95 |
python-test-2983 | python | What does the code compute ? | the analytic signal | def hilbert x N None axis -1 x asarray x if iscomplexobj x raise Value Error 'xmustbereal ' if N is None N x shape[axis]if N < 0 raise Value Error ' Nmustbepositive ' Xf fftpack fft x N axis axis h zeros N if N % 2 0 h[ 0 ] h[ N // 2 ] 1h[ 1 N // 2 ] 2else h[ 0 ] 1h[ 1 N + 1 // 2 ] 2if x ndim > 1 ind [newaxis] * x ndim... | def hilbert x N None axis -1 x asarray x if iscomplexobj x raise ValueError 'xmustbereal ' if N is None N x shape[axis]if N < 0 raise ValueError 'Nmustbepositive ' Xf fftpack fft x N axis axis h zeros N if N % 2 0 h[0] h[ N // 2 ] 1h[1 N // 2 ] 2else h[0] 1h[1 N + 1 // 2 ] 2if x ndim > 1 ind [newaxis] * x ndim ind[axis... | 99 |
python-test-2985 | python | What does the code run ? | the default discovery | def run discovery entry points iter cached False reg cache {}if cached reg cache cache registry cache discovery Qt Widget Discovery cached descriptions reg cache registry Qt Widget Registry discovery found category connect registry register category discovery found widget connect registry register widget discovery run ... | def run_discovery entry_points_iter cached False reg_cache {}if cached reg_cache cache registry_cache discovery QtWidgetDiscovery cached_descriptions reg_cache registry QtWidgetRegistry discovery found_category connect registry register_category discovery found_widget connect registry register_widget discovery run if c... | 55 |
python-test-2990 | python | In which direction does the code build a lookup to bounding boxes ? | from image file | def build bounding box lookup bounding box file lines tf gfile Fast G File bounding box file 'r' readlines images to bboxes {}num bbox 0num image 0for l in lines if l parts l split ' ' assert len parts 5 ' Failedtoparse %s' % l filename parts[ 0 ]xmin float parts[ 1 ] ymin float parts[ 2 ] xmax float parts[ 3 ] ymax fl... | def _build_bounding_box_lookup bounding_box_file lines tf gfile FastGFile bounding_box_file 'r' readlines images_to_bboxes {}num_bbox 0num_image 0for l in lines if l parts l split ' ' assert len parts 5 'Failedtoparse %s' % l filename parts[0]xmin float parts[1] ymin float parts[2] xmax float parts[3] ymax float parts[... | 107 |
python-test-2991 | python | What does the code build to bounding boxes from image file ? | a lookup | def build bounding box lookup bounding box file lines tf gfile Fast G File bounding box file 'r' readlines images to bboxes {}num bbox 0num image 0for l in lines if l parts l split ' ' assert len parts 5 ' Failedtoparse %s' % l filename parts[ 0 ]xmin float parts[ 1 ] ymin float parts[ 2 ] xmax float parts[ 3 ] ymax fl... | def _build_bounding_box_lookup bounding_box_file lines tf gfile FastGFile bounding_box_file 'r' readlines images_to_bboxes {}num_bbox 0num_image 0for l in lines if l parts l split ' ' assert len parts 5 'Failedtoparse %s' % l filename parts[0]xmin float parts[1] ymin float parts[2] xmax float parts[3] ymax float parts[... | 107 |
python-test-2993 | python | How does the code bring the string to the given length ? | by either removing characters or adding spaces | def adjust string original length if not length > 0 raise Assertion Errorresulting string originalif len resulting string > length unit db resulting string endswith 'd B' and resulting string find ' ' -1 if len resulting string strip > length and unit db resulting string resulting string[ -2 ]if len resulting string > ... | def adjust_string original length if not length > 0 raise AssertionErrorresulting_string originalif len resulting_string > length unit_db resulting_string endswith 'dB' and resulting_string find ' ' -1 if len resulting_string strip > length and unit_db resulting_string resulting_string[ -2 ]if len resulting_string > le... | 127 |
python-test-2996 | python | What does the code setup ? | the swiss hydrological sensor | def setup platform hass config add devices discovery info None import xmltodictname config get CONF NAME station config get CONF STATION try response requests get RESOURCE timeout 5 if any str station location get '@ Str Nr' for location in xmltodict parse response text ['AKT Data'][' Mes Par'] is False LOGGER error ' ... | def setup_platform hass config add_devices discovery_info None import xmltodictname config get CONF_NAME station config get CONF_STATION try response requests get _RESOURCE timeout 5 if any str station location get '@StrNr' for location in xmltodict parse response text ['AKT_Data']['MesPar'] is False _LOGGER error 'The... | 83 |
python-test-2997 | python | What does the code grab from wordnik ? | a random word | @hook command 'wordrandom' 'randomword' autohelp False def random word if not api key return ' Thiscommandrequiresan AP Ikeyfromwordnik com 'url API URL + 'words json/random Word' params {'api key' api key 'has Dictionarydef' 'true' 'vulgar' 'true'}json requests get url params params json if json word json['word']retur... | @hook command 'wordrandom' 'randomword' autohelp False def random_word if not api_key return 'ThiscommandrequiresanAPIkeyfromwordnik com 'url API_URL + 'words json/randomWord' params {'api_key' api_key 'hasDictionarydef' 'true' 'vulgar' 'true'}json requests get url params params json if json word json['word']return 'Yo... | 61 |
python-test-3004 | python | What does the code create ? | user accounts cli example | def create user username password permissions users None uids set if users is None users list users if username in users log warning "'{ 0 }'alreadyexists" format username return Falsefor idx in six iterkeys users uids add users[idx]['index'] uid sorted list set range 2 12 - uids reverse True pop if not execute cmd 'co... | def create_user username password permissions users None _uids set if users is None users list_users if username in users log warning "'{0}'alreadyexists" format username return Falsefor idx in six iterkeys users _uids add users[idx]['index'] uid sorted list set range 2 12 - _uids reverse True pop if not __execute_cmd ... | 126 |
python-test-3005 | python | What does the code make ? | it suitable for use in urls | def title to url title max length 50 title force unicode title title rx whitespace sub ' ' title title rx notsafe sub '' title title rx underscore sub ' ' title title title strip ' ' title title lower if len title > max length title title[ max length]last word title rfind ' ' if last word > 0 title title[ last word]ret... | def title_to_url title max_length 50 title _force_unicode title title rx_whitespace sub '_' title title rx_notsafe sub '' title title rx_underscore sub '_' title title title strip '_' title title lower if len title > max_length title title[ max_length]last_word title rfind '_' if last_word > 0 title title[ last_word]re... | 68 |
python-test-3006 | python | What used in a particular country ? | timezones | def country timezones iso 3166 code iso 3166 code iso 3166 code upper if not country timezones cache zone tab open resource 'zone tab' for line in zone tab if line startswith '#' continue code coordinates zone line split None 4 [ 3]try country timezones cache[code] append zone except Key Error country timezones cache[c... | def country_timezones iso3166_code iso3166_code iso3166_code upper if not _country_timezones_cache zone_tab open_resource 'zone tab' for line in zone_tab if line startswith '#' continue code coordinates zone line split None 4 [ 3]try _country_timezones_cache[code] append zone except KeyError _country_timezones_cache[co... | 60 |
python-test-3007 | python | Where did timezones use ? | in a particular country | def country timezones iso 3166 code iso 3166 code iso 3166 code upper if not country timezones cache zone tab open resource 'zone tab' for line in zone tab if line startswith '#' continue code coordinates zone line split None 4 [ 3]try country timezones cache[code] append zone except Key Error country timezones cache[c... | def country_timezones iso3166_code iso3166_code iso3166_code upper if not _country_timezones_cache zone_tab open_resource 'zone tab' for line in zone_tab if line startswith '#' continue code coordinates zone line split None 4 [ 3]try _country_timezones_cache[code] append zone except KeyError _country_timezones_cache[co... | 60 |
python-test-3008 | python | Where be the disk saved ? | in the given image | def vm disk save name kwargs None call None if call 'action' raise Salt Cloud System Exit ' Thevm disk saveactionmustbecalledwith-aor--action ' if kwargs is None kwargs {}disk id kwargs get 'disk id' None image name kwargs get 'image name' None image type kwargs get 'image type' '' snapshot id int kwargs get 'snapshot ... | def vm_disk_save name kwargs None call None if call 'action' raise SaltCloudSystemExit 'Thevm_disk_saveactionmustbecalledwith-aor--action ' if kwargs is None kwargs {}disk_id kwargs get 'disk_id' None image_name kwargs get 'image_name' None image_type kwargs get 'image_type' '' snapshot_id int kwargs get 'snapshot_id' ... | 137 |
python-test-3009 | python | What be saved in the given image ? | the disk | def vm disk save name kwargs None call None if call 'action' raise Salt Cloud System Exit ' Thevm disk saveactionmustbecalledwith-aor--action ' if kwargs is None kwargs {}disk id kwargs get 'disk id' None image name kwargs get 'image name' None image type kwargs get 'image type' '' snapshot id int kwargs get 'snapshot ... | def vm_disk_save name kwargs None call None if call 'action' raise SaltCloudSystemExit 'Thevm_disk_saveactionmustbecalledwith-aor--action ' if kwargs is None kwargs {}disk_id kwargs get 'disk_id' None image_name kwargs get 'image_name' None image_type kwargs get 'image_type' '' snapshot_id int kwargs get 'snapshot_id' ... | 137 |
python-test-3010 | python | For what purpose does the disk set ? | to be saved in the given image | def vm disk save name kwargs None call None if call 'action' raise Salt Cloud System Exit ' Thevm disk saveactionmustbecalledwith-aor--action ' if kwargs is None kwargs {}disk id kwargs get 'disk id' None image name kwargs get 'image name' None image type kwargs get 'image type' '' snapshot id int kwargs get 'snapshot ... | def vm_disk_save name kwargs None call None if call 'action' raise SaltCloudSystemExit 'Thevm_disk_saveactionmustbecalledwith-aor--action ' if kwargs is None kwargs {}disk_id kwargs get 'disk_id' None image_name kwargs get 'image_name' None image_type kwargs get 'image_type' '' snapshot_id int kwargs get 'snapshot_id' ... | 137 |
python-test-3011 | python | What does this find ? | the best possible application in the module | def find best app module from import Flaskfor attr name in 'app' 'application' app getattr module attr name None if app is not None and isinstance app Flask return appmatches [v for k v in iteritems module dict if isinstance v Flask ]if len matches 1 return matches[ 0 ]raise No App Exception ' Failedtofindapplicationin... | def find_best_app module from import Flaskfor attr_name in 'app' 'application' app getattr module attr_name None if app is not None and isinstance app Flask return appmatches [v for k v in iteritems module __dict__ if isinstance v Flask ]if len matches 1 return matches[0]raise NoAppException 'Failedtofindapplicationinm... | 64 |
python-test-3012 | python | What does this try ? | to find the best possible application in the module | def find best app module from import Flaskfor attr name in 'app' 'application' app getattr module attr name None if app is not None and isinstance app Flask return appmatches [v for k v in iteritems module dict if isinstance v Flask ]if len matches 1 return matches[ 0 ]raise No App Exception ' Failedtofindapplicationin... | def find_best_app module from import Flaskfor attr_name in 'app' 'application' app getattr module attr_name None if app is not None and isinstance app Flask return appmatches [v for k v in iteritems module __dict__ if isinstance v Flask ]if len matches 1 return matches[0]raise NoAppException 'Failedtofindapplicationinm... | 64 |
python-test-3013 | python | Where does a guest agent locate ? | at the path specified by agent_rel_path | def find guest agent base dir if CONF xenserver disable agent return Falseagent rel path CONF xenserver agent pathagent path os path join base dir agent rel path if os path isfile agent path LOG info LI ' Xen Servertoolsinstalledinthisimagearecapableofnetworkinjection Networkingfileswillnotbemanipulated' return Truexe ... | def find_guest_agent base_dir if CONF xenserver disable_agent return Falseagent_rel_path CONF xenserver agent_pathagent_path os path join base_dir agent_rel_path if os path isfile agent_path LOG info _LI 'XenServertoolsinstalledinthisimagearecapableofnetworkinjection Networkingfileswillnotbemanipulated' return Truexe_d... | 75 |
python-test-3014 | python | When does the reader ignore whitespace ? | at the beginning of fields | @pytest mark parametrize 'parallel' [ True False] def test lstrip whitespace parallel read basic text '\n 1 2 DCTB 3\n A DCTB DCTB B C\na b c\n' + '\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_lstrip_whitespace parallel read_basic text '\n1 2 DCTB 3\nA DCTB DCTB B C\na b c\n' + '\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-3017 | python | What does the code make ? | the app with the appropriate model | def make app app name test path name os chdir '%s/applications/%s' % os environ['WEB 2 PY PATH'] app name sys path append '%s/applications/%s' % os environ['WEB 2 PY PATH'] app name os mkdir 'private' os mkdir 'databases' os mkdir 'models' os mkdir 'controllers' os mkdir 'cron' os mkdir 'languages' os mkdir 'cache' os ... | def make_app app_name test_path_name os chdir '%s/applications/%s' % os environ['WEB2PY_PATH'] app_name sys path append '%s/applications/%s' % os environ['WEB2PY_PATH'] app_name os mkdir 'private' os mkdir 'databases' os mkdir 'models' os mkdir 'controllers' os mkdir 'cron' os mkdir 'languages' os mkdir 'cache' os mkdi... | 100 |
python-test-3019 | python | What does tween factory produce ? | a tween that catches an exception raised by downstream tweens and | def excview tween factory handler registry def excview tween request attrs request dict try response handler request except Exception as exc attrs['exc info'] sys exc info attrs['exception'] excif 'response' in attrs del attrs['response']request iface attrs get 'request iface' I Request provides provided By exc try res... | def excview_tween_factory handler registry def excview_tween request attrs request __dict__try response handler request except Exception as exc attrs['exc_info'] sys exc_info attrs['exception'] excif 'response' in attrs del attrs['response']request_iface attrs get 'request_iface' IRequest provides providedBy exc try re... | 79 |
python-test-3020 | python | What catches an exception raised by downstream tweens and ? | a tween | def excview tween factory handler registry def excview tween request attrs request dict try response handler request except Exception as exc attrs['exc info'] sys exc info attrs['exception'] excif 'response' in attrs del attrs['response']request iface attrs get 'request iface' I Request provides provided By exc try res... | def excview_tween_factory handler registry def excview_tween request attrs request __dict__try response handler request except Exception as exc attrs['exc_info'] sys exc_info attrs['exception'] excif 'response' in attrs del attrs['response']request_iface attrs get 'request_iface' IRequest provides providedBy exc try re... | 79 |
python-test-3021 | python | What produces a tween that catches an exception raised by downstream tweens and ? | tween factory | def excview tween factory handler registry def excview tween request attrs request dict try response handler request except Exception as exc attrs['exc info'] sys exc info attrs['exception'] excif 'response' in attrs del attrs['response']request iface attrs get 'request iface' I Request provides provided By exc try res... | def excview_tween_factory handler registry def excview_tween request attrs request __dict__try response handler request except Exception as exc attrs['exc_info'] sys exc_info attrs['exception'] excif 'response' in attrs del attrs['response']request_iface attrs get 'request_iface' IRequest provides providedBy exc try re... | 79 |
python-test-3022 | python | What does a tween catch ? | an exception raised by downstream tweens and | def excview tween factory handler registry def excview tween request attrs request dict try response handler request except Exception as exc attrs['exc info'] sys exc info attrs['exception'] excif 'response' in attrs del attrs['response']request iface attrs get 'request iface' I Request provides provided By exc try res... | def excview_tween_factory handler registry def excview_tween request attrs request __dict__try response handler request except Exception as exc attrs['exc_info'] sys exc_info attrs['exception'] excif 'response' in attrs del attrs['response']request_iface attrs get 'request_iface' IRequest provides providedBy exc try re... | 79 |
python-test-3024 | python | What did the code set ? | an explicit indentation level for a block scalar | def set block scalar indent Token Class def callback lexer match context text match group context block scalar indent Noneif not text returnincrement match group 1 if increment current indent max context indent 0 increment int increment context block scalar indent current indent + increment if text yield match start To... | def set_block_scalar_indent TokenClass def callback lexer match context text match group context block_scalar_indent Noneif not text returnincrement match group 1 if increment current_indent max context indent 0 increment int increment context block_scalar_indent current_indent + increment if text yield match start Tok... | 59 |
python-test-3025 | python | What does a folder upload ? | to cloud files | def upload folder cf folder container ttl None headers None total bytes 0for root dirs files in os walk folder for fname in files full path os path join root fname obj name os path relpath full path folder obj size os path getsize full path cf upload file container full path obj name obj name return none True ttl ttl h... | def _upload_folder cf folder container ttl None headers None total_bytes 0for root dirs files in os walk folder for fname in files full_path os path join root fname obj_name os path relpath full_path folder obj_size os path getsize full_path cf upload_file container full_path obj_name obj_name return_none True ttl ttl ... | 70 |
python-test-3026 | python | What does the code check ? | the contents of file2 for substrings found in file1 | def files contains file 1 file 2 attributes None local file open file 1 'U' readlines history data open file 2 'U' read lines diff int attributes get 'lines diff' 0 line diff count 0while local file contains local file pop 0 rstrip '\n\r' if contains not in history data line diff count + 1if line diff count > lines dif... | def files_contains file1 file2 attributes None local_file open file1 'U' readlines history_data open file2 'U' read lines_diff int attributes get 'lines_diff' 0 line_diff_count 0while local_file contains local_file pop 0 rstrip '\n\r' if contains not in history_data line_diff_count + 1if line_diff_count > lines_diff ra... | 74 |
python-test-3027 | python | Where did substrings find ? | in file1 | def files contains file 1 file 2 attributes None local file open file 1 'U' readlines history data open file 2 'U' read lines diff int attributes get 'lines diff' 0 line diff count 0while local file contains local file pop 0 rstrip '\n\r' if contains not in history data line diff count + 1if line diff count > lines dif... | def files_contains file1 file2 attributes None local_file open file1 'U' readlines history_data open file2 'U' read lines_diff int attributes get 'lines_diff' 0 line_diff_count 0while local_file contains local_file pop 0 rstrip '\n\r' if contains not in history_data line_diff_count + 1if line_diff_count > lines_diff ra... | 74 |
python-test-3028 | python | What found in file1 ? | substrings | def files contains file 1 file 2 attributes None local file open file 1 'U' readlines history data open file 2 'U' read lines diff int attributes get 'lines diff' 0 line diff count 0while local file contains local file pop 0 rstrip '\n\r' if contains not in history data line diff count + 1if line diff count > lines dif... | def files_contains file1 file2 attributes None local_file open file1 'U' readlines history_data open file2 'U' read lines_diff int attributes get 'lines_diff' 0 line_diff_count 0while local_file contains local_file pop 0 rstrip '\n\r' if contains not in history_data line_diff_count + 1if line_diff_count > lines_diff ra... | 74 |
python-test-3029 | python | When do an interable of emailmessages send ? | when a new post is created | def new post mails reply users and watches post url add utm reply get absolute url 'kbforums-post' c {'post' reply content 'post html' reply content parsed 'author' reply creator 'host' Site objects get current domain 'thread' reply thread title 'forum' reply thread document title 'post url' post url}return emails with... | def new_post_mails reply users_and_watches post_url add_utm reply get_absolute_url 'kbforums-post' c {'post' reply content 'post_html' reply content_parsed 'author' reply creator 'host' Site objects get_current domain 'thread' reply thread title 'forum' reply thread document title 'post_url' post_url}return emails_with... | 77 |
python-test-3034 | python | What tests on a rlcompetition experiment ? | an agent | def test Agent path agent port DEFAULT PORT agent adapt Agent Object Benchmarking Agent agent experiment RLC Experiment path str port experiment start client Agent Client Agent agent client Agent connect DEFAULT HOST port CLIENT TIMEOUT logging info ' Agentconnected' client Agent run Agent Event Loop client Agent close... | def testAgent path agent port DEFAULT_PORT agent adaptAgentObject BenchmarkingAgent agent experiment RLCExperiment path str port experiment start clientAgent ClientAgent agent clientAgent connect DEFAULT_HOST port CLIENT_TIMEOUT logging info 'Agentconnected' clientAgent runAgentEventLoop clientAgent close logging info ... | 59 |
python-test-3035 | python | Where do an agent test once ? | on a rlcompetition experiment | def test Agent path agent port DEFAULT PORT agent adapt Agent Object Benchmarking Agent agent experiment RLC Experiment path str port experiment start client Agent Client Agent agent client Agent connect DEFAULT HOST port CLIENT TIMEOUT logging info ' Agentconnected' client Agent run Agent Event Loop client Agent close... | def testAgent path agent port DEFAULT_PORT agent adaptAgentObject BenchmarkingAgent agent experiment RLCExperiment path str port experiment start clientAgent ClientAgent agent clientAgent connect DEFAULT_HOST port CLIENT_TIMEOUT logging info 'Agentconnected' clientAgent runAgentEventLoop clientAgent close logging info ... | 59 |
python-test-3037 | python | How does the code compute the matrix exponential ? | using taylor series | @np deprecate new name 'expm' def expm 3 A q 20 A asarray square A n A shape[ 0 ]t A dtype charif t not in ['f' 'F' 'd' 'D'] A A astype 'd' t 'd'e A np identity n dtype t trm np identity n dtype t castfunc cast[t]for k in range 1 q trm[ ] trm dot A / castfunc k eA + trmreturn eA | @np deprecate new_name 'expm' def expm3 A q 20 A _asarray_square A n A shape[0]t A dtype charif t not in ['f' 'F' 'd' 'D'] A A astype 'd' t 'd'eA np identity n dtype t trm np identity n dtype t castfunc cast[t]for k in range 1 q trm[ ] trm dot A / castfunc k eA + trmreturn eA | 67 |
python-test-3038 | python | How did node states support ? | libcloud | def node state id states int {0 'RUNNING' 1 'REBOOTING' 2 'TERMINATED' 3 'PENDING' 4 'UNKNOWN' 5 'STOPPED' 6 'SUSPENDED' 7 'ERROR' 8 'PAUSED'}states str {'running' 'RUNNING' 'rebooting' 'REBOOTING' 'starting' 'STARTING' 'terminated' 'TERMINATED' 'pending' 'PENDING' 'unknown' 'UNKNOWN' 'stopping' 'STOPPING' 'stopped' 'S... | def node_state id_ states_int {0 'RUNNING' 1 'REBOOTING' 2 'TERMINATED' 3 'PENDING' 4 'UNKNOWN' 5 'STOPPED' 6 'SUSPENDED' 7 'ERROR' 8 'PAUSED'}states_str {'running' 'RUNNING' 'rebooting' 'REBOOTING' 'starting' 'STARTING' 'terminated' 'TERMINATED' 'pending' 'PENDING' 'unknown' 'UNKNOWN' 'stopping' 'STOPPING' 'stopped' '... | 61 |
python-test-3041 | python | What does the code fit a sphere to the headshape points ? | to determine head center | @verbosedef fit sphere to headshape info dig kinds 'auto' units 'm' verbose None if not isinstance units string types or units not in 'm' 'mm' raise Value Error 'unitsmustbea"m"or"mm"' radius origin head origin device fit sphere to headshape info dig kinds if units 'mm' radius * 1000 0origin head * 1000 0origin device ... | @verbosedef fit_sphere_to_headshape info dig_kinds 'auto' units 'm' verbose None if not isinstance units string_types or units not in 'm' 'mm' raise ValueError 'unitsmustbea"m"or"mm"' radius origin_head origin_device _fit_sphere_to_headshape info dig_kinds if units 'mm' radius * 1000 0origin_head * 1000 0origin_device ... | 61 |
python-test-3042 | python | What does the code fit to determine head center ? | a sphere to the headshape points | @verbosedef fit sphere to headshape info dig kinds 'auto' units 'm' verbose None if not isinstance units string types or units not in 'm' 'mm' raise Value Error 'unitsmustbea"m"or"mm"' radius origin head origin device fit sphere to headshape info dig kinds if units 'mm' radius * 1000 0origin head * 1000 0origin device ... | @verbosedef fit_sphere_to_headshape info dig_kinds 'auto' units 'm' verbose None if not isinstance units string_types or units not in 'm' 'mm' raise ValueError 'unitsmustbea"m"or"mm"' radius origin_head origin_device _fit_sphere_to_headshape info dig_kinds if units 'mm' radius * 1000 0origin_head * 1000 0origin_device ... | 61 |
python-test-3055 | python | What does the code get ? | a storage instance for a credential | def get credential storage filename client id user agent scope warn on readonly True filename os path realpath os path expanduser filename multistores lock acquire try multistore multistores setdefault filename Multi Store filename warn on readonly finally multistores lock release if type scope is list scope '' join sc... | def get_credential_storage filename client_id user_agent scope warn_on_readonly True filename os path realpath os path expanduser filename _multistores_lock acquire try multistore _multistores setdefault filename _MultiStore filename warn_on_readonly finally _multistores_lock release if type scope is list scope '' join... | 58 |
python-test-3056 | python | What does the code ensure ? | a team is absent | def team absent name profile 'github' **kwargs ret {'name' name 'changes' {} 'result' None 'comment' ''}target salt ['github get team'] name profile profile **kwargs if not target ret['comment'] ' Team{ 0 }doesnotexist' format name ret['result'] Truereturn retelse if opts ['test'] ret['comment'] ' Team{ 0 }willbedelete... | def team_absent name profile 'github' **kwargs ret {'name' name 'changes' {} 'result' None 'comment' ''}target __salt__['github get_team'] name profile profile **kwargs if not target ret['comment'] 'Team{0}doesnotexist' format name ret['result'] Truereturn retelse if __opts__['test'] ret['comment'] 'Team{0}willbedelete... | 97 |
python-test-3059 | python | What do options specify ? | short and longopt alternatives | def find option with arg argv short opts None long opts None for i arg in enumerate argv if arg startswith u'-' if long opts and arg startswith u'--' name sep val arg partition u' ' if name in long opts return val if sep else argv[ i + 1 ] if short opts and arg in short opts return argv[ i + 1 ]raise Key Error u' ' joi... | def _find_option_with_arg argv short_opts None long_opts None for i arg in enumerate argv if arg startswith u'-' if long_opts and arg startswith u'--' name sep val arg partition u' ' if name in long_opts return val if sep else argv[ i + 1 ] if short_opts and arg in short_opts return argv[ i + 1 ]raise KeyError u' ' joi... | 79 |
python-test-3068 | python | How does the code convert a thrift structure to a json compatible dictionary ? | by recursing over the dictionary | def thrift 2 json tft if isinstance tft type None return Noneif isinstance tft float int long complex basestring return tftif isinstance tft dict d {}for key val in tft iteritems d[key] thrift 2 json val return dif isinstance tft list return [thrift 2 json x for x in tft]if isinstance tft set return dict x True for x i... | def thrift2json tft if isinstance tft type None return Noneif isinstance tft float int long complex basestring return tftif isinstance tft dict d {}for key val in tft iteritems d[key] thrift2json val return dif isinstance tft list return [thrift2json x for x in tft]if isinstance tft set return dict x True for x in tft ... | 98 |
python-test-3069 | python | What does the code convert to a json compatible dictionary by recursing over the dictionary ? | a thrift structure | def thrift 2 json tft if isinstance tft type None return Noneif isinstance tft float int long complex basestring return tftif isinstance tft dict d {}for key val in tft iteritems d[key] thrift 2 json val return dif isinstance tft list return [thrift 2 json x for x in tft]if isinstance tft set return dict x True for x i... | def thrift2json tft if isinstance tft type None return Noneif isinstance tft float int long complex basestring return tftif isinstance tft dict d {}for key val in tft iteritems d[key] thrift2json val return dif isinstance tft list return [thrift2json x for x in tft]if isinstance tft set return dict x True for x in tft ... | 98 |
python-test-3072 | python | For what purpose does html generate ? | to include the css listed in /modules / templates/<template>/css | def s3 include debug css request current requestfolder request folderappname request applicationsettings current deployment settingstheme settings get theme location current response s3 theme locationcss cfg '%s/modules/templates/%s%s/css cfg' % folder location theme try f open css cfg 'r' except raise HTTP 500 ' Theme... | def s3_include_debug_css request current requestfolder request folderappname request applicationsettings current deployment_settingstheme settings get_theme location current response s3 theme_locationcss_cfg '%s/modules/templates/%s%s/css cfg' % folder location theme try f open css_cfg 'r' except raise HTTP 500 'Themec... | 80 |
python-test-3073 | python | For what purpose does information track ? | for events occuring within celery tasks | def task track request info task info event type event page None full event dict event **task info with eventtracker get tracker context 'edx course task' contexts course context from url page event {'username' request info get 'username' 'unknown' 'ip' request info get 'ip' 'unknown' 'event source' 'task' 'event type'... | def task_track request_info task_info event_type event page None full_event dict event **task_info with eventtracker get_tracker context 'edx course task' contexts course_context_from_url page event {'username' request_info get 'username' 'unknown' 'ip' request_info get 'ip' 'unknown' 'event_source' 'task' 'event_type'... | 82 |
python-test-3074 | python | Where do events occur ? | within celery tasks | def task track request info task info event type event page None full event dict event **task info with eventtracker get tracker context 'edx course task' contexts course context from url page event {'username' request info get 'username' 'unknown' 'ip' request info get 'ip' 'unknown' 'event source' 'task' 'event type'... | def task_track request_info task_info event_type event page None full_event dict event **task_info with eventtracker get_tracker context 'edx course task' contexts course_context_from_url page event {'username' request_info get 'username' 'unknown' 'ip' request_info get 'ip' 'unknown' 'event_source' 'task' 'event_type'... | 82 |
python-test-3075 | python | What does the code perform ? | an inverse iteration | def tridi inverse iteration d e w x0 None rtol 1e- 08 eig diag d - w if x0 is None x0 np random randn len d x prev np zeros like x0 norm x np linalg norm x0 x0 / norm xwhile np linalg norm np abs x0 - np abs x prev > rtol x prev x0 copy tridisolve eig diag e x0 norm x np linalg norm x0 x0 / norm xreturn x0 | def tridi_inverse_iteration d e w x0 None rtol 1e-08 eig_diag d - w if x0 is None x0 np random randn len d x_prev np zeros_like x0 norm_x np linalg norm x0 x0 / norm_xwhile np linalg norm np abs x0 - np abs x_prev > rtol x_prev x0 copy tridisolve eig_diag e x0 norm_x np linalg norm x0 x0 / norm_xreturn x0 | 76 |
python-test-3077 | python | How did the code set the service command line parameters ? | in registry | def set serv parms service args import winreguargs []for arg in args uargs append unicoder arg try key winreg Create Key winreg HKEY LOCAL MACHINE SERVICE KEY + service winreg Set Value Ex key SERVICE PARM None winreg REG MULTI SZ uargs winreg Close Key key except Windows Error return Falsereturn True | def set_serv_parms service args import _winreguargs []for arg in args uargs append unicoder arg try key _winreg CreateKey _winreg HKEY_LOCAL_MACHINE _SERVICE_KEY + service _winreg SetValueEx key _SERVICE_PARM None _winreg REG_MULTI_SZ uargs _winreg CloseKey key except WindowsError return Falsereturn True | 52 |
python-test-3079 | python | What does the code run ? | the app server | @taskdef server ctx host None port 5000 debug True gitlogs False if os environ get 'WERKZEUG RUN MAIN' 'true' or not debug if os environ get 'WEB REMOTE DEBUG' None import pydevdremote parts os environ get 'WEB REMOTE DEBUG' split ' ' pydevd settrace remote parts[ 0 ] port int remote parts[ 1 ] suspend False stdout To ... | @taskdef server ctx host None port 5000 debug True gitlogs False if os environ get 'WERKZEUG_RUN_MAIN' 'true' or not debug if os environ get 'WEB_REMOTE_DEBUG' None import pydevdremote_parts os environ get 'WEB_REMOTE_DEBUG' split ' ' pydevd settrace remote_parts[0] port int remote_parts[1] suspend False stdoutToServer... | 130 |
python-test-3082 | python | What does the code setup ? | the onkyo platform | def setup platform hass config add devices discovery info None import eiscpfrom eiscp import eISC Phost config get CONF HOST hosts []if CONF HOST in config and host not in KNOWN HOSTS try hosts append Onkyo Device eiscp eISCP host config get CONF SOURCES name config get CONF NAME KNOWN HOSTS append host except OS Error... | def setup_platform hass config add_devices discovery_info None import eiscpfrom eiscp import eISCPhost config get CONF_HOST hosts []if CONF_HOST in config and host not in KNOWN_HOSTS try hosts append OnkyoDevice eiscp eISCP host config get CONF_SOURCES name config get CONF_NAME KNOWN_HOSTS append host except OSError _L... | 92 |
python-test-3083 | python | What did the code set from a file or a template ? | selections | def set file name source template None context None defaults None **kwargs ret {'name' name 'changes' {} 'result' True 'comment' ''}if context is None context {}elif not isinstance context dict ret['result'] Falseret['comment'] ' Contextmustbeformedasadict'return retif defaults is None defaults {}elif not isinstance de... | def set_file name source template None context None defaults None **kwargs ret {'name' name 'changes' {} 'result' True 'comment' ''}if context is None context {}elif not isinstance context dict ret['result'] Falseret['comment'] 'Contextmustbeformedasadict'return retif defaults is None defaults {}elif not isinstance def... | 88 |
python-test-3092 | python | What accesss in a text file ? | a list of urls | @command 'url file\\s \\S+ ' def yt url file file name try with open file name 'r' as fo output '' join [line strip for line in fo if line strip ] except IO Error g message c r + ' Errorwhileopeningthefile checkthevalidityofthepath' + c w g content g content or content generate songlist display zeromsg g message return... | @command 'url_file\\s \\S+ ' def yt_url_file file_name try with open file_name 'r' as fo output '' join [line strip for line in fo if line strip ] except IOError g message c r + 'Errorwhileopeningthefile checkthevalidityofthepath' + c w g content g content or content generate_songlist_display zeromsg g message returnyt... | 61 |
python-test-3093 | python | Where do a list of urls access ? | in a text file | @command 'url file\\s \\S+ ' def yt url file file name try with open file name 'r' as fo output '' join [line strip for line in fo if line strip ] except IO Error g message c r + ' Errorwhileopeningthefile checkthevalidityofthepath' + c w g content g content or content generate songlist display zeromsg g message return... | @command 'url_file\\s \\S+ ' def yt_url_file file_name try with open file_name 'r' as fo output '' join [line strip for line in fo if line strip ] except IOError g message c r + 'Errorwhileopeningthefile checkthevalidityofthepath' + c w g content g content or content generate_songlist_display zeromsg g message returnyt... | 61 |
python-test-3102 | python | How did an image encode ? | in base64 | def build image data cmap 'gray' import matplotlib pyplot as pltfrom matplotlib figure import Figurefrom matplotlib backends backend agg import Figure Canvas Agg as Figure Canvasfigsize data shape[ -1 ]if figsize[ 0 ] 1 figsize tuple figsize[ 1 ] data data[ 0]fig Figure figsize figsize dpi 1 0 frameon False Figure Canv... | def _build_image data cmap 'gray' import matplotlib pyplot as pltfrom matplotlib figure import Figurefrom matplotlib backends backend_agg import FigureCanvasAgg as FigureCanvasfigsize data shape[ -1 ]if figsize[0] 1 figsize tuple figsize[1 ] data data[ 0]fig Figure figsize figsize dpi 1 0 frameon False FigureCanvas fig... | 86 |
python-test-3103 | python | What does the code build ? | an image encoded in base64 | def build image data cmap 'gray' import matplotlib pyplot as pltfrom matplotlib figure import Figurefrom matplotlib backends backend agg import Figure Canvas Agg as Figure Canvasfigsize data shape[ -1 ]if figsize[ 0 ] 1 figsize tuple figsize[ 1 ] data data[ 0]fig Figure figsize figsize dpi 1 0 frameon False Figure Canv... | def _build_image data cmap 'gray' import matplotlib pyplot as pltfrom matplotlib figure import Figurefrom matplotlib backends backend_agg import FigureCanvasAgg as FigureCanvasfigsize data shape[ -1 ]if figsize[0] 1 figsize tuple figsize[1 ] data data[ 0]fig Figure figsize figsize dpi 1 0 frameon False FigureCanvas fig... | 86 |
python-test-3112 | python | How do executable build ? | using guidata | def create executable dist Distribution name 'spyder'ver spyder version try imp find module ' Py Qt 4 ' python qt 'pyqt'except Import Error python qt 'pyside'dist setup name ' Spyder' version ver script 'spyder/spyder py' description ' Scientific P Ython Development Envi Ronment' target name '%s exe' % name icon '%s ic... | def create_executable dist Distribution name 'spyder'ver spyder __version__try imp find_module 'PyQt4' python_qt 'pyqt'except ImportError python_qt 'pyside'dist setup name 'Spyder' version ver script 'spyder/spyder py' description 'ScientificPYthonDevelopmentEnviRonment' target_name '%s exe' % name icon '%s ico' % name... | 132 |
python-test-3120 | python | What does the code do on the error_dict keys ? | some i18n stuff | def error summary error dict def prettify field name field name re sub ' ?< \\w [ Uu]rl ? \\w ' 'URL' field name replace ' ' '' capitalize return field name replace ' ' '' summary {}for key error in error dict iteritems if key 'resources' summary[ ' Resources' ] ' Packageresource s invalid' elif key 'extras' summary[ '... | def error_summary error_dict def prettify field_name field_name re sub ' ?< \\w [Uu]rl ? \\w ' 'URL' field_name replace '_' '' capitalize return _ field_name replace '_' '' summary {}for key error in error_dict iteritems if key 'resources' summary[_ 'Resources' ] _ 'Packageresource s invalid' elif key 'extras' summary[... | 84 |
python-test-3121 | python | Where does the code do some i18n stuff ? | on the error_dict keys | def error summary error dict def prettify field name field name re sub ' ?< \\w [ Uu]rl ? \\w ' 'URL' field name replace ' ' '' capitalize return field name replace ' ' '' summary {}for key error in error dict iteritems if key 'resources' summary[ ' Resources' ] ' Packageresource s invalid' elif key 'extras' summary[ '... | def error_summary error_dict def prettify field_name field_name re sub ' ?< \\w [Uu]rl ? \\w ' 'URL' field_name replace '_' '' capitalize return _ field_name replace '_' '' summary {}for key error in error_dict iteritems if key 'resources' summary[_ 'Resources' ] _ 'Packageresource s invalid' elif key 'extras' summary[... | 84 |
python-test-3134 | python | What does this return ? | the snippet of html to be rendered on the course info page | def get course info section request user course section key info module get course info section module request user course section key html ''if info module is not None try html info module render STUDENT VIEW contentexcept Exception html render to string 'courseware/error-message html' None log exception u' Errorrende... | def get_course_info_section request user course section_key info_module get_course_info_section_module request user course section_key html ''if info_module is not None try html info_module render STUDENT_VIEW contentexcept Exception html render_to_string 'courseware/error-message html' None log exception u'Errorrender... | 61 |
python-test-3135 | python | Where be the snippet of html rendered ? | on the course info page | def get course info section request user course section key info module get course info section module request user course section key html ''if info module is not None try html info module render STUDENT VIEW contentexcept Exception html render to string 'courseware/error-message html' None log exception u' Errorrende... | def get_course_info_section request user course section_key info_module get_course_info_section_module request user course section_key html ''if info_module is not None try html info_module render STUDENT_VIEW contentexcept Exception html render_to_string 'courseware/error-message html' None log exception u'Errorrender... | 61 |
python-test-3136 | python | What does utility method give ? | a dict of unknown and unsupported optional transitive path attributes of path | def get unknown opttrans attr path path attrs path pathattr mapunknown opt tran attrs {}for attr in path attrs items if isinstance attr BGP Path Attribute Unknown and attr flags & BGP ATTR FLAG OPTIONAL BGP ATTR FLAG TRANSITIVE or isinstance attr BGP Path Attribute As 4 Path or isinstance attr BGP Path Attribute As 4 A... | def get_unknown_opttrans_attr path path_attrs path pathattr_mapunknown_opt_tran_attrs {}for _ attr in path_attrs items if isinstance attr BGPPathAttributeUnknown and attr flags & BGP_ATTR_FLAG_OPTIONAL BGP_ATTR_FLAG_TRANSITIVE or isinstance attr BGPPathAttributeAs4Path or isinstance attr BGPPathAttributeAs4Aggregator u... | 67 |
python-test-3137 | python | Where are we running proper version of pip ? | in run_pip | def test correct pip version script result script pip '--version' dir re match 'pip\\d \\ [\\d] + \\ ? rc dev pre post \\d+ ?from * \\ python\\d [\\d] +\\ $' result stdout group 4 pip folder join SRC DIR 'pip' pip folder outputed join dir 'pip' diffs filecmp dircmp pip folder pip folder outputed mismatch py [x for x in... | def test_correct_pip_version script result script pip '--version' dir re match 'pip\\d \\ [\\d] + \\ ? rc dev pre post \\d+ ?from * \\ python\\d [\\d] +\\ $' result stdout group 4 pip_folder join SRC_DIR 'pip' pip_folder_outputed join dir 'pip' diffs filecmp dircmp pip_folder pip_folder_outputed mismatch_py [x for x in... | 91 |
python-test-3138 | python | What are we running in run_pip ? | proper version of pip | def test correct pip version script result script pip '--version' dir re match 'pip\\d \\ [\\d] + \\ ? rc dev pre post \\d+ ?from * \\ python\\d [\\d] +\\ $' result stdout group 4 pip folder join SRC DIR 'pip' pip folder outputed join dir 'pip' diffs filecmp dircmp pip folder pip folder outputed mismatch py [x for x in... | def test_correct_pip_version script result script pip '--version' dir re match 'pip\\d \\ [\\d] + \\ ? rc dev pre post \\d+ ?from * \\ python\\d [\\d] +\\ $' result stdout group 4 pip_folder join SRC_DIR 'pip' pip_folder_outputed join dir 'pip' diffs filecmp dircmp pip_folder pip_folder_outputed mismatch_py [x for x in... | 91 |
python-test-3139 | python | What did the code set ? | a specific selinux label on a given path cli example | def set selinux context path user None role None type None range None if not any user role type range return Falsecmd ['chcon']if user cmd extend ['-u' user] if role cmd extend ['-r' role] if type cmd extend ['-t' type] if range cmd extend ['-l' range] cmd append path ret not salt ['cmd retcode'] cmd python shell False... | def set_selinux_context path user None role None type None range None if not any user role type range return Falsecmd ['chcon']if user cmd extend ['-u' user] if role cmd extend ['-r' role] if type cmd extend ['-t' type] if range cmd extend ['-l' range] cmd append path ret not __salt__['cmd retcode'] cmd python_shell Fa... | 68 |
python-test-3145 | python | What found in a directory ? | all domain config files | def domain config finder conf dir LOG info LI ' Scanning%rfordomainconfigfiles' conf dir for r d f in os walk conf dir for fname in f if fname startswith DOMAIN CONF FHEAD and fname endswith DOMAIN CONF FTAIL if fname count ' ' > 2 domain name fname[len DOMAIN CONF FHEAD - len DOMAIN CONF FTAIL ] yield os path join r f... | def _domain_config_finder conf_dir LOG info _LI 'Scanning%rfordomainconfigfiles' conf_dir for r d f in os walk conf_dir for fname in f if fname startswith DOMAIN_CONF_FHEAD and fname endswith DOMAIN_CONF_FTAIL if fname count ' ' > 2 domain_name fname[len DOMAIN_CONF_FHEAD - len DOMAIN_CONF_FTAIL ] yield os path join r ... | 74 |
python-test-3146 | python | How does a style object return ? | with the color scheme | def color style if not supports color style no style else SPIDER COLORS os environ get 'SPIDER COLORS' '' color settings termcolors parse color setting SPIDER 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 SPIDER_COLORS os environ get 'SPIDER_COLORS' '' color_settings termcolors parse_color_setting SPIDER_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-3148 | python | What does the code set ? | workflow parameters | def check T 1 s T1 files cw 256 False import sysimport nibabel as nibfrom nipype utils filemanip import filename to list T 1 files filename to list T1 files if len T1 files 0 print "ERROR No T 1 's Given"sys exit -1 shape nib load T1 files[ 0 ] shapefor t1 in T1 files[ 1 ] if nib load t1 shape shape print 'ERROR T1 sno... | def checkT1s T1_files cw256 False import sysimport nibabel as nibfrom nipype utils filemanip import filename_to_listT1_files filename_to_list T1_files if len T1_files 0 print "ERROR NoT1'sGiven"sys exit -1 shape nib load T1_files[0] shapefor t1 in T1_files[1 ] if nib load t1 shape shape print 'ERROR T1snotthesamesize C... | 141 |
python-test-3153 | python | What does the code create ? | a new datacenter with the given name | def create datacenter dcname None service instance None folder None if len dcname > 79 raise Value Error ' Thenameofthedatacentermustbeunder 80 characters ' if folder is None folder service instance content root Folderif folder is not None and isinstance folder vim Folder dc moref folder Create Datacenter name dcname r... | def create_datacenter dcname None service_instance None folder None if len dcname > 79 raise ValueError 'Thenameofthedatacentermustbeunder80characters ' if folder is None folder service_instance content rootFolderif folder is not None and isinstance folder vim Folder dc_moref folder CreateDatacenter name dcname return ... | 52 |
python-test-3155 | python | How do a dict return ? | with information about users of a postgres server | def role get name user None host None port None maintenance db None password None runas None return password False all users user list user user host host port port maintenance db maintenance db password password runas runas return password return password try return all users get name None except Attribute Error log e... | def role_get name user None host None port None maintenance_db None password None runas None return_password False all_users user_list user user host host port port maintenance_db maintenance_db password password runas runas return_password return_password try return all_users get name None except AttributeError log er... | 61 |
python-test-3158 | python | What does the code add states here ? | to control | def main run it tools Control setup ORIGINAL CAPTION state dict {c MAIN MENU main menu Menu c LOAD SCREEN load screen Load Screen c TIME OUT load screen Time Out c GAME OVER load screen Game Over c LEVEL 1 level 1 Level 1 }run it setup states state dict c MAIN MENU run it main | def main run_it tools Control setup ORIGINAL_CAPTION state_dict {c MAIN_MENU main_menu Menu c LOAD_SCREEN load_screen LoadScreen c TIME_OUT load_screen TimeOut c GAME_OVER load_screen GameOver c LEVEL1 level1 Level1 }run_it setup_states state_dict c MAIN_MENU run_it main | 57 |
python-test-3159 | python | What does this create ? | a decorator that will work similar to : func : pass_obj but instead of passing the object of the current context | def make pass decorator object type ensure False def decorator f def new func *args **kwargs ctx get current context if ensure obj ctx ensure object object type else obj ctx find object object type if obj is None raise Runtime Error ' Managedtoinvokecallbackwithoutacontextobjectoftype%rexisting' % object type name retu... | def make_pass_decorator object_type ensure False def decorator f def new_func *args **kwargs ctx get_current_context if ensure obj ctx ensure_object object_type else obj ctx find_object object_type if obj is None raise RuntimeError 'Managedtoinvokecallbackwithoutacontextobjectoftype%rexisting' % object_type __name__ re... | 65 |
python-test-3160 | python | How will a decorator work ? | similar to : func : pass_obj but instead | def make pass decorator object type ensure False def decorator f def new func *args **kwargs ctx get current context if ensure obj ctx ensure object object type else obj ctx find object object type if obj is None raise Runtime Error ' Managedtoinvokecallbackwithoutacontextobjectoftype%rexisting' % object type name retu... | def make_pass_decorator object_type ensure False def decorator f def new_func *args **kwargs ctx get_current_context if ensure obj ctx ensure_object object_type else obj ctx find_object object_type if obj is None raise RuntimeError 'Managedtoinvokecallbackwithoutacontextobjectoftype%rexisting' % object_type __name__ re... | 65 |
python-test-3161 | python | When has a subtask been updated ? | before really updating | def my update subtask status entry id current task id new subtask status entry Instructor Task objects get pk entry id subtask dict json loads entry subtasks subtask status info subtask dict['status']current subtask status Subtask Status from dict subtask status info[current task id] current retry count current subtask... | def my_update_subtask_status entry_id current_task_id new_subtask_status entry InstructorTask objects get pk entry_id subtask_dict json loads entry subtasks subtask_status_info subtask_dict['status']current_subtask_status SubtaskStatus from_dict subtask_status_info[current_task_id] current_retry_count current_subtask_s... | 80 |
python-test-3162 | python | What does the code check ? | whether a subtask has been updated before really updating | def my update subtask status entry id current task id new subtask status entry Instructor Task objects get pk entry id subtask dict json loads entry subtasks subtask status info subtask dict['status']current subtask status Subtask Status from dict subtask status info[current task id] current retry count current subtask... | def my_update_subtask_status entry_id current_task_id new_subtask_status entry InstructorTask objects get pk entry_id subtask_dict json loads entry subtasks subtask_status_info subtask_dict['status']current_subtask_status SubtaskStatus from_dict subtask_status_info[current_task_id] current_retry_count current_subtask_s... | 80 |
python-test-3163 | python | What returns for saving data locally create folder if not exists ? | the current local path | def get Local Android Path client args local Path os path join args local Output Folder '{ 0 }-{ 1 }' format client conn modules['pupydroid utils'] get Android ID client desc['user'] if not os path exists local Path logging info ' Creating{ 0 }folderlocally' format local Path os makedirs local Path return local Path | def getLocalAndroidPath client args localPath os path join args localOutputFolder '{0}-{1}' format client conn modules['pupydroid utils'] getAndroidID client desc['user'] if not os path exists localPath logging info 'Creating{0}folderlocally' format localPath os makedirs localPath return localPath | 54 |
python-test-3164 | python | What does the current local path return ? | for saving data locally create folder if not exists | def get Local Android Path client args local Path os path join args local Output Folder '{ 0 }-{ 1 }' format client conn modules['pupydroid utils'] get Android ID client desc['user'] if not os path exists local Path logging info ' Creating{ 0 }folderlocally' format local Path os makedirs local Path return local Path | def getLocalAndroidPath client args localPath os path join args localOutputFolder '{0}-{1}' format client conn modules['pupydroid utils'] getAndroidID client desc['user'] if not os path exists localPath logging info 'Creating{0}folderlocally' format localPath os makedirs localPath return localPath | 54 |
python-test-3167 | python | For what purpose does a list of non - ssd disks return ? | for the given host or list of host_names | @depends HAS PYVMOMI def list non ssds host username password protocol None port None host names None service instance salt utils vmware get service instance host host username username password password protocol protocol port port host names check hosts service instance host host names ret {}names []for host name in h... | @depends HAS_PYVMOMI def list_non_ssds host username password protocol None port None host_names None service_instance salt utils vmware get_service_instance host host username username password password protocol protocol port port host_names _check_hosts service_instance host host_names ret {}names []for host_name in ... | 87 |
python-test-3169 | python | What does the code create ? | a simple jndi binding in the running jboss instance jboss_config configuration dictionary with properties specified above | def create simple binding jboss config binding name value profile None log debug ' MODULEFUNCTION jboss 7 create simple binding binding name %s value %s profile %s' binding name value profile operation '/subsystem naming/binding "{binding name}" add binding-type simple value "{value}" ' format binding name binding name... | def create_simple_binding jboss_config binding_name value profile None log debug ' MODULEFUNCTION jboss7 create_simple_binding binding_name %s value %s profile %s' binding_name value profile operation '/subsystem naming/binding "{binding_name}" add binding-type simple value "{value}" ' format binding_name binding_name ... | 75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.