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-4212 | python | What do non - datetime columns force ? | to be read as such | def parse date columns data frame parse dates if parse dates is True or parse dates is None or parse dates is False parse dates []if not hasattr parse dates ' iter ' parse dates [parse dates]for col name in parse dates df col data frame[col name]try fmt parse dates[col name]except Type Error fmt Nonedata frame[col name... | def _parse_date_columns data_frame parse_dates if parse_dates is True or parse_dates is None or parse_dates is False parse_dates []if not hasattr parse_dates '__iter__' parse_dates [parse_dates]for col_name in parse_dates df_col data_frame[col_name]try fmt parse_dates[col_name]except TypeError fmt Nonedata_frame[col_na... | 92 |
python-test-4213 | python | What forces to be read as such ? | non - datetime columns | def parse date columns data frame parse dates if parse dates is True or parse dates is None or parse dates is False parse dates []if not hasattr parse dates ' iter ' parse dates [parse dates]for col name in parse dates df col data frame[col name]try fmt parse dates[col name]except Type Error fmt Nonedata frame[col name... | def _parse_date_columns data_frame parse_dates if parse_dates is True or parse_dates is None or parse_dates is False parse_dates []if not hasattr parse_dates '__iter__' parse_dates [parse_dates]for col_name in parse_dates df_col data_frame[col_name]try fmt parse_dates[col_name]except TypeError fmt Nonedata_frame[col_na... | 92 |
python-test-4214 | python | How does the code read the config file ? | using configparser | def read config conf file None if conf file is None paths '/etc/supervisor/supervisord conf' '/etc/supervisord conf' for path in paths if os path exists path conf file pathbreakif conf file is None raise Command Execution Error ' Nosuitableconfigfilefound' config configparser Config Parser try config read conf file exc... | def _read_config conf_file None if conf_file is None paths '/etc/supervisor/supervisord conf' '/etc/supervisord conf' for path in paths if os path exists path conf_file pathbreakif conf_file is None raise CommandExecutionError 'Nosuitableconfigfilefound' config configparser ConfigParser try config read conf_file except... | 70 |
python-test-4223 | python | What does the main function run with user specified query ? | the codesearchexample application | def main try opts args getopt getopt sys argv[ 1 ] '' ['query '] except getopt error as msg print 'python Codesearch Example py--query[query text]'sys exit 2 query ''for o a in opts if o '--query' query aif query '' print 'python Codesearch Example py--query[query]'sys exit 2 sample Codesearch Example sample Print Code... | def main try opts args getopt getopt sys argv[1 ] '' ['query '] except getopt error as msg print 'pythonCodesearchExample py--query[query_text]'sys exit 2 query ''for o a in opts if o '--query' query aif query '' print 'pythonCodesearchExample py--query[query]'sys exit 2 sample CodesearchExample sample PrintCodeSnippet... | 55 |
python-test-4224 | python | How does the main function run the codesearchexample application ? | with user specified query | def main try opts args getopt getopt sys argv[ 1 ] '' ['query '] except getopt error as msg print 'python Codesearch Example py--query[query text]'sys exit 2 query ''for o a in opts if o '--query' query aif query '' print 'python Codesearch Example py--query[query]'sys exit 2 sample Codesearch Example sample Print Code... | def main try opts args getopt getopt sys argv[1 ] '' ['query '] except getopt error as msg print 'pythonCodesearchExample py--query[query_text]'sys exit 2 query ''for o a in opts if o '--query' query aif query '' print 'pythonCodesearchExample py--query[query]'sys exit 2 sample CodesearchExample sample PrintCodeSnippet... | 55 |
python-test-4233 | python | How do mimedata return ? | with a list of absolute path urls | def mimedata from paths paths abspaths [core abspath path for path in paths]urls [ Qt Core Q Url from Local File path for path in abspaths]mimedata Qt Core Q Mime Data mimedata set Urls urls paths text core list 2 cmdline abspaths encoding gitcfg current get u'cola dragencoding' u'utf- 16 ' moz text core encode paths t... | def mimedata_from_paths paths abspaths [core abspath path for path in paths]urls [QtCore QUrl fromLocalFile path for path in abspaths]mimedata QtCore QMimeData mimedata setUrls urls paths_text core list2cmdline abspaths encoding gitcfg current get u'cola dragencoding' u'utf-16' moz_text core encode paths_text encoding ... | 67 |
python-test-4235 | python | For what purpose do cloud cache data return ? | for target | def cloud tgt provider None if not isinstance tgt six string types return {}ret {}opts salt config cloud config '/etc/salt/cloud' cloud cache utils ['cloud list cache nodes full'] opts opts provider provider for driver providers in cloud cache items for provider servers in providers items for name data in servers items... | def cloud tgt provider None if not isinstance tgt six string_types return {}ret {}opts salt config cloud_config '/etc/salt/cloud' cloud_cache __utils__['cloud list_cache_nodes_full'] opts opts provider provider for driver providers in cloud_cache items for provider servers in providers items for name data in servers it... | 60 |
python-test-4241 | python | What does the code build ? | the perl module cix element tree | def scan multilang tokens module elem tokenizer perl lexer Perl Multi Lang Lexer tokens parser perl parser Parser tokenizer lang ' Perl HTML' provide full docs g Provide Full Docs parser module Name ''parser parse parse tree parser produce CIX No Header module elem csl tokens tokenizer get csl tokens return csl tokens ... | def scan_multilang tokens module_elem tokenizer perl_lexer PerlMultiLangLexer tokens parser perl_parser Parser tokenizer lang 'PerlHTML' provide_full_docs gProvideFullDocs parser moduleName ''parser parse parse_tree parser produce_CIX_NoHeader module_elem csl_tokens tokenizer get_csl_tokens return csl_tokens tokenizer ... | 57 |
python-test-4243 | python | What does the code generate ? | a dict of filename - > mtime | def generate mtime map opts path map file map {}for saltenv path list in six iteritems path map for path in path list for directory dirnames filenames in os walk path dirnames[ ] [d for d in dirnames if not is file ignored opts d ]for item in filenames try file path os path join directory item file map[file path] os pa... | def generate_mtime_map opts path_map file_map {}for saltenv path_list in six iteritems path_map for path in path_list for directory dirnames filenames in os walk path dirnames[ ] [d for d in dirnames if not is_file_ignored opts d ]for item in filenames try file_path os path join directory item file_map[file_path] os pa... | 83 |
python-test-4247 | python | What does the code create ? | a servicepair that uses zfs for testing remotevolumemanager | def create realistic servicepair test from pool Storage Pool reactor create zfs pool test File Path test mktemp from config File Path test mktemp from service Volume Service from config from pool reactor Clock from service start Service test add Cleanup from service stop Service to pool Storage Pool reactor create zfs ... | def create_realistic_servicepair test from_pool StoragePool reactor create_zfs_pool test FilePath test mktemp from_config FilePath test mktemp from_service VolumeService from_config from_pool reactor Clock from_service startService test addCleanup from_service stopService to_pool StoragePool reactor create_zfs_pool tes... | 120 |
python-test-4248 | python | What does a servicepair use for testing remotevolumemanager ? | zfs | def create realistic servicepair test from pool Storage Pool reactor create zfs pool test File Path test mktemp from config File Path test mktemp from service Volume Service from config from pool reactor Clock from service start Service test add Cleanup from service stop Service to pool Storage Pool reactor create zfs ... | def create_realistic_servicepair test from_pool StoragePool reactor create_zfs_pool test FilePath test mktemp from_config FilePath test mktemp from_service VolumeService from_config from_pool reactor Clock from_service startService test addCleanup from_service stopService to_pool StoragePool reactor create_zfs_pool tes... | 120 |
python-test-4249 | python | What does the code ensure ? | that the marathon app with the given i d is not present | def absent name ret {'name' name 'changes' {} 'result' False 'comment' ''}if not salt ['marathon has app'] name ret['result'] Trueret['comment'] ' App{ 0 }alreadyabsent' format name return retif opts ['test'] ret['result'] Noneret['comment'] ' App{ 0 }issettoberemoved' format name return retif salt ['marathon rm app'] ... | def absent name ret {'name' name 'changes' {} 'result' False 'comment' ''}if not __salt__['marathon has_app'] name ret['result'] Trueret['comment'] 'App{0}alreadyabsent' format name return retif __opts__['test'] ret['result'] Noneret['comment'] 'App{0}issettoberemoved' format name return retif __salt__['marathon rm_app... | 67 |
python-test-4250 | python | What did the code read ? | an entry from a cache file | def read cache entry f beginoffset f tell ctime read cache time f mtime read cache time f dev ino mode uid gid size sha flags struct unpack '>LLLLLL 20 s H' f read 20 + 4 * 6 + 2 name f read flags & 4095 real size f tell - beginoffset + 8 & ~ 7 f read beginoffset + real size - f tell return name ctime mtime dev ino mod... | def read_cache_entry f beginoffset f tell ctime read_cache_time f mtime read_cache_time f dev ino mode uid gid size sha flags struct unpack '>LLLLLL20sH' f read 20 + 4 * 6 + 2 name f read flags & 4095 real_size f tell - beginoffset + 8 & ~ 7 f read beginoffset + real_size - f tell return name ctime mtime dev ino mode u... | 85 |
python-test-4255 | python | What does the code expect ? | the given message in the qutebrowser log | @bdd then bdd parsers re 'the ?P<category>error message warning " ?P<message> * "shouldbeshown' def expect message quteproc httpbin category message category to loglevel {'message' logging INFO 'error' logging ERROR 'warning' logging WARNING}message message replace ' port ' str httpbin port quteproc mark expected categ... | @bdd then bdd parsers re 'the ?P<category>error message warning " ?P<message> * "shouldbeshown' def expect_message quteproc httpbin category message category_to_loglevel {'message' logging INFO 'error' logging ERROR 'warning' logging WARNING}message message replace ' port ' str httpbin port quteproc mark_expected categ... | 51 |
python-test-4256 | python | For what purpose does the module object return ? | for given doctype | def load doctype module doctype module None prefix u'' suffix u'' if not module module get doctype module doctype app get module app module key app doctype prefix suffix module name get module name doctype module prefix suffix try if key not in doctype python modules doctype python modules[key] frappe get module module... | def load_doctype_module doctype module None prefix u'' suffix u'' if not module module get_doctype_module doctype app get_module_app module key app doctype prefix suffix module_name get_module_name doctype module prefix suffix try if key not in doctype_python_modules doctype_python_modules[key] frappe get_module module... | 75 |
python-test-4262 | python | What do arbitrary matrices transform ? | to matrices with singular values less than one | def constrain sv less than one python unconstrained order None k endog None from scipy import linalgconstrained []if order is None order len unconstrained if k endog is None k endog unconstrained[ 0 ] shape[ 0 ]eye np eye k endog for i in range order A unconstrained[i] B lower linalg cho factor eye + np dot A A T lower... | def _constrain_sv_less_than_one_python unconstrained order None k_endog None from scipy import linalgconstrained []if order is None order len unconstrained if k_endog is None k_endog unconstrained[0] shape[0]eye np eye k_endog for i in range order A unconstrained[i] B lower linalg cho_factor eye + np dot A A T lower Tr... | 73 |
python-test-4263 | python | What transforms to matrices with singular values less than one ? | arbitrary matrices | def constrain sv less than one python unconstrained order None k endog None from scipy import linalgconstrained []if order is None order len unconstrained if k endog is None k endog unconstrained[ 0 ] shape[ 0 ]eye np eye k endog for i in range order A unconstrained[i] B lower linalg cho factor eye + np dot A A T lower... | def _constrain_sv_less_than_one_python unconstrained order None k_endog None from scipy import linalgconstrained []if order is None order len unconstrained if k_endog is None k_endog unconstrained[0] shape[0]eye np eye k_endog for i in range order A unconstrained[i] B lower linalg cho_factor eye + np dot A A T lower Tr... | 73 |
python-test-4265 | python | In which direction does chracters read ? | from the console buffer | def read console output character x 0 y 0 fd 1 buf None bufsize 1024 raw False hcon STDHANDLES[fd]if buf is None if raw buf ctypes c char p '' * bufsize else buf ctypes c wchar p '' * bufsize coord COORD x y n DWORD if raw Read Console Output Character A hcon buf bufsize coord byref n else Read Console Output Character... | def read_console_output_character x 0 y 0 fd 1 buf None bufsize 1024 raw False hcon STDHANDLES[fd]if buf is None if raw buf ctypes c_char_p '' * bufsize else buf ctypes c_wchar_p '' * bufsize coord COORD x y n DWORD if raw ReadConsoleOutputCharacterA hcon buf bufsize coord byref n else ReadConsoleOutputCharacterW hcon ... | 77 |
python-test-4266 | python | What does the code renew ? | a certificate lineage | def renew cert config domains le client lineage renewal params lineage configuration['renewalparams']original server renewal params get 'server' cli flag default 'server' avoid invalidating lineage config lineage original server if not domains domains lineage names new certr new chain new key le client obtain certifica... | def renew_cert config domains le_client lineage renewal_params lineage configuration['renewalparams']original_server renewal_params get 'server' cli flag_default 'server' _avoid_invalidating_lineage config lineage original_server if not domains domains lineage names new_certr new_chain new_key _ le_client obtain_certif... | 121 |
python-test-4268 | python | What does the code add to your locally installed overlays ? | the given overlay from the cached remote list | def add overlay ret list old overlays list local cmd 'layman--quietness 0--add{ 0 }' format overlay add attempt salt ['cmd run all'] cmd python shell False stdin 'y' if add attempt['retcode'] 0 raise salt exceptions Command Execution Error add attempt['stdout'] new overlays list local if len old overlays 0 and len new ... | def add overlay ret list old_overlays list_local cmd 'layman--quietness 0--add{0}' format overlay add_attempt __salt__['cmd run_all'] cmd python_shell False stdin 'y' if add_attempt['retcode'] 0 raise salt exceptions CommandExecutionError add_attempt['stdout'] new_overlays list_local if len old_overlays 0 and len new_o... | 87 |
python-test-4269 | python | How does a posix process kill ? | with os | def Posix Shutdown dev process Global Process children dev process Children for term signal in signal SIGTERM signal SIGKILL for child in children if child process is None continueif child process returncode is not None continuepid child process pidtry logging debug 'posixkill%dwithsignal%d' pid term signal os kill pid... | def PosixShutdown dev_process GlobalProcess children dev_process Children for term_signal in signal SIGTERM signal SIGKILL for child in children if child process is None continueif child process returncode is not None continuepid child process pidtry logging debug 'posixkill%dwithsignal%d' pid term_signal os kill pid t... | 100 |
python-test-4272 | python | What does the code generate ? | a word relationships file | def wordrelationships relationshiplist relationships etree fromstring '< Relationshipsxmlns "http //schemas openxmlformats org/package/ 2006 /relationships"></ Relationships>' count 0for relationship in relationshiplist rel elm makeelement ' Relationship' nsprefix None attributes {' Id' 'r Id' + str count + 1 ' Type' r... | def wordrelationships relationshiplist relationships etree fromstring '<Relationshipsxmlns "http //schemas openxmlformats org/package/2006/relationships"></Relationships>' count 0for relationship in relationshiplist rel_elm makeelement 'Relationship' nsprefix None attributes {'Id' 'rId' + str count + 1 'Type' relations... | 55 |
python-test-4276 | python | What does the code detect ? | all offsets in a byte code which are jump targets | def findlabels code labels []n len code i 0while i < n c code[i]op ord c i i + 1 if op > HAVE ARGUMENT oparg ord code[i] + ord code[ i + 1 ] * 256 i i + 2 label -1 if op in hasjrel label i + oparg elif op in hasjabs label opargif label > 0 if label not in labels labels append label return labels | def findlabels code labels []n len code i 0while i < n c code[i]op ord c i i + 1 if op > HAVE_ARGUMENT oparg ord code[i] + ord code[ i + 1 ] * 256 i i + 2 label -1 if op in hasjrel label i + oparg elif op in hasjabs label opargif label > 0 if label not in labels labels append label return labels | 70 |
python-test-4277 | python | What does the code get ? | taxes grouped by priority from effective tax rules | def get taxes of effective rules taxing context tax rules matching rules tax rule for tax rule in tax rules if tax rule matches taxing context grouped by override groupby matching rules attrgetter 'override group' highest override group first grouped by override None [] [1 ]grouped rules groupby highest override group ... | def get_taxes_of_effective_rules taxing_context tax_rules matching_rules tax_rule for tax_rule in tax_rules if tax_rule matches taxing_context grouped_by_override groupby matching_rules attrgetter 'override_group' highest_override_group first grouped_by_override None [] [1]grouped_rules groupby highest_override_group a... | 68 |
python-test-4283 | python | How does multiple clones create ? | according to config using a model_fn | def create clones config model fn args None kwargs None clones []args args or [] kwargs kwargs or {} with slim arg scope [slim model variable slim variable] device config variables device for i in range 0 config num clones with tf name scope config clone scope i as clone scope clone device config clone device i with tf... | def create_clones config model_fn args None kwargs None clones []args args or [] kwargs kwargs or {} with slim arg_scope [slim model_variable slim variable] device config variables_device for i in range 0 config num_clones with tf name_scope config clone_scope i as clone_scope clone_device config clone_device i with tf... | 93 |
python-test-4287 | python | What does the code create ? | a dataframe representing futures for root_symbols during year | def make future info first sid root symbols years notice date func expiration date func start date func month codes None if month codes is None month codes CME CODE TO MONT Hyear strs list map str years years [pd Timestamp s tz 'UTC' for s in year strs]contract suffix to beginning of month tuple month code + year str[ ... | def make_future_info first_sid root_symbols years notice_date_func expiration_date_func start_date_func month_codes None if month_codes is None month_codes CME_CODE_TO_MONTHyear_strs list map str years years [pd Timestamp s tz 'UTC' for s in year_strs]contract_suffix_to_beginning_of_month tuple month_code + year_str[ -... | 158 |
python-test-4289 | python | What does the code run ? | the specified command | def execute *cmd **kwargs process input kwargs pop 'process input' None run as root kwargs pop 'run as root' True ret 0try if len cmd > 3 and cmd[ 0 ] 'raidcom' and cmd[ 1 ] '-login' stdout stderr cinder utils execute process input process input run as root run as root loglevel base logging NOTSET *cmd [ 2]else stdout ... | def execute *cmd **kwargs process_input kwargs pop 'process_input' None run_as_root kwargs pop 'run_as_root' True ret 0try if len cmd > 3 and cmd[0] 'raidcom' and cmd[1] '-login' stdout stderr cinder_utils execute process_input process_input run_as_root run_as_root loglevel base_logging NOTSET *cmd [ 2]else stdout stde... | 131 |
python-test-4292 | python | Where did the grains set ? | in the grains file | def config if 'conf file' not in opts return {}if os path isdir opts ['conf file'] gfn os path join opts ['conf file'] 'grains' else gfn os path join os path dirname opts ['conf file'] 'grains' if os path isfile gfn with salt utils fopen gfn 'rb' as fp try return yaml safe load fp read except Exception log warning ' Ba... | def config if 'conf_file' not in __opts__ return {}if os path isdir __opts__['conf_file'] gfn os path join __opts__['conf_file'] 'grains' else gfn os path join os path dirname __opts__['conf_file'] 'grains' if os path isfile gfn with salt utils fopen gfn 'rb' as fp_ try return yaml safe_load fp_ read except Exception l... | 67 |
python-test-4293 | python | What does the code update ? | the root_service | def org service root service service id db current dbtable current s3 db org servicerecord db table id service id select table id table root service table parent first try parent record parentcurrent root record root serviceexcept Attribute Error current log error ' Cannotfindrecordwithservice id %s' % service id raise... | def org_service_root_service service_id db current dbtable current s3db org_servicerecord db table id service_id select table id table root_service table parent first try parent record parentcurrent_root record root_serviceexcept AttributeError current log error 'Cannotfindrecordwithservice_id %s' % service_id raiseif ... | 128 |
python-test-4295 | python | What did the code give ? | a l{kleinroute | def introspect Route route example By Identifier schema store result {}try user documentation route attributes['user documentation']except Key Error raise Sphinx Error ' Undocumentedroute {}' format route result['description'] prepare docstring user documentation text result['header'] user documentation headerresult['s... | def _introspectRoute route exampleByIdentifier schema_store result {}try user_documentation route attributes['user_documentation']except KeyError raise SphinxError 'Undocumentedroute {}' format route result['description'] prepare_docstring user_documentation text result['header'] user_documentation headerresult['sectio... | 98 |
python-test-4296 | python | What does this dependency check function use the information stored in the platforms module ? | to call the function in core | def dependency check should exit mdep check dependency set GUI exit on failure False try import pygtkpygtk require '2 0' import gtkimport gobjectassert gtk gtk version > 2 12 assert gtk pygtk version > 2 12 except msg ' The GT Kpackagerequirementsarenotmet pleasemakesureyoursystemmeetstheserequirements \n- Py GTK> 2 12... | def dependency_check should_exit mdep_check dependency_set GUI exit_on_failure False try import pygtkpygtk require '2 0' import gtkimport gobjectassert gtk gtk_version > 2 12 assert gtk pygtk_version > 2 12 except msg 'TheGTKpackagerequirementsarenotmet pleasemakesureyoursystemmeetstheserequirements \n-PyGTK> 2 12\n-GT... | 71 |
python-test-4297 | python | What does this dependency check function use to call the function in core ? | the information stored in the platforms module | def dependency check should exit mdep check dependency set GUI exit on failure False try import pygtkpygtk require '2 0' import gtkimport gobjectassert gtk gtk version > 2 12 assert gtk pygtk version > 2 12 except msg ' The GT Kpackagerequirementsarenotmet pleasemakesureyoursystemmeetstheserequirements \n- Py GTK> 2 12... | def dependency_check should_exit mdep_check dependency_set GUI exit_on_failure False try import pygtkpygtk require '2 0' import gtkimport gobjectassert gtk gtk_version > 2 12 assert gtk pygtk_version > 2 12 except msg 'TheGTKpackagerequirementsarenotmet pleasemakesureyoursystemmeetstheserequirements \n-PyGTK> 2 12\n-GT... | 71 |
python-test-4298 | python | Where did the information store ? | in the platforms module | def dependency check should exit mdep check dependency set GUI exit on failure False try import pygtkpygtk require '2 0' import gtkimport gobjectassert gtk gtk version > 2 12 assert gtk pygtk version > 2 12 except msg ' The GT Kpackagerequirementsarenotmet pleasemakesureyoursystemmeetstheserequirements \n- Py GTK> 2 12... | def dependency_check should_exit mdep_check dependency_set GUI exit_on_failure False try import pygtkpygtk require '2 0' import gtkimport gobjectassert gtk gtk_version > 2 12 assert gtk pygtk_version > 2 12 except msg 'TheGTKpackagerequirementsarenotmet pleasemakesureyoursystemmeetstheserequirements \n-PyGTK> 2 12\n-GT... | 71 |
python-test-4299 | python | What does this dependency check function call ? | the function in core | def dependency check should exit mdep check dependency set GUI exit on failure False try import pygtkpygtk require '2 0' import gtkimport gobjectassert gtk gtk version > 2 12 assert gtk pygtk version > 2 12 except msg ' The GT Kpackagerequirementsarenotmet pleasemakesureyoursystemmeetstheserequirements \n- Py GTK> 2 12... | def dependency_check should_exit mdep_check dependency_set GUI exit_on_failure False try import pygtkpygtk require '2 0' import gtkimport gobjectassert gtk gtk_version > 2 12 assert gtk pygtk_version > 2 12 except msg 'TheGTKpackagerequirementsarenotmet pleasemakesureyoursystemmeetstheserequirements \n-PyGTK> 2 12\n-GT... | 71 |
python-test-4300 | python | What separated from out ? | this | @csrf exempt@facebook required lazydef connect request graph backend get registration backend try response connect request graph except open facebook exceptions Facebook Unreachable as e warning format u'%s oftencausedby Facebookslowdown error%s'warn message warning format % type e str e send warning warn message e e a... | @csrf_exempt@facebook_required_lazydef connect request graph backend get_registration_backend try response _connect request graph except open_facebook_exceptions FacebookUnreachable as e warning_format u'%s oftencausedbyFacebookslowdown error%s'warn_message warning_format % type e str e send_warning warn_message e e ad... | 61 |
python-test-4301 | python | What do exception and validation functionality around the _ connect view separated this out from _ connect to preserve readability nt bother ? | reading this code | @csrf exempt@facebook required lazydef connect request graph backend get registration backend try response connect request graph except open facebook exceptions Facebook Unreachable as e warning format u'%s oftencausedby Facebookslowdown error%s'warn message warning format % type e str e send warning warn message e e a... | @csrf_exempt@facebook_required_lazydef connect request graph backend get_registration_backend try response _connect request graph except open_facebook_exceptions FacebookUnreachable as e warning_format u'%s oftencausedbyFacebookslowdown error%s'warn_message warning_format % type e str e send_warning warn_message e e ad... | 61 |
python-test-4302 | python | Do exception and validation functionality around the _ connect view separated this out from _ connect to preserve readability bother reading this code ? | No | @csrf exempt@facebook required lazydef connect request graph backend get registration backend try response connect request graph except open facebook exceptions Facebook Unreachable as e warning format u'%s oftencausedby Facebookslowdown error%s'warn message warning format % type e str e send warning warn message e e a... | @csrf_exempt@facebook_required_lazydef connect request graph backend get_registration_backend try response _connect request graph except open_facebook_exceptions FacebookUnreachable as e warning_format u'%s oftencausedbyFacebookslowdown error%s'warn_message warning_format % type e str e send_warning warn_message e e ad... | 61 |
python-test-4303 | python | What do nt bother reading this code ? | exception and validation functionality around the _ connect view separated this out from _ connect to preserve readability | @csrf exempt@facebook required lazydef connect request graph backend get registration backend try response connect request graph except open facebook exceptions Facebook Unreachable as e warning format u'%s oftencausedby Facebookslowdown error%s'warn message warning format % type e str e send warning warn message e e a... | @csrf_exempt@facebook_required_lazydef connect request graph backend get_registration_backend try response _connect request graph except open_facebook_exceptions FacebookUnreachable as e warning_format u'%s oftencausedbyFacebookslowdown error%s'warn_message warning_format % type e str e send_warning warn_message e e ad... | 61 |
python-test-4304 | python | Where did this separate from ? | out | @csrf exempt@facebook required lazydef connect request graph backend get registration backend try response connect request graph except open facebook exceptions Facebook Unreachable as e warning format u'%s oftencausedby Facebookslowdown error%s'warn message warning format % type e str e send warning warn message e e a... | @csrf_exempt@facebook_required_lazydef connect request graph backend get_registration_backend try response _connect request graph except open_facebook_exceptions FacebookUnreachable as e warning_format u'%s oftencausedbyFacebookslowdown error%s'warn_message warning_format % type e str e send_warning warn_message e e ad... | 61 |
python-test-4306 | python | For what purpose is this the function responsible for making sure jids do nt collide ? | so do what you have to do to make sure that stays the case | def prep jid nocache False passed jid None if passed jid is None jid salt utils jid gen jid else jid passed jidcb get connection try cb add str jid {'nocache' nocache} ttl get ttl except couchbase exceptions Key Exists Error if passed jid is None return prep jid nocache nocache return jid | def prep_jid nocache False passed_jid None if passed_jid is None jid salt utils jid gen_jid else jid passed_jidcb_ _get_connection try cb_ add str jid {'nocache' nocache} ttl _get_ttl except couchbase exceptions KeyExistsError if passed_jid is None return prep_jid nocache nocache return jid | 53 |
python-test-4307 | python | For what purpose have what you have to do do ? | to make sure that stays the case | def prep jid nocache False passed jid None if passed jid is None jid salt utils jid gen jid else jid passed jidcb get connection try cb add str jid {'nocache' nocache} ttl get ttl except couchbase exceptions Key Exists Error if passed jid is None return prep jid nocache nocache return jid | def prep_jid nocache False passed_jid None if passed_jid is None jid salt utils jid gen_jid else jid passed_jidcb_ _get_connection try cb_ add str jid {'nocache' nocache} ttl _get_ttl except couchbase exceptions KeyExistsError if passed_jid is None return prep_jid nocache nocache return jid | 53 |
python-test-4310 | python | How does cropped_image generate ? | using a one of the bboxes randomly distorted | def distorted bounding box crop image bbox min object covered 0 1 aspect ratio range 0 75 1 33 area range 0 05 1 0 max attempts 100 scope None with tf name scope scope 'distorted bounding box crop' [image bbox] sample distorted bounding box tf image sample distorted bounding box tf shape image bounding boxes bbox min o... | def distorted_bounding_box_crop image bbox min_object_covered 0 1 aspect_ratio_range 0 75 1 33 area_range 0 05 1 0 max_attempts 100 scope None with tf name_scope scope 'distorted_bounding_box_crop' [image bbox] sample_distorted_bounding_box tf image sample_distorted_bounding_box tf shape image bounding_boxes bbox min_o... | 107 |
python-test-4311 | python | Where do edges produce ? | in a depth - first - search labeled by type | def dfs labeled edges G source None if source is None nodes Gelse nodes [source]visited set for start in nodes if start in visited continue yield start start 'forward' visited add start stack [ start iter G[start] ]while stack parent children stack[ -1 ]try child next children if child in visited yield parent child 'no... | def dfs_labeled_edges G source None if source is None nodes Gelse nodes [source]visited set for start in nodes if start in visited continue yield start start 'forward' visited add start stack [ start iter G[start] ]while stack parent children stack[ -1 ]try child next children if child in visited yield parent child 'no... | 87 |
python-test-4312 | python | What does the code convert to a native array structure ? | a numpy array object | @unbox types Array def unbox array typ obj c nativearycls c context make array typ nativeary nativearycls c context c builder aryptr nativeary getpointer ptr c builder bitcast aryptr c pyapi voidptr if c context enable nrt errcode c pyapi nrt adapt ndarray from python obj ptr else errcode c pyapi numba array adaptor ob... | @unbox types Array def unbox_array typ obj c nativearycls c context make_array typ nativeary nativearycls c context c builder aryptr nativeary _getpointer ptr c builder bitcast aryptr c pyapi voidptr if c context enable_nrt errcode c pyapi nrt_adapt_ndarray_from_python obj ptr else errcode c pyapi numba_array_adaptor o... | 74 |
python-test-4316 | python | What does the code turn into a normalized byte string ? | a long - int | def deflate long n add sign padding True s bytes n long n while n 0 and n -1 s struct pack '>I' n & xffffffff + s n >> 32 for i in enumerate s if n 0 and i[ 1 ] deflate zero breakif n -1 and i[ 1 ] deflate ff breakelse i 0 if n 0 s zero byteelse s max bytes s[i[ 0 ] ]if add sign padding if n 0 and byte ord s[ 0 ] > 128... | def deflate_long n add_sign_padding True s bytes n long n while n 0 and n -1 s struct pack '>I' n & xffffffff + s n >> 32for i in enumerate s if n 0 and i[1] deflate_zero breakif n -1 and i[1] deflate_ff breakelse i 0 if n 0 s zero_byteelse s max_bytes s[i[0] ]if add_sign_padding if n 0 and byte_ord s[0] > 128 s zero_b... | 107 |
python-test-4325 | python | What does the code build ? | an in - memory representation of the item tree | def build tree structure queryset all nodes {}mptt opts queryset model mptt metaitems queryset order by mptt opts tree id attr mptt opts left attr values list u'pk' u'%s id' % mptt opts parent attr for p id parent id in items all nodes setdefault str parent id if parent id else 0 [] append p id return all nodes | def _build_tree_structure queryset all_nodes {}mptt_opts queryset model _mptt_metaitems queryset order_by mptt_opts tree_id_attr mptt_opts left_attr values_list u'pk' u'%s_id' % mptt_opts parent_attr for p_id parent_id in items all_nodes setdefault str parent_id if parent_id else 0 [] append p_id return all_nodes | 60 |
python-test-4328 | python | What does the code create ? | a new usercontributionsmodel | def create user contributions user id created exploration ids edited exploration ids user contributions get user contributions user id strict False if user contributions raise Exception ' Usercontributionsmodelforuser%salreadyexists ' % user id else user contributions User Contributions user id created exploration ids ... | def create_user_contributions user_id created_exploration_ids edited_exploration_ids user_contributions get_user_contributions user_id strict False if user_contributions raise Exception 'Usercontributionsmodelforuser%salreadyexists ' % user_id else user_contributions UserContributions user_id created_exploration_ids ed... | 53 |
python-test-4329 | python | What does the code return ? | the domain object | def create user contributions user id created exploration ids edited exploration ids user contributions get user contributions user id strict False if user contributions raise Exception ' Usercontributionsmodelforuser%salreadyexists ' % user id else user contributions User Contributions user id created exploration ids ... | def create_user_contributions user_id created_exploration_ids edited_exploration_ids user_contributions get_user_contributions user_id strict False if user_contributions raise Exception 'Usercontributionsmodelforuser%salreadyexists ' % user_id else user_contributions UserContributions user_id created_exploration_ids ed... | 53 |
python-test-4330 | python | What did the code use ? | to execute the linter | def main epilog ' Formorehelpusingthesafetemplatelinter includingdetailsonhow\n'epilog + 'tounderstandandfixanyviolations readthedocshere \n'epilog + '\n'epilog + 'http //edx readthedocs org/projects/edx-developer-guide/en/latest/conventions/safe templates html#safe-template-linter\n'parser argparse Argument Parser for... | def main epilog 'Formorehelpusingthesafetemplatelinter includingdetailsonhow\n'epilog + 'tounderstandandfixanyviolations readthedocshere \n'epilog + '\n'epilog + 'http //edx readthedocs org/projects/edx-developer-guide/en/latest/conventions/safe_templates html#safe-template-linter\n'parser argparse ArgumentParser forma... | 134 |
python-test-4333 | python | How does the code retrieve the processlist from the mysql server ? | via " show full processlist " | def processlist **connection args ret []dbc connect **connection args if dbc is None return []cur dbc cursor execute cur 'SHOWFULLPROCESSLIST' hdr [c[ 0 ] for c in cur description]for in range cur rowcount row cur fetchone idx r {}for idx j in range len hdr idx r[hdr[idx j]] row[idx j]ret append idx r cur close return ... | def processlist **connection_args ret []dbc _connect **connection_args if dbc is None return []cur dbc cursor _execute cur 'SHOWFULLPROCESSLIST' hdr [c[0] for c in cur description]for _ in range cur rowcount row cur fetchone idx_r {}for idx_j in range len hdr idx_r[hdr[idx_j]] row[idx_j]ret append idx_r cur close retur... | 57 |
python-test-4334 | python | What does the code retrieve from the mysql server via " show full processlist " ? | the processlist | def processlist **connection args ret []dbc connect **connection args if dbc is None return []cur dbc cursor execute cur 'SHOWFULLPROCESSLIST' hdr [c[ 0 ] for c in cur description]for in range cur rowcount row cur fetchone idx r {}for idx j in range len hdr idx r[hdr[idx j]] row[idx j]ret append idx r cur close return ... | def processlist **connection_args ret []dbc _connect **connection_args if dbc is None return []cur dbc cursor _execute cur 'SHOWFULLPROCESSLIST' hdr [c[0] for c in cur description]for _ in range cur rowcount row cur fetchone idx_r {}for idx_j in range len hdr idx_r[hdr[idx_j]] row[idx_j]ret append idx_r cur close retur... | 57 |
python-test-4337 | python | How does the code get geometry output ? | by sorted | def get Geometry Output By Nested Ring derivation nested Ring portion Directions loop Lists get Loop Lists By Path derivation None nested Ring vector 3 Loop portion Directions outside Output triangle mesh get Pillars Output loop Lists if len nested Ring inner Nested Rings < 1 return outside Outputshapes [outside Output... | def getGeometryOutputByNestedRing derivation nestedRing portionDirections loopLists getLoopListsByPath derivation None nestedRing vector3Loop portionDirections outsideOutput triangle_mesh getPillarsOutput loopLists if len nestedRing innerNestedRings < 1 return outsideOutputshapes [outsideOutput]for nestedRing innerNest... | 95 |
python-test-4343 | python | What creates a 3-tuple of the fields name ? | iterator for the atomic components of a model definition and relevant data | def atoms cls instance or dict field getter serializable getter instance or dict gettry field getter instance or dict data getexcept Attribute Error passsequences cls field list field getter cls serializables items serializable getter for sequence get in sequences for field name field in sequence yield field name field... | def atoms cls instance_or_dict field_getter serializable_getter instance_or_dict gettry field_getter instance_or_dict _data getexcept AttributeError passsequences cls _field_list field_getter cls _serializables items serializable_getter for sequence get in sequences for field_name field in sequence yield field_name fie... | 53 |
python-test-4344 | python | What does iterator for the atomic components of a model definition and relevant data create ? | a 3-tuple of the fields name | def atoms cls instance or dict field getter serializable getter instance or dict gettry field getter instance or dict data getexcept Attribute Error passsequences cls field list field getter cls serializables items serializable getter for sequence get in sequences for field name field in sequence yield field name field... | def atoms cls instance_or_dict field_getter serializable_getter instance_or_dict gettry field_getter instance_or_dict _data getexcept AttributeError passsequences cls _field_list field_getter cls _serializables items serializable_getter for sequence get in sequences for field_name field in sequence yield field_name fie... | 53 |
python-test-4353 | python | What does the code take ? | hints about what s coming | def Pre Plot num None rows None cols None if num Brewer Initialize Iter num if rows is None and cols is None returnif rows is not None and cols is None cols 1if cols is not None and rows is None rows 1size map { 1 1 8 6 1 2 14 6 1 3 14 6 2 2 10 10 2 3 16 10 3 1 8 10 }if rows cols in size map fig pyplot gcf fig set size... | def PrePlot num None rows None cols None if num _Brewer InitializeIter num if rows is None and cols is None returnif rows is not None and cols is None cols 1if cols is not None and rows is None rows 1size_map { 1 1 8 6 1 2 14 6 1 3 14 6 2 2 10 10 2 3 16 10 3 1 8 10 }if rows cols in size_map fig pyplot gcf fig set_size_... | 111 |
python-test-4357 | python | How did the map composer open to the map ? | with the given map i d | def map view request mapid snapshot None template 'maps/map view html' map obj resolve map request mapid 'base view resourcebase' PERMISSION MSG VIEW if 'access token' in request session access token request session['access token']else access token Noneif snapshot is None config map obj viewer json request user access ... | def map_view request mapid snapshot None template 'maps/map_view html' map_obj _resolve_map request mapid 'base view_resourcebase' _PERMISSION_MSG_VIEW if 'access_token' in request session access_token request session['access_token']else access_token Noneif snapshot is None config map_obj viewer_json request user acces... | 83 |
python-test-4358 | python | What does the code convert into line endings ? | windows line endings | def read file unix endings file name encoding 'utf 8 ' ignore True if ST 3 errors 'ignore' if ignore else 'strict' with open file name 'rt' encoding encoding errors errors as f file content f read else file content read file content file name encoding ignore file content file content replace '\r\n' '\n' return file con... | def read_file_unix_endings file_name encoding 'utf8' ignore True if _ST3 errors 'ignore' if ignore else 'strict' with open file_name 'rt' encoding encoding errors errors as f file_content f read else file_content _read_file_content file_name encoding ignore file_content file_content replace '\r\n' '\n' return file_cont... | 57 |
python-test-4359 | python | What does the code read ? | a file with unix line endings | def read file unix endings file name encoding 'utf 8 ' ignore True if ST 3 errors 'ignore' if ignore else 'strict' with open file name 'rt' encoding encoding errors errors as f file content f read else file content read file content file name encoding ignore file content file content replace '\r\n' '\n' return file con... | def read_file_unix_endings file_name encoding 'utf8' ignore True if _ST3 errors 'ignore' if ignore else 'strict' with open file_name 'rt' encoding encoding errors errors as f file_content f read else file_content _read_file_content file_name encoding ignore file_content file_content replace '\r\n' '\n' return file_cont... | 57 |
python-test-4360 | python | For what purpose did the ctx_rev retrieve ? | for a repository defined by the combination of a name | def get ctx rev app tool shed url name owner changeset revision tool shed url common util get tool shed url from tool shed registry app tool shed url params dict name name owner owner changeset revision changeset revision pathspec ['repository' 'get ctx rev']ctx rev util url get tool shed url password mgr app tool shed... | def get_ctx_rev app tool_shed_url name owner changeset_revision tool_shed_url common_util get_tool_shed_url_from_tool_shed_registry app tool_shed_url params dict name name owner owner changeset_revision changeset_revision pathspec ['repository' 'get_ctx_rev']ctx_rev util url_get tool_shed_url password_mgr app tool_shed... | 69 |
python-test-4361 | python | For what purpose does the code send a request to the tool shed ? | to retrieve the ctx_rev for a repository defined by the combination of a name | def get ctx rev app tool shed url name owner changeset revision tool shed url common util get tool shed url from tool shed registry app tool shed url params dict name name owner owner changeset revision changeset revision pathspec ['repository' 'get ctx rev']ctx rev util url get tool shed url password mgr app tool shed... | def get_ctx_rev app tool_shed_url name owner changeset_revision tool_shed_url common_util get_tool_shed_url_from_tool_shed_registry app tool_shed_url params dict name name owner owner changeset_revision changeset_revision pathspec ['repository' 'get_ctx_rev']ctx_rev util url_get tool_shed_url password_mgr app tool_shed... | 69 |
python-test-4363 | python | What does the code get ? | install server profiles | def get install server profiles install server Noneinstall server info get install server info install server type install server info get 'type' None install server url install server info get 'xmlrpc url' None if install server type 'cobbler' and install server url install server xmlrpclib Server Proxy install server... | def get_install_server_profiles install_server Noneinstall_server_info get_install_server_info install_server_type install_server_info get 'type' None install_server_url install_server_info get 'xmlrpc_url' None if install_server_type 'cobbler' and install_server_url install_server xmlrpclib ServerProxy install_server_... | 63 |
python-test-4364 | python | What does the code get ? | loop inset from clockwise loop | def get Simplified Inset From Clockwise Loop loop radius inset []for point Index begin in enumerate loop center loop[ point Index + 1 % len loop ]end loop[ point Index + 2 % len loop ]add Inset Point From Clockwise Triple begin center end inset radius return get Without Intersections euclidean get Simplified Loop inset... | def getSimplifiedInsetFromClockwiseLoop loop radius inset []for pointIndex begin in enumerate loop center loop[ pointIndex + 1 % len loop ]end loop[ pointIndex + 2 % len loop ]addInsetPointFromClockwiseTriple begin center end inset radius return getWithoutIntersections euclidean getSimplifiedLoop inset radius | 56 |
python-test-4369 | python | How do astropy give consistent results ? | with one pyephem example | def test against pyephem obstime Time u' 2011 - 09 - 1808 50 00 ' location Earth Location lon Angle u'- 109 d 24 m 53 1s' lat Angle u' 33 d 41 m 46 0s' height 30000 0 * u m altaz frame Alt Az obstime obstime location location temperature 15 * u deg C pressure 1 01 * u bar altaz Sky Coord u' 6 8927 d- 60 7665 d' frame a... | def test_against_pyephem obstime Time u'2011-09-1808 50 00' location EarthLocation lon Angle u'-109d24m53 1s' lat Angle u'33d41m46 0s' height 30000 0 * u m altaz_frame AltAz obstime obstime location location temperature 15 * u deg_C pressure 1 01 * u bar altaz SkyCoord u'6 8927d-60 7665d' frame altaz_frame radec_actual... | 138 |
python-test-4370 | python | For what purpose did by the servicetester call the code ? | in order to test unlink_identity service api call | def Test Unlink Identity tester user cookie request dict validator tester validator user id device id tester Get Ids From Cookie user cookie request dict deepcopy request dict actual dict tester Send Request 'unlink identity' user cookie request dict op dict tester Derive Notification Op Dict user id device id request ... | def _TestUnlinkIdentity tester user_cookie request_dict validator tester validator user_id device_id tester GetIdsFromCookie user_cookie request_dict deepcopy request_dict actual_dict tester SendRequest 'unlink_identity' user_cookie request_dict op_dict tester _DeriveNotificationOpDict user_id device_id request_dict va... | 76 |
python-test-4373 | python | What does the code get ? | the ctx file path for the latest revision of filename from the repository manifest up to the value of changeset_revision | def get ctx file path from manifest filename repo changeset revision stripped filename basic util strip path filename for changeset in reversed upper bounded changelog repo changeset revision manifest ctx repo changectx changeset for ctx file in manifest ctx files ctx file name basic util strip path ctx file if ctx fil... | def get_ctx_file_path_from_manifest filename repo changeset_revision stripped_filename basic_util strip_path filename for changeset in reversed_upper_bounded_changelog repo changeset_revision manifest_ctx repo changectx changeset for ctx_file in manifest_ctx files ctx_file_name basic_util strip_path ctx_file if ctx_fil... | 63 |
python-test-4380 | python | What does the code get ? | a value for a specific augeas path cli example | def get path value '' load path None load path check load paths load path aug Augeas loadpath load path ret {}path path rstrip '/' if value path + '/{ 0 }' format value strip '/' try match aug match path except Runtime Error as err return {'error' str err }if match ret[path] aug get path else ret[path] ''return ret | def get path value '' load_path None load_path _check_load_paths load_path aug _Augeas loadpath load_path ret {}path path rstrip '/' if value path + '/{0}' format value strip '/' try _match aug match path except RuntimeError as err return {'error' str err }if _match ret[path] aug get path else ret[path] ''return ret | 60 |
python-test-4383 | python | What sets the attributes of the test object from file system ? | first pass | def set attributes clean test data test type {'client' 1 'server' 2}test time {'short' 1 'medium' 2 'long' 3}test test type test type[data test type lower ]test test time test time[data time lower ]string attributes 'name' 'author' 'test class' 'test category' 'test category' 'sync count' for attribute in string attrib... | def _set_attributes_clean test data test_type {'client' 1 'server' 2}test_time {'short' 1 'medium' 2 'long' 3}test test_type test_type[data test_type lower ]test test_time test_time[data time lower ]string_attributes 'name' 'author' 'test_class' 'test_category' 'test_category' 'sync_count' for attribute in string_attri... | 83 |
python-test-4384 | python | What does first pass set from file system ? | the attributes of the test object | def set attributes clean test data test type {'client' 1 'server' 2}test time {'short' 1 'medium' 2 'long' 3}test test type test type[data test type lower ]test test time test time[data time lower ]string attributes 'name' 'author' 'test class' 'test category' 'test category' 'sync count' for attribute in string attrib... | def _set_attributes_clean test data test_type {'client' 1 'server' 2}test_time {'short' 1 'medium' 2 'long' 3}test test_type test_type[data test_type lower ]test test_time test_time[data time lower ]string_attributes 'name' 'author' 'test_class' 'test_category' 'test_category' 'sync_count' for attribute in string_attri... | 83 |
python-test-4386 | python | What does a site have ? | inventory | def org site has inv row tablename 'org facility' if not current deployment settings has module 'inv' return Falseif hasattr row tablename row row[tablename]try id row idexcept Attribute Error return Nones 3 db current s3 dbitable s3 db inv inv itemstable s3 db[tablename]query itable deleted True & stable id id & itabl... | def org_site_has_inv row tablename 'org_facility' if not current deployment_settings has_module 'inv' return Falseif hasattr row tablename row row[tablename]try id row idexcept AttributeError return Nones3db current s3dbitable s3db inv_inv_itemstable s3db[tablename]query itable deleted True & stable id id & itable site... | 79 |
python-test-4395 | python | What does a regex match ? | ordered permutations of a sentences words | def ordered permutation regex sentence sentence RE REF sub '\\ 1 ' sentence sentence RE REF LANG sub '\\ 1 ' sentence sentence RE SELF REF sub '' sentence words sentence split combinations itertools product True False repeat len words solution []for combination in combinations comb []for iword word in enumerate words i... | def ordered_permutation_regex sentence sentence _RE_REF sub '\\1' sentence sentence _RE_REF_LANG sub '\\1' sentence sentence _RE_SELF_REF sub '' sentence words sentence split combinations itertools product True False repeat len words solution []for combination in combinations comb []for iword word in enumerate words if... | 100 |
python-test-4400 | python | What does the code create ? | a complete latex document with colorized source code | def latex highlight classified text title 'python' commands default latex commands document default latex document macros '\n' join '\\newcommand{\\py%s}[ 1 ]{%s}' % c for c in commands items result []for kind text in classified text if kind result append '\\py%s{' % kind result append alltt escape text if kind result ... | def latex_highlight classified_text title 'python' commands default_latex_commands document default_latex_document macros '\n' join '\\newcommand{\\py%s}[1]{%s}' % c for c in commands items result []for kind text in classified_text if kind result append '\\py%s{' % kind result append alltt_escape text if kind result ap... | 66 |
python-test-4401 | python | How do simple preductions test ? | using weights just produced | def test predict 1 sp Sequence Pattern ts 2 s TF Learn Seq 2 Seq sp verbose 1 wfn 'test %s' % ts 2 s canonical weights fn 0 print 'usingweightsfilename%s' % wfn tf reset default graph prediction y ts 2 s predict Xin range 10 weights input fn wfn assert len prediction 10 | def test_predict1 sp SequencePattern ts2s TFLearnSeq2Seq sp verbose 1 wfn 'test_%s' % ts2s canonical_weights_fn 0 print 'usingweightsfilename%s' % wfn tf reset_default_graph prediction y ts2s predict Xin range 10 weights_input_fn wfn assert len prediction 10 | 54 |
python-test-4402 | python | What does the code execute ? | a runner function | def runner name **kwargs jid kwargs pop ' orchestration jid ' None saltenv kwargs pop ' env ' 'base' full return kwargs pop 'full return' False kwargs salt utils clean kwargs **kwargs if 'master job cache' not in opts master config os path join os path dirname opts ['conf file'] 'master' master opts salt config master ... | def runner name **kwargs jid kwargs pop '__orchestration_jid__' None saltenv kwargs pop '__env__' 'base' full_return kwargs pop 'full_return' False kwargs salt utils clean_kwargs **kwargs if 'master_job_cache' not in __opts__ master_config os path join os path dirname __opts__['conf_file'] 'master' master_opts salt con... | 123 |
python-test-4403 | python | What does the code retrieve ? | the number of elements to show | def get elements count N N1 W2 thresh 0 9max count 0total counts 0 0for i in xrange N w W2 [ i]wa np abs w total wa sum s np asarray sorted wa count 1while s[ - count ] sum < thresh * total count + 1if count > max count max count counttotal counts + countave total counts / float N print 'averageneededfilters' ave count... | def get_elements_count N N1 W2 thresh 0 9max_count 0total_counts 0 0for i in xrange N w W2[ i]wa np abs w total wa sum s np asarray sorted wa count 1while s[ - count ] sum < thresh * total count + 1if count > max_count max_count counttotal_counts + countave total_counts / float N print 'averageneededfilters' ave count ... | 101 |
python-test-4404 | python | What does this function find ? | the get_notepad_pages ( ) based on the configuration | def find get notepad pages if config WEB GET NOTEPAD PAGES is None return Noneif type config WEB GET NOTEPAD PAGES is not tuple config WEB GET NOTEPAD PAGES config WEB GET NOTEPAD PAGES return functools partial GET NOTEPAD PAGES[config WEB GET NOTEPAD PAGES[ 0 ]] *config WEB GET NOTEPAD PAGES[ 1 ] | def _find_get_notepad_pages if config WEB_GET_NOTEPAD_PAGES is None return Noneif type config WEB_GET_NOTEPAD_PAGES is not tuple config WEB_GET_NOTEPAD_PAGES config WEB_GET_NOTEPAD_PAGES return functools partial GET_NOTEPAD_PAGES[config WEB_GET_NOTEPAD_PAGES[0]] *config WEB_GET_NOTEPAD_PAGES[1] | 53 |
python-test-4409 | python | What does the code define ? | a llvm function for atomic increment / decrement | def define atomic inc dec module op ordering ftype ir Function Type word type [ word type as pointer ] fn atomic ir Function module ftype name 'nrt atomic {0 }' format op [ptr] fn atomic argsbb fn atomic append basic block builder ir IR Builder bb ONE ir Constant word type 1 if not disable atomicity oldval builder atom... | def _define_atomic_inc_dec module op ordering ftype ir FunctionType _word_type [_word_type as_pointer ] fn_atomic ir Function module ftype name 'nrt_atomic_{0}' format op [ptr] fn_atomic argsbb fn_atomic append_basic_block builder ir IRBuilder bb ONE ir Constant _word_type 1 if not _disable_atomicity oldval builder ato... | 96 |
python-test-4417 | python | In which direction may a draft registration be created ? | with which | def get metaschemas *args **kwargs count request args get 'count' 100 include request args get 'include' 'latest' meta schemas []if include 'latest' schema names list Meta Schema objects all values list 'name' flat True distinct for name in schema names meta schema set Meta Schema find Q 'name' 'eq' name & Q 'schema ve... | def get_metaschemas *args **kwargs count request args get 'count' 100 include request args get 'include' 'latest' meta_schemas []if include 'latest' schema_names list MetaSchema objects all values_list 'name' flat True distinct for name in schema_names meta_schema_set MetaSchema find Q 'name' 'eq' name & Q 'schema_vers... | 116 |
python-test-4418 | python | What is default behaviour of pushd adding to the stack ? | the current dir | def test pushd appends current dir to stack if empty mox Mox old os io osio os mox Create Mock Anything class My Fs io File System stack []@classmethoddef current dir cls return 'shouldbecurrentdir'io os chdir 'somewhere' mox Replay All try assert len My Fs stack is 0 My Fs pushd 'somewhere' assert len My Fs stack is 2... | def test_pushd_appends_current_dir_to_stack_if_empty mox Mox old_os io osio os mox CreateMockAnything class MyFs io FileSystem stack []@classmethoddef current_dir cls return 'shouldbecurrentdir'io os chdir 'somewhere' mox ReplayAll try assert len MyFs stack is 0 MyFs pushd 'somewhere' assert len MyFs stack is 2 assert_... | 74 |
python-test-4419 | python | What is adding the current dir to the stack ? | default behaviour of pushd | def test pushd appends current dir to stack if empty mox Mox old os io osio os mox Create Mock Anything class My Fs io File System stack []@classmethoddef current dir cls return 'shouldbecurrentdir'io os chdir 'somewhere' mox Replay All try assert len My Fs stack is 0 My Fs pushd 'somewhere' assert len My Fs stack is 2... | def test_pushd_appends_current_dir_to_stack_if_empty mox Mox old_os io osio os mox CreateMockAnything class MyFs io FileSystem stack []@classmethoddef current_dir cls return 'shouldbecurrentdir'io os chdir 'somewhere' mox ReplayAll try assert len MyFs stack is 0 MyFs pushd 'somewhere' assert len MyFs stack is 2 assert_... | 74 |
python-test-4420 | python | What does the code compute ? | a markov chain associated with a discretized version of the linear gaussian ar(1 ) process y_{t+1 } = rho * y_t + u_{t+1 } using tauchens method | def tauchen rho sigma u m 3 n 7 std y np sqrt sigma u ** 2 / 1 - rho ** 2 x max m * std y x min - x max x np linspace x min x max n step x max - x min / n - 1 half step 0 5 * step P np empty n n fill tauchen x P n rho sigma u half step mc Markov Chain P state values x return mc | def tauchen rho sigma_u m 3 n 7 std_y np sqrt sigma_u ** 2 / 1 - rho ** 2 x_max m * std_y x_min - x_max x np linspace x_min x_max n step x_max - x_min / n - 1 half_step 0 5 * step P np empty n n _fill_tauchen x P n rho sigma_u half_step mc MarkovChain P state_values x return mc | 82 |
python-test-4424 | python | When do attachments work correctly ? | after merging | def test doc api merge children en tokenizer text u'WKR Oplayedsongsbythebeachboysallnight'doc en tokenizer text assert len doc 9 doc merge doc[ 4 ] idx doc[ 6 ] idx + len doc[ 6 ] u'NAMED' u'LEMMA' u'TYPE' for word in doc if word i < word head i assert word in list word head lefts elif word i > word head i assert word... | def test_doc_api_merge_children en_tokenizer text u'WKROplayedsongsbythebeachboysallnight'doc en_tokenizer text assert len doc 9 doc merge doc[4] idx doc[6] idx + len doc[6] u'NAMED' u'LEMMA' u'TYPE' for word in doc if word i < word head i assert word in list word head lefts elif word i > word head i assert word in lis... | 68 |
python-test-4425 | python | What does the code update ? | the given apikey with the given description | def update api key description api Key description region None key None keyid None profile None try conn get conn region region key key keyid keyid profile profile response api key patch replace conn api Key '/description' description return {'updated' True 'api Key' convert datetime str response }except Client Error a... | def update_api_key_description apiKey description region None key None keyid None profile None try conn _get_conn region region key key keyid keyid profile profile response _api_key_patch_replace conn apiKey '/description' description return {'updated' True 'apiKey' _convert_datetime_str response }except ClientError as... | 64 |
python-test-4428 | python | When does string return ? | since tag-7 digit commit i d | def get tag commit try return check output ['git' 'describe' '--tags'] stderr STDOUT cwd os path dirname os path abspath file except Called Process Error as e logger error ' Errorcallinggit "{}"\noutput "{}"' format e e output return Noneexcept OS Error as e logger error ' Couldnotcallgit isitinstalled?errormsg "{}"' f... | def get_tag_commit try return check_output ['git' 'describe' '--tags'] stderr STDOUT cwd os path dirname os path abspath __file__ except CalledProcessError as e logger error 'Errorcallinggit "{}"\noutput "{}"' format e e output return Noneexcept OSError as e logger error 'Couldnotcallgit isitinstalled?errormsg "{}"' fo... | 53 |
python-test-4429 | python | What did the code let ? | this thing fly | def main args get args si Smart Connect host args host user args user pwd args password port args port atexit register Disconnect si content si Retrieve Content template Nonetemplate get obj content [vim Virtual Machine] args template if template clone vm content template args vm name si args datacenter name args vm fo... | def main args get_args si SmartConnect host args host user args user pwd args password port args port atexit register Disconnect si content si RetrieveContent template Nonetemplate get_obj content [vim VirtualMachine] args template if template clone_vm content template args vm_name si args datacenter_name args vm_folde... | 69 |
python-test-4435 | python | What does the command output not contain ? | log records from the provided log categories | @then 'thecommandoutputshouldnotcontainlogrecordsfromcategories' def step command output should not contain log records from categories context assert context table 'REQUIRE context table'context table require column 'category' record schema context log record row schema Log Record Table annotate with row schema contex... | @then 'thecommandoutputshouldnotcontainlogrecordsfromcategories' def step_command_output_should_not_contain_log_records_from_categories context assert context table 'REQUIRE context table'context table require_column 'category' record_schema context log_record_row_schemaLogRecordTable annotate_with_row_schema context t... | 57 |
python-test-4436 | python | What not contains log records from the provided log categories ? | the command output | @then 'thecommandoutputshouldnotcontainlogrecordsfromcategories' def step command output should not contain log records from categories context assert context table 'REQUIRE context table'context table require column 'category' record schema context log record row schema Log Record Table annotate with row schema contex... | @then 'thecommandoutputshouldnotcontainlogrecordsfromcategories' def step_command_output_should_not_contain_log_records_from_categories context assert context table 'REQUIRE context table'context table require_column 'category' record_schema context log_record_row_schemaLogRecordTable annotate_with_row_schema context t... | 57 |
python-test-4437 | python | Does the command output contain log records from the provided log categories ? | No | @then 'thecommandoutputshouldnotcontainlogrecordsfromcategories' def step command output should not contain log records from categories context assert context table 'REQUIRE context table'context table require column 'category' record schema context log record row schema Log Record Table annotate with row schema contex... | @then 'thecommandoutputshouldnotcontainlogrecordsfromcategories' def step_command_output_should_not_contain_log_records_from_categories context assert context table 'REQUIRE context table'context table require_column 'category' record_schema context log_record_row_schemaLogRecordTable annotate_with_row_schema context t... | 57 |
python-test-4439 | python | What does the code update ? | an accounts metadata | def post account url token headers http conn None response dict None service token None query string None data None if http conn parsed conn http connelse parsed conn http connection url method 'POST'path parsed pathif query string path + '?' + query string headers['X- Auth- Token'] tokenif service token headers['X- Se... | def post_account url token headers http_conn None response_dict None service_token None query_string None data None if http_conn parsed conn http_connelse parsed conn http_connection url method 'POST'path parsed pathif query_string path + '?' + query_string headers['X-Auth-Token'] tokenif service_token headers['X-Servi... | 116 |
python-test-4440 | python | What does the code assert ? | a config can be changed with keyword args | def test config alterations kwargs class Line Config Config no prefix Trueshow legend Falsefill Truepretty print Truex labels ['a' 'b' 'c']config Line Config line 1 Line config line 1 add ' ' [1 2 3] l1 line 1 render line 1 stroke Falsel 1 bis line 1 render assert l1 l1 bis line 2 Line config line 2 add ' ' [1 2 3] l2 ... | def test_config_alterations_kwargs class LineConfig Config no_prefix Trueshow_legend Falsefill Truepretty_print Truex_labels ['a' 'b' 'c']config LineConfig line1 Line config line1 add '_' [1 2 3] l1 line1 render line1 stroke Falsel1bis line1 render assert l1 l1bis line2 Line config line2 add '_' [1 2 3] l2 line2 render... | 106 |
python-test-4441 | python | How can a config be changed ? | with keyword args | def test config alterations kwargs class Line Config Config no prefix Trueshow legend Falsefill Truepretty print Truex labels ['a' 'b' 'c']config Line Config line 1 Line config line 1 add ' ' [1 2 3] l1 line 1 render line 1 stroke Falsel 1 bis line 1 render assert l1 l1 bis line 2 Line config line 2 add ' ' [1 2 3] l2 ... | def test_config_alterations_kwargs class LineConfig Config no_prefix Trueshow_legend Falsefill Truepretty_print Truex_labels ['a' 'b' 'c']config LineConfig line1 Line config line1 add '_' [1 2 3] l1 line1 render line1 stroke Falsel1bis line1 render assert l1 l1bis line2 Line config line2 add '_' [1 2 3] l2 line2 render... | 106 |
python-test-4442 | python | What does the code retrieve ? | the reparse point data structure for the given path | def get reparse data path if sys getwindowsversion major < 6 raise Salt Invocation Error ' Symlinksareonlysupportedon Windows Vistaorlater ' path os path normpath path if not is reparse point path return Nonefile Handle Nonetry file Handle win 32 file Create File W path 2147483648 1 None 3 2097152 33554432 reparse Data... | def _get_reparse_data path if sys getwindowsversion major < 6 raise SaltInvocationError 'SymlinksareonlysupportedonWindowsVistaorlater ' path os path normpath path if not _is_reparse_point path return NonefileHandle Nonetry fileHandle win32file CreateFileW path 2147483648 1 None 3 2097152 33554432 reparseData win32file... | 77 |
python-test-4443 | python | What does the code serialize for json ? | non - serializable data | def json handler obj if isinstance obj datetime date datetime timedelta datetime datetime return unicode obj elif isinstance obj Local Proxy return unicode obj elif isinstance obj frappe model document Base Document doc obj as dict no nulls True return docelif type obj type or isinstance obj Exception return repr obj e... | def json_handler obj if isinstance obj datetime date datetime timedelta datetime datetime return unicode obj elif isinstance obj LocalProxy return unicode obj elif isinstance obj frappe model document BaseDocument doc obj as_dict no_nulls True return docelif type obj type or isinstance obj Exception return repr obj els... | 64 |
python-test-4444 | python | What does the code create ? | a manhole server service | def make Service options svc service Multi Service namespace options['namespace']if namespace is None namespace {}checker checkers File Password DB options['passwd'] if options['telnet Port'] telnet Realm Stupid Realm telnet Telnet Bootstrap Protocol insults Server Protocol manhole Colored Manhole namespace telnet Port... | def makeService options svc service MultiService namespace options['namespace']if namespace is None namespace {}checker checkers FilePasswordDB options['passwd'] if options['telnetPort'] telnetRealm _StupidRealm telnet TelnetBootstrapProtocol insults ServerProtocol manhole ColoredManhole namespace telnetPortal portal P... | 121 |
python-test-4449 | python | What does the code generate ? | a data - structure that represents the current configuration model | def generate model root class ROOT CLASS classes result {}result {u'root' fqpn root class u'classes' classes result}classes {root class}while classes klass classes pop klass name fqpn klass if klass name in classes result continueif issubclass klass P Record P Class to model precord modelelif issubclass klass Checked P... | def generate_model root_class ROOT_CLASS classes_result {}result {u'root' fqpn root_class u'classes' classes_result}classes {root_class}while classes klass classes pop klass_name fqpn klass if klass_name in classes_result continueif issubclass klass PRecord PClass to_model _precord_modelelif issubclass klass CheckedPMa... | 82 |
python-test-4450 | python | What represents the current configuration model ? | a data - structure | def generate model root class ROOT CLASS classes result {}result {u'root' fqpn root class u'classes' classes result}classes {root class}while classes klass classes pop klass name fqpn klass if klass name in classes result continueif issubclass klass P Record P Class to model precord modelelif issubclass klass Checked P... | def generate_model root_class ROOT_CLASS classes_result {}result {u'root' fqpn root_class u'classes' classes_result}classes {root_class}while classes klass classes pop klass_name fqpn klass if klass_name in classes_result continueif issubclass klass PRecord PClass to_model _precord_modelelif issubclass klass CheckedPMa... | 82 |
python-test-4451 | python | What does a data - structure represent ? | the current configuration model | def generate model root class ROOT CLASS classes result {}result {u'root' fqpn root class u'classes' classes result}classes {root class}while classes klass classes pop klass name fqpn klass if klass name in classes result continueif issubclass klass P Record P Class to model precord modelelif issubclass klass Checked P... | def generate_model root_class ROOT_CLASS classes_result {}result {u'root' fqpn root_class u'classes' classes_result}classes {root_class}while classes klass classes pop klass_name fqpn klass if klass_name in classes_result continueif issubclass klass PRecord PClass to_model _precord_modelelif issubclass klass CheckedPMa... | 82 |
python-test-4452 | python | What does the code expand ? | windows user environment variables based | def Expand Windows User Environment Variables data string knowledge base sid None username None win environ regex re compile '% [^%]+? %' components []offset 0for match in win environ regex finditer data string components append data string[offset match start ] kb user knowledge base Get User sid sid username username ... | def ExpandWindowsUserEnvironmentVariables data_string knowledge_base sid None username None win_environ_regex re compile '% [^%]+? %' components []offset 0for match in win_environ_regex finditer data_string components append data_string[offset match start ] kb_user knowledge_base GetUser sid sid username username kb_va... | 97 |
python-test-4453 | python | What does the code replace with param description ? | $ meta in docstring | def insert meta param description *args **kwargs if not args return lambda f insert meta param description f **kwargs f args[ 0 ]if f doc indent '' * kwargs get 'pad' 8 body textwrap wrap META DESCRIPTION initial indent indent subsequent indent indent width 78 descr '{ 0 }\n{ 1 }' format META TYPES '\n' join body f doc... | def insert_meta_param_description *args **kwargs if not args return lambda f insert_meta_param_description f **kwargs f args[0]if f __doc__ indent '' * kwargs get 'pad' 8 body textwrap wrap _META_DESCRIPTION initial_indent indent subsequent_indent indent width 78 descr '{0}\n{1}' format _META_TYPES '\n' join body f __d... | 66 |
python-test-4458 | python | Where do 3 dimensions represent using x ? | in a heatmap chart | def Heat Map data x None y None values None stat 'count' xgrid False ygrid False hover tool True hover text None **kw kw['x'] xkw['y'] ykw['values'] valueskw['stat'] statchart create and build Heat Map Builder data xgrid xgrid ygrid ygrid **kw if hover tool tooltip build agg tooltip hover text hover text aggregated col... | def HeatMap data x None y None values None stat 'count' xgrid False ygrid False hover_tool True hover_text None **kw kw['x'] xkw['y'] ykw['values'] valueskw['stat'] statchart create_and_build HeatMapBuilder data xgrid xgrid ygrid ygrid **kw if hover_tool tooltip build_agg_tooltip hover_text hover_text aggregated_col va... | 63 |
python-test-4459 | python | What represent in a heatmap chart ? | 3 dimensions | def Heat Map data x None y None values None stat 'count' xgrid False ygrid False hover tool True hover text None **kw kw['x'] xkw['y'] ykw['values'] valueskw['stat'] statchart create and build Heat Map Builder data xgrid xgrid ygrid ygrid **kw if hover tool tooltip build agg tooltip hover text hover text aggregated col... | def HeatMap data x None y None values None stat 'count' xgrid False ygrid False hover_tool True hover_text None **kw kw['x'] xkw['y'] ykw['values'] valueskw['stat'] statchart create_and_build HeatMapBuilder data xgrid xgrid ygrid ygrid **kw if hover_tool tooltip build_agg_tooltip hover_text hover_text aggregated_col va... | 63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.