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-6823
python
Where did the algorithm describe ?
in this paper
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
python-test-6824
python
What must URL messages have ?
the following properties : to_addr - [
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
python-test-6825
python
What does the code generate ?
a set of simple sequences
def generate Simple Sequences n Coinc 10 seq Length [5 6 7] n Seq 100 coinc List range n Coinc seq List []for i in xrange n Seq if max seq Length < n Coinc seq List append random sample coinc List random choice seq Length else len random choice seq Length seq []for x in xrange len seq append random choice coinc List se...
def generateSimpleSequences nCoinc 10 seqLength [5 6 7] nSeq 100 coincList range nCoinc seqList []for i in xrange nSeq if max seqLength < nCoinc seqList append random sample coincList random choice seqLength else len random choice seqLength seq []for x in xrange len seq append random choice coincList seqList append seq...
71
python-test-6828
python
How do an empty revision return ?
with enough stuff filled out
def revision save False **kwargs doc Noneif 'document' not in kwargs doc document save True else doc kwargs['document']defaults {'summary' ' Somesummary' 'content' ' Somecontent' 'comment' ' Somecomment' 'creator' kwargs get 'creator' get user 'document' doc 'tags' '"some" "tags"' 'toc depth' 1}defaults update kwargs r...
def revision save False **kwargs doc Noneif 'document' not in kwargs doc document save True else doc kwargs['document']defaults {'summary' 'Somesummary' 'content' 'Somecontent' 'comment' 'Somecomment' 'creator' kwargs get 'creator' get_user 'document' doc 'tags' '"some" "tags"' 'toc_depth' 1}defaults update kwargs rev ...
52
python-test-6829
python
When do the dot product calculate efficiently ?
when one or all operands is sparse
def dot x y if hasattr x 'getnnz' x as sparse variable x if hasattr y 'getnnz' y as sparse variable y x is sparse variable is sparse variable x y is sparse variable is sparse variable y if not x is sparse variable and not y is sparse variable raise Type Error return dot x y
def dot x y if hasattr x 'getnnz' x as_sparse_variable x if hasattr y 'getnnz' y as_sparse_variable y x_is_sparse_variable _is_sparse_variable x y_is_sparse_variable _is_sparse_variable y if not x_is_sparse_variable and not y_is_sparse_variable raise TypeError return _dot x y
57
python-test-6831
python
What does the code map across an array ?
a function in parallel
def apply parallel function array chunks None depth 0 mode None extra arguments extra keywords {} if not dask available raise Runtime Error " Couldnotimport'dask' Pleaseinstallusing'pipinstalldask'" if chunks is None shape array shapetry ncpu cpu count except Not Implemented Error ncpu 4chunks get chunks shape ncpu if ...
def apply_parallel function array chunks None depth 0 mode None extra_arguments extra_keywords {} if not dask_available raise RuntimeError "Couldnotimport'dask' Pleaseinstallusing'pipinstalldask'" if chunks is None shape array shapetry ncpu cpu_count except NotImplementedError ncpu 4chunks _get_chunks shape ncpu if mod...
86
python-test-6832
python
Where does the code map a function in parallel ?
across an array
def apply parallel function array chunks None depth 0 mode None extra arguments extra keywords {} if not dask available raise Runtime Error " Couldnotimport'dask' Pleaseinstallusing'pipinstalldask'" if chunks is None shape array shapetry ncpu cpu count except Not Implemented Error ncpu 4chunks get chunks shape ncpu if ...
def apply_parallel function array chunks None depth 0 mode None extra_arguments extra_keywords {} if not dask_available raise RuntimeError "Couldnotimport'dask' Pleaseinstallusing'pipinstalldask'" if chunks is None shape array shapetry ncpu cpu_count except NotImplementedError ncpu 4chunks _get_chunks shape ncpu if mod...
86
python-test-6837
python
What does the code execute ?
the given java runner
def execute runner runner workunit factory None workunit name None workunit labels None workunit log config None if not isinstance runner Executor Runner raise Value Error u' Therunnerargumentmustbeajava Executor Runnerinstance given{}oftype{}' format runner type runner if workunit factory is None return runner run els...
def execute_runner runner workunit_factory None workunit_name None workunit_labels None workunit_log_config None if not isinstance runner Executor Runner raise ValueError u'TherunnerargumentmustbeajavaExecutor Runnerinstance given{}oftype{}' format runner type runner if workunit_factory is None return runner run else w...
116
python-test-6844
python
Why do we test it here ?
as this is the optimization only that we test
def test local abstractconv gemm image tensor ftensor 4 W tensor ftensor 4 conv tensor nnet conv 2 d image W input shape 1 32 32 32 filter shape 32 32 3 3 border mode 'half' f theano function [image W] [conv] mode mode with gpu f numpy random rand 1 32 32 32 astype 'float 32 ' numpy random rand 32 32 3 3 astype 'float ...
def test_local_abstractconv_gemm image tensor ftensor4 W tensor ftensor4 conv tensor nnet conv2d image W input_shape 1 32 32 32 filter_shape 32 32 3 3 border_mode 'half' f theano function [image W] [conv] mode mode_with_gpu f numpy random rand 1 32 32 32 astype 'float32' numpy random rand 32 32 3 3 astype 'float32'
69
python-test-6845
python
What does the code create ?
a new user confirmation
def create new user confirmation user address id chars string ascii letters + string digits rand random System Random random id '' join [rand choice id chars for i in range 42 ] record User Confirmation Record user address user address id random id record put return 'https //{}/user/confirm?code {}' format socket getfq...
def create_new_user_confirmation user_address id_chars string ascii_letters + string digits rand random SystemRandom random_id '' join [rand choice id_chars for i in range 42 ] record UserConfirmationRecord user_address user_address id random_id record put return 'https //{}/user/confirm?code {}' format socket getfqdn ...
57
python-test-6846
python
What copys to output stream in reverse order ?
lines from input stream
def Copy Reversed Lines instream outstream blocksize 2 ** 16 line count 0instream seek 0 2 last block instream tell // blocksize spillover ''for iblock in xrange last block + 1 -1 -1 instream seek iblock * blocksize data instream read blocksize lines data splitlines True lines[ -1 ] '' join lines[ -1 ] + [spillover] sp...
def CopyReversedLines instream outstream blocksize 2 ** 16 line_count 0instream seek 0 2 last_block instream tell // blocksize spillover ''for iblock in xrange last_block + 1 -1 -1 instream seek iblock * blocksize data instream read blocksize lines data splitlines True lines[ -1 ] '' join lines[ -1 ] + [spillover] spli...
106
python-test-6847
python
What do lines from input stream copy in reverse order ?
to output stream
def Copy Reversed Lines instream outstream blocksize 2 ** 16 line count 0instream seek 0 2 last block instream tell // blocksize spillover ''for iblock in xrange last block + 1 -1 -1 instream seek iblock * blocksize data instream read blocksize lines data splitlines True lines[ -1 ] '' join lines[ -1 ] + [spillover] sp...
def CopyReversedLines instream outstream blocksize 2 ** 16 line_count 0instream seek 0 2 last_block instream tell // blocksize spillover ''for iblock in xrange last_block + 1 -1 -1 instream seek iblock * blocksize data instream read blocksize lines data splitlines True lines[ -1 ] '' join lines[ -1 ] + [spillover] spli...
106
python-test-6853
python
When does helper method iterate ?
once over a dict of headers
def prep headers to info headers server type meta {}sysmeta {}other {}for key val in dict headers items lkey key lower if is user meta server type lkey meta[strip user meta prefix server type lkey ] valelif is sys meta server type lkey sysmeta[strip sys meta prefix server type lkey ] valelse other[lkey] valreturn other...
def _prep_headers_to_info headers server_type meta {}sysmeta {}other {}for key val in dict headers items lkey key lower if is_user_meta server_type lkey meta[strip_user_meta_prefix server_type lkey ] valelif is_sys_meta server_type lkey sysmeta[strip_sys_meta_prefix server_type lkey ] valelse other[lkey] valreturn othe...
57
python-test-6855
python
For what purpose are this takes a tensorvariable ?
so that incoming weight norms are below a specified constraint value
def norm constraint tensor var max norm norm axes None epsilon 1e- 07 ndim tensor var ndimif norm axes is not None sum over tuple norm axes elif ndim 2 sum over 0 elif ndim in [3 4 5] sum over tuple range 1 ndim else raise Value Error ' Unsupportedtensordimensionality{} Mustspecify`norm axes`' format ndim dtype np dtyp...
def norm_constraint tensor_var max_norm norm_axes None epsilon 1e-07 ndim tensor_var ndimif norm_axes is not None sum_over tuple norm_axes elif ndim 2 sum_over 0 elif ndim in [3 4 5] sum_over tuple range 1 ndim else raise ValueError 'Unsupportedtensordimensionality{} Mustspecify`norm_axes`' format ndim dtype np dtype t...
100
python-test-6856
python
What are this takes so that incoming weight norms are below a specified constraint value ?
a tensorvariable
def norm constraint tensor var max norm norm axes None epsilon 1e- 07 ndim tensor var ndimif norm axes is not None sum over tuple norm axes elif ndim 2 sum over 0 elif ndim in [3 4 5] sum over tuple range 1 ndim else raise Value Error ' Unsupportedtensordimensionality{} Mustspecify`norm axes`' format ndim dtype np dtyp...
def norm_constraint tensor_var max_norm norm_axes None epsilon 1e-07 ndim tensor_var ndimif norm_axes is not None sum_over tuple norm_axes elif ndim 2 sum_over 0 elif ndim in [3 4 5] sum_over tuple range 1 ndim else raise ValueError 'Unsupportedtensordimensionality{} Mustspecify`norm_axes`' format ndim dtype np dtype t...
100
python-test-6860
python
What does the code return from the repository ?
the latest version of config_filename
def get config config file repo ctx dir config file basic util strip path config file for changeset in reversed upper bounded changelog repo ctx changeset ctx repo changectx changeset for ctx file in changeset ctx files ctx file name basic util strip path ctx file if ctx file name config file return get named tmpfile f...
def get_config config_file repo ctx dir config_file basic_util strip_path config_file for changeset in reversed_upper_bounded_changelog repo ctx changeset_ctx repo changectx changeset for ctx_file in changeset_ctx files ctx_file_name basic_util strip_path ctx_file if ctx_file_name config_file return get_named_tmpfile_f...
65
python-test-6861
python
What does a helper function determine ?
the destination path
def find dest path comp key files src path None src files['src']dest files['dest']src type src['type']dest type dest['type']if src path is None src path src['path']sep table {'s 3 ' '/' 'local' os sep}if files['dir op'] rel path src path[len src['path'] ]else rel path src path split sep table[src type] [ -1 ]compare ke...
def find_dest_path_comp_key files src_path None src files['src']dest files['dest']src_type src['type']dest_type dest['type']if src_path is None src_path src['path']sep_table {'s3' '/' 'local' os sep}if files['dir_op'] rel_path src_path[len src['path'] ]else rel_path src_path split sep_table[src_type] [ -1 ]compare_key ...
85
python-test-6862
python
What does a helper function compare ?
key given parameters received from the fileformat class
def find dest path comp key files src path None src files['src']dest files['dest']src type src['type']dest type dest['type']if src path is None src path src['path']sep table {'s 3 ' '/' 'local' os sep}if files['dir op'] rel path src path[len src['path'] ]else rel path src path split sep table[src type] [ -1 ]compare ke...
def find_dest_path_comp_key files src_path None src files['src']dest files['dest']src_type src['type']dest_type dest['type']if src_path is None src_path src['path']sep_table {'s3' '/' 'local' os sep}if files['dir_op'] rel_path src_path[len src['path'] ]else rel_path src_path split sep_table[src_type] [ -1 ]compare_key ...
85
python-test-6864
python
What do we have ?
labels parameters train
def filter labels train label classes None if isinstance train theano tensor sharedvar Shared Variable train train get value borrow True if isinstance label theano tensor sharedvar Shared Variable label label get value borrow True if not isinstance train numpy ndarray or scipy sparse issparse train raise Type Error 'tr...
def filter_labels train label classes None if isinstance train theano tensor sharedvar SharedVariable train train get_value borrow True if isinstance label theano tensor sharedvar SharedVariable label label get_value borrow True if not isinstance train numpy ndarray or scipy sparse issparse train raise TypeError 'train...
91
python-test-6865
python
What does the code create ?
a module dictionary for the hardened part of the process
def Setup Shared Modules module dict output dict {}for module name module in module dict iteritems if module is None continueif Is Encodings Module module name output dict[module name] modulecontinueshared prefix Module Name Has Prefix module name SHARED MODULE PREFIXES banned prefix Module Name Has Prefix module name ...
def SetupSharedModules module_dict output_dict {}for module_name module in module_dict iteritems if module is None continueif IsEncodingsModule module_name output_dict[module_name] modulecontinueshared_prefix ModuleNameHasPrefix module_name SHARED_MODULE_PREFIXES banned_prefix ModuleNameHasPrefix module_name NOT_SHARED...
65
python-test-6867
python
How does img resize ?
along dimension
def reduce along dim img dim weights indicies other dim abs dim - 1 if other dim 0 weights np tile weights[np newaxis np newaxis] img shape[other dim] 1 1 3 out img img[ indicies ] * weights out img np sum out img axis 2 else weights np tile weights[ np newaxis np newaxis] 1 1 img shape[other dim] 3 out img img[indicie...
def reduce_along_dim img dim weights indicies other_dim abs dim - 1 if other_dim 0 weights np tile weights[np newaxis np newaxis] img shape[other_dim] 1 1 3 out_img img[ indicies ] * weights out_img np sum out_img axis 2 else weights np tile weights[ np newaxis np newaxis] 1 1 img shape[other_dim] 3 out_img img[indicie...
78
python-test-6869
python
What do all models have ?
a direct relationship to the given model
def get related models m related models [subclass for subclass in m subclasses if issubclass subclass models Model ]related fields models set for f in m meta get fields include parents True include hidden True if f is relation and f related model is not None and not isinstance f related model str related fields models ...
def _get_related_models m related_models [subclass for subclass in m __subclasses__ if issubclass subclass models Model ]related_fields_models set for f in m _meta get_fields include_parents True include_hidden True if f is_relation and f related_model is not None and not isinstance f related_model str related_fields_m...
85
python-test-6870
python
How does white space pass ?
from start
def parse identifier source start throw True start pass white source start end startif not end < len source if throw raise Syntax Error ' Missingidentifier ' return Noneif source[end] not in IDENTIFIER START if throw raise Syntax Error ' Invalididentifierstart "%s"' % source[end] return Noneend + 1while end < len sourc...
def parse_identifier source start throw True start pass_white source start end startif not end < len source if throw raise SyntaxError 'Missingidentifier ' return Noneif source[end] not in IDENTIFIER_START if throw raise SyntaxError 'Invalididentifierstart "%s"' % source[end] return Noneend + 1while end < len source an...
82
python-test-6875
python
What does the code retrieve ?
the log messages
@get '/scan/<taskid>/log' def scan log taskid json log messages list if taskid not in Data Store tasks logger warning '[%s] Invalidtask I Dprovidedtoscan log ' % taskid return jsonize {'success' False 'message' ' Invalidtask ID'} for time level message in Data Store current db execute 'SELEC Ttime level message FRO Mlo...
@get '/scan/<taskid>/log' def scan_log taskid json_log_messages list if taskid not in DataStore tasks logger warning '[%s]InvalidtaskIDprovidedtoscan_log ' % taskid return jsonize {'success' False 'message' 'InvalidtaskID'} for time_ level message in DataStore current_db execute 'SELECTtime level messageFROMlogsWHEREta...
81
python-test-6878
python
What does the code generate ?
a sql where clause for job status filtering
def extra job filters not yet run False running False finished False assert not not yet run and running or not yet run and finished or running and finished ' Cannotspecifymorethanonefiltertothisfunction'not queued ' SELEC Tjob id FRO Mafe host queue entries WHER Estatus "%s" ' % models Host Queue Entry Status QUEUED no...
def extra_job_filters not_yet_run False running False finished False assert not not_yet_run and running or not_yet_run and finished or running and finished 'Cannotspecifymorethanonefiltertothisfunction'not_queued ' SELECTjob_idFROMafe_host_queue_entriesWHEREstatus "%s" ' % models HostQueueEntry Status QUEUED not_finish...
106
python-test-6879
python
What does the code get ?
all mfa devices associated with an iam user
def get all mfa devices user name region None key None keyid None profile None user get user user name region key keyid profile if not user msg ' Username{ 0 }doesnotexist'log error msg format user name return Falseconn get conn region region key key keyid keyid profile profile try result conn get all mfa devices user ...
def get_all_mfa_devices user_name region None key None keyid None profile None user get_user user_name region key keyid profile if not user msg 'Username{0}doesnotexist'log error msg format user_name return Falseconn _get_conn region region key key keyid keyid profile profile try result conn get_all_mfa_devices user_na...
110
python-test-6880
python
What does generic retry decorator try ?
to call the decorated function
def retry exception processor generic exception processor def yield new function from f def shim *args **kwargs exc processor cxt Nonewhile True gevent sleep 0 1 try return f *args **kwargs except Keyboard Interrupt raiseexcept exception info tuple Nonetry exception info tuple sys exc info exc processor cxt exception p...
def retry exception_processor generic_exception_processor def yield_new_function_from f def shim *args **kwargs exc_processor_cxt Nonewhile True gevent sleep 0 1 try return f *args **kwargs except KeyboardInterrupt raiseexcept exception_info_tuple Nonetry exception_info_tuple sys exc_info exc_processor_cxt exception_pr...
73
python-test-6884
python
What does the code generate ?
a string for use with the coordinate packages docstring to show the available transforms and coordinate systems
def make transform graph docs import inspectfrom textwrap import dedentfrom extern import sixfrom baseframe import Base Coordinate Frame frame transform graphisclass inspect isclasscoosys [item for item in six itervalues globals if isclass item and issubclass item Base Coordinate Frame ]graphstr frame transform graph t...
def _make_transform_graph_docs import inspectfrom textwrap import dedentfrom extern import sixfrom baseframe import BaseCoordinateFrame frame_transform_graphisclass inspect isclasscoosys [item for item in six itervalues globals if isclass item and issubclass item BaseCoordinateFrame ]graphstr frame_transform_graph to_d...
73
python-test-6886
python
What is this device getting from another device ?
data - related objects
@csrf exempt@require sync session@api handle error with jsondef model upload data session if 'models' not in data return Json Response Message Error ' Mustprovidemodels ' data {'saved model count' 0} status 400 try result save serialized models data['models'] src version session client version except Exception as e pri...
@csrf_exempt@require_sync_session@api_handle_error_with_jsondef model_upload data session if 'models' not in data return JsonResponseMessageError 'Mustprovidemodels ' data {'saved_model_count' 0} status 400 try result save_serialized_models data['models'] src_version session client_version except Exception as e print '...
87
python-test-6899
python
What does the code add to an object ?
a function / method
def magic set obj def decorator func is class isinstance obj six class types args varargs varkw defaults inspect getargspec func if not args or args[ 0 ] not in 'self' 'cls' 'klass' if is class replacement staticmethod func else replacement funcelif args[ 0 ] 'self' if is class replacement funcelse def replacement *arg...
def magic_set obj def decorator func is_class isinstance obj six class_types args varargs varkw defaults inspect getargspec func if not args or args[0] not in 'self' 'cls' 'klass' if is_class replacement staticmethod func else replacement funcelif args[0] 'self' if is_class replacement funcelse def replacement *args **...
97
python-test-6901
python
For what purpose did any overrides set on this block ?
for this ccx
def get overrides for ccx ccx overrides cache request cache get cache 'ccx-overrides' if ccx not in overrides cache overrides {}query Ccx Field Override objects filter ccx ccx for override in query block overrides overrides setdefault override location {} block overrides[override field] json loads override value block ...
def _get_overrides_for_ccx ccx overrides_cache request_cache get_cache 'ccx-overrides' if ccx not in overrides_cache overrides {}query CcxFieldOverride objects filter ccx ccx for override in query block_overrides overrides setdefault override location {} block_overrides[override field] json loads override value block_o...
68
python-test-6904
python
What does the code use to parse the metadata from the provided url ?
the metadata module
def get data url try request requests get url request raise for status except requests exceptions HTTP Error requests exceptions Connection Error as e raise Parse Error e items microdata get items request text for item in items if item itemtype [microdata URI 'http //schema org/ Recipe' ] return itemraise Parse Error '...
def get_data url try request requests get url request raise_for_status except requests exceptions HTTPError requests exceptions ConnectionError as e raise ParseError e items microdata get_items request text for item in items if item itemtype [microdata URI 'http //schema org/Recipe' ] return itemraise ParseError 'Norec...
54
python-test-6905
python
What does the code use the metadata module ?
to parse the metadata from the provided url
def get data url try request requests get url request raise for status except requests exceptions HTTP Error requests exceptions Connection Error as e raise Parse Error e items microdata get items request text for item in items if item itemtype [microdata URI 'http //schema org/ Recipe' ] return itemraise Parse Error '...
def get_data url try request requests get url request raise_for_status except requests exceptions HTTPError requests exceptions ConnectionError as e raise ParseError e items microdata get_items request text for item in items if item itemtype [microdata URI 'http //schema org/Recipe' ] return itemraise ParseError 'Norec...
54
python-test-6906
python
What does the code parse ?
the metadata from the provided url
def get data url try request requests get url request raise for status except requests exceptions HTTP Error requests exceptions Connection Error as e raise Parse Error e items microdata get items request text for item in items if item itemtype [microdata URI 'http //schema org/ Recipe' ] return itemraise Parse Error '...
def get_data url try request requests get url request raise_for_status except requests exceptions HTTPError requests exceptions ConnectionError as e raise ParseError e items microdata get_items request text for item in items if item itemtype [microdata URI 'http //schema org/Recipe' ] return itemraise ParseError 'Norec...
54
python-test-6907
python
What will this limit ?
constraints
def limit max file size f @functools wraps f def wrapper *args **kwargs test max file size constraints MAX FILE SIZ Eif constraints MAX FILE SIZE > sys maxsize test max file size 2 ** 30 + 2 with mock patch object constraints 'MAX FILE SIZE' test max file size return f *args **kwargs return wrapper
def _limit_max_file_size f @functools wraps f def wrapper *args **kwargs test_max_file_size constraints MAX_FILE_SIZEif constraints MAX_FILE_SIZE > sys maxsize test_max_file_size 2 ** 30 + 2 with mock patch object constraints 'MAX_FILE_SIZE' test_max_file_size return f *args **kwargs return wrapper
56
python-test-6911
python
What does the code fetch by task_id ?
an taskinfo entity
def task info get context task id session None session session or get session query session query models Task Info query query filter by task id task id try task info ref query one except sa orm exc No Result Found LOG debug ' Task Infowasnotfoundfortaskwithid% task id s' {'task id' task id} task info ref Nonereturn ta...
def _task_info_get context task_id session None session session or get_session query session query models TaskInfo query query filter_by task_id task_id try task_info_ref query one except sa_orm exc NoResultFound LOG debug 'TaskInfowasnotfoundfortaskwithid% task_id s' {'task_id' task_id} task_info_ref Nonereturn task_i...
60
python-test-6912
python
How does the code fetch an taskinfo entity ?
by task_id
def task info get context task id session None session session or get session query session query models Task Info query query filter by task id task id try task info ref query one except sa orm exc No Result Found LOG debug ' Task Infowasnotfoundfortaskwithid% task id s' {'task id' task id} task info ref Nonereturn ta...
def _task_info_get context task_id session None session session or get_session query session query models TaskInfo query query filter_by task_id task_id try task_info_ref query one except sa_orm exc NoResultFound LOG debug 'TaskInfowasnotfoundfortaskwithid% task_id s' {'task_id' task_id} task_info_ref Nonereturn task_i...
60
python-test-6913
python
What does the code start ?
the server mode
def start server config args logger info ' Startservermode' global serverfrom glances server import Glances Serverserver Glances Server cached time args cached time config config args args print ' Glancesserverisrunningon{} {}' format args bind address args port if args password '' server add user args username args pa...
def start_server config args logger info 'Startservermode' global serverfrom glances server import GlancesServerserver GlancesServer cached_time args cached_time config config args args print 'Glancesserverisrunningon{} {}' format args bind_address args port if args password '' server add_user args username args passwo...
54
python-test-6914
python
When did the missing feature explain ?
at [ 0
@mock ec 2 def test modify attribute block Device Mapping conn boto ec 2 connect to region u'us-east- 1 ' reservation conn run instances u'ami- 1234 abcd' instance reservation instances[ 0 ]with assert raises JSON Response Error as ex instance modify attribute u'block Device Mapping' {u'/dev/sda 1 ' True} dry run True ...
@mock_ec2def test_modify_attribute_blockDeviceMapping conn boto ec2 connect_to_region u'us-east-1' reservation conn run_instances u'ami-1234abcd' instance reservation instances[0]with assert_raises JSONResponseError as ex instance modify_attribute u'blockDeviceMapping' {u'/dev/sda1' True} dry_run True ex exception reas...
127
python-test-6915
python
What does the code get within transaction ?
port record for update
def get port context port id with context session begin subtransactions True try record context session query models v2 Port enable eagerloads False filter models v2 Port id startswith port id one return recordexcept exc No Result Found returnexcept exc Multiple Results Found LOG error LE ' Multipleportshaveport idstar...
def get_port context port_id with context session begin subtransactions True try record context session query models_v2 Port enable_eagerloads False filter models_v2 Port id startswith port_id one return recordexcept exc NoResultFound returnexcept exc MultipleResultsFound LOG error _LE 'Multipleportshaveport_idstarting...
52
python-test-6916
python
For what purpose do url return ?
for a gravatar
@register simple tagdef get gravatar email size 80 rating 'g' default None protocol PROTOCOL gravatar protocols {'http' 'http //www' 'https' 'https //secure'}url '%s gravatar com/avatar/%s' % gravatar protocols[protocol] md 5 email strip lower encode 'utf- 8 ' hexdigest options {'s' size 'r' rating}if default options['...
@register simple_tagdef get_gravatar email size 80 rating 'g' default None protocol PROTOCOL gravatar_protocols {'http' 'http //www' 'https' 'https //secure'}url '%s gravatar com/avatar/%s' % gravatar_protocols[protocol] md5 email strip lower encode 'utf-8' hexdigest options {'s' size 'r' rating}if default options['d']...
57
python-test-6921
python
What be this decorator used ?
in modelviewsets methods to lock them based on the model and the i d of the selected object
def model pk lock func def decorator self *args **kwargs from taiga base utils db import get typename for model classpk self kwargs get self pk url kwarg None tn get typename for model class self get queryset model key '{ 0 } {1 }' format tn pk with advisory lock key return func self *args **kwargs return decorator
def model_pk_lock func def decorator self *args **kwargs from taiga base utils db import get_typename_for_model_classpk self kwargs get self pk_url_kwarg None tn get_typename_for_model_class self get_queryset model key '{0} {1}' format tn pk with advisory_lock key return func self *args **kwargs return decorator
59
python-test-6922
python
What is this decorator d designed ?
to be used in modelviewsets methods to lock them based on the model and the i d of the selected object
def model pk lock func def decorator self *args **kwargs from taiga base utils db import get typename for model classpk self kwargs get self pk url kwarg None tn get typename for model class self get queryset model key '{ 0 } {1 }' format tn pk with advisory lock key return func self *args **kwargs return decorator
def model_pk_lock func def decorator self *args **kwargs from taiga base utils db import get_typename_for_model_classpk self kwargs get self pk_url_kwarg None tn get_typename_for_model_class self get_queryset model key '{0} {1}' format tn pk with advisory_lock key return func self *args **kwargs return decorator
59
python-test-6923
python
How did them lock ?
based on the model and the i d of the selected object
def model pk lock func def decorator self *args **kwargs from taiga base utils db import get typename for model classpk self kwargs get self pk url kwarg None tn get typename for model class self get queryset model key '{ 0 } {1 }' format tn pk with advisory lock key return func self *args **kwargs return decorator
def model_pk_lock func def decorator self *args **kwargs from taiga base utils db import get_typename_for_model_classpk self kwargs get self pk_url_kwarg None tn get_typename_for_model_class self get_queryset model key '{0} {1}' format tn pk with advisory_lock key return func self *args **kwargs return decorator
59
python-test-6924
python
What adds to elementtree in - place ?
line breaks and indentation
def indent elem level 0 i '\n' + level * '' if len elem if not elem text or not elem text strip elem text i + '' for e in elem indent e level + 1 if not e tail or not e tail strip e tail i + '' if not e tail or not e tail strip e tail ielif level and not elem tail or not elem tail strip elem tail i
def _indent elem level 0 i '\n' + level * '' if len elem if not elem text or not elem text strip elem text i + '' for e in elem _indent e level + 1 if not e tail or not e tail strip e tail i + '' if not e tail or not e tail strip e tail ielif level and not elem tail or not elem tail strip elem tail i
76
python-test-6925
python
What do line breaks and indentation add ?
to elementtree in - place
def indent elem level 0 i '\n' + level * '' if len elem if not elem text or not elem text strip elem text i + '' for e in elem indent e level + 1 if not e tail or not e tail strip e tail i + '' if not e tail or not e tail strip e tail ielif level and not elem tail or not elem tail strip elem tail i
def _indent elem level 0 i '\n' + level * '' if len elem if not elem text or not elem text strip elem text i + '' for e in elem _indent e level + 1 if not e tail or not e tail strip e tail i + '' if not e tail or not e tail strip e tail ielif level and not elem tail or not elem tail strip elem tail i
76
python-test-6928
python
What does this test ?
what happens when you parse a date with no timezone
def test parse no timezone d iso 8601 parse date '2007 - 01 - 01 T 08 00 00 ' assert d year 2007 assert d month 1 assert d day 1 assert d hour 8 assert d minute 0 assert d second 0 assert d microsecond 0 assert d tzinfo iso 8601 UTC
def test_parse_no_timezone d iso8601 parse_date '2007-01-01T08 00 00' assert d year 2007 assert d month 1 assert d day 1 assert d hour 8 assert d minute 0 assert d second 0 assert d microsecond 0 assert d tzinfo iso8601 UTC
54
python-test-6929
python
What does you parse when ?
a date with no timezone
def test parse no timezone d iso 8601 parse date '2007 - 01 - 01 T 08 00 00 ' assert d year 2007 assert d month 1 assert d day 1 assert d hour 8 assert d minute 0 assert d second 0 assert d microsecond 0 assert d tzinfo iso 8601 UTC
def test_parse_no_timezone d iso8601 parse_date '2007-01-01T08 00 00' assert d year 2007 assert d month 1 assert d day 1 assert d hour 8 assert d minute 0 assert d second 0 assert d microsecond 0 assert d tzinfo iso8601 UTC
54
python-test-6930
python
When does what happen ?
when you parse a date with no timezone
def test parse no timezone d iso 8601 parse date '2007 - 01 - 01 T 08 00 00 ' assert d year 2007 assert d month 1 assert d day 1 assert d hour 8 assert d minute 0 assert d second 0 assert d microsecond 0 assert d tzinfo iso 8601 UTC
def test_parse_no_timezone d iso8601 parse_date '2007-01-01T08 00 00' assert d year 2007 assert d month 1 assert d day 1 assert d hour 8 assert d minute 0 assert d second 0 assert d microsecond 0 assert d tzinfo iso8601 UTC
54
python-test-6931
python
What d i d download for given image ?
the specified layer
def get image files json image id files json get image files cache image id if files json return files jsonimage path store image layer path image id with tempfile Temporary File as tmp fobj for buf in store stream read image path tmp fobj write buf tmp fobj seek 0 files json json dumps get image files from fobj tmp fo...
def get_image_files_json image_id files_json get_image_files_cache image_id if files_json return files_jsonimage_path store image_layer_path image_id with tempfile TemporaryFile as tmp_fobj for buf in store stream_read image_path tmp_fobj write buf tmp_fobj seek 0 files_json json dumps get_image_files_from_fobj tmp_fob...
73
python-test-6934
python
What does the code create ?
an api key given name and description
def create api key name description enabled True stage Keys None region None key None keyid None profile None try stage Keys list if stage Keys is None else stage Keys conn get conn region region key key keyid keyid profile profile response conn create api key name name description description enabled enabled stage Key...
def create_api_key name description enabled True stageKeys None region None key None keyid None profile None try stageKeys list if stageKeys is None else stageKeys conn _get_conn region region key key keyid keyid profile profile response conn create_api_key name name description description enabled enabled stageKeys st...
88
python-test-6937
python
Where does the code run an esxcli command directly ?
on the host or list of hosts
@depends HAS ESX CLI def esxcli cmd cmd str host None username None password None protocol None port None esxi hosts None ret {}if esxi hosts if not isinstance esxi hosts list raise Command Execution Error "'esxi hosts'mustbealist " for esxi host in esxi hosts response salt utils vmware esxcli host username password cm...
@depends HAS_ESX_CLI def esxcli_cmd cmd_str host None username None password None protocol None port None esxi_hosts None ret {}if esxi_hosts if not isinstance esxi_hosts list raise CommandExecutionError "'esxi_hosts'mustbealist " for esxi_host in esxi_hosts response salt utils vmware esxcli host username password cmd_...
116
python-test-6938
python
What does the code run on the host or list of hosts directly ?
an esxcli command
@depends HAS ESX CLI def esxcli cmd cmd str host None username None password None protocol None port None esxi hosts None ret {}if esxi hosts if not isinstance esxi hosts list raise Command Execution Error "'esxi hosts'mustbealist " for esxi host in esxi hosts response salt utils vmware esxcli host username password cm...
@depends HAS_ESX_CLI def esxcli_cmd cmd_str host None username None password None protocol None port None esxi_hosts None ret {}if esxi_hosts if not isinstance esxi_hosts list raise CommandExecutionError "'esxi_hosts'mustbealist " for esxi_host in esxi_hosts response salt utils vmware esxcli host username password cmd_...
116
python-test-6939
python
What does the code compare for tests ?
filter - based and more optimized subrange implementations helper
def subrange exercise mult lb ub m Multiset Partition Traverser assert m count partitions mult m count partitions slow mult ma Multiset Partition Traverser mc Multiset Partition Traverser md Multiset Partition Traverser a it ma enum range mult lb ub b it part range filter multiset partitions taocp mult lb ub c it part ...
def subrange_exercise mult lb ub m MultisetPartitionTraverser assert m count_partitions mult m count_partitions_slow mult ma MultisetPartitionTraverser mc MultisetPartitionTraverser md MultisetPartitionTraverser a_it ma enum_range mult lb ub b_it part_range_filter multiset_partitions_taocp mult lb ub c_it part_range_fi...
110
python-test-6944
python
What does the code restore at the location given its argument with the contents of the database ?
the running osf database
@taskdef mongorestore ctx path drop False db settings DB NAM Eport settings DB POR Tcmd 'mongorestore--db{db}--port{port}' format db db port port pty True if settings DB USER cmd + '--username{ 0 }' format settings DB USER if settings DB PASS cmd + '--password{ 0 }' format settings DB PASS if drop cmd + '--drop'cmd + '...
@taskdef mongorestore ctx path drop False db settings DB_NAMEport settings DB_PORTcmd 'mongorestore--db{db}--port{port}' format db db port port pty True if settings DB_USER cmd + '--username{0}' format settings DB_USER if settings DB_PASS cmd + '--password{0}' format settings DB_PASS if drop cmd + '--drop'cmd + '' + pa...
63
python-test-6945
python
How does the code restore the running osf database at the location given its argument ?
with the contents of the database
@taskdef mongorestore ctx path drop False db settings DB NAM Eport settings DB POR Tcmd 'mongorestore--db{db}--port{port}' format db db port port pty True if settings DB USER cmd + '--username{ 0 }' format settings DB USER if settings DB PASS cmd + '--password{ 0 }' format settings DB PASS if drop cmd + '--drop'cmd + '...
@taskdef mongorestore ctx path drop False db settings DB_NAMEport settings DB_PORTcmd 'mongorestore--db{db}--port{port}' format db db port port pty True if settings DB_USER cmd + '--username{0}' format settings DB_USER if settings DB_PASS cmd + '--password{0}' format settings DB_PASS if drop cmd + '--drop'cmd + '' + pa...
63
python-test-6946
python
Where does the code restore the running osf database with the contents of the database ?
at the location given its argument
@taskdef mongorestore ctx path drop False db settings DB NAM Eport settings DB POR Tcmd 'mongorestore--db{db}--port{port}' format db db port port pty True if settings DB USER cmd + '--username{ 0 }' format settings DB USER if settings DB PASS cmd + '--password{ 0 }' format settings DB PASS if drop cmd + '--drop'cmd + '...
@taskdef mongorestore ctx path drop False db settings DB_NAMEport settings DB_PORTcmd 'mongorestore--db{db}--port{port}' format db db port port pty True if settings DB_USER cmd + '--username{0}' format settings DB_USER if settings DB_PASS cmd + '--password{0}' format settings DB_PASS if drop cmd + '--drop'cmd + '' + pa...
63
python-test-6947
python
What does the code get ?
all submodules of the main scientific modules and others of our interest
def get preferred submodules if 'submodules' in modules db return modules db['submodules']mods ['numpy' 'scipy' 'sympy' 'pandas' 'networkx' 'statsmodels' 'matplotlib' 'sklearn' 'skimage' 'mpmath' 'os' 'PIL' ' Open GL' 'array' 'audioop' 'binascii' 'c Pickle' 'c String IO' 'cmath' 'collections' 'datetime' 'errno' 'except...
def get_preferred_submodules if 'submodules' in modules_db return modules_db['submodules']mods ['numpy' 'scipy' 'sympy' 'pandas' 'networkx' 'statsmodels' 'matplotlib' 'sklearn' 'skimage' 'mpmath' 'os' 'PIL' 'OpenGL' 'array' 'audioop' 'binascii' 'cPickle' 'cStringIO' 'cmath' 'collections' 'datetime' 'errno' 'exceptions'...
86
python-test-6950
python
What does the code prepare ?
our list of parsing plugins and default parsers
@event u'manager startup' def init parsers manager for parser type in PARSER TYPES parsers[parser type] {}for p in plugin get plugins interface parser type + u' parser' parsers[parser type][p name replace u'parser ' u'' ] p instancefunc name u'parse ' + parser type default parsers[parser type] max iter parsers[parser t...
@event u'manager startup' def init_parsers manager for parser_type in PARSER_TYPES parsers[parser_type] {}for p in plugin get_plugins interface parser_type + u'_parser' parsers[parser_type][p name replace u'parser_' u'' ] p instancefunc_name u'parse_' + parser_type default_parsers[parser_type] max iter parsers[parser_t...
78
python-test-6951
python
What places remaining rows ?
remaining queens
def place board queens r c d g if not queens solutions append None if len queens > len board returnif len queens > len r returnif len queens > len c returnif len queens > len d returnif len queens > len g returnfor ip pos in enumerate board ar ac ad ag attackmap[pos]attacked frozenset union ar ac ad ag nboard [b for b ...
def place board queens r c d g if not queens solutions append None if len queens > len board returnif len queens > len r returnif len queens > len c returnif len queens > len d returnif len queens > len g returnfor ip pos in enumerate board ar ac ad ag attackmap[pos]attacked frozenset union ar ac ad ag nboard [b for b ...
93
python-test-6952
python
What do remaining queens place ?
remaining rows
def place board queens r c d g if not queens solutions append None if len queens > len board returnif len queens > len r returnif len queens > len c returnif len queens > len d returnif len queens > len g returnfor ip pos in enumerate board ar ac ad ag attackmap[pos]attacked frozenset union ar ac ad ag nboard [b for b ...
def place board queens r c d g if not queens solutions append None if len queens > len board returnif len queens > len r returnif len queens > len c returnif len queens > len d returnif len queens > len g returnfor ip pos in enumerate board ar ac ad ag attackmap[pos]attacked frozenset union ar ac ad ag nboard [b for b ...
93
python-test-6953
python
What does the code reconstruct ?
a rational number frac a b
def integer rational reconstruction c m domain if c < 0 c + m r0 s0 m domain zero r1 s1 c domain one bound sqrt m / 2 while r1 > bound quo r0 // r1 r0 r1 r1 r0 - quo * r1 s0 s1 s1 s0 - quo * s1 if abs s1 > bound return Noneif s1 < 0 a b - r1 - s1 elif s1 > 0 a b r1 s1 else return Nonefield domain get field return field...
def _integer_rational_reconstruction c m domain if c < 0 c + m r0 s0 m domain zero r1 s1 c domain one bound sqrt m / 2 while r1 > bound quo r0 // r1 r0 r1 r1 r0 - quo * r1 s0 s1 s1 s0 - quo * s1 if abs s1 > bound return Noneif s1 < 0 a b - r1 - s1 elif s1 > 0 a b r1 s1 else return Nonefield domain get_field return fiel...
89
python-test-6956
python
How does application run ?
with environ and start_response
def capture output environ start response application warnings warn 'wsgilib capture outputhasbeendeprecatedinfavorofwsgilib intercept output' Deprecation Warning 2 data []output String IO def replacement start response status headers exc info None if data data[ ] []data append status data append headers start response...
def capture_output environ start_response application warnings warn 'wsgilib capture_outputhasbeendeprecatedinfavorofwsgilib intercept_output' DeprecationWarning 2 data []output StringIO def replacement_start_response status headers exc_info None if data data[ ] []data append status data append headers start_response s...
93
python-test-6957
python
What does the code reverse ?
the bits of a 64-bit integer
def Reverse Bits Int 64 v v v >> 1 & 6148914691236517205 v & 6148914691236517205 << 1 v v >> 2 & 3689348814741910323 v & 3689348814741910323 << 2 v v >> 4 & 1085102592571150095 v & 1085102592571150095 << 4 v v >> 8 & 71777214294589695 v & 71777214294589695 << 8 v v >> 16 & 281470681808895 v & 281470681808895 << 16 v in...
def ReverseBitsInt64 v v v >> 1 & 6148914691236517205 v & 6148914691236517205 << 1 v v >> 2 & 3689348814741910323 v & 3689348814741910323 << 2 v v >> 4 & 1085102592571150095 v & 1085102592571150095 << 4 v v >> 8 & 71777214294589695 v & 71777214294589695 << 8 v v >> 16 & 281470681808895 v & 281470681808895 << 16 v int v...
74
python-test-6961
python
What are painted an rgb image ?
color - coded labels
def label 2 rgb label image None colors None alpha 0 3 bg label -1 bg color 0 0 0 image alpha 1 kind 'overlay' if kind 'overlay' return label 2 rgb overlay label image colors alpha bg label bg color image alpha else return label 2 rgb avg label image bg label bg color
def label2rgb label image None colors None alpha 0 3 bg_label -1 bg_color 0 0 0 image_alpha 1 kind 'overlay' if kind 'overlay' return _label2rgb_overlay label image colors alpha bg_label bg_color image_alpha else return _label2rgb_avg label image bg_label bg_color
55
python-test-6962
python
What does the code create ?
a player with the given name and password
def create normal player session name password if throttle session maxlim 5 timeout 5 * 60 session msg '{R Youmadetoomanyconnectionattempts Tryagaininafewminutes {n' return Noneplayer authenticate username name password password if not player session msg ' Incorrectlogininformationgiven ' throttle session player Player...
def create_normal_player session name password if _throttle session maxlim 5 timeout 5 * 60 session msg '{RYoumadetoomanyconnectionattempts Tryagaininafewminutes {n' return Noneplayer authenticate username name password password if not player session msg 'Incorrectlogininformationgiven ' _throttle session player Player...
113
python-test-6964
python
What does the code rebuild from the file system ?
the cache indexes
def Rebuild verbose 1 clsid To Typelib clear infos Get Generated Infos if verbose and len infos print ' Rebuildingcacheofgeneratedfilesfor CO Msupport 'for info in infos iid lcid major minor infoif verbose print ' Checking' Get Generated File Name *info try Add Module To Cache iid lcid major minor verbose 0 except prin...
def Rebuild verbose 1 clsidToTypelib clear infos GetGeneratedInfos if verbose and len infos print 'RebuildingcacheofgeneratedfilesforCOMsupport 'for info in infos iid lcid major minor infoif verbose print 'Checking' GetGeneratedFileName *info try AddModuleToCache iid lcid major minor verbose 0 except print 'Couldnotadd...
79
python-test-6969
python
What does the code take ?
a continuous subsequence of terms of f in x_j in k[x ]
def dmp slice in f m n j u K if j < 0 or j > u raise Index Error '-%s< j<%sexpected got%s' % u u j if not u return dup slice f m n K f g dmp to dict f u {} for monom coeff in f items k monom[j]if k < m or k > n monom monom[ j] + 0 + monom[ j + 1 ] if monom in g g[monom] + coeffelse g[monom] coeffreturn dmp from dict g ...
def dmp_slice_in f m n j u K if j < 0 or j > u raise IndexError '-%s< j<%sexpected got%s' % u u j if not u return dup_slice f m n K f g dmp_to_dict f u {} for monom coeff in f items k monom[j]if k < m or k > n monom monom[ j] + 0 + monom[ j + 1 ] if monom in g g[monom] + coeffelse g[monom] coeffreturn dmp_from_dict g u...
87
python-test-6973
python
What does the code render ?
a response consisting of an html chunk and a js onload chunk in the format required by the modal - workflow framework
def render modal workflow request html template js template template vars None response keyvars []if html template html render to string html template template vars or {} request request response keyvars append u"'html' %s" % json dumps html if js template js render to string js template template vars or {} request req...
def render_modal_workflow request html_template js_template template_vars None response_keyvars []if html_template html render_to_string html_template template_vars or {} request request response_keyvars append u"'html' %s" % json dumps html if js_template js render_to_string js_template template_vars or {} request req...
77
python-test-6976
python
What do function implement when scaling down the image ?
matlabs imresize functionality default behaviour cubic spline interpolation with antialiasing correction
def imresize img cropped width cropped height width scale float cropped width / img shape[ 1 ] height scale float cropped height / img shape[ 0 ] if len img shape 2 img np tile img[ np newaxis] 1 1 3 order np argsort [height scale width scale] scale [height scale width scale]out dim [cropped height cropped width]weight...
def imresize img cropped_width cropped_height width_scale float cropped_width / img shape[1] height_scale float cropped_height / img shape[0] if len img shape 2 img np tile img[ np newaxis] 1 1 3 order np argsort [height_scale width_scale] scale [height_scale width_scale]out_dim [cropped_height cropped_width]weights [0...
92
python-test-6977
python
When do function implement matlabs imresize functionality default behaviour cubic spline interpolation with antialiasing correction ?
when scaling down the image
def imresize img cropped width cropped height width scale float cropped width / img shape[ 1 ] height scale float cropped height / img shape[ 0 ] if len img shape 2 img np tile img[ np newaxis] 1 1 3 order np argsort [height scale width scale] scale [height scale width scale]out dim [cropped height cropped width]weight...
def imresize img cropped_width cropped_height width_scale float cropped_width / img shape[1] height_scale float cropped_height / img shape[0] if len img shape 2 img np tile img[ np newaxis] 1 1 3 order np argsort [height_scale width_scale] scale [height_scale width_scale]out_dim [cropped_height cropped_width]weights [0...
92
python-test-6978
python
What does the code determine from an ismaster response ?
the server type
def get server type doc if not doc get 'ok' return SERVER TYPE Unknownif doc get 'isreplicaset' return SERVER TYPE RS Ghostelif doc get 'set Name' if doc get 'hidden' return SERVER TYPE RS Otherelif doc get 'ismaster' return SERVER TYPE RS Primaryelif doc get 'secondary' return SERVER TYPE RS Secondaryelif doc get 'arb...
def _get_server_type doc if not doc get 'ok' return SERVER_TYPE Unknownif doc get 'isreplicaset' return SERVER_TYPE RSGhostelif doc get 'setName' if doc get 'hidden' return SERVER_TYPE RSOtherelif doc get 'ismaster' return SERVER_TYPE RSPrimaryelif doc get 'secondary' return SERVER_TYPE RSSecondaryelif doc get 'arbiter...
77
python-test-6979
python
How does the code determine the server type ?
from an ismaster response
def get server type doc if not doc get 'ok' return SERVER TYPE Unknownif doc get 'isreplicaset' return SERVER TYPE RS Ghostelif doc get 'set Name' if doc get 'hidden' return SERVER TYPE RS Otherelif doc get 'ismaster' return SERVER TYPE RS Primaryelif doc get 'secondary' return SERVER TYPE RS Secondaryelif doc get 'arb...
def _get_server_type doc if not doc get 'ok' return SERVER_TYPE Unknownif doc get 'isreplicaset' return SERVER_TYPE RSGhostelif doc get 'setName' if doc get 'hidden' return SERVER_TYPE RSOtherelif doc get 'ismaster' return SERVER_TYPE RSPrimaryelif doc get 'secondary' return SERVER_TYPE RSSecondaryelif doc get 'arbiter...
77
python-test-6980
python
What does the code decode ?
a bson code_w_scope
def get code w scope data position obj end opts element name code end position + UNPACK INT data[position position + 4 ] [0 ] code position get string data position + 4 code end opts element name scope position get object data position code end opts element name if position code end raise Invalid BSON 'scopeoutsideofja...
def _get_code_w_scope data position obj_end opts element_name code_end position + _UNPACK_INT data[position position + 4 ] [0] code position _get_string data position + 4 code_end opts element_name scope position _get_object data position code_end opts element_name if position code_end raise InvalidBSON 'scopeoutsideof...
62
python-test-6984
python
What does the code build ?
a map of all dynamically linked tables
def get dynamic link map for delete False if getattr frappe local 'dynamic link map' None None or frappe flags in test dynamic link map {}for df in get dynamic links meta frappe get meta df parent if meta issingle dynamic link map setdefault meta name [] append df else links frappe db sql list 'selectdistinct{options}f...
def get_dynamic_link_map for_delete False if getattr frappe local 'dynamic_link_map' None None or frappe flags in_test dynamic_link_map {}for df in get_dynamic_links meta frappe get_meta df parent if meta issingle dynamic_link_map setdefault meta name [] append df else links frappe db sql_list 'selectdistinct{options}f...
83
python-test-6986
python
What does shop contain when ?
multiple relation types
@pytest mark django dbdef test cross sell plugin type shop get default shop supplier get default supplier product create product 'test-sku' shop shop supplier supplier stock behavior Stock Behavior UNSTOCKED context get jinja context product product type counts Product Cross Sell Type RELATED 1 Product Cross Sell Type ...
@pytest mark django_dbdef test_cross_sell_plugin_type shop get_default_shop supplier get_default_supplier product create_product 'test-sku' shop shop supplier supplier stock_behavior StockBehavior UNSTOCKED context get_jinja_context product product type_counts ProductCrossSellType RELATED 1 ProductCrossSellType RECOMME...
105
python-test-6987
python
What contains multiple relation types when ?
shop
@pytest mark django dbdef test cross sell plugin type shop get default shop supplier get default supplier product create product 'test-sku' shop shop supplier supplier stock behavior Stock Behavior UNSTOCKED context get jinja context product product type counts Product Cross Sell Type RELATED 1 Product Cross Sell Type ...
@pytest mark django_dbdef test_cross_sell_plugin_type shop get_default_shop supplier get_default_supplier product create_product 'test-sku' shop shop supplier supplier stock_behavior StockBehavior UNSTOCKED context get_jinja_context product product type_counts ProductCrossSellType RELATED 1 ProductCrossSellType RECOMME...
105
python-test-6988
python
What does the code add ?
the given number of days on to the current date
def get http expiry Expirestype num if Expirestype 'd' expire date datetime datetime now + datetime timedelta days num elif Expirestype 'h' expire date datetime datetime now + datetime timedelta hours num else expire date datetime datetime now + datetime timedelta minutes num return expire date strftime '%a %d%b%Y%H %M...
def get_http_expiry _Expirestype _num if _Expirestype 'd' expire_date datetime datetime now + datetime timedelta days _num elif _Expirestype 'h' expire_date datetime datetime now + datetime timedelta hours _num else expire_date datetime datetime now + datetime timedelta minutes _num return expire_date strftime '%a %d%b...
51
python-test-6989
python
What does the code return ?
the future date
def get http expiry Expirestype num if Expirestype 'd' expire date datetime datetime now + datetime timedelta days num elif Expirestype 'h' expire date datetime datetime now + datetime timedelta hours num else expire date datetime datetime now + datetime timedelta minutes num return expire date strftime '%a %d%b%Y%H %M...
def get_http_expiry _Expirestype _num if _Expirestype 'd' expire_date datetime datetime now + datetime timedelta days _num elif _Expirestype 'h' expire_date datetime datetime now + datetime timedelta hours _num else expire_date datetime datetime now + datetime timedelta minutes _num return expire_date strftime '%a %d%b...
51
python-test-6990
python
How does the docs build ?
using sphinx in the buildenv virtualenv
def build pdf branch os chdir os path join gitdname 'statsmodels' 'docs' sphinx dir os path join virtual dir 'bin' retcode subprocess call '' join ['make' 'latexpdf' 'SPHINXBUILD ' + sphinx dir + '/sphinx-build' ] shell True if retcode 0 msg ' Couldnotbuildthepdfdocsforbranch%s' % branch raise Exception msg os chdir dn...
def build_pdf branch os chdir os path join gitdname 'statsmodels' 'docs' sphinx_dir os path join virtual_dir 'bin' retcode subprocess call '' join ['make' 'latexpdf' 'SPHINXBUILD ' + sphinx_dir + '/sphinx-build' ] shell True if retcode 0 msg 'Couldnotbuildthepdfdocsforbranch%s' % branch raise Exception msg os chdir dna...
51
python-test-6991
python
What is using in the buildenv virtualenv ?
sphinx
def build pdf branch os chdir os path join gitdname 'statsmodels' 'docs' sphinx dir os path join virtual dir 'bin' retcode subprocess call '' join ['make' 'latexpdf' 'SPHINXBUILD ' + sphinx dir + '/sphinx-build' ] shell True if retcode 0 msg ' Couldnotbuildthepdfdocsforbranch%s' % branch raise Exception msg os chdir dn...
def build_pdf branch os chdir os path join gitdname 'statsmodels' 'docs' sphinx_dir os path join virtual_dir 'bin' retcode subprocess call '' join ['make' 'latexpdf' 'SPHINXBUILD ' + sphinx_dir + '/sphinx-build' ] shell True if retcode 0 msg 'Couldnotbuildthepdfdocsforbranch%s' % branch raise Exception msg os chdir dna...
51
python-test-6992
python
Where do sphinx use ?
in the buildenv virtualenv
def build pdf branch os chdir os path join gitdname 'statsmodels' 'docs' sphinx dir os path join virtual dir 'bin' retcode subprocess call '' join ['make' 'latexpdf' 'SPHINXBUILD ' + sphinx dir + '/sphinx-build' ] shell True if retcode 0 msg ' Couldnotbuildthepdfdocsforbranch%s' % branch raise Exception msg os chdir dn...
def build_pdf branch os chdir os path join gitdname 'statsmodels' 'docs' sphinx_dir os path join virtual_dir 'bin' retcode subprocess call '' join ['make' 'latexpdf' 'SPHINXBUILD ' + sphinx_dir + '/sphinx-build' ] shell True if retcode 0 msg 'Couldnotbuildthepdfdocsforbranch%s' % branch raise Exception msg os chdir dna...
51
java-test-2
java
In which direction did that move to the tangent ?
from the current touch point
private float y ( Touch State s ) { final float curr To Tan = ( float ) Math . sqrt ( ( s . distance * s . distance ) - ( m Scaled Touch Slop * m Scaled Touch Slop ) ) ; return curr To Tan * ( m Scaled Touch Slop / s . distance ) ; }
private float y ( TouchState s ) { final float currToTan = ( float ) Math . sqrt ( ( s . distance * s . distance ) - ( mScaledTouchSlop * mScaledTouchSlop ) ) ; return currToTan * ( mScaledTouchSlop / s . distance ) ; }
62
java-test-7
java
Does the code create the rcs keystore ?
Yes
private static void create Key Store ( ) throws Key Store Exception , IO Exception { if ( s Key Store != null ) { return ; } try { s Key Store = Key Store . get Instance ( get Keystore Type ( ) ) ; synchronized ( Key Store Manager . class ) { s Key Store . load ( null , KEYSTORE PASSWORD . to Char Array ( ) ) ; } save ...
private static void createKeyStore ( ) throws KeyStoreException , IOException { if ( sKeyStore != null ) { return ; } try { sKeyStore = KeyStore . getInstance ( getKeystoreType ( ) ) ; synchronized ( KeyStoreManager . class ) { sKeyStore . load ( null , KEYSTORE_PASSWORD . toCharArray ( ) ) ; } saveKeyStoreToFile ( sKe...
128
java-test-8
java
What does the code create ?
the rcs keystore
private static void create Key Store ( ) throws Key Store Exception , IO Exception { if ( s Key Store != null ) { return ; } try { s Key Store = Key Store . get Instance ( get Keystore Type ( ) ) ; synchronized ( Key Store Manager . class ) { s Key Store . load ( null , KEYSTORE PASSWORD . to Char Array ( ) ) ; } save ...
private static void createKeyStore ( ) throws KeyStoreException , IOException { if ( sKeyStore != null ) { return ; } try { sKeyStore = KeyStore . getInstance ( getKeystoreType ( ) ) ; synchronized ( KeyStoreManager . class ) { sKeyStore . load ( null , KEYSTORE_PASSWORD . toCharArray ( ) ) ; } saveKeyStoreToFile ( sKe...
128
java-test-9
java
What does the code add ?
the given number of period units to this date
public Julian Date add ( int units , int amount ) { Julian Date date = null ; synchronized ( gc ) { gc . set Time ( get Java Date ( ) ) ; gc . add ( units , amount ) ; date = new Julian Date ( gc . get Time ( ) ) ; } return date ; }
public JulianDate add ( int units , int amount ) { JulianDate date = null ; synchronized ( gc ) { gc . setTime ( getJavaDate ( ) ) ; gc . add ( units , amount ) ; date = new JulianDate ( gc . getTime ( ) ) ; } return date ; }
63
java-test-10
java
Does the code add the given number of period units to this date ?
Yes
public Julian Date add ( int units , int amount ) { Julian Date date = null ; synchronized ( gc ) { gc . set Time ( get Java Date ( ) ) ; gc . add ( units , amount ) ; date = new Julian Date ( gc . get Time ( ) ) ; } return date ; }
public JulianDate add ( int units , int amount ) { JulianDate date = null ; synchronized ( gc ) { gc . setTime ( getJavaDate ( ) ) ; gc . add ( units , amount ) ; date = new JulianDate ( gc . getTime ( ) ) ; } return date ; }
63
java-test-24
java
How does the code update the documents with partial updates ?
with the given fields
public void updates ( String type , List < String > ids , Metacat Context metacat Context , Object Node node ) { if ( ids == null || ids . is Empty ( ) ) { return ; } try { RETRY ES PUBLISH . call ( null ) ; } catch ( Exception e ) { log . error ( String . format ( STRING , type , ids ) , e ) ; Counter Wrapper . increm...
public void updates ( String type , List < String > ids , MetacatContext metacatContext , ObjectNode node ) { if ( ids == null || ids . isEmpty ( ) ) { return ; } try { RETRY_ES_PUBLISH . call ( null ) ; } catch ( Exception e ) { log . error ( String . format ( STRING , type , ids ) , e ) ; CounterWrapper . incrementCo...
114
java-test-25
java
Does the code update the documents with partial updates with the given fields ?
Yes
public void updates ( String type , List < String > ids , Metacat Context metacat Context , Object Node node ) { if ( ids == null || ids . is Empty ( ) ) { return ; } try { RETRY ES PUBLISH . call ( null ) ; } catch ( Exception e ) { log . error ( String . format ( STRING , type , ids ) , e ) ; Counter Wrapper . increm...
public void updates ( String type , List < String > ids , MetacatContext metacatContext , ObjectNode node ) { if ( ids == null || ids . isEmpty ( ) ) { return ; } try { RETRY_ES_PUBLISH . call ( null ) ; } catch ( Exception e ) { log . error ( String . format ( STRING , type , ids ) , e ) ; CounterWrapper . incrementCo...
114
java-test-26
java
What does the code update with the given fields ?
the documents with partial updates
public void updates ( String type , List < String > ids , Metacat Context metacat Context , Object Node node ) { if ( ids == null || ids . is Empty ( ) ) { return ; } try { RETRY ES PUBLISH . call ( null ) ; } catch ( Exception e ) { log . error ( String . format ( STRING , type , ids ) , e ) ; Counter Wrapper . increm...
public void updates ( String type , List < String > ids , MetacatContext metacatContext , ObjectNode node ) { if ( ids == null || ids . isEmpty ( ) ) { return ; } try { RETRY_ES_PUBLISH . call ( null ) ; } catch ( Exception e ) { log . error ( String . format ( STRING , type , ids ) , e ) ; CounterWrapper . incrementCo...
114
java-test-27
java
How should a source directory name be skipped ?
based on the avoid and limit list
protected boolean check To Skip Directory ( String name ) { if ( dir Suffix Avoids != null ) { for ( int i = NUM ; i < dir Suffix Avoids . length ; i ++ ) { if ( name . ends With ( dir Suffix Avoids [ i ] ) ) { return BOOL ; } } } if ( dir Suffix Limits != null ) { for ( int i = NUM ; i < dir Suffix Limits . length ; i...
protected boolean checkToSkipDirectory ( String name ) { if ( dirSuffixAvoids != null ) { for ( int i = _NUM ; i < dirSuffixAvoids . length ; i ++ ) { if ( name . endsWith ( dirSuffixAvoids [ i ] ) ) { return _BOOL ; } } } if ( dirSuffixLimits != null ) { for ( int i = _NUM ; i < dirSuffixLimits . length ; i ++ ) { if ...
118
java-test-28
java
Does the code add " val " months to the month object that contains " time " and ?
Yes
@ Override public Enter From Date To To Date Activity . Time Object add ( long time , int val ) { Calendar c = Calendar . get Instance ( ) ; c . set Time In Millis ( time ) ; c . add ( Calendar . MONTH , val ) ; return time Object From Calendar ( c ) ; }
@ Override public EnterFromDateToToDateActivity . TimeObject add ( long time , int val ) { Calendar c = Calendar . getInstance ( ) ; c . setTimeInMillis ( time ) ; c . add ( Calendar . MONTH , val ) ; return timeObjectFromCalendar ( c ) ; }
63
java-test-29
java
What does the code add to the month object that contains " time " and ?
" val " months
@ Override public Enter From Date To To Date Activity . Time Object add ( long time , int val ) { Calendar c = Calendar . get Instance ( ) ; c . set Time In Millis ( time ) ; c . add ( Calendar . MONTH , val ) ; return time Object From Calendar ( c ) ; }
@ Override public EnterFromDateToToDateActivity . TimeObject add ( long time , int val ) { Calendar c = Calendar . getInstance ( ) ; c . setTimeInMillis ( time ) ; c . add ( Calendar . MONTH , val ) ; return timeObjectFromCalendar ( c ) ; }
63
java-test-39
java
In which direction do string data read ?
from a inputstream
public static String to String ( final Input Stream is ) throws IO Exception { final Buffered Reader br = new Buffered Reader ( new Input Stream Reader ( is ) ) ; final String Buffer content = new String Buffer ( ) ; String line = br . read Line ( ) ; if ( line != null ) { content . append ( line ) ; while ( ( line = b...
public static String toString ( final InputStream is ) throws IOException { final BufferedReader br = new BufferedReader ( new InputStreamReader ( is ) ) ; final StringBuffer content = new StringBuffer ( ) ; String line = br . readLine ( ) ; if ( line != null ) { content . append ( line ) ; while ( ( line = br . readLi...
108
java-test-44
java
Does the code tell ?
Yes
private boolean is Number ( String string ) { String s = string . trim ( ) ; if ( s . length ( ) < NUM ) return BOOL ; double value = NUM ; try { value = Double . parse Double ( s ) ; } catch ( Number Format Exception e ) { return BOOL ; } return BOOL ; }
private boolean isNumber ( String string ) { String s = string . trim ( ) ; if ( s . length ( ) < _NUM ) return _BOOL ; double value = _NUM ; try { value = Double . parseDouble ( s ) ; } catch ( NumberFormatException e ) { return _BOOL ; } return _BOOL ; }
65
java-test-45
java
What does the code tell ?
whether the string contains a number
private boolean is Number ( String string ) { String s = string . trim ( ) ; if ( s . length ( ) < NUM ) return BOOL ; double value = NUM ; try { value = Double . parse Double ( s ) ; } catch ( Number Format Exception e ) { return BOOL ; } return BOOL ; }
private boolean isNumber ( String string ) { String s = string . trim ( ) ; if ( s . length ( ) < _NUM ) return _BOOL ; double value = _NUM ; try { value = Double . parseDouble ( s ) ; } catch ( NumberFormatException e ) { return _BOOL ; } return _BOOL ; }
65
java-test-46
java
Do the string contain a number ?
No
private boolean is Number ( String string ) { String s = string . trim ( ) ; if ( s . length ( ) < NUM ) return BOOL ; double value = NUM ; try { value = Double . parse Double ( s ) ; } catch ( Number Format Exception e ) { return BOOL ; } return BOOL ; }
private boolean isNumber ( String string ) { String s = string . trim ( ) ; if ( s . length ( ) < _NUM ) return _BOOL ; double value = _NUM ; try { value = Double . parseDouble ( s ) ; } catch ( NumberFormatException e ) { return _BOOL ; } return _BOOL ; }
65
java-test-47
java
Does the code initialize the calculated values ?
Yes
private void initialize Values ( ) { mn Size = Math . min ( get Measured Height ( ) , get Measured Width ( ) ) ; mn Ring Radius = ( int ) ( mn Size - mn Ring Width ) / NUM ; mn Inner Circle Radius = ( int ) ( mn Size - ( mn Ring Width * NUM ) ) / NUM ; mn View Center = mn Size / NUM ; mn Line Width = STATUS SYMBOL WIDT...
private void initializeValues ( ) { mnSize = Math . min ( getMeasuredHeight ( ) , getMeasuredWidth ( ) ) ; mnRingRadius = ( int ) ( mnSize - mnRingWidth ) / _NUM ; mnInnerCircleRadius = ( int ) ( mnSize - ( mnRingWidth * _NUM ) ) / _NUM ; mnViewCenter = mnSize / _NUM ; mnLineWidth = STATUS_SYMBOL_WIDTH_PERCENT * mnSize...
90
java-test-48
java
What does the code initialize ?
the calculated values
private void initialize Values ( ) { mn Size = Math . min ( get Measured Height ( ) , get Measured Width ( ) ) ; mn Ring Radius = ( int ) ( mn Size - mn Ring Width ) / NUM ; mn Inner Circle Radius = ( int ) ( mn Size - ( mn Ring Width * NUM ) ) / NUM ; mn View Center = mn Size / NUM ; mn Line Width = STATUS SYMBOL WIDT...
private void initializeValues ( ) { mnSize = Math . min ( getMeasuredHeight ( ) , getMeasuredWidth ( ) ) ; mnRingRadius = ( int ) ( mnSize - mnRingWidth ) / _NUM ; mnInnerCircleRadius = ( int ) ( mnSize - ( mnRingWidth * _NUM ) ) / _NUM ; mnViewCenter = mnSize / _NUM ; mnLineWidth = STATUS_SYMBOL_WIDTH_PERCENT * mnSize...
90
java-test-49
java
Where does the code create the gradle wrapper ?
in the project
@ Visible For Testing public static boolean create Gradle Wrapper ( @ Not Null File project Dir Path , @ Not Null String gradle Version ) throws IO Exception { File project Wrapper Dir Path = new File ( project Dir Path , FD GRADLE WRAPPER ) ; if ( ! project Wrapper Dir Path . is Directory ( ) ) { File wrapper Src Dir ...
@ VisibleForTesting public static boolean createGradleWrapper ( @ NotNull File projectDirPath , @ NotNull String gradleVersion ) throws IOException { File projectWrapperDirPath = new File ( projectDirPath , FD_GRADLE_WRAPPER ) ; if ( ! projectWrapperDirPath . isDirectory ( ) ) { File wrapperSrcDirPath = new File ( Temp...
221