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-2441 | python | What do controller manage ? | the second phase of the import of vulnerability indicators from csv | def import vul csv part 2 job id request post vars jobif not job id return " Error No Job ID'sprovided"output s3 rest controller 'vulnerability' 'data' csv stylesheet 'data xsl' total Records output[ 0 ]total Errors output[ 1 ]total Ignored output[ 2 ]from gluon serializers import json as jsonsresponse headers[' Conten... | def import_vul_csv_part2 job_id request post_vars jobif not job_id return "ErrorNoJobID'sprovided"output s3_rest_controller 'vulnerability' 'data' csv_stylesheet 'data xsl' totalRecords output[0]totalErrors output[1]totalIgnored output[2]from gluon serializers import json as jsonsresponse headers['Content-Type'] 'appli... | 66 |
python-test-2455 | python | What does the code get ? | a python module for a clsid given a clsid | def Get Module For CLSID clsid clsid str str clsid try typelib CLSID lcid major minor clsid To Typelib[clsid str]except Key Error return Nonetry mod Get Module For Typelib typelib CLSID lcid major minor except Import Error mod Noneif mod is not None sub mod mod CLSID To Package Map get clsid str if sub mod is None sub ... | def GetModuleForCLSID clsid clsid_str str clsid try typelibCLSID lcid major minor clsidToTypelib[clsid_str]except KeyError return Nonetry mod GetModuleForTypelib typelibCLSID lcid major minor except ImportError mod Noneif mod is not None sub_mod mod CLSIDToPackageMap get clsid_str if sub_mod is None sub_mod mod VTables... | 128 |
python-test-2458 | python | What does the code setup ? | the roku platform | def setup platform hass config add devices discovery info None hosts []if discovery info and discovery info in KNOWN HOSTS returnif discovery info is not None LOGGER debug ' Discovered Roku %s' discovery info[ 0 ] hosts append discovery info[ 0 ] elif CONF HOST in config hosts append config get CONF HOST rokus []for ho... | def setup_platform hass config add_devices discovery_info None hosts []if discovery_info and discovery_info in KNOWN_HOSTS returnif discovery_info is not None _LOGGER debug 'DiscoveredRoku %s' discovery_info[0] hosts append discovery_info[0] elif CONF_HOST in config hosts append config get CONF_HOST rokus []for host in... | 87 |
python-test-2459 | python | What does the code write ? | a bem model with solution | def write bem solution fname bem check bem size bem['surfs'] with start file fname as fid start block fid FIFF FIFFB BEM write int fid FIFF FIFF BEM COORD FRAME bem['surfs'][ 0 ]['coord frame'] write bem surfaces block fid bem['surfs'] if 'solution' in bem if bem['bem method'] FIFF FWD BEM LINEAR COLL raise Runtime Err... | def write_bem_solution fname bem _check_bem_size bem['surfs'] with start_file fname as fid start_block fid FIFF FIFFB_BEM write_int fid FIFF FIFF_BEM_COORD_FRAME bem['surfs'][0]['coord_frame'] _write_bem_surfaces_block fid bem['surfs'] if 'solution' in bem if bem['bem_method'] FIFF FWD_BEM_LINEAR_COLL raise RuntimeErro... | 88 |
python-test-2460 | python | What does prints colors and styles to the terminal use ? | ansi escape sequences | def color print *args **kwargs file kwargs get u'file' get stdout end kwargs get u'end' u'\n' write file writeif isatty file and conf use color for i in range 0 len args 2 msg args[i]if i + 1 len args color u''else color args[ i + 1 ]if color msg color text msg color if six PY 2 and isinstance msg bytes msg decode pref... | def color_print *args **kwargs file kwargs get u'file' _get_stdout end kwargs get u'end' u'\n' write file writeif isatty file and conf use_color for i in range 0 len args 2 msg args[i]if i + 1 len args color u''else color args[ i + 1 ]if color msg _color_text msg color if six PY2 and isinstance msg bytes msg _decode_pr... | 103 |
python-test-2461 | python | What uses ansi escape sequences ? | prints colors and styles to the terminal | def color print *args **kwargs file kwargs get u'file' get stdout end kwargs get u'end' u'\n' write file writeif isatty file and conf use color for i in range 0 len args 2 msg args[i]if i + 1 len args color u''else color args[ i + 1 ]if color msg color text msg color if six PY 2 and isinstance msg bytes msg decode pref... | def color_print *args **kwargs file kwargs get u'file' _get_stdout end kwargs get u'end' u'\n' write file writeif isatty file and conf use_color for i in range 0 len args 2 msg args[i]if i + 1 len args color u''else color args[ i + 1 ]if color msg _color_text msg color if six PY2 and isinstance msg bytes msg _decode_pr... | 103 |
python-test-2465 | python | In which direction does the code kick a user ? | from the channel | @require chanmsg@require privilege OP u' Youarenotachanneloperator ' @commands u'kick' @priority u'high' def kick bot trigger if bot privileges[trigger sender][bot nick] < HALFOP return bot reply u"I'mnotachanneloperator " text trigger group split argc len text if argc < 2 returnopt Identifier text[ 1 ] nick optchannel... | @require_chanmsg@require_privilege OP u'Youarenotachanneloperator ' @commands u'kick' @priority u'high' def kick bot trigger if bot privileges[trigger sender][bot nick] < HALFOP return bot reply u"I'mnotachanneloperator " text trigger group split argc len text if argc < 2 returnopt Identifier text[1] nick optchannel tr... | 78 |
python-test-2466 | python | What does this function prepare ? | a dataframe for ros | def ros sort df observations censorship warn False censored sort values df[df[censorship]] observations axis 0 uncensored sort values df[ ~ df[censorship] ] observations axis 0 if censored[observations] max > uncensored[observations] max censored censored[ censored[observations] < uncensored[observations] max ]if warn ... | def _ros_sort df observations censorship warn False censored sort_values df[df[censorship]] observations axis 0 uncensored sort_values df[ ~ df[censorship] ] observations axis 0 if censored[observations] max > uncensored[observations] max censored censored[ censored[observations] < uncensored[observations] max ]if warn... | 55 |
python-test-2476 | python | What does the code get ? | a vif or physical nic representation | def get eth link vif ifc num link id vif get 'devname' if not link id link id 'interface%d' % ifc num if vif get 'type' 'ethernet' nic type 'phy'else nic type vif get 'type' link {'id' link id 'vif id' vif['id'] 'type' nic type 'mtu' vif['network']['meta'] get 'mtu' 'ethernet mac address' vif get 'address' }return link | def _get_eth_link vif ifc_num link_id vif get 'devname' if not link_id link_id 'interface%d' % ifc_num if vif get 'type' 'ethernet' nic_type 'phy'else nic_type vif get 'type' link {'id' link_id 'vif_id' vif['id'] 'type' nic_type 'mtu' vif['network']['meta'] get 'mtu' 'ethernet_mac_address' vif get 'address' }return lin... | 57 |
python-test-2478 | python | What do lomb - scargle periodogram compute ? | the expected probability density function of the periodogram for the null hypothesis - i | def lombscargle pdf z N normalization dH 1 dK 3 if dK - dH 2 raise Not Implemented Error ' Degreesoffreedom 2' Nk N - dK if normalization 'psd' return np exp - z elif normalization 'standard' return 0 5 * Nk * 1 + z ** -0 5 * Nk - 1 elif normalization 'model' return 0 5 * Nk * 1 - z ** 0 5 * Nk - 1 elif normalization '... | def _lombscargle_pdf z N normalization dH 1 dK 3 if dK - dH 2 raise NotImplementedError 'Degreesoffreedom 2' Nk N - dK if normalization 'psd' return np exp - z elif normalization 'standard' return 0 5 * Nk * 1 + z ** -0 5 * Nk - 1 elif normalization 'model' return 0 5 * Nk * 1 - z ** 0 5 * Nk - 1 elif normalization 'lo... | 99 |
python-test-2479 | python | What compute the expected probability density function of the periodogram for the null hypothesis - i ? | lomb - scargle periodogram | def lombscargle pdf z N normalization dH 1 dK 3 if dK - dH 2 raise Not Implemented Error ' Degreesoffreedom 2' Nk N - dK if normalization 'psd' return np exp - z elif normalization 'standard' return 0 5 * Nk * 1 + z ** -0 5 * Nk - 1 elif normalization 'model' return 0 5 * Nk * 1 - z ** 0 5 * Nk - 1 elif normalization '... | def _lombscargle_pdf z N normalization dH 1 dK 3 if dK - dH 2 raise NotImplementedError 'Degreesoffreedom 2' Nk N - dK if normalization 'psd' return np exp - z elif normalization 'standard' return 0 5 * Nk * 1 + z ** -0 5 * Nk - 1 elif normalization 'model' return 0 5 * Nk * 1 - z ** 0 5 * Nk - 1 elif normalization 'lo... | 99 |
python-test-2485 | python | What does the code ensure ? | an apache site is enabled | def enabled name ret {'name' name 'result' True 'comment' '' 'changes' {}}is enabled salt ['apache check site enabled'] name if not is enabled if opts ['test'] msg ' Apachesite{ 0 }issettobeenabled ' format name ret['comment'] msgret['changes']['old'] Noneret['changes']['new'] nameret['result'] Nonereturn retstatus sal... | def enabled name ret {'name' name 'result' True 'comment' '' 'changes' {}}is_enabled __salt__['apache check_site_enabled'] name if not is_enabled if __opts__['test'] msg 'Apachesite{0}issettobeenabled ' format name ret['comment'] msgret['changes']['old'] Noneret['changes']['new'] nameret['result'] Nonereturn retstatus ... | 93 |
python-test-2487 | python | What does the code get for example ? | the name of the node | def get print name node simple form True name node fullnameif hasattr node u' interface' pkglist node interface class module split u' ' interface node interface class name destclass u''if len pkglist > 2 destclass u' %s' % pkglist[ 2 ] if simple form name node fullname + destclass else name u' ' join [node fullname int... | def get_print_name node simple_form True name node fullnameif hasattr node u'_interface' pkglist node _interface __class__ __module__ split u' ' interface node _interface __class__ __name__destclass u''if len pkglist > 2 destclass u' %s' % pkglist[2] if simple_form name node fullname + destclass else name u' ' join [no... | 91 |
python-test-2498 | python | What does approximate joint diagonalization implementation obtain ? | same results as the matlab implementation by pham dinh - tuan | def test ajd n times n channels 10 3 seed np random Random State 0 diags 2 0 + 0 1 * seed randn n times n channels A 2 * seed rand n channels n channels - 1 A / np atleast 2d np sqrt np sum A ** 2 1 Tcovmats np empty n times n channels n channels for i in range n times covmats[i] np dot np dot A np diag diags[i] A T V ... | def test_ajd n_times n_channels 10 3 seed np random RandomState 0 diags 2 0 + 0 1 * seed randn n_times n_channels A 2 * seed rand n_channels n_channels - 1 A / np atleast_2d np sqrt np sum A ** 2 1 Tcovmats np empty n_times n_channels n_channels for i in range n_times covmats[i] np dot np dot A np diag diags[i] A T V D... | 114 |
python-test-2499 | python | What obtains same results as the matlab implementation by pham dinh - tuan ? | approximate joint diagonalization implementation | def test ajd n times n channels 10 3 seed np random Random State 0 diags 2 0 + 0 1 * seed randn n times n channels A 2 * seed rand n channels n channels - 1 A / np atleast 2d np sqrt np sum A ** 2 1 Tcovmats np empty n times n channels n channels for i in range n times covmats[i] np dot np dot A np diag diags[i] A T V ... | def test_ajd n_times n_channels 10 3 seed np random RandomState 0 diags 2 0 + 0 1 * seed randn n_times n_channels A 2 * seed rand n_channels n_channels - 1 A / np atleast_2d np sqrt np sum A ** 2 1 Tcovmats np empty n_times n_channels n_channels for i in range n_times covmats[i] np dot np dot A np diag diags[i] A T V D... | 114 |
python-test-2503 | python | Where does the code run an arbitrary replacement function ? | on any urls matching the static file directory | def process static urls text replacement function data dir None def wrap part extraction match '\n Unwrapsamatchgroupforthecapturesspecifiedin url replace regex\nandforwardthemonasfunctionarguments\n'original match group 0 prefix match group 'prefix' quote match group 'quote' rest match group 'rest' full url prefix + r... | def process_static_urls text replacement_function data_dir None def wrap_part_extraction match '\nUnwrapsamatchgroupforthecapturesspecifiedin_url_replace_regex\nandforwardthemonasfunctionarguments\n'original match group 0 prefix match group 'prefix' quote match group 'quote' rest match group 'rest' full_url prefix + re... | 119 |
python-test-2504 | python | What does the code run on any urls matching the static file directory ? | an arbitrary replacement function | def process static urls text replacement function data dir None def wrap part extraction match '\n Unwrapsamatchgroupforthecapturesspecifiedin url replace regex\nandforwardthemonasfunctionarguments\n'original match group 0 prefix match group 'prefix' quote match group 'quote' rest match group 'rest' full url prefix + r... | def process_static_urls text replacement_function data_dir None def wrap_part_extraction match '\nUnwrapsamatchgroupforthecapturesspecifiedin_url_replace_regex\nandforwardthemonasfunctionarguments\n'original match group 0 prefix match group 'prefix' quote match group 'quote' rest match group 'rest' full_url prefix + re... | 119 |
python-test-2505 | python | What does the code use ? | conv2d with a single input channel | def conv 1 d sc input filters image shape None filter shape None border mode 'valid' subsample 1 filter flip True if border mode not in 'valid' 0 0 raise Runtime Error ' Unsupportedborder modeforconv 1 d sc %s' % border mode if image shape is None image shape sc Noneelse image shape sc image shape[ 0 ] 1 image shape[ 1... | def conv1d_sc input filters image_shape None filter_shape None border_mode 'valid' subsample 1 filter_flip True if border_mode not in 'valid' 0 0 raise RuntimeError 'Unsupportedborder_modeforconv1d_sc %s' % border_mode if image_shape is None image_shape_sc Noneelse image_shape_sc image_shape[0] 1 image_shape[1] image_s... | 139 |
python-test-2507 | python | What does the code make ? | a file system < fs_type > on partition < device > | def mkfs device fs type validate device device if fs type not in set ['ext 2 ' 'fat 32 ' 'fat 16 ' 'linux-swap' 'reiserfs' 'hfs' 'hfs+' 'hfsx' 'NTFS' 'ufs'] raise Command Execution Error ' Invalidfs typepassedtopartition mkfs' if fs type is 'linux-swap' mkfs cmd 'mkswap'else mkfs cmd 'mkfs {0 }' format fs type if not s... | def mkfs device fs_type _validate_device device if fs_type not in set ['ext2' 'fat32' 'fat16' 'linux-swap' 'reiserfs' 'hfs' 'hfs+' 'hfsx' 'NTFS' 'ufs'] raise CommandExecutionError 'Invalidfs_typepassedtopartition mkfs' if fs_type is 'linux-swap' mkfs_cmd 'mkswap'else mkfs_cmd 'mkfs {0}' format fs_type if not salt utils... | 84 |
python-test-2508 | python | What does the code generate ? | a list of salt://<formula>/defaults | def load formula mk client paths []for ext in 'yaml' 'json' source url salt utils url create formula + '/defaults ' + ext paths append source url defaults files context ['cp fileclient'] cache files paths for file in defaults files if not file continuesuffix file rsplit ' ' 1 [ -1 ]if suffix 'yaml' loader yamlelif suff... | def _load formula _mk_client paths []for ext in 'yaml' 'json' source_url salt utils url create formula + '/defaults ' + ext paths append source_url defaults_files __context__['cp fileclient'] cache_files paths for file_ in defaults_files if not file_ continuesuffix file_ rsplit ' ' 1 [ -1 ]if suffix 'yaml' loader yamle... | 95 |
python-test-2512 | python | What does the code create ? | a formatted message from a service health report | def Format Service Health Report report assert report get 'status' 'ALERT' message ''sub messages []alerts report get 'alerts' if len alerts > 1 message + ' %d Alerts ' % len alerts for a in alerts sub message '' + a get 'description' a get 'name' if a get 'cluster' False sub message + ' Cluster 'else sub message + ' %... | def _FormatServiceHealthReport report assert report get 'status' 'ALERT' message ''sub_messages []alerts report get 'alerts' if len alerts > 1 message + ' %dAlerts ' % len alerts for a in alerts sub_message '' + a get 'description' a get 'name' if a get 'cluster' False sub_message + ' Cluster 'else sub_message + ' %dma... | 80 |
python-test-2513 | python | What does the code blink ? | a lamp | def call blink *args **kwargs devices get lights pause kwargs get 'pause' 0 res dict for dev id in 'id' not in kwargs and sorted devices keys or get devices kwargs state devices[str dev id ]['state']['on'] set dev id state and Const LAMP OFF or Const LAMP ON if pause time sleep pause res[dev id] set dev id not state an... | def call_blink *args **kwargs devices _get_lights pause kwargs get 'pause' 0 res dict for dev_id in 'id' not in kwargs and sorted devices keys or _get_devices kwargs state devices[str dev_id ]['state']['on']_set dev_id state and Const LAMP_OFF or Const LAMP_ON if pause time sleep pause res[dev_id] _set dev_id not state... | 70 |
python-test-2519 | python | What does the code follow if not already followed ? | one or more logs | def follow log module le path logs name None logtype None followed count 0for log in logs if query log status module le path log continueif module check mode module exit json changed True cmd [le path 'follow' log]if name cmd extend ['--name' name] if logtype cmd extend ['--type' logtype] rc out err module run command ... | def follow_log module le_path logs name None logtype None followed_count 0for log in logs if query_log_status module le_path log continueif module check_mode module exit_json changed True cmd [le_path 'follow' log]if name cmd extend ['--name' name] if logtype cmd extend ['--type' logtype] rc out err module run_command ... | 107 |
python-test-2520 | python | What does the code make ? | a new extension | def make extension name files *args **kwargs ext Delayed Extension name files *args **kwargs for dir in get base dirs include dir os path join dir 'include' if os path exists include dir ext include dirs append include dir for lib in 'lib' 'lib 64 ' lib dir os path join dir lib if os path exists lib dir ext library dir... | def make_extension name files *args **kwargs ext DelayedExtension name files *args **kwargs for dir in get_base_dirs include_dir os path join dir 'include' if os path exists include_dir ext include_dirs append include_dir for lib in 'lib' 'lib64' lib_dir os path join dir lib if os path exists lib_dir ext library_dirs a... | 73 |
python-test-2526 | python | What returns on host ? | a free tcp port | @utils synchronized SERIAL LOCK def acquire port host start stop get port range for port in six moves range start stop if host port in ALLOCATED PORTS continuetry verify port host port ALLOCATED PORTS add host port return portexcept exception Socket Port In Use Exception as e LOG warning e format message raise exceptio... | @utils synchronized SERIAL_LOCK def acquire_port host start stop _get_port_range for port in six moves range start stop if host port in ALLOCATED_PORTS continuetry _verify_port host port ALLOCATED_PORTS add host port return portexcept exception SocketPortInUseException as e LOG warning e format_message raise exception ... | 61 |
python-test-2530 | python | What does the code start in a thread ? | celery worker | @contextmanagerdef start worker thread app concurrency 1 pool u'solo' loglevel WORKER LOGLEVEL logfile None Work Controller Test Work Controller **kwargs setup app for worker app loglevel logfile assert u'celery ping' in app tasks with app connection as conn conn default channel queue declareworker Work Controller app ... | @contextmanagerdef _start_worker_thread app concurrency 1 pool u'solo' loglevel WORKER_LOGLEVEL logfile None WorkController TestWorkController **kwargs setup_app_for_worker app loglevel logfile assert u'celery ping' in app tasks with app connection as conn conn default_channel queue_declareworker WorkController app app... | 104 |
python-test-2533 | python | For what purpose do at least two string columns need ? | to test str_cat | @pytest mark parametrize 'sep' [ None 'sep'] def test str cat sep if sep is None expr t str cat name str cat t str cat comment expected '\n SELEC Taccounts 2 name accounts 2 comment\n A Sanon 1FRO Maccounts 2 \n'else expr t str cat name str cat t str cat comment sep sep expected '\n SELEC Taccounts 2 name name 1 accoun... | @pytest mark parametrize 'sep' [None 'sep'] def test_str_cat sep if sep is None expr t_str_cat name str_cat t_str_cat comment expected '\nSELECTaccounts2 name accounts2 comment\nASanon_1FROMaccounts2\n'else expr t_str_cat name str_cat t_str_cat comment sep sep expected '\nSELECTaccounts2 name name_1 accounts2 comment\n... | 86 |
python-test-2538 | python | What does the code get ? | sign - flip | def get label flip labels label vertidx src from label import label sign fliplabel flip list for label vertidx in zip labels label vertidx if label hemi 'both' raise Value Error ' Bi Hemi Labelnotsupportedwhenusingsign-flip' if vertidx is not None flip label sign flip label src [ None]else flip Nonelabel flip append fl... | def _get_label_flip labels label_vertidx src from label import label_sign_fliplabel_flip list for label vertidx in zip labels label_vertidx if label hemi 'both' raise ValueError 'BiHemiLabelnotsupportedwhenusingsign-flip' if vertidx is not None flip label_sign_flip label src [ None]else flip Nonelabel_flip append flip ... | 56 |
python-test-2543 | python | What does this function perform ? | the boolean sliding window probability estimation | def p boolean sliding window texts segmented topics dictionary window size top ids ret top ids segmented topics window id 0per topic postings {}token 2 id dict dictionary token 2 iddef add topic posting top ids window per topic postings window id token 2 id dict for word in window word id token 2 id dict[word]if word i... | def p_boolean_sliding_window texts segmented_topics dictionary window_size top_ids _ret_top_ids segmented_topics window_id 0per_topic_postings {}token2id_dict dictionary token2iddef add_topic_posting top_ids window per_topic_postings window_id token2id_dict for word in window word_id token2id_dict[word]if word_id in to... | 161 |
python-test-2546 | python | What does the code build ? | the source coordinates for the output of a 2-d image warp | def warp coords coord map shape dtype np float 64 shape safe as int shape rows cols shape[ 0 ] shape[ 1 ] coords shape [len shape rows cols]if len shape 3 coords shape append shape[ 2 ] coords np empty coords shape dtype dtype tf coords np indices cols rows dtype dtype reshape 2 -1 Ttf coords coord map tf coords tf coo... | def warp_coords coord_map shape dtype np float64 shape safe_as_int shape rows cols shape[0] shape[1] coords_shape [len shape rows cols]if len shape 3 coords_shape append shape[2] coords np empty coords_shape dtype dtype tf_coords np indices cols rows dtype dtype reshape 2 -1 Ttf_coords coord_map tf_coords tf_coords tf_... | 103 |
python-test-2548 | python | What does this function compute ? | the lfsr autocorrelation function | def lfsr autocorrelation L P k if not isinstance L list raise Type Error 'L %s mustbealist' % L P int P k int k L0 L[ P]L 1 L0 + L0 [ k] L2 [ -1 ** L1 [i] to int + L1 [ i + k ] to int for i in range P ]tot sum L2 return Rational tot P | def lfsr_autocorrelation L P k if not isinstance L list raise TypeError 'L %s mustbealist' % L P int P k int k L0 L[ P]L1 L0 + L0[ k] L2 [ -1 ** L1[i] to_int + L1[ i + k ] to_int for i in range P ]tot sum L2 return Rational tot P | 63 |
python-test-2549 | python | What does the code delete if present ? | its minion key | def purge name delete key True quiet False path None data do names name 'destroy' path path if data is False return dataif delete key skey salt key Key opts skey delete key name if data is None returnif not quiet jid event fire event {'data' data 'outputter' 'lxc purge'} 'progress' return data | def purge name delete_key True quiet False path None data _do_names name 'destroy' path path if data is False return dataif delete_key skey salt key Key __opts__ skey delete_key name if data is None returnif not quiet __jid_event__ fire_event {'data' data 'outputter' 'lxc_purge'} 'progress' return data | 53 |
python-test-2559 | python | What forces a locale ? | set return | def set locale cls request force None locales cls app config get 'locales' if not locales return Nonelocale forceif locale not in locales locale cls request get 'hl' None if locale not in locales locale cls request cookies get 'hl' None if locale not in locales locale get locale from accept header cls request if locale... | def set_locale cls request force None locales cls app config get 'locales' if not locales return Nonelocale forceif locale not in locales locale cls request get 'hl' None if locale not in locales locale cls request cookies get 'hl' None if locale not in locales locale get_locale_from_accept_header cls request if locale... | 103 |
python-test-2560 | python | For what purpose do detail show ? | for a single personal access token | @must be logged indef personal access token detail auth **kwargs id kwargs get ' id' try record Api O Auth 2 Personal Token find one Q ' id' 'eq' id except No Results Found raise HTTP Error http NOT FOUND if record owner auth user raise HTTP Error http FORBIDDEN if record is active is False raise HTTP Error http GONE t... | @must_be_logged_indef personal_access_token_detail auth **kwargs _id kwargs get '_id' try record ApiOAuth2PersonalToken find_one Q '_id' 'eq' _id except NoResultsFound raise HTTPError http NOT_FOUND if record owner auth user raise HTTPError http FORBIDDEN if record is_active is False raise HTTPError http GONE token_det... | 87 |
python-test-2561 | python | What does the code add ? | a permission to a lambda function | def add permission Function Name Statement Id Action Principal Source Arn None Source Account None Qualifier None region None key None keyid None profile None try conn get conn region region key key keyid keyid profile profile kwargs {}for key in ' Source Arn' ' Source Account' ' Qualifier' if locals [key] is not None ... | def add_permission FunctionName StatementId Action Principal SourceArn None SourceAccount None Qualifier None region None key None keyid None profile None try conn _get_conn region region key key keyid keyid profile profile kwargs {}for key in 'SourceArn' 'SourceAccount' 'Qualifier' if locals [key] is not None kwargs[k... | 95 |
python-test-2562 | python | What does the code approve ? | the files waiting for review | def approve files files with review type for file review type in files with review type version file versionaddon version addonhelper Review Helper request None addon addon version file version helper set data {'addon files' [file ] 'comments' u'bulkapproval'} if review type 'full' helper handler process public log inf... | def approve_files files_with_review_type for file_ review_type in files_with_review_type version file_ versionaddon version addonhelper ReviewHelper request None addon addon version file_ version helper set_data {'addon_files' [file_] 'comments' u'bulkapproval'} if review_type 'full' helper handler process_public log i... | 76 |
python-test-2565 | python | What does a simple view echo ? | its status line | def trace view request if request method upper 'TRACE' return Http Response Not Allowed 'TRACE' elif request body return Http Response Bad Request 'TRAC Erequests MUSTNO Tincludeanentity' else protocol request META['SERVER PROTOCOL']t Template '{{method}}{{uri}}{{version}}' name 'TRACE Template' c Context {'method' req... | def trace_view request if request method upper 'TRACE' return HttpResponseNotAllowed 'TRACE' elif request body return HttpResponseBadRequest 'TRACErequestsMUSTNOTincludeanentity' else protocol request META['SERVER_PROTOCOL']t Template '{{method}}{{uri}}{{version}}' name 'TRACETemplate' c Context {'method' request metho... | 53 |
python-test-2566 | python | What does a simple view expect ? | a trace request | def trace view request if request method upper 'TRACE' return Http Response Not Allowed 'TRACE' elif request body return Http Response Bad Request 'TRAC Erequests MUSTNO Tincludeanentity' else protocol request META['SERVER PROTOCOL']t Template '{{method}}{{uri}}{{version}}' name 'TRACE Template' c Context {'method' req... | def trace_view request if request method upper 'TRACE' return HttpResponseNotAllowed 'TRACE' elif request body return HttpResponseBadRequest 'TRACErequestsMUSTNOTincludeanentity' else protocol request META['SERVER_PROTOCOL']t Template '{{method}}{{uri}}{{version}}' name 'TRACETemplate' c Context {'method' request metho... | 53 |
python-test-2568 | python | What does the code return ? | the number of bytes specified from a file | def get Bytes From File filename offset num Bytes if not isinstance offset int or not isinstance num Bytes int return -1 ' Theoffsetandthenumberofbytesmustbeintegers' if os path exists filename file Size os path getsize filename bytes File open filename 'rb' bytes File seek offset if offset + num Bytes > file Size byte... | def getBytesFromFile filename offset numBytes if not isinstance offset int or not isinstance numBytes int return -1 'Theoffsetandthenumberofbytesmustbeintegers' if os path exists filename fileSize os path getsize filename bytesFile open filename 'rb' bytesFile seek offset if offset + numBytes > fileSize bytes bytesFile... | 74 |
python-test-2572 | python | What does the code get ? | an auth token | def get token username opts get 'rallydev' {} get 'username' None password opts get 'rallydev' {} get 'password' None path 'https //rally 1 rallydev com/slm/webservice/v 2 0/security/authorize'result salt utils http query path decode True decode type 'json' text True status True username username password password cook... | def _get_token username __opts__ get 'rallydev' {} get 'username' None password __opts__ get 'rallydev' {} get 'password' None path 'https //rally1 rallydev com/slm/webservice/v2 0/security/authorize'result salt utils http query path decode True decode_type 'json' text True status True username username password passwo... | 64 |
python-test-2577 | python | For what purpose does the code extract all least squares problems in this file ? | for benchmarking | def extract lsq problems problems Ordered Dict for name problem class in inspect getmembers sys modules[ name ] inspect isclass if name 'LSQ Benchmark Problem' and issubclass problem class LSQ Benchmark Problem and hasattr problem class 'INITIAL GUESSES' for i x0 in enumerate problem class INITIAL GUESSES if len proble... | def extract_lsq_problems problems OrderedDict for name problem_class in inspect getmembers sys modules[__name__] inspect isclass if name 'LSQBenchmarkProblem' and issubclass problem_class LSQBenchmarkProblem and hasattr problem_class 'INITIAL_GUESSES' for i x0 in enumerate problem_class INITIAL_GUESSES if len problem_c... | 75 |
python-test-2578 | python | What does the code extract in this file for benchmarking ? | all least squares problems | def extract lsq problems problems Ordered Dict for name problem class in inspect getmembers sys modules[ name ] inspect isclass if name 'LSQ Benchmark Problem' and issubclass problem class LSQ Benchmark Problem and hasattr problem class 'INITIAL GUESSES' for i x0 in enumerate problem class INITIAL GUESSES if len proble... | def extract_lsq_problems problems OrderedDict for name problem_class in inspect getmembers sys modules[__name__] inspect isclass if name 'LSQBenchmarkProblem' and issubclass problem_class LSQBenchmarkProblem and hasattr problem_class 'INITIAL_GUESSES' for i x0 in enumerate problem_class INITIAL_GUESSES if len problem_c... | 75 |
python-test-2579 | python | What does the code ensure ? | that its possible to output a hug api method as camelcased json | def test json camelcase test data {'under score' 'values can' 'be converted' [{'to camelcase' 'value'} 'wont be convert']}output hug output format json camelcase test data decode 'utf 8 ' assert 'under Score' in output assert 'values can' in output assert 'be Converted' in output assert 'to Camelcase' in output assert ... | def test_json_camelcase test_data {'under_score' 'values_can' 'be_converted' [{'to_camelcase' 'value'} 'wont_be_convert']}output hug output_format json_camelcase test_data decode 'utf8' assert 'underScore' in output assert 'values_can' in output assert 'beConverted' in output assert 'toCamelcase' in output assert 'valu... | 59 |
python-test-2586 | python | How do test average ? | with acqparserfif vs | @testing requires testing datadef test acqparser averaging raw read raw fif fname raw elekta preload True acqp Acq Parser FIF raw info for cat in acqp categories cond acqp get condition raw cat eps Epochs raw baseline -0 05 0 **cond ev eps average ev ref read evokeds fname ave elekta cat['comment'] baseline -0 05 0 pro... | @testing requires_testing_datadef test_acqparser_averaging raw read_raw_fif fname_raw_elekta preload True acqp AcqParserFIF raw info for cat in acqp categories cond acqp get_condition raw cat eps Epochs raw baseline -0 05 0 **cond ev eps average ev_ref read_evokeds fname_ave_elekta cat['comment'] baseline -0 05 0 proj ... | 142 |
python-test-2588 | python | What computes in gf(p)[x]/(f ? | polynomial trace map | def gf trace map a b c n f p K u gf compose mod a b f p K v bif n & 1 U gf add a u p K V belse U aV cn >> 1while n u gf add u gf compose mod u v f p K p K v gf compose mod v v f p K if n & 1 U gf add U gf compose mod u V f p K p K V gf compose mod v V f p K n >> 1return gf compose mod a V f p K U | def gf_trace_map a b c n f p K u gf_compose_mod a b f p K v bif n & 1 U gf_add a u p K V belse U aV cn >> 1while n u gf_add u gf_compose_mod u v f p K p K v gf_compose_mod v v f p K if n & 1 U gf_add U gf_compose_mod u V f p K p K V gf_compose_mod v V f p K n >> 1return gf_compose_mod a V f p K U | 102 |
python-test-2589 | python | Where do polynomial trace map compute ? | in gf(p)[x]/(f | def gf trace map a b c n f p K u gf compose mod a b f p K v bif n & 1 U gf add a u p K V belse U aV cn >> 1while n u gf add u gf compose mod u v f p K p K v gf compose mod v v f p K if n & 1 U gf add U gf compose mod u V f p K p K V gf compose mod v V f p K n >> 1return gf compose mod a V f p K U | def gf_trace_map a b c n f p K u gf_compose_mod a b f p K v bif n & 1 U gf_add a u p K V belse U aV cn >> 1while n u gf_add u gf_compose_mod u v f p K p K v gf_compose_mod v v f p K if n & 1 U gf_add U gf_compose_mod u V f p K p K V gf_compose_mod v V f p K n >> 1return gf_compose_mod a V f p K U | 102 |
python-test-2597 | python | What are visible here ? | all inbound messages | def inbox if not auth s3 logged in session error T ' Requires Login ' redirect URL c 'default' f 'user' args 'login' table s3 db msg messages 3 filter table inbound True table inbound readable Falsetablename 'msg message's 3 crud strings[tablename] Storage title display T ' Message Details' title list T ' In Box' label... | def inbox if not auth s3_logged_in session error T 'RequiresLogin ' redirect URL c 'default' f 'user' args 'login' table s3db msg_messages3 filter table inbound True table inbound readable Falsetablename 'msg_message's3 crud_strings[tablename] Storage title_display T 'MessageDetails' title_list T 'InBox' label_list_but... | 108 |
python-test-2600 | python | Where did columns define implicitly ? | on its child | def test column params should be preserved under inheritance class My Table A My Table u'\nhavinganempty`class Meta`shouldnotundotheexplicitdefinition\nofcolumnitem 1 in My Table \n'class Meta My Table Meta passclass My Table B My Table u'\nhavinganon-empty`class Meta`shouldnotundotheexplicitdefinition\nofcolumnitem 1 ... | def test_column_params_should_be_preserved_under_inheritance class MyTableA MyTable u'\nhavinganempty`classMeta`shouldnotundotheexplicitdefinition\nofcolumnitem1inMyTable \n'class Meta MyTable Meta passclass MyTableB MyTable u'\nhavinganon-empty`classMeta`shouldnotundotheexplicitdefinition\nofcolumnitem1inMyTable \n'cl... | 100 |
python-test-2601 | python | How does direct integration to support aws only currently ? | with aws vpc coming soon | @pytest fixture scope 'session' def dcos launchpad dcos api session if 'AWS STACK NAME' not in os environ pytest skip ' Mustusea AWS Cloudformationtoruntest' stack name os environ['AWS STACK NAME']aws region os environ['AWS REGION']aws access key id os environ['AWS ACCESS KEY ID']aws secret access key os environ['AWS S... | @pytest fixture scope 'session' def dcos_launchpad dcos_api_session if 'AWS_STACK_NAME' not in os environ pytest skip 'MustuseaAWSCloudformationtoruntest' stack_name os environ['AWS_STACK_NAME']aws_region os environ['AWS_REGION']aws_access_key_id os environ['AWS_ACCESS_KEY_ID']aws_secret_access_key os environ['AWS_SECR... | 75 |
python-test-2602 | python | When do vpc come ? | soon | @pytest fixture scope 'session' def dcos launchpad dcos api session if 'AWS STACK NAME' not in os environ pytest skip ' Mustusea AWS Cloudformationtoruntest' stack name os environ['AWS STACK NAME']aws region os environ['AWS REGION']aws access key id os environ['AWS ACCESS KEY ID']aws secret access key os environ['AWS S... | @pytest fixture scope 'session' def dcos_launchpad dcos_api_session if 'AWS_STACK_NAME' not in os environ pytest skip 'MustuseaAWSCloudformationtoruntest' stack_name os environ['AWS_STACK_NAME']aws_region os environ['AWS_REGION']aws_access_key_id os environ['AWS_ACCESS_KEY_ID']aws_secret_access_key os environ['AWS_SECR... | 75 |
python-test-2603 | python | What do cache directory store ? | reused files like kernels | def get cache dir subdir None cache dir os environ get 'NEON CACHE DIR' if cache dir is None cache dir appdirs user cache dir 'neon' 'neon' if subdir subdir subdir if isinstance subdir list else [subdir] cache dir os path join cache dir *subdir if not os path exists cache dir os makedirs cache dir return cache dir | def get_cache_dir subdir None cache_dir os environ get 'NEON_CACHE_DIR' if cache_dir is None cache_dir appdirs user_cache_dir 'neon' 'neon' if subdir subdir subdir if isinstance subdir list else [subdir] cache_dir os path join cache_dir *subdir if not os path exists cache_dir os makedirs cache_dir return cache_dir | 59 |
python-test-2610 | python | How do rational expressions combine ? | using symbolic methods | @publicdef together expr deep False def together expr if isinstance expr Basic if expr is Atom or expr is Function and not deep return exprelif expr is Add return gcd terms list map together Add make args expr elif expr is Pow base together expr base if deep exp together expr exp else exp expr expreturn expr class base... | @publicdef together expr deep False def _together expr if isinstance expr Basic if expr is_Atom or expr is_Function and not deep return exprelif expr is_Add return gcd_terms list map _together Add make_args expr elif expr is_Pow base _together expr base if deep exp _together expr exp else exp expr expreturn expr __clas... | 90 |
python-test-2613 | python | When does that handle dates ? | before 1900 | def strftime fmt t None if not fmt return u''if t is None t time localtime if hasattr t 'timetuple' t t timetuple early year t[ 0 ] < 1900 if early year replacement 1900 if t[ 0 ] % 4 0 else 1901 fmt fmt replace '%Y' ' earlyyearhack##' t list t orig year t[ 0 ]t[ 0 ] replacementans Noneif iswindows if isinstance fmt un... | def strftime fmt t None if not fmt return u''if t is None t time localtime if hasattr t 'timetuple' t t timetuple early_year t[0] < 1900 if early_year replacement 1900 if t[0] % 4 0 else 1901 fmt fmt replace '%Y' '_earlyyearhack##' t list t orig_year t[0]t[0] replacementans Noneif iswindows if isinstance fmt unicode fm... | 106 |
python-test-2614 | python | What do a version of strftime try ? | to handle dates before 1900 | def strftime fmt t None if not fmt return u''if t is None t time localtime if hasattr t 'timetuple' t t timetuple early year t[ 0 ] < 1900 if early year replacement 1900 if t[ 0 ] % 4 0 else 1901 fmt fmt replace '%Y' ' earlyyearhack##' t list t orig year t[ 0 ]t[ 0 ] replacementans Noneif iswindows if isinstance fmt un... | def strftime fmt t None if not fmt return u''if t is None t time localtime if hasattr t 'timetuple' t t timetuple early_year t[0] < 1900 if early_year replacement 1900 if t[0] % 4 0 else 1901 fmt fmt replace '%Y' '_earlyyearhack##' t list t orig_year t[0]t[0] replacementans Noneif iswindows if isinstance fmt unicode fm... | 106 |
python-test-2615 | python | What tries to handle dates before 1900 ? | a version of strftime | def strftime fmt t None if not fmt return u''if t is None t time localtime if hasattr t 'timetuple' t t timetuple early year t[ 0 ] < 1900 if early year replacement 1900 if t[ 0 ] % 4 0 else 1901 fmt fmt replace '%Y' ' earlyyearhack##' t list t orig year t[ 0 ]t[ 0 ] replacementans Noneif iswindows if isinstance fmt un... | def strftime fmt t None if not fmt return u''if t is None t time localtime if hasattr t 'timetuple' t t timetuple early_year t[0] < 1900 if early_year replacement 1900 if t[0] % 4 0 else 1901 fmt fmt replace '%Y' '_earlyyearhack##' t list t orig_year t[0]t[0] replacementans Noneif iswindows if isinstance fmt unicode fm... | 106 |
python-test-2618 | python | What does the code remove ? | unused put opcodes | def optimize p gets set puts []prevpos Nonefor opcode arg pos in genops p if prevpos is not None puts append prevarg prevpos pos prevpos Noneif 'PUT' in opcode name prevarg prevpos arg pos elif 'GET' in opcode name gets add arg s []i 0for arg start stop in puts j stop if arg in gets else start s append p[i j] i stops a... | def optimize p gets set puts []prevpos Nonefor opcode arg pos in genops p if prevpos is not None puts append prevarg prevpos pos prevpos Noneif 'PUT' in opcode name prevarg prevpos arg pos elif 'GET' in opcode name gets add arg s []i 0for arg start stop in puts j stop if arg in gets else start s append p[i j] i stops a... | 71 |
python-test-2619 | python | How did opcodes put ? | unused | def optimize p gets set puts []prevpos Nonefor opcode arg pos in genops p if prevpos is not None puts append prevarg prevpos pos prevpos Noneif 'PUT' in opcode name prevarg prevpos arg pos elif 'GET' in opcode name gets add arg s []i 0for arg start stop in puts j stop if arg in gets else start s append p[i j] i stops a... | def optimize p gets set puts []prevpos Nonefor opcode arg pos in genops p if prevpos is not None puts append prevarg prevpos pos prevpos Noneif 'PUT' in opcode name prevarg prevpos arg pos elif 'GET' in opcode name gets add arg s []i 0for arg start stop in puts j stop if arg in gets else start s append p[i j] i stops a... | 71 |
python-test-2620 | python | How does the code optimize a pickle string ? | by removing unused put opcodes | def optimize p gets set puts []prevpos Nonefor opcode arg pos in genops p if prevpos is not None puts append prevarg prevpos pos prevpos Noneif 'PUT' in opcode name prevarg prevpos arg pos elif 'GET' in opcode name gets add arg s []i 0for arg start stop in puts j stop if arg in gets else start s append p[i j] i stops a... | def optimize p gets set puts []prevpos Nonefor opcode arg pos in genops p if prevpos is not None puts append prevarg prevpos pos prevpos Noneif 'PUT' in opcode name prevarg prevpos arg pos elif 'GET' in opcode name gets add arg s []i 0for arg start stop in puts j stop if arg in gets else start s append p[i j] i stops a... | 71 |
python-test-2621 | python | What does the code optimize by removing unused put opcodes ? | a pickle string | def optimize p gets set puts []prevpos Nonefor opcode arg pos in genops p if prevpos is not None puts append prevarg prevpos pos prevpos Noneif 'PUT' in opcode name prevarg prevpos arg pos elif 'GET' in opcode name gets add arg s []i 0for arg start stop in puts j stop if arg in gets else start s append p[i j] i stops a... | def optimize p gets set puts []prevpos Nonefor opcode arg pos in genops p if prevpos is not None puts append prevarg prevpos pos prevpos Noneif 'PUT' in opcode name prevarg prevpos arg pos elif 'GET' in opcode name gets add arg s []i 0for arg start stop in puts j stop if arg in gets else start s append p[i j] i stops a... | 71 |
python-test-2622 | python | How should the fastcommentedheader reader mimic the behavior of the commentedheader ? | by overriding the default header behavior of fastbasic | @pytest mark parametrize 'parallel' [ True False] def test commented header parallel read commented header text '\n#ABC\n 123 \n 456 \n't 1 read commented header text parallel parallel expected Table [[ 1 4] [2 5] [3 6]] names 'A' 'B' 'C' assert table equal t1 expected text '#firstcommentedline\n#secondcommentedline\n\... | @pytest mark parametrize 'parallel' [True False] def test_commented_header parallel read_commented_header text '\n#ABC\n123\n456\n't1 read_commented_header text parallel parallel expected Table [[1 4] [2 5] [3 6]] names 'A' 'B' 'C' assert_table_equal t1 expected text '#firstcommentedline\n#secondcommentedline\n\n' + te... | 138 |
python-test-2623 | python | What should the fastcommentedheader reader mimic by overriding the default header behavior of fastbasic ? | the behavior of the commentedheader | @pytest mark parametrize 'parallel' [ True False] def test commented header parallel read commented header text '\n#ABC\n 123 \n 456 \n't 1 read commented header text parallel parallel expected Table [[ 1 4] [2 5] [3 6]] names 'A' 'B' 'C' assert table equal t1 expected text '#firstcommentedline\n#secondcommentedline\n\... | @pytest mark parametrize 'parallel' [True False] def test_commented_header parallel read_commented_header text '\n#ABC\n123\n456\n't1 read_commented_header text parallel parallel expected Table [[1 4] [2 5] [3 6]] names 'A' 'B' 'C' assert_table_equal t1 expected text '#firstcommentedline\n#secondcommentedline\n\n' + te... | 138 |
python-test-2624 | python | What do the fastcommentedheader reader override ? | the default header behavior of fastbasic | @pytest mark parametrize 'parallel' [ True False] def test commented header parallel read commented header text '\n#ABC\n 123 \n 456 \n't 1 read commented header text parallel parallel expected Table [[ 1 4] [2 5] [3 6]] names 'A' 'B' 'C' assert table equal t1 expected text '#firstcommentedline\n#secondcommentedline\n\... | @pytest mark parametrize 'parallel' [True False] def test_commented_header parallel read_commented_header text '\n#ABC\n123\n456\n't1 read_commented_header text parallel parallel expected Table [[1 4] [2 5] [3 6]] names 'A' 'B' 'C' assert_table_equal t1 expected text '#firstcommentedline\n#secondcommentedline\n\n' + te... | 138 |
python-test-2627 | python | For what purpose do list of nodes check ? | to see if any nodes which were previously known about in the cache have been removed from the node list | def missing node cache prov dir node list provider opts cached nodes []for node in os listdir prov dir cached nodes append os path splitext node [0 ] for node in cached nodes if node not in node list delete minion cachedir node provider opts if 'diff cache events' in opts and opts['diff cache events'] fire event 'event... | def missing_node_cache prov_dir node_list provider opts cached_nodes []for node in os listdir prov_dir cached_nodes append os path splitext node [0] for node in cached_nodes if node not in node_list delete_minion_cachedir node provider opts if 'diff_cache_events' in opts and opts['diff_cache_events'] fire_event 'event'... | 87 |
python-test-2628 | python | What were known in the cache ? | about | def missing node cache prov dir node list provider opts cached nodes []for node in os listdir prov dir cached nodes append os path splitext node [0 ] for node in cached nodes if node not in node list delete minion cachedir node provider opts if 'diff cache events' in opts and opts['diff cache events'] fire event 'event... | def missing_node_cache prov_dir node_list provider opts cached_nodes []for node in os listdir prov_dir cached_nodes append os path splitext node [0] for node in cached_nodes if node not in node_list delete_minion_cachedir node provider opts if 'diff_cache_events' in opts and opts['diff_cache_events'] fire_event 'event'... | 87 |
python-test-2629 | python | What does the code ensure ? | that the directory containing this path is available | def makedirs path user None group None mode None path os path expanduser path dirname os path normpath os path dirname path if os path isdir dirname msg " Directory'{ 0 }'alreadyexists" format dirname log debug msg return msgif os path exists dirname msg " Thepath'{ 0 }'alreadyexistsandisnotadirectory" format dirname l... | def makedirs_ path user None group None mode None path os path expanduser path dirname os path normpath os path dirname path if os path isdir dirname msg "Directory'{0}'alreadyexists" format dirname log debug msg return msgif os path exists dirname msg "Thepath'{0}'alreadyexistsandisnotadirectory" format dirname log de... | 122 |
python-test-2630 | python | Where does the code perform the jarque - bera goodness of fit test ? | on sample data | def jarque bera x x np asarray x n float x size if n 0 raise Value Error ' Atleastoneobservationisrequired ' mu x mean diffx x - mu skewness 1 / n * np sum diffx ** 3 / 1 / n * np sum diffx ** 2 ** 3 / 2 0 kurtosis 1 / n * np sum diffx ** 4 / 1 / n * np sum diffx ** 2 ** 2 jb value n / 6 * skewness ** 2 + kurtosis - 3 ... | def jarque_bera x x np asarray x n float x size if n 0 raise ValueError 'Atleastoneobservationisrequired ' mu x mean diffx x - mu skewness 1 / n * np sum diffx ** 3 / 1 / n * np sum diffx ** 2 ** 3 / 2 0 kurtosis 1 / n * np sum diffx ** 4 / 1 / n * np sum diffx ** 2 ** 2 jb_value n / 6 * skewness ** 2 + kurtosis - 3 **... | 106 |
python-test-2631 | python | What does the code perform on sample data ? | the jarque - bera goodness of fit test | def jarque bera x x np asarray x n float x size if n 0 raise Value Error ' Atleastoneobservationisrequired ' mu x mean diffx x - mu skewness 1 / n * np sum diffx ** 3 / 1 / n * np sum diffx ** 2 ** 3 / 2 0 kurtosis 1 / n * np sum diffx ** 4 / 1 / n * np sum diffx ** 2 ** 2 jb value n / 6 * skewness ** 2 + kurtosis - 3 ... | def jarque_bera x x np asarray x n float x size if n 0 raise ValueError 'Atleastoneobservationisrequired ' mu x mean diffx x - mu skewness 1 / n * np sum diffx ** 3 / 1 / n * np sum diffx ** 2 ** 3 / 2 0 kurtosis 1 / n * np sum diffx ** 4 / 1 / n * np sum diffx ** 2 ** 2 jb_value n / 6 * skewness ** 2 + kurtosis - 3 **... | 106 |
python-test-2632 | python | What attachs to each object of the queryset ? | a is fan boolean | def attach is fan queryset user as field 'is fan attr' model queryset modelif user is None or user is anonymous sql 'SELEC Tfalse'else sql "\n SELECTCOUNT likes like id >0 \n FRO Mlikes like\n INNERJOI Ndjango content type O Nlikes like content type id django content type id\n WHER Edjango content type model 'project'A... | def attach_is_fan queryset user as_field 'is_fan_attr' model queryset modelif user is None or user is_anonymous sql 'SELECTfalse'else sql "\nSELECTCOUNT likes_like id >0\nFROMlikes_like\nINNERJOINdjango_content_typeONlikes_like content_type_id django_content_type id\nWHEREdjango_content_type model 'project'AND\ndjango_... | 90 |
python-test-2633 | python | What do a is fan boolean attach ? | to each object of the queryset | def attach is fan queryset user as field 'is fan attr' model queryset modelif user is None or user is anonymous sql 'SELEC Tfalse'else sql "\n SELECTCOUNT likes like id >0 \n FRO Mlikes like\n INNERJOI Ndjango content type O Nlikes like content type id django content type id\n WHER Edjango content type model 'project'A... | def attach_is_fan queryset user as_field 'is_fan_attr' model queryset modelif user is None or user is_anonymous sql 'SELECTfalse'else sql "\nSELECTCOUNT likes_like id >0\nFROMlikes_like\nINNERJOINdjango_content_typeONlikes_like content_type_id django_content_type id\nWHEREdjango_content_type model 'project'AND\ndjango_... | 90 |
python-test-2636 | python | What does api deployment delete ? | for a given restapiid and deploymentid cli example | def delete api deployment rest Api Id deployment Id region None key None keyid None profile None try conn get conn region region key key keyid keyid profile profile conn delete deployment rest Api Id rest Api Id deployment Id deployment Id return {'deleted' True}except Client Error as e return {'deleted' False 'error' ... | def delete_api_deployment restApiId deploymentId region None key None keyid None profile None try conn _get_conn region region key key keyid keyid profile profile conn delete_deployment restApiId restApiId deploymentId deploymentId return {'deleted' True}except ClientError as e return {'deleted' False 'error' salt util... | 61 |
python-test-2637 | python | What deletes for a given restapiid and deploymentid cli example ? | api deployment | def delete api deployment rest Api Id deployment Id region None key None keyid None profile None try conn get conn region region key key keyid keyid profile profile conn delete deployment rest Api Id rest Api Id deployment Id deployment Id return {'deleted' True}except Client Error as e return {'deleted' False 'error' ... | def delete_api_deployment restApiId deploymentId region None key None keyid None profile None try conn _get_conn region region key key keyid keyid profile profile conn delete_deployment restApiId restApiId deploymentId deploymentId return {'deleted' True}except ClientError as e return {'deleted' False 'error' salt util... | 61 |
python-test-2640 | python | What does the code switch to upper case ? | all sql statement keywords | def clean Query query ret Val queryfor sql Statements in SQL STATEMENTS values for sql Statement in sql Statements sql Statement Esc sql Statement replace ' ' '\\ ' query Match re search ' %s ' % sql Statement Esc query re I if query Match and 'sys exec' not in query ret Val ret Val replace query Match group 1 sql Stat... | def cleanQuery query retVal queryfor sqlStatements in SQL_STATEMENTS values for sqlStatement in sqlStatements sqlStatementEsc sqlStatement replace ' ' '\\ ' queryMatch re search ' %s ' % sqlStatementEsc query re I if queryMatch and 'sys_exec' not in query retVal retVal replace queryMatch group 1 sqlStatement upper retu... | 67 |
python-test-2641 | python | Where did the code deprecate the editor ? | at the given filename | def fix error editor self filename linenum column msg warnings warn '\n`fix error editor`ispendingdeprecationasof I Python 5 0andwillberemoved\ninfutureversions Itappearstobeusedonlyforautomaticallyfixingsyntax\nerrorthathasbeenbrokenforafewyearsandhasthusbeenremoved Ifyou\nhappendtousethisfunctionandstillneeditpleasem... | def fix_error_editor self filename linenum column msg warnings warn '\n`fix_error_editor`ispendingdeprecationasofIPython5 0andwillberemoved\ninfutureversions Itappearstobeusedonlyforautomaticallyfixingsyntax\nerrorthathasbeenbrokenforafewyearsandhasthusbeenremoved Ifyou\nhappendtousethisfunctionandstillneeditpleasemake... | 89 |
python-test-2643 | python | How did nodes crash ? | with crashfile info | def report nodes not run notrun if notrun logger info u'***********************************' for info in notrun logger error u'couldnotrunnode %s' % u' ' join info[u'node'] hierarchy info[u'node'] id logger info u'crashfile %s' % info[u'crashfile'] logger debug u' Thefollowingdependentnodeswerenotrun' for subnode in in... | def report_nodes_not_run notrun if notrun logger info u'***********************************' for info in notrun logger error u'couldnotrunnode %s' % u' ' join info[u'node'] _hierarchy info[u'node'] _id logger info u'crashfile %s' % info[u'crashfile'] logger debug u'Thefollowingdependentnodeswerenotrun' for subnode in i... | 54 |
python-test-2644 | python | What displays dependent nodes that were nt executed as a result of the crash optionally ? | list nodes that crashed with crashfile info | def report nodes not run notrun if notrun logger info u'***********************************' for info in notrun logger error u'couldnotrunnode %s' % u' ' join info[u'node'] hierarchy info[u'node'] id logger info u'crashfile %s' % info[u'crashfile'] logger debug u' Thefollowingdependentnodeswerenotrun' for subnode in in... | def report_nodes_not_run notrun if notrun logger info u'***********************************' for info in notrun logger error u'couldnotrunnode %s' % u' ' join info[u'node'] _hierarchy info[u'node'] _id logger info u'crashfile %s' % info[u'crashfile'] logger debug u'Thefollowingdependentnodeswerenotrun' for subnode in i... | 54 |
python-test-2645 | python | Why were dependent nodes nt executed ? | as a result of the crash | def report nodes not run notrun if notrun logger info u'***********************************' for info in notrun logger error u'couldnotrunnode %s' % u' ' join info[u'node'] hierarchy info[u'node'] id logger info u'crashfile %s' % info[u'crashfile'] logger debug u' Thefollowingdependentnodeswerenotrun' for subnode in in... | def report_nodes_not_run notrun if notrun logger info u'***********************************' for info in notrun logger error u'couldnotrunnode %s' % u' ' join info[u'node'] _hierarchy info[u'node'] _id logger info u'crashfile %s' % info[u'crashfile'] logger debug u'Thefollowingdependentnodeswerenotrun' for subnode in i... | 54 |
python-test-2646 | python | What does list nodes that crashed with crashfile info display optionally ? | dependent nodes that were nt executed as a result of the crash | def report nodes not run notrun if notrun logger info u'***********************************' for info in notrun logger error u'couldnotrunnode %s' % u' ' join info[u'node'] hierarchy info[u'node'] id logger info u'crashfile %s' % info[u'crashfile'] logger debug u' Thefollowingdependentnodeswerenotrun' for subnode in in... | def report_nodes_not_run notrun if notrun logger info u'***********************************' for info in notrun logger error u'couldnotrunnode %s' % u' ' join info[u'node'] _hierarchy info[u'node'] _id logger info u'crashfile %s' % info[u'crashfile'] logger debug u'Thefollowingdependentnodeswerenotrun' for subnode in i... | 54 |
python-test-2647 | python | How does the code add a store_fs ? | using store= rather than pootle_path | @pytest mark django dbdef test add store fs by store po directory english fs path '/some/fs/example store po'project Project DB Factory source language english language Language DB Factory tp Translation Project Factory project project language language store Store DB Factory translation project tp parent tp directory ... | @pytest mark django_dbdef test_add_store_fs_by_store po_directory english fs_path '/some/fs/example_store po'project ProjectDBFactory source_language english language LanguageDBFactory tp TranslationProjectFactory project project language language store StoreDBFactory translation_project tp parent tp directory name 'ex... | 134 |
python-test-2648 | python | What does the code compute ? | the generalized s - polynomial of f and g | def sdm spoly f g O K phantom None if not f or not g return sdm zero LM 1 sdm LM f LM 2 sdm LM g if LM 1 [ 0 ] LM 2 [ 0 ] return sdm zero LM 1 LM 1 [ 1 ]LM 2 LM 2 [ 1 ]lcm monomial lcm LM 1 LM 2 m1 monomial div lcm LM 1 m2 monomial div lcm LM 2 c K quo - sdm LC f K sdm LC g K r1 sdm add sdm mul term f m1 K one O K sdm ... | def sdm_spoly f g O K phantom None if not f or not g return sdm_zero LM1 sdm_LM f LM2 sdm_LM g if LM1[0] LM2[0] return sdm_zero LM1 LM1[1 ]LM2 LM2[1 ]lcm monomial_lcm LM1 LM2 m1 monomial_div lcm LM1 m2 monomial_div lcm LM2 c K quo - sdm_LC f K sdm_LC g K r1 sdm_add sdm_mul_term f m1 K one O K sdm_mul_term g m2 c O K O ... | 143 |
python-test-2649 | python | What does the code remove if it exists ? | the named sqs queue | def absent name region user None opts False ret {'name' name 'result' True 'comment' '' 'changes' {}}does exist salt ['aws sqs queue exists'] name region opts user if does exist if opts ['test'] ret['result'] Noneret['comment'] 'AWSSQ Squeue{ 0 }issettoberemoved' format name return retremoved salt ['aws sqs delete queu... | def absent name region user None opts False ret {'name' name 'result' True 'comment' '' 'changes' {}}does_exist __salt__['aws_sqs queue_exists'] name region opts user if does_exist if __opts__['test'] ret['result'] Noneret['comment'] 'AWSSQSqueue{0}issettoberemoved' format name return retremoved __salt__['aws_sqs delet... | 71 |
python-test-2656 | python | What does the code return ? | the name of the default version for the server | def get default version server None req servers service pb Get Default Version Request if server req set server server resp servers service pb Get Default Version Response try apiproxy stub map Make Sync Call 'servers' ' Get Default Version' req resp except apiproxy errors Application Error as e if e application error ... | def get_default_version server None req servers_service_pb GetDefaultVersionRequest if server req set_server server resp servers_service_pb GetDefaultVersionResponse try apiproxy_stub_map MakeSyncCall 'servers' 'GetDefaultVersion' req resp except apiproxy_errors ApplicationError as e if e application_error servers_serv... | 87 |
python-test-2663 | python | For what purpose does the clip crop ? | to make dimensions even | @apply to maskdef even size clip w h clip sizeif w % 2 0 and h % 2 0 return clipif w % 2 0 and h % 2 0 fl image lambda a a[ -1 -1 ] elif w % 2 0 fl image lambda a a[ -1 ] else fl image lambda a a[ -1 ] return clip fl image fl image | @apply_to_maskdef even_size clip w h clip sizeif w % 2 0 and h % 2 0 return clipif w % 2 0 and h % 2 0 fl_image lambda a a[ -1 -1 ] elif w % 2 0 fl_image lambda a a[ -1 ] else fl_image lambda a a[ -1 ] return clip fl_image fl_image | 64 |
python-test-2666 | python | What does the code get by name ? | an runnertype | def get runnertype by name runnertype name try runnertypes Runner Type query name runnertype name except Value Error Validation Error as e LOG error ' Databaselookupforname "%s"resultedinexception %s' runnertype name e raise Stack Storm DB Object Not Found Error ' Unabletofindrunnertypewithname "%s"' % runnertype name ... | def get_runnertype_by_name runnertype_name try runnertypes RunnerType query name runnertype_name except ValueError ValidationError as e LOG error 'Databaselookupforname "%s"resultedinexception %s' runnertype_name e raise StackStormDBObjectNotFoundError 'Unabletofindrunnertypewithname "%s"' % runnertype_name if not runn... | 84 |
python-test-2672 | python | What does the code create from a native sets items ? | a python list | def native set to python list typ payload c nitems payload usedlistobj c pyapi list new nitems ok cgutils is not null c builder listobj with c builder if then ok likely True index cgutils alloca once value c builder ir Constant nitems type 0 with payload iterate as loop i c builder load index item loop entry keyitemobj... | def _native_set_to_python_list typ payload c nitems payload usedlistobj c pyapi list_new nitems ok cgutils is_not_null c builder listobj with c builder if_then ok likely True index cgutils alloca_once_value c builder ir Constant nitems type 0 with payload _iterate as loop i c builder load index item loop entry keyitemo... | 89 |
python-test-2677 | python | What does the code find ? | appropriate c compiler for extension module builds | def find appropriate compiler config vars if 'CC' in os environ return config varscc oldcc config vars['CC'] split [0 ]if not find executable cc cc find build tool 'clang' elif os path basename cc startswith 'gcc' data read output "'%s'--version" % cc replace "'" '\'"\'"\'' if data and 'llvm-gcc' in data cc find build ... | def _find_appropriate_compiler _config_vars if 'CC' in os environ return _config_varscc oldcc _config_vars['CC'] split [0]if not _find_executable cc cc _find_build_tool 'clang' elif os path basename cc startswith 'gcc' data _read_output "'%s'--version" % cc replace "'" '\'"\'"\'' if data and 'llvm-gcc' in data cc _find... | 114 |
python-test-2678 | python | What manage the configuration to fin dthe appropriate class ? | a dispatcher for the packet list field | def pnio rtc guess payload class pkt underlayer None *args **kargs config pnio get config underlayer if isinstance config list cur index - len pkt for index cls params in config if cur index index return cls pkt config params *args **kargs return PNIO Real Time I Ox S pkt *args **kargs else return PNIO Real Time Raw Da... | def _pnio_rtc_guess_payload_class _pkt _underlayer None *args **kargs config pnio_get_config _underlayer if isinstance config list cur_index - len _pkt for index cls params in config if cur_index index return cls _pkt config params *args **kargs return PNIORealTimeIOxS _pkt *args **kargs else return PNIORealTimeRawData... | 67 |
python-test-2679 | python | What do a dispatcher for the packet list field manage ? | the configuration to fin dthe appropriate class | def pnio rtc guess payload class pkt underlayer None *args **kargs config pnio get config underlayer if isinstance config list cur index - len pkt for index cls params in config if cur index index return cls pkt config params *args **kargs return PNIO Real Time I Ox S pkt *args **kargs else return PNIO Real Time Raw Da... | def _pnio_rtc_guess_payload_class _pkt _underlayer None *args **kargs config pnio_get_config _underlayer if isinstance config list cur_index - len _pkt for index cls params in config if cur_index index return cls _pkt config params *args **kargs return PNIORealTimeIOxS _pkt *args **kargs else return PNIORealTimeRawData... | 67 |
python-test-2688 | python | Where did records store to a sql database ? | in a dataframe | def to sql frame name con flavor None schema None if exists 'fail' index True index label None chunksize None dtype None if if exists not in 'fail' 'replace' 'append' raise Value Error "'{ 0 }'isnotvalidforif exists" format if exists pandas sql pandas SQL builder con schema schema flavor flavor if isinstance frame Seri... | def to_sql frame name con flavor None schema None if_exists 'fail' index True index_label None chunksize None dtype None if if_exists not in 'fail' 'replace' 'append' raise ValueError "'{0}'isnotvalidforif_exists" format if_exists pandas_sql pandasSQL_builder con schema schema flavor flavor if isinstance frame Series f... | 94 |
python-test-2689 | python | What do calculate_changes calculate ? | the given desired datasets invoked with the given state and configuration | def assert desired datasets case deployer desired manifestations local datasets local applications additional node config set expected datasets leases Leases calculator Recording Calculator NOTHING TO DO deployer deployer set calculator calculator cluster configuration Deployment nodes { Node uuid deployer node uuid ho... | def assert_desired_datasets case deployer desired_manifestations local_datasets local_applications additional_node_config set expected_datasets leases Leases calculator RecordingCalculator NOTHING_TO_DO deployer deployer set calculator calculator cluster_configuration Deployment nodes {Node uuid deployer node_uuid host... | 141 |
python-test-2690 | python | What does the code rescind ? | a due date extension for a student on a particular unit | @handle dashboard error@require POST@ensure csrf cookie@cache control no cache True no store True must revalidate True @require level 'staff' @require post params 'student' 'url' def reset due date request course id course get course by id Slash Separated Course Key from deprecated string course id student require stud... | @handle_dashboard_error@require_POST@ensure_csrf_cookie@cache_control no_cache True no_store True must_revalidate True @require_level 'staff' @require_post_params 'student' 'url' def reset_due_date request course_id course get_course_by_id SlashSeparatedCourseKey from_deprecated_string course_id student require_student... | 114 |
python-test-2691 | python | What does the code retrieve ? | a list of nat gateways args | def get nat gateways client subnet id None nat gateway id None states None check mode False params dict err msg ''gateways retrieved Falseexisting gateways list if not states states ['available' 'pending']if nat gateway id params[' Nat Gateway Ids'] [nat gateway id]else params[' Filter'] [{' Name' 'subnet-id' ' Values'... | def get_nat_gateways client subnet_id None nat_gateway_id None states None check_mode False params dict err_msg ''gateways_retrieved Falseexisting_gateways list if not states states ['available' 'pending']if nat_gateway_id params['NatGatewayIds'] [nat_gateway_id]else params['Filter'] [{'Name' 'subnet-id' 'Values' [subn... | 152 |
python-test-2692 | python | What does the code convert to an entity type based on the feature ? | a json result | def entity from response type feature type results detected objects []if feature type FACE ANNOTATIONS detected objects extend Face from api repr face for face in results elif feature type IMAGE PROPERTIES ANNOTATION return Image Properties Annotation from api repr results elif feature type SAFE SEARCH ANNOTATION retur... | def _entity_from_response_type feature_type results detected_objects []if feature_type _FACE_ANNOTATIONS detected_objects extend Face from_api_repr face for face in results elif feature_type _IMAGE_PROPERTIES_ANNOTATION return ImagePropertiesAnnotation from_api_repr results elif feature_type _SAFE_SEARCH_ANNOTATION ret... | 72 |
python-test-2695 | python | What does the code create from a mapping of variable identifiers to value identifiers ? | a combination hash | def get combination hash from variable mapping parent variables mapping {}for variable identifier value identifier in variables items variable Product Variation Variable objects get or create product parent identifier force text variable identifier value Product Variation Variable Value objects get or create variable v... | def get_combination_hash_from_variable_mapping parent variables mapping {}for variable_identifier value_identifier in variables items variable _ ProductVariationVariable objects get_or_create product parent identifier force_text variable_identifier value _ ProductVariationVariableValue objects get_or_create variable va... | 54 |
python-test-2696 | python | What does the code setup ? | the google travel time platform | def setup platform hass config add devices callback discovery info None def run setup event ' Delaythesetupuntil Home Assistantisfullyinitialized \n\n Thisallowsanyentitiestobecreatedalready\n'options config get CONF OPTIONS if options get 'units' is None options['units'] hass config units nametravel mode config get CO... | def setup_platform hass config add_devices_callback discovery_info None def run_setup event 'DelaythesetupuntilHomeAssistantisfullyinitialized \n\nThisallowsanyentitiestobecreatedalready\n'options config get CONF_OPTIONS if options get 'units' is None options['units'] hass config units nametravel_mode config get CONF_T... | 141 |
python-test-2703 | python | What does the code move ? | a song | @command ' mv sw \\s* \\d{ 1 4} \\s*[\\s ]\\s* \\d{ 1 4} ' def songlist mv sw action a b i j int a - 1 int b - 1 if action 'mv' g model songs insert j g model songs pop i g message util F 'songmove' % g model[j] title b elif action 'sw' g model[i] g model[j] g model[j] g model[i] g message util F 'songsw' % min a b max... | @command ' mv sw \\s* \\d{1 4} \\s*[\\s ]\\s* \\d{1 4} ' def songlist_mv_sw action a b i j int a - 1 int b - 1 if action 'mv' g model songs insert j g model songs pop i g message util F 'songmove' % g model[j] title b elif action 'sw' g model[i] g model[j] g model[j] g model[i] g message util F 'songsw' % min a b max a... | 83 |
python-test-2704 | python | What does the code swap ? | two songs | @command ' mv sw \\s* \\d{ 1 4} \\s*[\\s ]\\s* \\d{ 1 4} ' def songlist mv sw action a b i j int a - 1 int b - 1 if action 'mv' g model songs insert j g model songs pop i g message util F 'songmove' % g model[j] title b elif action 'sw' g model[i] g model[j] g model[j] g model[i] g message util F 'songsw' % min a b max... | @command ' mv sw \\s* \\d{1 4} \\s*[\\s ]\\s* \\d{1 4} ' def songlist_mv_sw action a b i j int a - 1 int b - 1 if action 'mv' g model songs insert j g model songs pop i g message util F 'songmove' % g model[j] title b elif action 'sw' g model[i] g model[j] g model[j] g model[i] g message util F 'songsw' % min a b max a... | 83 |
python-test-2705 | python | For what purpose does the url return ? | for an xblocks local resource | def xblock local resource url block uri xblock class getattr block class 'unmixed class' block class if settings PIPELINE ENABLED or not settings REQUIRE DEBUG return staticfiles storage url 'xblock/resources/{package name}/{path}' format package name xblock class module path uri else return reverse 'xblock resource ur... | def xblock_local_resource_url block uri xblock_class getattr block __class__ 'unmixed_class' block __class__ if settings PIPELINE_ENABLED or not settings REQUIRE_DEBUG return staticfiles_storage url 'xblock/resources/{package_name}/{path}' format package_name xblock_class __module__ path uri else return reverse 'xblock... | 55 |
python-test-2708 | python | How does this shuffle an array ? | in a batch - wise fashion | def batch shuffle index array batch size batch count int len index array / batch size last batch index array[ batch count * batch size ]index array index array[ batch count * batch size ]index array index array reshape batch count batch size np random shuffle index array index array index array flatten return np append... | def batch_shuffle index_array batch_size batch_count int len index_array / batch_size last_batch index_array[ batch_count * batch_size ]index_array index_array[ batch_count * batch_size ]index_array index_array reshape batch_count batch_size np random shuffle index_array index_array index_array flatten return np append... | 60 |
python-test-2713 | python | How do a folder instal ? | using pip install folder1/folder2 | def test install folder using relative path script script scratch path join 'initools' mkdir script scratch path join 'initools' 'mock' mkdir pkg path script scratch path / 'initools' / 'mock' pkg path join 'setup py' write mock 100 setup py result script pip 'install' Path 'initools' / 'mock' egg folder script site pa... | def test_install_folder_using_relative_path script script scratch_path join 'initools' mkdir script scratch_path join 'initools' 'mock' mkdir pkg_path script scratch_path / 'initools' / 'mock' pkg_path join 'setup py' write mock100_setup_py result script pip 'install' Path 'initools' / 'mock' egg_folder script site_pac... | 69 |
python-test-2714 | python | Where does this endpoint exist ? | in both the registry api [ 1 ] and the indexer api [ 2 ] | @app route '/v 1 /repositories/<path repository>/' methods ['DELETE'] @app route '/v 1 /repositories/<path repository>/tags' methods ['DELETE'] @toolkit parse repository name@toolkit requires authdef delete repository namespace repository logger debug '[delete repository]namespace {0 } repository {1 }' format namespace... | @app route '/v1/repositories/<path repository>/' methods ['DELETE'] @app route '/v1/repositories/<path repository>/tags' methods ['DELETE'] @toolkit parse_repository_name@toolkit requires_authdef delete_repository namespace repository logger debug '[delete_repository]namespace {0} repository {1}' format namespace repos... | 103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.