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-6588 | python | What does the code check ? | enrollment mode and status | def enrollment mode display enrollment mode verification status course id course mode slugs [mode slug for mode in Course Mode modes for course course id ]if enrollment mode Course Mode VERIFIED if verification status in [VERIFY STATUS NEED TO VERIFY VERIFY STATUS SUBMITTED VERIFY STATUS APPROVED] display mode DISPLAY ... | def _enrollment_mode_display enrollment_mode verification_status course_id course_mode_slugs [mode slug for mode in CourseMode modes_for_course course_id ]if enrollment_mode CourseMode VERIFIED if verification_status in [VERIFY_STATUS_NEED_TO_VERIFY VERIFY_STATUS_SUBMITTED VERIFY_STATUS_APPROVED] display_mode DISPLAY_V... | 91 |
python-test-6590 | python | How can that be ignored ? | by passing --yes as parameter | def confirmation option *param decls **attrs def decorator f def callback ctx param value if not value ctx abort attrs setdefault 'is flag' True attrs setdefault 'callback' callback attrs setdefault 'expose value' False attrs setdefault 'prompt' ' Doyouwanttocontinue?' attrs setdefault 'help' ' Confirmtheactionwithoutp... | def confirmation_option *param_decls **attrs def decorator f def callback ctx param value if not value ctx abort attrs setdefault 'is_flag' True attrs setdefault 'callback' callback attrs setdefault 'expose_value' False attrs setdefault 'prompt' 'Doyouwanttocontinue?' attrs setdefault 'help' 'Confirmtheactionwithoutpro... | 55 |
python-test-6593 | python | What does the user have ? | staff access to the wiki represented by wiki_slug | def has wiki staff access user wiki slug modstore course keys modstore get courses for wiki wiki slug if wiki slug endswith ' ' and slug is numerical wiki slug[ -1 ] course keys extend modstore get courses for wiki wiki slug[ -1 ] for course key in course keys course modstore get course course key if courseware access ... | def _has_wiki_staff_access user wiki_slug modstore course_keys modstore get_courses_for_wiki wiki_slug if wiki_slug endswith '_' and slug_is_numerical wiki_slug[ -1 ] course_keys extend modstore get_courses_for_wiki wiki_slug[ -1 ] for course_key in course_keys course modstore get_course course_key if courseware access... | 69 |
python-test-6594 | python | What does the code compute ? | the logmgf value given q and privacy eps | def logmgf exact q priv eps l if q < 0 5 t one 1 - q * math pow 1 - q / 1 - math exp priv eps * q l t two q * math exp priv eps * l t t one + t two try log t math log t except Value Error print ' Got Value Errorinmath logforvalues ' + str q priv eps l t log t priv eps * l else log t priv eps * l return min 0 5 * priv e... | def logmgf_exact q priv_eps l if q < 0 5 t_one 1 - q * math pow 1 - q / 1 - math exp priv_eps * q l t_two q * math exp priv_eps * l t t_one + t_two try log_t math log t except ValueError print 'GotValueErrorinmath logforvalues ' + str q priv_eps l t log_t priv_eps * l else log_t priv_eps * l return min 0 5 * priv_eps *... | 107 |
python-test-6595 | python | What did this function set into the configuration singleton ? | some needed attributes | def set Conf Attributes debug Msg 'initializingtheconfiguration'logger debug debug Msg conf auth Username Noneconf auth Password Noneconf boundaries []conf cj Noneconf dbms Connector Noneconf dbms Handler Noneconf dns Server Noneconf dump Path Noneconf hash DB Noneconf hash DB File Noneconf http Headers []conf hostname... | def _setConfAttributes debugMsg 'initializingtheconfiguration'logger debug debugMsg conf authUsername Noneconf authPassword Noneconf boundaries []conf cj Noneconf dbmsConnector Noneconf dbmsHandler Noneconf dnsServer Noneconf dumpPath Noneconf hashDB Noneconf hashDBFile Noneconf httpHeaders []conf hostname Noneconf ipv... | 83 |
python-test-6599 | python | What does the code create ? | a scenario for a stack of actions | def create scenario actions logs None keys [str i for i in range len actions ]key provider create mock key provider keys digest provider Mock Digest Provider actions logs digest validator Mock def validate bucket key public key digest data digest str if ' invalid' in digest data raise Digest Error 'invaliderror' digest... | def create_scenario actions logs None keys [str i for i in range len actions ]key_provider create_mock_key_provider keys digest_provider MockDigestProvider actions logs digest_validator Mock def validate bucket key public_key digest_data digest_str if '_invalid' in digest_data raise DigestError 'invaliderror' digest_va... | 62 |
python-test-6602 | python | What does the code take ? | the results produced by each bear | def print result results file dict retval print results section log printer file diff dict ignore ranges console printer min severity str str section get 'min severity' 'INFO' upper min severity RESULT SEVERITY str dict get min severity str 'INFO' results list filter lambda result type result is Result and result sever... | def print_result results file_dict retval print_results section log_printer file_diff_dict ignore_ranges console_printer min_severity_str str section get 'min_severity' 'INFO' upper min_severity RESULT_SEVERITY str_dict get min_severity_str 'INFO' results list filter lambda result type result is Result and result sever... | 100 |
python-test-6603 | python | What does the code give them ? | to the print_results method to present to the user | def print result results file dict retval print results section log printer file diff dict ignore ranges console printer min severity str str section get 'min severity' 'INFO' upper min severity RESULT SEVERITY str dict get min severity str 'INFO' results list filter lambda result type result is Result and result sever... | def print_result results file_dict retval print_results section log_printer file_diff_dict ignore_ranges console_printer min_severity_str str section get 'min_severity' 'INFO' upper min_severity RESULT_SEVERITY str_dict get min_severity_str 'INFO' results list filter lambda result type result is Result and result sever... | 100 |
python-test-6604 | python | How does the code get the current form data ? | with prepared | def get form data form prepared False if isinstance form Form Group data {}for subform in form forms values data update get form data subform prepared prepared return dataif isinstance form Base Form Set data {}for subform in chain [form management form] form forms data update get form data subform prepared prepared re... | def get_form_data form prepared False if isinstance form FormGroup data {}for subform in form forms values data update get_form_data subform prepared prepared return dataif isinstance form BaseFormSet data {}for subform in chain [form management_form] form forms data update get_form_data subform prepared prepared retur... | 113 |
python-test-6605 | python | What does the code get with prepared ? | the current form data | def get form data form prepared False if isinstance form Form Group data {}for subform in form forms values data update get form data subform prepared prepared return dataif isinstance form Base Form Set data {}for subform in chain [form management form] form forms data update get form data subform prepared prepared re... | def get_form_data form prepared False if isinstance form FormGroup data {}for subform in form forms values data update get_form_data subform prepared prepared return dataif isinstance form BaseFormSet data {}for subform in chain [form management_form] form forms data update get_form_data subform prepared prepared retur... | 113 |
python-test-6606 | python | What proposed in [ colette2010 ] ? | the ask - tell model | def ea Generate Update toolbox ngen halloffame None stats None verbose debug logbook tools Logbook logbook header ['gen' 'nevals'] + stats fields if stats else [] for gen in xrange ngen population toolbox generate fitnesses toolbox map toolbox evaluate population for ind fit in zip population fitnesses ind fitness valu... | def eaGenerateUpdate toolbox ngen halloffame None stats None verbose __debug__ logbook tools Logbook logbook header ['gen' 'nevals'] + stats fields if stats else [] for gen in xrange ngen population toolbox generate fitnesses toolbox map toolbox evaluate population for ind fit in zip population fitnesses ind fitness va... | 87 |
python-test-6607 | python | Where did the ask - tell model propose ? | in [ colette2010 ] | def ea Generate Update toolbox ngen halloffame None stats None verbose debug logbook tools Logbook logbook header ['gen' 'nevals'] + stats fields if stats else [] for gen in xrange ngen population toolbox generate fitnesses toolbox map toolbox evaluate population for ind fit in zip population fitnesses ind fitness valu... | def eaGenerateUpdate toolbox ngen halloffame None stats None verbose __debug__ logbook tools Logbook logbook header ['gen' 'nevals'] + stats fields if stats else [] for gen in xrange ngen population toolbox generate fitnesses toolbox map toolbox evaluate population for ind fit in zip population fitnesses ind fitness va... | 87 |
python-test-6610 | python | What does the code compute ? | the matrix solution of the orthogonal procrustes problem | def orthogonal procrustes A B check finite True if check finite A np asarray chkfinite A B np asarray chkfinite B else A np asanyarray A B np asanyarray B if A ndim 2 raise Value Error 'expectedndimtobe 2 butobserved%s' % A ndim if A shape B shape raise Value Error 'theshapesof Aand Bdiffer %svs%s ' % A shape B shape u... | def orthogonal_procrustes A B check_finite True if check_finite A np asarray_chkfinite A B np asarray_chkfinite B else A np asanyarray A B np asanyarray B if A ndim 2 raise ValueError 'expectedndimtobe2 butobserved%s' % A ndim if A shape B shape raise ValueError 'theshapesofAandBdiffer %svs%s ' % A shape B shape u w vt... | 80 |
python-test-6612 | python | What extracts to a new dir under parent_dir ? | configs | def extract configs configs parent dir config dir os path join parent dir 'configs' if os path isdir configs shutil copytree configs config dir symlinks True elif tarfile is tarfile configs with tarfile open configs 'r' as tar tar extractall config dir else raise errors Error ' Unknownconfigurationsfiletype' return con... | def extract_configs configs parent_dir config_dir os path join parent_dir 'configs' if os path isdir configs shutil copytree configs config_dir symlinks True elif tarfile is_tarfile configs with tarfile open configs 'r' as tar tar extractall config_dir else raise errors Error 'Unknownconfigurationsfiletype' return conf... | 51 |
python-test-6613 | python | Where does configs extract to a new dir ? | under parent_dir | def extract configs configs parent dir config dir os path join parent dir 'configs' if os path isdir configs shutil copytree configs config dir symlinks True elif tarfile is tarfile configs with tarfile open configs 'r' as tar tar extractall config dir else raise errors Error ' Unknownconfigurationsfiletype' return con... | def extract_configs configs parent_dir config_dir os path join parent_dir 'configs' if os path isdir configs shutil copytree configs config_dir symlinks True elif tarfile is_tarfile configs with tarfile open configs 'r' as tar tar extractall config_dir else raise errors Error 'Unknownconfigurationsfiletype' return conf... | 51 |
python-test-6614 | python | What does the code initialize ? | the site configuration | def init siteconfig app created models verbosity db None **kwargs try site Site objects get current except Site Does Not Exist from django contrib sites management import create default sitecreate default site app created models verbosity db db site Site objects get current siteconfig is new Site Configuration objects ... | def init_siteconfig app created_models verbosity db None **kwargs try site Site objects get_current except Site DoesNotExist from django contrib sites management import create_default_sitecreate_default_site app created_models verbosity db db site Site objects get_current siteconfig is_new SiteConfiguration objects get... | 134 |
python-test-6617 | python | What does the code require ? | a package source | def source name uri distribution *components from fabtools require import file as require filepath '/etc/apt/sources list d/% name s list' % locals components '' join components source line 'deb% uri s% distribution s% components s\n' % locals with watch path as config require file path path contents source line use su... | def source name uri distribution *components from fabtools require import file as require_filepath '/etc/apt/sources list d/% name s list' % locals components '' join components source_line 'deb% uri s% distribution s% components s\n' % locals with watch path as config require_file path path contents source_line use_su... | 66 |
python-test-6620 | python | What will use a single call to this manager ? | most test cases | @contextmanagerdef persistent grades feature flags global flag enabled for all courses False course id None enabled for course False Persistent Grades Enabled Flag objects create enabled global flag enabled for all courses enabled for all courses if course id Course Persistent Grades Flag objects create course id cours... | @contextmanagerdef persistent_grades_feature_flags global_flag enabled_for_all_courses False course_id None enabled_for_course False PersistentGradesEnabledFlag objects create enabled global_flag enabled_for_all_courses enabled_for_all_courses if course_id CoursePersistentGradesFlag objects create course_id course_id e... | 54 |
python-test-6621 | python | What will most test cases use ? | a single call to this manager | @contextmanagerdef persistent grades feature flags global flag enabled for all courses False course id None enabled for course False Persistent Grades Enabled Flag objects create enabled global flag enabled for all courses enabled for all courses if course id Course Persistent Grades Flag objects create course id cours... | @contextmanagerdef persistent_grades_feature_flags global_flag enabled_for_all_courses False course_id None enabled_for_course False PersistentGradesEnabledFlag objects create enabled global_flag enabled_for_all_courses enabled_for_all_courses if course_id CoursePersistentGradesFlag objects create course_id course_id e... | 54 |
python-test-6622 | python | What provides all the interfaces ? | the assigned value | def interface field interfaces **field kwargs if not isinstance interfaces tuple raise Type Error ' The``interfaces``argumentmustbeatuple Got { r}' format interfaces original invariant field kwargs pop 'invariant' None def invariant value error messages []if original invariant is not None original invariant result orig... | def interface_field interfaces **field_kwargs if not isinstance interfaces tuple raise TypeError 'The``interfaces``argumentmustbeatuple Got { r}' format interfaces original_invariant field_kwargs pop 'invariant' None def invariant value error_messages []if original_invariant is not None original_invariant_result _origi... | 112 |
python-test-6623 | python | What does a pclass field check ? | that the assigned value provides all the interfaces | def interface field interfaces **field kwargs if not isinstance interfaces tuple raise Type Error ' The``interfaces``argumentmustbeatuple Got { r}' format interfaces original invariant field kwargs pop 'invariant' None def invariant value error messages []if original invariant is not None original invariant result orig... | def interface_field interfaces **field_kwargs if not isinstance interfaces tuple raise TypeError 'The``interfaces``argumentmustbeatuple Got { r}' format interfaces original_invariant field_kwargs pop 'invariant' None def invariant value error_messages []if original_invariant is not None original_invariant_result _origi... | 112 |
python-test-6624 | python | What does the assigned value provide ? | all the interfaces | def interface field interfaces **field kwargs if not isinstance interfaces tuple raise Type Error ' The``interfaces``argumentmustbeatuple Got { r}' format interfaces original invariant field kwargs pop 'invariant' None def invariant value error messages []if original invariant is not None original invariant result orig... | def interface_field interfaces **field_kwargs if not isinstance interfaces tuple raise TypeError 'The``interfaces``argumentmustbeatuple Got { r}' format interfaces original_invariant field_kwargs pop 'invariant' None def invariant value error_messages []if original_invariant is not None original_invariant_result _origi... | 112 |
python-test-6627 | python | How do image intensity range return ? | based on desired value type | def intensity range image range values 'image' clip negative False if range values 'dtype' range values image dtype typeif range values 'image' i min np min image i max np max image elif range values in DTYPE RANGE i min i max DTYPE RANGE[range values]if clip negative i min 0else i min i max range valuesreturn i min i ... | def intensity_range image range_values 'image' clip_negative False if range_values 'dtype' range_values image dtype typeif range_values 'image' i_min np min image i_max np max image elif range_values in DTYPE_RANGE i_min i_max DTYPE_RANGE[range_values]if clip_negative i_min 0else i_min i_max range_valuesreturn i_min i_... | 60 |
python-test-6630 | python | How do all trig functions replace the code ? | with hyperbolic functions | def osbornei e d def f rv if not isinstance rv Trigonometric Function return rva rv args[ 0 ] xreplace {d S One} if rv func is sin return sinh a / I elif rv func is cos return cosh a elif rv func is tan return tanh a / I elif rv func is cot return coth a * I elif rv func is sec return 1 / cosh a elif rv func is csc ret... | def _osbornei e d def f rv if not isinstance rv TrigonometricFunction return rva rv args[0] xreplace {d S One} if rv func is sin return sinh a / I elif rv func is cos return cosh a elif rv func is tan return tanh a / I elif rv func is cot return coth a * I elif rv func is sec return 1 / cosh a elif rv func is csc retur... | 95 |
python-test-6631 | python | What contains only nzb files ? | this job | def nzb redirect wdir nzbname pp script cat priority files []for root dirs names in os walk wdir for name in names files append os path join root name for file in files if os path splitext file [1 ] lower ' nzb' return Noneif len files 1 nzbname Nonefor file in files dirscanner Process Single File os path split file [1... | def nzb_redirect wdir nzbname pp script cat priority files []for root _dirs names in os walk wdir for name in names files append os path join root name for file_ in files if os path splitext file_ [1] lower ' nzb' return Noneif len files 1 nzbname Nonefor file_ in files dirscanner ProcessSingleFile os path split file_ ... | 78 |
python-test-6632 | python | What does this job contain ? | only nzb files | def nzb redirect wdir nzbname pp script cat priority files []for root dirs names in os walk wdir for name in names files append os path join root name for file in files if os path splitext file [1 ] lower ' nzb' return Noneif len files 1 nzbname Nonefor file in files dirscanner Process Single File os path split file [1... | def nzb_redirect wdir nzbname pp script cat priority files []for root _dirs names in os walk wdir for name in names files append os path join root name for file_ in files if os path splitext file_ [1] lower ' nzb' return Noneif len files 1 nzbname Nonefor file_ in files dirscanner ProcessSingleFile os path split file_ ... | 78 |
python-test-6635 | python | What does the code dump ? | the local machine groups | def Dump Local Groups path ' Win NT //%s computer' % local name ob A Ds Get Object path IID IA Ds Container ob put Filter [' Group'] for sub ob in ob print ' Group %s %s ' % sub ob Name sub ob A Ds Path members sub ob Members for member in members print ' Groupmember %s %s ' % member Name member A Ds Path | def DumpLocalGroups path 'WinNT //%s computer' % local_name ob ADsGetObject path IID_IADsContainer ob put_Filter ['Group'] for sub_ob in ob print 'Group %s %s ' % sub_ob Name sub_ob ADsPath members sub_ob Members for member in members print 'Groupmember %s %s ' % member Name member ADsPath | 69 |
python-test-6641 | python | What calculates in a paper by some of the leading authorities on model selection - dx ? | bayesian predictive information criterion n of the samples | def bpic trace model None model modelcontext model mean deviance -2 * np mean [model logp pt for pt in trace] free rv means {rv name trace[rv name] mean axis 0 for rv in model free R Vs}deviance at mean -2 * model logp free rv means return 3 * mean deviance - 2 * deviance at mean | def bpic trace model None model modelcontext model mean_deviance -2 * np mean [model logp pt for pt in trace] free_rv_means {rv name trace[rv name] mean axis 0 for rv in model free_RVs}deviance_at_mean -2 * model logp free_rv_means return 3 * mean_deviance - 2 * deviance_at_mean | 58 |
python-test-6645 | python | What does the code get ? | gating milestone associated with the given content usage key | def get prerequisite milestone prereq content key milestones milestones api get milestones '{usage key}{qualifier}' format usage key prereq content key qualifier GATING NAMESPACE QUALIFIER if not milestones log warning ' Couldnotfindgatingmilestoneforprereq Usage Key%s' prereq content key return Noneif len milestones >... | def _get_prerequisite_milestone prereq_content_key milestones milestones_api get_milestones '{usage_key}{qualifier}' format usage_key prereq_content_key qualifier GATING_NAMESPACE_QUALIFIER if not milestones log warning 'CouldnotfindgatingmilestoneforprereqUsageKey%s' prereq_content_key return Noneif len milestones > 1... | 55 |
python-test-6646 | python | What do a context manager toggle ? | site configuration settings | @contextmanagerdef set siteconfig settings settings siteconfig Site Configuration objects get current old settings {}for setting value in six iteritems settings old settings[setting] siteconfig get setting siteconfig set setting value siteconfig save load site config try yield finally for setting value in six iteritems... | @contextmanagerdef set_siteconfig_settings settings siteconfig SiteConfiguration objects get_current old_settings {}for setting value in six iteritems settings old_settings[setting] siteconfig get setting siteconfig set setting value siteconfig save load_site_config try yield finally for setting value in six iteritems ... | 54 |
python-test-6650 | python | What does the code update ? | the user preferences for the given user | @intercept errors User API Internal Error ignore errors [ User API Request Error] def update user preferences requesting user update user None if not user or isinstance user basestring user get authorized user requesting user user else check authorized requesting user user username errors {}serializers {}for preference... | @intercept_errors UserAPIInternalError ignore_errors [UserAPIRequestError] def update_user_preferences requesting_user update user None if not user or isinstance user basestring user _get_authorized_user requesting_user user else _check_authorized requesting_user user username errors {}serializers {}for preference_key ... | 153 |
python-test-6651 | python | How did a nagios - appropriate string and return code obtain ? | by parsing the desired file on disk | def nagios from file results file data open results file read strip pieces data split ' ' if not len pieces 4 state 'UNKNOWN'ret 3data ' Resultsfilemalformed'else timestamp int pieces[ 0 ] time diff time time - timestamp if time diff > 60 * 2 ret 3state 'UNKNOWN'data ' Resultsfileisstale'else ret int pieces[ 1 ] state ... | def nagios_from_file results_file data open results_file read strip pieces data split ' ' if not len pieces 4 state 'UNKNOWN'ret 3data 'Resultsfilemalformed'else timestamp int pieces[0] time_diff time time - timestamp if time_diff > 60 * 2 ret 3state 'UNKNOWN'data 'Resultsfileisstale'else ret int pieces[1] state pieces... | 68 |
python-test-6652 | python | What is parsing on disk ? | the desired file | def nagios from file results file data open results file read strip pieces data split ' ' if not len pieces 4 state 'UNKNOWN'ret 3data ' Resultsfilemalformed'else timestamp int pieces[ 0 ] time diff time time - timestamp if time diff > 60 * 2 ret 3state 'UNKNOWN'data ' Resultsfileisstale'else ret int pieces[ 1 ] state ... | def nagios_from_file results_file data open results_file read strip pieces data split ' ' if not len pieces 4 state 'UNKNOWN'ret 3data 'Resultsfilemalformed'else timestamp int pieces[0] time_diff time time - timestamp if time_diff > 60 * 2 ret 3state 'UNKNOWN'data 'Resultsfileisstale'else ret int pieces[1] state pieces... | 68 |
python-test-6653 | python | Where do all the threads view ? | in a discussion forum | def threads request document slug doc get document document slug request try sort int request GET get 'sort' 0 except Value Error sort 0try desc int request GET get 'desc' 0 except Value Error desc 0desc toggle 0 if desc else 1 threads sort threads doc thread set sort desc threads paginate request threads per page kbfo... | def threads request document_slug doc get_document document_slug request try sort int request GET get 'sort' 0 except ValueError sort 0try desc int request GET get 'desc' 0 except ValueError desc 0desc_toggle 0 if desc else 1 threads_ sort_threads doc thread_set sort desc threads_ paginate request threads_ per_page kbf... | 114 |
python-test-6654 | python | What views in a discussion forum ? | all the threads | def threads request document slug doc get document document slug request try sort int request GET get 'sort' 0 except Value Error sort 0try desc int request GET get 'desc' 0 except Value Error desc 0desc toggle 0 if desc else 1 threads sort threads doc thread set sort desc threads paginate request threads per page kbfo... | def threads request document_slug doc get_document document_slug request try sort int request GET get 'sort' 0 except ValueError sort 0try desc int request GET get 'desc' 0 except ValueError desc 0desc_toggle 0 if desc else 1 threads_ sort_threads doc thread_set sort desc threads_ paginate request threads_ per_page kbf... | 114 |
python-test-6658 | python | How does preferences set for exploration ? | with given exploration_id of user with given user_id | def set email preferences for exploration user id exploration id mute feedback notifications None mute suggestion notifications None exploration user model user models Exploration User Data Model get user id exploration id if exploration user model is None exploration user model user models Exploration User Data Model ... | def set_email_preferences_for_exploration user_id exploration_id mute_feedback_notifications None mute_suggestion_notifications None exploration_user_model user_models ExplorationUserDataModel get user_id exploration_id if exploration_user_model is None exploration_user_model user_models ExplorationUserDataModel create... | 86 |
python-test-6659 | python | For what purpose does preferences set with given exploration_id of user with given user_id ? | for exploration | def set email preferences for exploration user id exploration id mute feedback notifications None mute suggestion notifications None exploration user model user models Exploration User Data Model get user id exploration id if exploration user model is None exploration user model user models Exploration User Data Model ... | def set_email_preferences_for_exploration user_id exploration_id mute_feedback_notifications None mute_suggestion_notifications None exploration_user_model user_models ExplorationUserDataModel get user_id exploration_id if exploration_user_model is None exploration_user_model user_models ExplorationUserDataModel create... | 86 |
python-test-6660 | python | How does the code parse the start and end lines from a line string ? | like start - end | def Get Lines line strings lines []for line string in line strings line list map int line string split '-' 1 if line[ 0 ] < 1 raise errors Yapf Error 'invalidstartoflinerange %r' % line if line[ 0 ] > line[ 1 ] raise errors Yapf Error 'endcomesbeforestartinlinerange %r' line lines append tuple line return lines | def _GetLines line_strings lines []for line_string in line_strings line list map int line_string split '-' 1 if line[0] < 1 raise errors YapfError 'invalidstartoflinerange %r' % line if line[0] > line[1] raise errors YapfError 'endcomesbeforestartinlinerange %r' line lines append tuple line return lines | 56 |
python-test-6661 | python | In which direction does the code parse the start and end lines like start - end ? | from a line string | def Get Lines line strings lines []for line string in line strings line list map int line string split '-' 1 if line[ 0 ] < 1 raise errors Yapf Error 'invalidstartoflinerange %r' % line if line[ 0 ] > line[ 1 ] raise errors Yapf Error 'endcomesbeforestartinlinerange %r' line lines append tuple line return lines | def _GetLines line_strings lines []for line_string in line_strings line list map int line_string split '-' 1 if line[0] < 1 raise errors YapfError 'invalidstartoflinerange %r' % line if line[0] > line[1] raise errors YapfError 'endcomesbeforestartinlinerange %r' line lines append tuple line return lines | 56 |
python-test-6662 | python | What does the code parse from a line string like start - end ? | the start and end lines | def Get Lines line strings lines []for line string in line strings line list map int line string split '-' 1 if line[ 0 ] < 1 raise errors Yapf Error 'invalidstartoflinerange %r' % line if line[ 0 ] > line[ 1 ] raise errors Yapf Error 'endcomesbeforestartinlinerange %r' line lines append tuple line return lines | def _GetLines line_strings lines []for line_string in line_strings line list map int line_string split '-' 1 if line[0] < 1 raise errors YapfError 'invalidstartoflinerange %r' % line if line[0] > line[1] raise errors YapfError 'endcomesbeforestartinlinerange %r' line lines append tuple line return lines | 56 |
python-test-6663 | python | What does the code get ? | ids corresponding to words in text | def Get Word Ids text vocab pad len None pad id None ids []for w in text split i vocab Word To Id w if i > 0 ids append i else ids append vocab Word To Id UNKNOWN TOKEN if pad len is not None return Pad ids pad id pad len return ids | def GetWordIds text vocab pad_len None pad_id None ids []for w in text split i vocab WordToId w if i > 0 ids append i else ids append vocab WordToId UNKNOWN_TOKEN if pad_len is not None return Pad ids pad_id pad_len return ids | 55 |
python-test-6664 | python | What does the code create ? | a metadata object | def main query ip Metadata QUERY I Poptions parse command line if options options mock from tornado import testingport testing get unused port class Handler web Request Handler def get self path self write path split '/' [ -1 ] application web Application [ '/ * ' Handler ] application listen port query ip 'localhost {... | def main query_ip Metadata _QUERY_IPoptions parse_command_line if options options mock from tornado import testingport testing get_unused_port class Handler web RequestHandler def get self path self write path split '/' [ -1 ] application web Application [ '/ * ' Handler ] application listen port query_ip 'localhost {0... | 84 |
python-test-6672 | python | What does decorator function instantiate ? | the retrying object | def retry *dargs **dkw if len dargs 1 and callable dargs[ 0 ] def wrap simple f @six wraps f def wrapped f *args **kw return Retrying call f *args **kw return wrapped freturn wrap simple dargs[ 0 ] else def wrap f @six wraps f def wrapped f *args **kw return Retrying *dargs **dkw call f *args **kw return wrapped fretur... | def retry *dargs **dkw if len dargs 1 and callable dargs[0] def wrap_simple f @six wraps f def wrapped_f *args **kw return Retrying call f *args **kw return wrapped_freturn wrap_simple dargs[0] else def wrap f @six wraps f def wrapped_f *args **kw return Retrying *dargs **dkw call f *args **kw return wrapped_freturn wr... | 63 |
python-test-6675 | python | What did the code split ? | the datastore path to components | def split datastore path datastore path splits datastore path split '[' 1 [1 ] split ']' 1 datastore name Nonefolder path Nonefile name Noneif len splits 1 datastore name splits[ 0 ]else datastore name path splitssplits path split '/' file name splits[ len splits - 1 ]folder path path[ - len file name ]return datastore... | def split_datastore_path datastore_path splits datastore_path split '[' 1 [1] split ']' 1 datastore_name Nonefolder_path Nonefile_name Noneif len splits 1 datastore_name splits[0]else datastore_name path splitssplits path split '/' file_name splits[ len splits - 1 ]folder_path path[ - len file_name ]return datastore_na... | 63 |
python-test-6676 | python | What does the code create ? | a server and a client | def connect Server And Client test client Factory server Factory addr '127 0 0 1' client Broker client Factory build Protocol addr server Broker server Factory build Protocol addr client Transport String IO server Transport String IO client Broker make Connection protocol File Wrapper client Transport server Broker mak... | def connectServerAndClient test clientFactory serverFactory addr '127 0 0 1' clientBroker clientFactory buildProtocol addr serverBroker serverFactory buildProtocol addr clientTransport StringIO serverTransport StringIO clientBroker makeConnection protocol FileWrapper clientTransport serverBroker makeConnection protocol... | 127 |
python-test-6677 | python | What does the code connect with an l{iopump ? | the two | def connect Server And Client test client Factory server Factory addr '127 0 0 1' client Broker client Factory build Protocol addr server Broker server Factory build Protocol addr client Transport String IO server Transport String IO client Broker make Connection protocol File Wrapper client Transport server Broker mak... | def connectServerAndClient test clientFactory serverFactory addr '127 0 0 1' clientBroker clientFactory buildProtocol addr serverBroker serverFactory buildProtocol addr clientTransport StringIO serverTransport StringIO clientBroker makeConnection protocol FileWrapper clientTransport serverBroker makeConnection protocol... | 127 |
python-test-6678 | python | How does the code connect the two ? | with an l{iopump | def connect Server And Client test client Factory server Factory addr '127 0 0 1' client Broker client Factory build Protocol addr server Broker server Factory build Protocol addr client Transport String IO server Transport String IO client Broker make Connection protocol File Wrapper client Transport server Broker mak... | def connectServerAndClient test clientFactory serverFactory addr '127 0 0 1' clientBroker clientFactory buildProtocol addr serverBroker serverFactory buildProtocol addr clientTransport StringIO serverTransport StringIO clientBroker makeConnection protocol FileWrapper clientTransport serverBroker makeConnection protocol... | 127 |
python-test-6680 | python | What does the code keep ? | only objects that can be pickled | def globalsfilter input dict check all False filters None exclude private None exclude capitalized None exclude uppercase None exclude unsupported None excluded names None output dict {}for key value in list input dict items excluded exclude private and key startswith ' ' or exclude capitalized and key[ 0 ] isupper or ... | def globalsfilter input_dict check_all False filters None exclude_private None exclude_capitalized None exclude_uppercase None exclude_unsupported None excluded_names None output_dict {}for key value in list input_dict items excluded exclude_private and key startswith '_' or exclude_capitalized and key[0] isupper or ex... | 94 |
python-test-6690 | python | What does the code delete only if it exists ? | a network device | def delete net dev dev if device exists dev try utils execute 'ip' 'link' 'delete' dev run as root True check exit code [0 2 254 ] LOG debug " Netdeviceremoved '%s'" dev except processutils Process Execution Error with excutils save and reraise exception LOG error LE " Failedremovingnetdevice '%s'" dev | def delete_net_dev dev if device_exists dev try utils execute 'ip' 'link' 'delete' dev run_as_root True check_exit_code [0 2 254] LOG debug "Netdeviceremoved '%s'" dev except processutils ProcessExecutionError with excutils save_and_reraise_exception LOG error _LE "Failedremovingnetdevice '%s'" dev | 51 |
python-test-6693 | python | When does distance metric take partial agreement into account ? | when multiple labels are assigned | def masi distance label 1 label 2 len intersection len label 1 intersection label 2 len union len label 1 union label 2 len label 1 len label 1 len label 2 len label 2 if len label 1 len label 2 and len label 1 len intersection m 1elif len intersection min len label 1 len label 2 m 0 67 elif len intersection > 0 m 0 33... | def masi_distance label1 label2 len_intersection len label1 intersection label2 len_union len label1 union label2 len_label1 len label1 len_label2 len label2 if len_label1 len_label2 and len_label1 len_intersection m 1elif len_intersection min len_label1 len_label2 m 0 67elif len_intersection > 0 m 0 33else m 0return 1... | 83 |
python-test-6695 | python | What does the code extract ? | a minibatch of examples | def get minibatch doc iter size pos class positive class data [ u'{title}\n\n{body}' format **doc pos class in doc['topics'] for doc in itertools islice doc iter size if doc['topics']]if not len data return np asarray [] dtype int np asarray [] dtype int X text y zip *data return X text np asarray y dtype int | def get_minibatch doc_iter size pos_class positive_class data [ u'{title}\n\n{body}' format **doc pos_class in doc['topics'] for doc in itertools islice doc_iter size if doc['topics']]if not len data return np asarray [] dtype int np asarray [] dtype int X_text y zip *data return X_text np asarray y dtype int | 56 |
python-test-6697 | python | When should returns be called ? | after import_pycaffe ( ) | def get version and flavor executable version string get version from pycaffe if version string is None version string get version from cmdline executable if version string is None version string get version from soname executable if version string is None raise Value Error ' Couldnotfindversioninformationfor Caffebuil... | def get_version_and_flavor executable version_string get_version_from_pycaffe if version_string is None version_string get_version_from_cmdline executable if version_string is None version_string get_version_from_soname executable if version_string is None raise ValueError 'CouldnotfindversioninformationforCaffebuild' ... | 101 |
python-test-6699 | python | What does the code return ? | an audio buffer that encodes that pattern | def make buffer from bit pattern pattern on freq off freq last bit pattern[ -1 ]output buffer []offset 0for i in range len pattern bit pattern[i]if i < len pattern - 1 next bit pattern[ i + 1 ]else next bit pattern[ 0 ]freq on freq if bit '1 ' else off freq tone quietnet tone freq DATASIZE offset offset output buffer +... | def make_buffer_from_bit_pattern pattern on_freq off_freq last_bit pattern[ -1 ]output_buffer []offset 0for i in range len pattern bit pattern[i]if i < len pattern - 1 next_bit pattern[ i + 1 ]else next_bit pattern[0]freq on_freq if bit '1' else off_freq tone quietnet tone freq DATASIZE offset offset output_buffer + qu... | 87 |
python-test-6704 | python | What does the code compute ? | the positions of split codons | def comp split codons hsp seq type scodon moves scodons []for idx in range len scodon moves[seq type] pair scodon moves[seq type][idx]if not any pair continueelse assert not all pair a b pairanchor pair hsp[ '%s ranges' % seq type ][ idx // 2 ]strand 1 if hsp[ '%s strand' % seq type ] > 0 else -1 if a func max if stran... | def _comp_split_codons hsp seq_type scodon_moves scodons []for idx in range len scodon_moves[seq_type] pair scodon_moves[seq_type][idx]if not any pair continueelse assert not all pair a b pairanchor_pair hsp[ '%s_ranges' % seq_type ][ idx // 2 ]strand 1 if hsp[ '%s_strand' % seq_type ] > 0 else -1 if a func max if stra... | 120 |
python-test-6710 | python | How do each segment visualise ? | in label_field with its mean color in image | def label 2 rgb avg label field image bg label 0 bg color 0 0 0 out np zeros like image labels np unique label field bg labels bg label if bg any labels labels[ labels bg label ]out[bg] bg colorfor label in labels mask label field label nonzero color image[mask] mean axis 0 out[mask] colorreturn out | def _label2rgb_avg label_field image bg_label 0 bg_color 0 0 0 out np zeros_like image labels np unique label_field bg labels bg_label if bg any labels labels[ labels bg_label ]out[bg] bg_colorfor label in labels mask label_field label nonzero color image[mask] mean axis 0 out[mask] colorreturn out | 57 |
python-test-6711 | python | What can alt_name be not used ? | to access arbitrary paths using a relative path | def test disk store alt name relpath with Test Config DISK TEST CONFIG as directory object store empty dataset Mock Dataset 1 directory write '' 'files 1 / 000 /dataset 1 dat' directory write 'foo' 'foo txt' try assert object store get data empty dataset extra dir 'dataset 1 files' alt name ' / / /foo txt' 'foo' except... | def test_disk_store_alt_name_relpath with TestConfig DISK_TEST_CONFIG as directory object_store empty_dataset MockDataset 1 directory write '' 'files1/000/dataset_1 dat' directory write 'foo' 'foo txt' try assert object_store get_data empty_dataset extra_dir 'dataset_1_files' alt_name ' / / /foo txt' 'foo' except Objec... | 62 |
python-test-6717 | python | What does this function not calculate ? | the estimate of the combined error between the underlying multivariate normal probability calculations and the integration | def mvstdtprob a b R df ieps 1e- 05 quadkwds None mvstkwds None kwds dict args a b R df epsabs 0 0001 epsrel 0 01 limit 150 if not quadkwds is None kwds update quadkwds res err integrate quad funbgh 2 *chi ppf [ieps 1 - ieps ] df **kwds prob res * bghfactor df return prob | def mvstdtprob a b R df ieps 1e-05 quadkwds None mvstkwds None kwds dict args a b R df epsabs 0 0001 epsrel 0 01 limit 150 if not quadkwds is None kwds update quadkwds res err integrate quad funbgh2 *chi ppf [ieps 1 - ieps ] df **kwds prob res * bghfactor df return prob | 58 |
python-test-6721 | python | What does the code create ? | a string of youtube ids from modules metadata attributes | def create youtube string module youtube ids [module youtube id 0 75 module youtube id 1 0 module youtube id 1 25 module youtube id 1 5]youtube speeds [' 0 75 ' '1 00 ' '1 25 ' '1 50 ']return ' ' join [' ' join pair for pair in zip youtube speeds youtube ids if pair[ 1 ]] | def create_youtube_string module youtube_ids [module youtube_id_0_75 module youtube_id_1_0 module youtube_id_1_25 module youtube_id_1_5]youtube_speeds ['0 75' '1 00' '1 25' '1 50']return ' ' join [' ' join pair for pair in zip youtube_speeds youtube_ids if pair[1]] | 60 |
python-test-6723 | python | What does the code destroy ? | a vm instance | def destroy vm session instance vm ref None try if not vm ref vm ref get vm ref session instance LOG debug ' Destroyingthe VM' instance instance destroy task session call method session vim ' Destroy Task' vm ref session wait for task destroy task LOG info LI ' Destroyedthe VM' instance instance except Exception LOG ex... | def destroy_vm session instance vm_ref None try if not vm_ref vm_ref get_vm_ref session instance LOG debug 'DestroyingtheVM' instance instance destroy_task session _call_method session vim 'Destroy_Task' vm_ref session _wait_for_task destroy_task LOG info _LI 'DestroyedtheVM' instance instance except Exception LOG exce... | 64 |
python-test-6724 | python | What does the code calculate ? | the log likelihood of the observed topic proportions | def dirichlet likelihood weights alpha None if type weights is Variable n topics weights data shape[ 1 ]else n topics weights W data shape[ 1 ]if alpha is None alpha 1 0 / n topics if type weights is Variable log proportions F log softmax weights else log proportions F log softmax weights W loss alpha - 1 0 * log propo... | def dirichlet_likelihood weights alpha None if type weights is Variable n_topics weights data shape[1]else n_topics weights W data shape[1]if alpha is None alpha 1 0 / n_topics if type weights is Variable log_proportions F log_softmax weights else log_proportions F log_softmax weights W loss alpha - 1 0 * log_proportio... | 67 |
python-test-6726 | python | What does the code associate with the specified instance URL cli examples ? | the specified ssm document | def ssm create association name None kwargs None instance id None call None if call 'action' raise Salt Cloud System Exit ' Thessm create associationactionmustbecalledwith-aor--action ' if not kwargs kwargs {}if 'instance id' in kwargs instance id kwargs['instance id']if name and not instance id instance id get node na... | def ssm_create_association name None kwargs None instance_id None call None if call 'action' raise SaltCloudSystemExit 'Thessm_create_associationactionmustbecalledwith-aor--action ' if not kwargs kwargs {}if 'instance_id' in kwargs instance_id kwargs['instance_id']if name and not instance_id instance_id _get_node name ... | 116 |
python-test-6727 | python | What does the code get ? | a list of cpus to build metric definitions with | def get cpu list ip user passwd cmd 'statcpu-iter 1 -t'showcpu list run ssh thread ip user passwd cmd cpu list []line num 0for line in showcpu list line num + 1if line num > 3 cpu stats line split if len cpu stats > 2 cpu list append cpu stats[ 0 ] split ' ' [0 ] return cpu list | def get_cpu_list ip user passwd cmd 'statcpu-iter1-t'showcpu_list run_ssh_thread ip user passwd cmd cpu_list []line_num 0for line in showcpu_list line_num + 1if line_num > 3 cpu_stats line split if len cpu_stats > 2 cpu_list append cpu_stats[0] split ' ' [0] return cpu_list | 61 |
python-test-6734 | python | Where did handlers define ? | in the handlers directory of module_name | def handlers module name handlers module try import '%s handlers' % module name if handlers module is None return []if not hasattr handlers module ' path ' raise Handler Error ' Module%smustbeadirectory ' % handlers module name files find python files handlers module path [0 ] module names [ '%s %s' % handlers module n... | def _handlers module_name handlers_module try_import '%s handlers' % module_name if handlers_module is None return []if not hasattr handlers_module '__path__' raise HandlerError 'Module%smustbeadirectory ' % handlers_module __name__ files find_python_files handlers_module __path__[0] module_names [ '%s %s' % handlers_m... | 81 |
python-test-6740 | python | What is preceding the class name ? | at least one module name | def load class dotted path dotted path split dotted path split ' ' if len dotted path split > 1 klass name dotted path split[ -1 ]module name ' ' join dotted path split[ -1 ] module load module module name if has attribute module klass name klass getattr module klass name return klasselse raise Attribute Error ' Module... | def load_class dotted_path dotted_path_split dotted_path split ' ' if len dotted_path_split > 1 klass_name dotted_path_split[ -1 ]module_name ' ' join dotted_path_split[ -1 ] module load_module module_name if has_attribute module klass_name klass getattr module klass_name return klasselse raise AttributeError 'Module%s... | 73 |
python-test-6741 | python | What do at least one module name precede ? | the class name | def load class dotted path dotted path split dotted path split ' ' if len dotted path split > 1 klass name dotted path split[ -1 ]module name ' ' join dotted path split[ -1 ] module load module module name if has attribute module klass name klass getattr module klass name return klasselse raise Attribute Error ' Module... | def load_class dotted_path dotted_path_split dotted_path split ' ' if len dotted_path_split > 1 klass_name dotted_path_split[ -1 ]module_name ' ' join dotted_path_split[ -1 ] module load_module module_name if has_attribute module klass_name klass getattr module klass_name return klasselse raise AttributeError 'Module%s... | 73 |
python-test-6745 | python | What does custom validate function support ? | default arguments combined with the " required " property | def validate instance schema cls None use default True allow default none False *args **kwargs instance copy deepcopy instance schema type schema get 'type' None instance is dict isinstance instance dict if use default and allow default none schema modify schema allow default none schema schema if use default and schem... | def validate instance schema cls None use_default True allow_default_none False *args **kwargs instance copy deepcopy instance schema_type schema get 'type' None instance_is_dict isinstance instance dict if use_default and allow_default_none schema modify_schema_allow_default_none schema schema if use_default and schem... | 77 |
python-test-6746 | python | What supports default arguments combined with the " required " property ? | custom validate function | def validate instance schema cls None use default True allow default none False *args **kwargs instance copy deepcopy instance schema type schema get 'type' None instance is dict isinstance instance dict if use default and allow default none schema modify schema allow default none schema schema if use default and schem... | def validate instance schema cls None use_default True allow_default_none False *args **kwargs instance copy deepcopy instance schema_type schema get 'type' None instance_is_dict isinstance instance dict if use_default and allow_default_none schema modify_schema_allow_default_none schema schema if use_default and schem... | 77 |
python-test-6747 | python | What does task handle ? | updating the models schema | def update schema task cursor None num updated 0 batch size 100 reload models v2 query models v2 Picture query pictures next cursor more query fetch page batch size start cursor cursor to put []for picture in pictures picture num votes 1picture avg rating 5to put append picture if to put ndb put multi to put num update... | def update_schema_task cursor None num_updated 0 batch_size 100 reload models_v2 query models_v2 Picture query pictures next_cursor more query fetch_page batch_size start_cursor cursor to_put []for picture in pictures picture num_votes 1picture avg_rating 5to_put append picture if to_put ndb put_multi to_put num_update... | 99 |
python-test-6754 | python | What does the code create ? | the ir_module_category entries for some categories | def create categories cr categories p id Nonecategory []while categories category append categories[ 0 ] xml id 'module category ' + ' ' join map lambda x x lower category replace '&' 'and' replace '' ' ' cr execute 'SELEC Tres id FRO Mir model data WHER Ename %s AN Dmodule %s AN Dmodel %s' xml id 'base' 'ir module cat... | def create_categories cr categories p_id Nonecategory []while categories category append categories[0] xml_id 'module_category_' + '_' join map lambda x x lower category replace '&' 'and' replace '' '_' cr execute 'SELECTres_idFROMir_model_dataWHEREname %sANDmodule %sANDmodel %s' xml_id 'base' 'ir module category' c_id... | 133 |
python-test-6756 | python | How do cifs upload files ? | via cifs | def cifs registry xml parent data console prefix 'CIFS 'plugin tag 'jenkins plugins publish over cifs Cifs Publisher Plugin'publisher tag 'jenkins plugins publish over cifs Cifs Publisher'transfer tag 'jenkins plugins publish over cifs Cifs Transfer'plugin reference tag 'jenkins plugins publish over cifs Cifs Publisher... | def cifs registry xml_parent data console_prefix 'CIFS 'plugin_tag 'jenkins plugins publish__over__cifs CifsPublisherPlugin'publisher_tag 'jenkins plugins publish__over__cifs CifsPublisher'transfer_tag 'jenkins plugins publish__over__cifs CifsTransfer'plugin_reference_tag 'jenkins plugins publish_over_cifs CifsPublishe... | 61 |
python-test-6757 | python | What upload files via cifs ? | cifs | def cifs registry xml parent data console prefix 'CIFS 'plugin tag 'jenkins plugins publish over cifs Cifs Publisher Plugin'publisher tag 'jenkins plugins publish over cifs Cifs Publisher'transfer tag 'jenkins plugins publish over cifs Cifs Transfer'plugin reference tag 'jenkins plugins publish over cifs Cifs Publisher... | def cifs registry xml_parent data console_prefix 'CIFS 'plugin_tag 'jenkins plugins publish__over__cifs CifsPublisherPlugin'publisher_tag 'jenkins plugins publish__over__cifs CifsPublisher'transfer_tag 'jenkins plugins publish__over__cifs CifsTransfer'plugin_reference_tag 'jenkins plugins publish_over_cifs CifsPublishe... | 61 |
python-test-6758 | python | Where does the code create a http server daemon ? | in any free port available | def start webserver any free port ip webroot handler Web Handler web server HTTP Server ip 0 webroot handler server thread threading Thread target web server serve forever server thread name ' Web Server'server thread daemon Trueserver thread start web server wait for start return server thread web server get port | def start_webserver_any_free_port ip webroot handler WebHandler web_server HTTPServer ip 0 webroot handler server_thread threading Thread target web_server serve_forever server_thread name 'WebServer'server_thread daemon Trueserver_thread start web_server wait_for_start return server_thread web_server get_port | 51 |
python-test-6759 | python | What does the code convert a matplotlib figure ? | to plotly dictionary | @utils template doc **get config file def mpl to plotly fig resize False strip style False verbose False if matplotlylib renderer matplotlylib Plotly Renderer matplotlylib Exporter renderer run fig if resize renderer resize if strip style renderer strip style if verbose print renderer msgreturn renderer plotly figelse ... | @utils template_doc **get_config_file def mpl_to_plotly fig resize False strip_style False verbose False if matplotlylib renderer matplotlylib PlotlyRenderer matplotlylib Exporter renderer run fig if resize renderer resize if strip_style renderer strip_style if verbose print renderer msgreturn renderer plotly_figelse w... | 55 |
python-test-6761 | python | What does the code serialize ? | the given instance of httperror | def default serialize error req resp exception representation Nonepreferred req client prefers 'application/xml' 'text/xml' 'application/json' if preferred is None accept req accept lower if '+json' in accept preferred 'application/json'elif '+xml' in accept preferred 'application/xml'if preferred is not None if prefer... | def default_serialize_error req resp exception representation Nonepreferred req client_prefers 'application/xml' 'text/xml' 'application/json' if preferred is None accept req accept lower if '+json' in accept preferred 'application/json'elif '+xml' in accept preferred 'application/xml'if preferred is not None if prefer... | 69 |
python-test-6765 | python | What does the code perform ? | non - local | def denoise nl means image patch size 7 patch distance 11 h 0 1 multichannel None fast mode True if multichannel is None warn 'denoise nl meanswilldefaulttomultichannel Falseinv 0 15 ' multichannel Trueif image ndim 2 image image[ np newaxis]multichannel Trueif image ndim 3 raise Not Implemented Error ' Non-localmeansd... | def denoise_nl_means image patch_size 7 patch_distance 11 h 0 1 multichannel None fast_mode True if multichannel is None warn 'denoise_nl_meanswilldefaulttomultichannel Falseinv0 15' multichannel Trueif image ndim 2 image image[ np newaxis]multichannel Trueif image ndim 3 raise NotImplementedError 'Non-localmeansdenois... | 129 |
python-test-6771 | python | What shares the same name ? | no two targets in the same directory | def Verify No Colliding Targets targets used {}for target in targets path name target rsplit ' ' 1 subdir gyp os path split path if not subdir subdir ' 'key subdir + ' ' + name if key in used raise Gyp Error ' Duplicatetargetname"%s"indirectory"%s"usedbothin"%s"and"%s" ' % name subdir gyp used[key] used[key] gyp | def VerifyNoCollidingTargets targets used {}for target in targets path name target rsplit ' ' 1 subdir gyp os path split path if not subdir subdir ' 'key subdir + ' ' + name if key in used raise GypError 'Duplicatetargetname"%s"indirectory"%s"usedbothin"%s"and"%s" ' % name subdir gyp used[key] used[key] gyp | 53 |
python-test-6772 | python | What does the code generate ? | a csv file containing the detailed information about the xblocks available per course arguments | def write course block detail report course data with open 'xblock course detail csv' 'wb' as csvfile detail writer csv writer csvfile delimiter ' ' quotechar '"' quoting csv QUOTE ALL detail writer writerow ['XBLOCK TYPE NAME' 'COURSE NAME' 'COURSE ID' 'COURSE START' 'COURSE END' 'NUM XBLOCK INSTANCES'] for course in ... | def write_course_block_detail_report course_data with open 'xblock_course_detail csv' 'wb' as csvfile detail_writer csv writer csvfile delimiter ' ' quotechar '"' quoting csv QUOTE_ALL detail_writer writerow ['XBLOCK_TYPE_NAME' 'COURSE_NAME' 'COURSE_ID' 'COURSE_START' 'COURSE_END' 'NUM_XBLOCK_INSTANCES'] for course in ... | 107 |
python-test-6773 | python | What do a csv file contain ? | the detailed information about the xblocks available per course arguments | def write course block detail report course data with open 'xblock course detail csv' 'wb' as csvfile detail writer csv writer csvfile delimiter ' ' quotechar '"' quoting csv QUOTE ALL detail writer writerow ['XBLOCK TYPE NAME' 'COURSE NAME' 'COURSE ID' 'COURSE START' 'COURSE END' 'NUM XBLOCK INSTANCES'] for course in ... | def write_course_block_detail_report course_data with open 'xblock_course_detail csv' 'wb' as csvfile detail_writer csv writer csvfile delimiter ' ' quotechar '"' quoting csv QUOTE_ALL detail_writer writerow ['XBLOCK_TYPE_NAME' 'COURSE_NAME' 'COURSE_ID' 'COURSE_START' 'COURSE_END' 'NUM_XBLOCK_INSTANCES'] for course in ... | 107 |
python-test-6777 | python | What does the code tokenize ? | a javascript source | def tokenize source may divide Falsepos 0lineno 1end len source while pos < end for token type rule in rules match rule match source pos if match is not None breakelse if may divide match division re match source pos token type 'operator'else match regex re match source pos token type 'regexp'if match is None pos + 1co... | def tokenize source may_divide Falsepos 0lineno 1end len source while pos < end for token_type rule in rules match rule match source pos if match is not None breakelse if may_divide match division_re match source pos token_type 'operator'else match regex_re match source pos token_type 'regexp'if match is None pos + 1co... | 92 |
python-test-6778 | python | What does the code generate ? | a tar ball containing all of the source files | def generate tar package target sources sources dir suffix mode get tar mode from suffix suffix tar tarfile open target mode manifest archive package sources tar add sources sources dir manifest path '%s MANIFEST' % target m open manifest path 'w' print >>m '\n' join manifest + '\n' m close tar add manifest path PACKAG... | def _generate_tar_package target sources sources_dir suffix mode _get_tar_mode_from_suffix suffix tar tarfile open target mode manifest _archive_package_sources tar add sources sources_dir manifest_path '%s MANIFEST' % target m open manifest_path 'w' print >>m '\n' join manifest + '\n' m close tar add manifest_path _PA... | 60 |
python-test-6779 | python | What is containing all of the source files ? | a tar ball | def generate tar package target sources sources dir suffix mode get tar mode from suffix suffix tar tarfile open target mode manifest archive package sources tar add sources sources dir manifest path '%s MANIFEST' % target m open manifest path 'w' print >>m '\n' join manifest + '\n' m close tar add manifest path PACKAG... | def _generate_tar_package target sources sources_dir suffix mode _get_tar_mode_from_suffix suffix tar tarfile open target mode manifest _archive_package_sources tar add sources sources_dir manifest_path '%s MANIFEST' % target m open manifest_path 'w' print >>m '\n' join manifest + '\n' m close tar add manifest_path _PA... | 60 |
python-test-6781 | python | What do a file object contain ? | a list of tweet ids | @verbosedef expand tweetids demo ids f String IO '588665495492124672 \n 588665495487909888 \n 588665495508766721 \n 588665495513006080 \n 588665495517200384 \n 588665495487811584 \n 588665495525588992 \n 588665495487844352 \n 588665495492014081 \n 588665495512948737 ' oauth credsfromfile client Query **oauth hydrated c... | @verbosedef expand_tweetids_demo ids_f StringIO '588665495492124672\n588665495487909888\n588665495508766721\n588665495513006080\n588665495517200384\n588665495487811584\n588665495525588992\n588665495487844352\n588665495492014081\n588665495512948737' oauth credsfromfile client Query **oauth hydrated client expand_tweetid... | 63 |
python-test-6782 | python | What does the code get ? | list of all public modules relative to a path | def get public modules path base package None result []for subdir files in os walk path if any [part startswith ' ' for part in subdir split os path sep ] continue rel dir subdir split path rel dir rel dir lstrip os path sep for filename in files if is valid module filename mod name os path splitext filename rel path o... | def get_public_modules path base_package None result []for subdir _ files in os walk path if any [part startswith '_' for part in subdir split os path sep ] continue _ rel_dir subdir split path rel_dir rel_dir lstrip os path sep for filename in files if is_valid_module filename mod_name _ os path splitext filename rel_... | 117 |
python-test-6783 | python | What does the code traverse ? | the alignment cost from the tracebacks | def trace backlinks source sents lens target sents lens links []position len source sents lens len target sents lens while position 0 0 and all p > 0 for p in position try s t backlinks[position]except Type Error position position[ 0 ] - 1 position[ 1 ] - 1 continuefor i in range s for j in range t links append positio... | def trace backlinks source_sents_lens target_sents_lens links []position len source_sents_lens len target_sents_lens while position 0 0 and all p > 0 for p in position try s t backlinks[position]except TypeError position position[0] - 1 position[1] - 1 continuefor i in range s for j in range t links append position[0] ... | 90 |
python-test-6784 | python | What does the code write ? | a translation file for a given language | def write translations file app lang full dict None app messages None if not app messages app messages get messages for app app if not app messages returntpath frappe get pymodule path app u'translations' frappe create folder tpath write csv file os path join tpath lang + u' csv' app messages full dict or get full dict... | def write_translations_file app lang full_dict None app_messages None if not app_messages app_messages get_messages_for_app app if not app_messages returntpath frappe get_pymodule_path app u'translations' frappe create_folder tpath write_csv_file os path join tpath lang + u' csv' app_messages full_dict or get_full_dict... | 58 |
python-test-6785 | python | What does the code read ? | the various installed | def read installed packages list def read from file config filename '\n Readsaninstalled lstfilefromagivenlocation\n\n paramconfig filename theconfigurationfiletoread\n'global installed packages listtry installed list file open config filename except IO Error passelse for line in installed list file l line rstrip split... | def read_installed_packages_list def read_from_file config_filename '\nReadsaninstalled lstfilefromagivenlocation\n\n paramconfig_filename theconfigurationfiletoread\n'global installed_packages_listtry installed_list_file open config_filename except IOError passelse for line in installed_list_file l line rstrip split '... | 149 |
python-test-6786 | python | What does the code create ? | a postgres group | def group create groupname user None host None port None maintenance db None password None createdb None createuser None createroles None encrypted None login None inherit None superuser None replication None rolepassword None groups None runas None return role create groupname user user typ 'group' host host port port... | def group_create groupname user None host None port None maintenance_db None password None createdb None createuser None createroles None encrypted None login None inherit None superuser None replication None rolepassword None groups None runas None return _role_create groupname user user typ_ 'group' host host port po... | 77 |
python-test-6787 | python | What does the code delete ? | an existing virtual | def delete virtual hostname username password name ret {'name' name 'changes' {} 'result' False 'comment' ''}if opts ['test'] return test output ret 'delete' params {'hostname' hostname 'username' username 'password' password 'name' name} existing salt ['bigip list virtual'] hostname username password name if existing[... | def delete_virtual hostname username password name ret {'name' name 'changes' {} 'result' False 'comment' ''}if __opts__['test'] return _test_output ret 'delete' params {'hostname' hostname 'username' username 'password' password 'name' name} existing __salt__['bigip list_virtual'] hostname username password name if ex... | 86 |
python-test-6794 | python | What does the code ensure ? | that the named user is absent name the name of the user to remove purge set purge to true to delete all of the users files as well as the user | def absent name purge False force False ret {'name' name 'changes' {} 'result' True 'comment' ''}lusr salt ['user info'] name if lusr if opts ['test'] ret['result'] Noneret['comment'] ' User{ 0 }setforremoval' format name return retbeforegroups set salt utils get group list name ret['result'] salt ['user delete'] name ... | def absent name purge False force False ret {'name' name 'changes' {} 'result' True 'comment' ''}lusr __salt__['user info'] name if lusr if __opts__['test'] ret['result'] Noneret['comment'] 'User{0}setforremoval' format name return retbeforegroups set salt utils get_group_list name ret['result'] __salt__['user delete']... | 104 |
python-test-6795 | python | For what purpose do purge set purge remove ? | to true to delete all of the users files as well as the user | def absent name purge False force False ret {'name' name 'changes' {} 'result' True 'comment' ''}lusr salt ['user info'] name if lusr if opts ['test'] ret['result'] Noneret['comment'] ' User{ 0 }setforremoval' format name return retbeforegroups set salt utils get group list name ret['result'] salt ['user delete'] name ... | def absent name purge False force False ret {'name' name 'changes' {} 'result' True 'comment' ''}lusr __salt__['user info'] name if lusr if __opts__['test'] ret['result'] Noneret['comment'] 'User{0}setforremoval' format name return retbeforegroups set salt utils get_group_list name ret['result'] __salt__['user delete']... | 104 |
python-test-6798 | python | How does the code update the sqlite database ? | with all clips from kippt | def udpate Database From Kippt global settingsif not os path exists os path join alp local settings['sqlite DB'] create Database clips read All Clips if clips None returnconn lite connect settings['sqlite DB'] with conn cur conn cursor cur execute 'DELETEFROM Clips' for clip in clips title clip['title']subtitle clip['t... | def udpateDatabaseFromKippt global settingsif not os path exists os path join alp local settings['sqliteDB'] createDatabase clips readAllClips if clips None returnconn lite connect settings['sqliteDB'] with conn cur conn cursor cur execute 'DELETEFROMClips' for clip in clips title clip['title']subtitle clip['title']url... | 93 |
python-test-6799 | python | What does the code update with all clips from kippt ? | the sqlite database | def udpate Database From Kippt global settingsif not os path exists os path join alp local settings['sqlite DB'] create Database clips read All Clips if clips None returnconn lite connect settings['sqlite DB'] with conn cur conn cursor cur execute 'DELETEFROM Clips' for clip in clips title clip['title']subtitle clip['t... | def udpateDatabaseFromKippt global settingsif not os path exists os path join alp local settings['sqliteDB'] createDatabase clips readAllClips if clips None returnconn lite connect settings['sqliteDB'] with conn cur conn cursor cur execute 'DELETEFROMClips' for clip in clips title clip['title']subtitle clip['title']url... | 93 |
python-test-6800 | python | What does the code turn into an identifier ? | any string | def identify str if not str return 'empty ae name 'rv ''ok string ascii letters + ' ' ok 2 ok + string digits for c in str if c in ok rv rv + c elif c '' rv rv + ' ' else rv rv + ' %02 2x ' % ord c ok ok 2 if keyword iskeyword rv rv rv + ' ' return rv | def identify str if not str return 'empty_ae_name_'rv ''ok string ascii_letters + '_' ok2 ok + string digits for c in str if c in ok rv rv + c elif c '' rv rv + '_' else rv rv + '_%02 2x_' % ord c ok ok2if keyword iskeyword rv rv rv + '_' return rv | 69 |
python-test-6801 | python | What does the code ensure ? | the endpoints of a range are finite and not too close together | def nonsingular vmin vmax expander 0 001 tiny 1e- 15 increasing True if not np isfinite vmin or not np isfinite vmax return - expander expander swapped Falseif vmax < vmin vmin vmax vmax vmin swapped Trueif vmax - vmin < max abs vmin abs vmax * tiny if vmin 0 0 vmin - expander vmax expanderelse vmin - expander * abs vm... | def nonsingular vmin vmax expander 0 001 tiny 1e-15 increasing True if not np isfinite vmin or not np isfinite vmax return - expander expander swapped Falseif vmax < vmin vmin vmax vmax vmin swapped Trueif vmax - vmin < max abs vmin abs vmax * tiny if vmin 0 0 vmin - expander vmax expanderelse vmin - expander * abs vmi... | 81 |
python-test-6805 | python | What does this call the windows in a unicode safe way ? | queryvalueex function | def Query Value Ex key value name regqueryvalueex advapi 32 [' Reg Query Value Ex W']regqueryvalueex restype ctypes c longregqueryvalueex argtypes [ctypes c void p ctypes c wchar p LPDWORD LPDWORD LPBYTE LPDWORD]size 256 data type ctypes wintypes DWORD while True tmp size ctypes wintypes DWORD size buf ctypes create st... | def QueryValueEx key value_name regqueryvalueex advapi32['RegQueryValueExW']regqueryvalueex restype ctypes c_longregqueryvalueex argtypes [ctypes c_void_p ctypes c_wchar_p LPDWORD LPDWORD LPBYTE LPDWORD]size 256data_type ctypes wintypes DWORD while True tmp_size ctypes wintypes DWORD size buf ctypes create_string_buffe... | 118 |
python-test-6817 | python | Where is the output cached ? | in _ sites_relpath_db | def relpath to site lang target lang path SITES RELPATH DB get lang target lang None if path is None siteurl SITE DB get lang MAIN SITEURL target siteurl SITE DB get target lang MAIN SITEURL path posixpath relpath get site path target siteurl get site path siteurl SITES RELPATH DB[ lang target lang ] pathreturn path | def relpath_to_site lang target_lang path _SITES_RELPATH_DB get lang target_lang None if path is None siteurl _SITE_DB get lang _MAIN_SITEURL target_siteurl _SITE_DB get target_lang _MAIN_SITEURL path posixpath relpath get_site_path target_siteurl get_site_path siteurl _SITES_RELPATH_DB[ lang target_lang ] pathreturn p... | 57 |
python-test-6818 | python | In which direction does the code get relative path ? | from siteurl of lang to siteurl of base_lang | def relpath to site lang target lang path SITES RELPATH DB get lang target lang None if path is None siteurl SITE DB get lang MAIN SITEURL target siteurl SITE DB get target lang MAIN SITEURL path posixpath relpath get site path target siteurl get site path siteurl SITES RELPATH DB[ lang target lang ] pathreturn path | def relpath_to_site lang target_lang path _SITES_RELPATH_DB get lang target_lang None if path is None siteurl _SITE_DB get lang _MAIN_SITEURL target_siteurl _SITE_DB get target_lang _MAIN_SITEURL path posixpath relpath get_site_path target_siteurl get_site_path siteurl _SITES_RELPATH_DB[ lang target_lang ] pathreturn p... | 57 |
python-test-6819 | python | What does the code notify ? | a list_user_subscribed event | def notify list user subscribed e target e['target']if target['screen name'] c['original name'] returnsource e['source']target object [e['target object']]created at e['created at']source user cycle color source['name'] + color func c['NOTIFICATION']['source nick'] '@' + source['screen name'] notify color func c['NOTIFI... | def notify_list_user_subscribed e target e['target']if target['screen_name'] c['original_name'] returnsource e['source']target_object [e['target_object']]created_at e['created_at']source_user cycle_color source['name'] + color_func c['NOTIFICATION']['source_nick'] '@' + source['screen_name'] notify color_func c['NOTIFI... | 89 |
python-test-6820 | python | What does the code ensure ? | a registry value is removed | def absent name vname None use 32 bit registry False ret {'name' name 'result' True 'changes' {} 'comment' ''} hive key parse key name reg check salt ['reg read value'] hive hive key key vname vname use 32 bit registry use 32 bit registry if not reg check['success'] or reg check['vdata'] ' valuenotset ' ret['comment'] ... | def absent name vname None use_32bit_registry False ret {'name' name 'result' True 'changes' {} 'comment' ''} hive key _parse_key name reg_check __salt__['reg read_value'] hive hive key key vname vname use_32bit_registry use_32bit_registry if not reg_check['success'] or reg_check['vdata'] ' valuenotset ' ret['comment']... | 147 |
python-test-6822 | python | What must have the following properties : to_addr - [ ? | URL messages | def calculate group scores messages user email now datetime datetime now message ids to scores {}molecules dict defaultdict set def get message list weight message ids return sum [message ids to scores[m id] for m id in message ids] for msg in messages participants get participants msg [user email] if len participants ... | def calculate_group_scores messages user_email now datetime datetime now message_ids_to_scores {}molecules_dict defaultdict set def get_message_list_weight message_ids return sum [message_ids_to_scores[m_id] for m_id in message_ids] for msg in messages participants _get_participants msg [user_email] if len participants... | 155 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.