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-223 | python | Does the code find the value of maximum single - commodity flow ? | Yes | def maximum flow value G s t capacity 'capacity' flow func None **kwargs if flow func is None if kwargs raise nx Network X Error ' Youhavetoexplicitlysetaflow funcifyouneedtopassparametersviakwargs ' flow func default flow funcif not callable flow func raise nx Network X Error 'flow funchastobecallable ' R flow func G ... | def maximum_flow_value G s t capacity 'capacity' flow_func None **kwargs if flow_func is None if kwargs raise nx NetworkXError 'Youhavetoexplicitlysetaflow_funcifyouneedtopassparametersviakwargs ' flow_func default_flow_funcif not callable flow_func raise nx NetworkXError 'flow_funchastobecallable ' R flow_func G s t c... | 62 |
python-test-224 | python | What does the code find ? | the value of maximum single - commodity flow | def maximum flow value G s t capacity 'capacity' flow func None **kwargs if flow func is None if kwargs raise nx Network X Error ' Youhavetoexplicitlysetaflow funcifyouneedtopassparametersviakwargs ' flow func default flow funcif not callable flow func raise nx Network X Error 'flow funchastobecallable ' R flow func G ... | def maximum_flow_value G s t capacity 'capacity' flow_func None **kwargs if flow_func is None if kwargs raise nx NetworkXError 'Youhavetoexplicitlysetaflow_funcifyouneedtopassparametersviakwargs ' flow_func default_flow_funcif not callable flow_func raise nx NetworkXError 'flow_funchastobecallable ' R flow_func G s t c... | 62 |
python-test-225 | python | Do targets have the prune_self_dependency variable set ? | Yes | def Remove Self Dependencies targets for target name target dict in targets iteritems for dependency key in dependency sections dependencies target dict get dependency key [] if dependencies for t in dependencies if t target name if targets[t] get 'variables' {} get 'prune self dependency' 0 target dict[dependency key]... | def RemoveSelfDependencies targets for target_name target_dict in targets iteritems for dependency_key in dependency_sections dependencies target_dict get dependency_key [] if dependencies for t in dependencies if t target_name if targets[t] get 'variables' {} get 'prune_self_dependency' 0 target_dict[dependency_key] F... | 53 |
python-test-226 | python | Does the code remove self dependencies from targets that have the prune_self_dependency variable set ? | Yes | def Remove Self Dependencies targets for target name target dict in targets iteritems for dependency key in dependency sections dependencies target dict get dependency key [] if dependencies for t in dependencies if t target name if targets[t] get 'variables' {} get 'prune self dependency' 0 target dict[dependency key]... | def RemoveSelfDependencies targets for target_name target_dict in targets iteritems for dependency_key in dependency_sections dependencies target_dict get dependency_key [] if dependencies for t in dependencies if t target_name if targets[t] get 'variables' {} get 'prune_self_dependency' 0 target_dict[dependency_key] F... | 53 |
python-test-227 | python | What does the code remove from targets that have the prune_self_dependency variable set ? | self dependencies | def Remove Self Dependencies targets for target name target dict in targets iteritems for dependency key in dependency sections dependencies target dict get dependency key [] if dependencies for t in dependencies if t target name if targets[t] get 'variables' {} get 'prune self dependency' 0 target dict[dependency key]... | def RemoveSelfDependencies targets for target_name target_dict in targets iteritems for dependency_key in dependency_sections dependencies target_dict get dependency_key [] if dependencies for t in dependencies if t target_name if targets[t] get 'variables' {} get 'prune_self_dependency' 0 target_dict[dependency_key] F... | 53 |
python-test-228 | python | What do targets have ? | the prune_self_dependency variable set | def Remove Self Dependencies targets for target name target dict in targets iteritems for dependency key in dependency sections dependencies target dict get dependency key [] if dependencies for t in dependencies if t target name if targets[t] get 'variables' {} get 'prune self dependency' 0 target dict[dependency key]... | def RemoveSelfDependencies targets for target_name target_dict in targets iteritems for dependency_key in dependency_sections dependencies target_dict get dependency_key [] if dependencies for t in dependencies if t target_name if targets[t] get 'variables' {} get 'prune_self_dependency' 0 target_dict[dependency_key] F... | 53 |
python-test-231 | python | Does the code get operating system type / distribution and major version using python platform module ? | Yes | def get python os info info platform system alias platform system platform release platform version os type os ver infoos type os type lower if os type startswith 'linux' info platform linux distribution if info[ 0 ] os type info[ 0 ]if info[ 1 ] os ver info[ 1 ]elif os type startswith 'darwin' os ver subprocess Popen ... | def get_python_os_info info platform system_alias platform system platform release platform version os_type os_ver _ infoos_type os_type lower if os_type startswith 'linux' info platform linux_distribution if info[0] os_type info[0]if info[1] os_ver info[1]elif os_type startswith 'darwin' os_ver subprocess Popen ['sw_v... | 112 |
python-test-232 | python | What does the code get ? | operating system type / distribution and major version using python platform module | def get python os info info platform system alias platform system platform release platform version os type os ver infoos type os type lower if os type startswith 'linux' info platform linux distribution if info[ 0 ] os type info[ 0 ]if info[ 1 ] os ver info[ 1 ]elif os type startswith 'darwin' os ver subprocess Popen ... | def get_python_os_info info platform system_alias platform system platform release platform version os_type os_ver _ infoos_type os_type lower if os_type startswith 'linux' info platform linux_distribution if info[0] os_type info[0]if info[1] os_ver info[1]elif os_type startswith 'darwin' os_ver subprocess Popen ['sw_v... | 112 |
python-test-234 | python | What does the code compute ? | the result of a broadcast expression | @dispatch Broadcast Mongo Query def post compute e q scope None columns dict col 1 for qry in q query for col in qry get '$project' [] scope {'$project' toolz merge {' id' 0} dict col 1 for col in columns }q q append scope dicts get result q coll aggregate list q query assert len columns 1 return list pluck first colum... | @dispatch Broadcast MongoQuery def post_compute e q scope None columns dict col 1 for qry in q query for col in qry get '$project' [] scope {'$project' toolz merge {'_id' 0} dict col 1 for col in columns }q q append scope dicts get_result q coll aggregate list q query assert len columns 1 return list pluck first column... | 65 |
python-test-235 | python | What did directory return ? | a list of all available python modules in the package and its subpackages : type package : str | def get modules package src directory blacklist STD BLACKLIST modules []for directory dirnames filenames in os walk src directory handle blacklist blacklist dirnames filenames if not ' init py' in filenames dirnames[ ] continueif directory src directory dir package directory[len src directory ] replace os sep ' ' modul... | def get_modules package src_directory blacklist STD_BLACKLIST modules []for directory dirnames filenames in os walk src_directory _handle_blacklist blacklist dirnames filenames if not '__init__ py' in filenames dirnames[ ] continueif directory src_directory dir_package directory[len src_directory ] replace os sep ' ' m... | 90 |
python-test-238 | python | For what purpose does the code generate the xml string ? | to define a libvirt storage volume | def gen vol xml vmname diskname size hypervisor **kwargs size int size * 1024 disk info get image info hypervisor vmname **kwargs context {'name' vmname 'filename' '{ 0 } {1 }' format diskname disk info['disktype'] 'volname' diskname 'disktype' disk info['disktype'] 'size' str size 'pool' disk info['pool']}fn 'libvirt ... | def _gen_vol_xml vmname diskname size hypervisor **kwargs size int size * 1024 disk_info _get_image_info hypervisor vmname **kwargs context {'name' vmname 'filename' '{0} {1}' format diskname disk_info['disktype'] 'volname' diskname 'disktype' disk_info['disktype'] 'size' str size 'pool' disk_info['pool']}fn_ 'libvirt_... | 74 |
python-test-240 | python | What does the code calculate ? | a covariance matrix shrunk on the diagonal | def shrunk covariance emp cov shrinkage 0 1 emp cov check array emp cov n features emp cov shape[ 0 ]mu np trace emp cov / n features shrunk cov 1 0 - shrinkage * emp cov shrunk cov flat[ n features + 1 ] + shrinkage * mu return shrunk cov | def shrunk_covariance emp_cov shrinkage 0 1 emp_cov check_array emp_cov n_features emp_cov shape[0]mu np trace emp_cov / n_features shrunk_cov 1 0 - shrinkage * emp_cov shrunk_cov flat[ n_features + 1 ] + shrinkage * mu return shrunk_cov | 52 |
python-test-243 | python | How does the code memoize the stacks ? | using intrinsic_key_maps | def memoize stacks func cache {}@wraps func def memoizer be optree optree key tensor index map index tensor map optree intrinsic key maps optree key optree key id be if optree key in cache stacks cached tensor index map cache[optree key]for stack in stacks for i in range len stack if isinstance stack[i] Tensor if stack... | def memoize_stacks func cache {}@wraps func def memoizer be optree optree_key tensor_index_map index_tensor_map optree intrinsic_key_maps optree_key optree_key id be if optree_key in cache stacks cached_tensor_index_map cache[optree_key]for stack in stacks for i in range len stack if isinstance stack[i] Tensor if stack... | 87 |
python-test-244 | python | What does the code use ? | intrinsic_key_maps | def memoize stacks func cache {}@wraps func def memoizer be optree optree key tensor index map index tensor map optree intrinsic key maps optree key optree key id be if optree key in cache stacks cached tensor index map cache[optree key]for stack in stacks for i in range len stack if isinstance stack[i] Tensor if stack... | def memoize_stacks func cache {}@wraps func def memoizer be optree optree_key tensor_index_map index_tensor_map optree intrinsic_key_maps optree_key optree_key id be if optree_key in cache stacks cached_tensor_index_map cache[optree_key]for stack in stacks for i in range len stack if isinstance stack[i] Tensor if stack... | 87 |
python-test-245 | python | What does the code memoize using intrinsic_key_maps ? | the stacks | def memoize stacks func cache {}@wraps func def memoizer be optree optree key tensor index map index tensor map optree intrinsic key maps optree key optree key id be if optree key in cache stacks cached tensor index map cache[optree key]for stack in stacks for i in range len stack if isinstance stack[i] Tensor if stack... | def memoize_stacks func cache {}@wraps func def memoizer be optree optree_key tensor_index_map index_tensor_map optree intrinsic_key_maps optree_key optree_key id be if optree_key in cache stacks cached_tensor_index_map cache[optree_key]for stack in stacks for i in range len stack if isinstance stack[i] Tensor if stack... | 87 |
python-test-246 | python | What does the code update ? | the simple jndi binding in the running jboss instance jboss_config configuration dictionary with properties specified above | def update simple binding jboss config binding name value profile None log debug ' MODULEFUNCTION jboss 7 update simple binding binding name %s value %s profile %s' binding name value profile operation '/subsystem naming/binding "{binding name}" write-attribute name value value "{value}" ' format binding name binding n... | def update_simple_binding jboss_config binding_name value profile None log debug ' MODULEFUNCTION jboss7 update_simple_binding binding_name %s value %s profile %s' binding_name value profile operation '/subsystem naming/binding "{binding_name}" write-attribute name value value "{value}" ' format binding_name binding_na... | 75 |
python-test-247 | python | What does the class of the action manager return ? | to use from actstream_settings[manager ] | def get action manager mod SETTINGS get 'MANAGER' 'actstream managers Action Manager' mod path mod split ' ' try return getattr import ' ' join mod path[ -1 ] {} {} [mod path[ -1 ]] mod path[ -1 ] except Import Error raise Import Error ' Cannotimport%stryfixing ACTSTREAM SETTINGS[MANAGER]setting ' % mod | def get_action_manager mod SETTINGS get 'MANAGER' 'actstream managers ActionManager' mod_path mod split ' ' try return getattr __import__ ' ' join mod_path[ -1 ] {} {} [mod_path[ -1 ]] mod_path[ -1 ] except ImportError raise ImportError 'Cannotimport%stryfixingACTSTREAM_SETTINGS[MANAGER]setting ' % mod | 52 |
python-test-248 | python | What returns to use from actstream_settings[manager ] ? | the class of the action manager | def get action manager mod SETTINGS get 'MANAGER' 'actstream managers Action Manager' mod path mod split ' ' try return getattr import ' ' join mod path[ -1 ] {} {} [mod path[ -1 ]] mod path[ -1 ] except Import Error raise Import Error ' Cannotimport%stryfixing ACTSTREAM SETTINGS[MANAGER]setting ' % mod | def get_action_manager mod SETTINGS get 'MANAGER' 'actstream managers ActionManager' mod_path mod split ' ' try return getattr __import__ ' ' join mod_path[ -1 ] {} {} [mod_path[ -1 ]] mod_path[ -1 ] except ImportError raise ImportError 'Cannotimport%stryfixingACTSTREAM_SETTINGS[MANAGER]setting ' % mod | 52 |
python-test-249 | python | What does the code train ? | an mlp which discards one input with a compositelayer | def test input discard mlp MLP layers [ Flattener Layer Composite Layer 'composite' [ Linear 10 'h 0 ' 0 1 ] {0 [0 ] 1 []} Softmax 5 'softmax' 0 1 ] input space Composite Space [ Vector Space 15 Vector Space 20 ] input source 'features 0 ' 'features 1 ' dataset Vector Spaces Dataset np random rand 20 20 astype theano c... | def test_input_discard mlp MLP layers [FlattenerLayer CompositeLayer 'composite' [Linear 10 'h0' 0 1 ] {0 [0] 1 []} Softmax 5 'softmax' 0 1 ] input_space CompositeSpace [VectorSpace 15 VectorSpace 20 ] input_source 'features0' 'features1' dataset VectorSpacesDataset np random rand 20 20 astype theano config floatX np r... | 127 |
python-test-250 | python | How does an mlp discard one input ? | with a compositelayer | def test input discard mlp MLP layers [ Flattener Layer Composite Layer 'composite' [ Linear 10 'h 0 ' 0 1 ] {0 [0 ] 1 []} Softmax 5 'softmax' 0 1 ] input space Composite Space [ Vector Space 15 Vector Space 20 ] input source 'features 0 ' 'features 1 ' dataset Vector Spaces Dataset np random rand 20 20 astype theano c... | def test_input_discard mlp MLP layers [FlattenerLayer CompositeLayer 'composite' [Linear 10 'h0' 0 1 ] {0 [0] 1 []} Softmax 5 'softmax' 0 1 ] input_space CompositeSpace [VectorSpace 15 VectorSpace 20 ] input_source 'features0' 'features1' dataset VectorSpacesDataset np random rand 20 20 astype theano config floatX np r... | 127 |
python-test-251 | python | What does the code perform ? | a one - time generation of a hash | def get or set hash name length 8 chars 'abcdefghijklmnopqrstuvwxyz 0123456789 @#$%^&* - + ' ret get name None if ret is None val '' join [random System Random choice chars for in range length ] if DEFAULT TARGET DELIM in name root rest name split DEFAULT TARGET DELIM 1 curr get root infinitedict val dict from path res... | def get_or_set_hash name length 8 chars 'abcdefghijklmnopqrstuvwxyz0123456789 @#$%^&* -_ + ' ret get name None if ret is None val '' join [random SystemRandom choice chars for _ in range length ] if DEFAULT_TARGET_DELIM in name root rest name split DEFAULT_TARGET_DELIM 1 curr get root _infinitedict val _dict_from_path ... | 73 |
python-test-262 | python | What does the code transform into a dictionary ? | a platerecord object | def to OPM plate d dict plate qualifiers items d[ csv Data] {}d[ csv Data][ plate] plate idd[ measurements] {}d[ measurements][ hour] []times set for wid w in plate wells items d[ measurements][wid] []for hour in w signals times add hour for hour in sorted times d[ measurements][ hour] append hour for wid w in plate we... | def _toOPM plate d dict plate qualifiers items d[_csvData] {}d[_csvData][_plate] plate idd[_measurements] {}d[_measurements][_hour] []times set for wid w in plate _wells items d[_measurements][wid] []for hour in w _signals times add hour for hour in sorted times d[_measurements][_hour] append hour for wid w in plate _w... | 75 |
python-test-264 | python | How does the code generate a random string ? | using the given sequence pool | def generate random string length None entropy None pool ALPHANUMERIC pool list set pool if length and entropy raise Value Error ' Uselengthorentropy notboth ' if length < 0 and entropy < 0 raise Value Error ' Lengthorentropymustbegreaterthan 0 ' if entropy log of 2 0 6931471805599453 length long math ceil log of 2 / m... | def generate_random_string length None entropy None pool ALPHANUMERIC pool list set pool if length and entropy raise ValueError 'Uselengthorentropy notboth ' if length < 0 and entropy < 0 raise ValueError 'Lengthorentropymustbegreaterthan0 ' if entropy log_of_2 0 6931471805599453length long math ceil log_of_2 / math lo... | 71 |
python-test-265 | python | Where does an index on specified columns create ? | in table_name | def create index table name session *column names index name u' ' join [u'ix' table name] + list column names table table schema table name session columns [getattr table c column for column in column names]try Index index name *columns create bind session bind except Operational Error log debug u' Errorcreatingindex '... | def create_index table_name session *column_names index_name u'_' join [u'ix' table_name] + list column_names table table_schema table_name session columns [getattr table c column for column in column_names]try Index index_name *columns create bind session bind except OperationalError log debug u'Errorcreatingindex ' e... | 55 |
python-test-266 | python | What creates in table_name ? | an index on specified columns | def create index table name session *column names index name u' ' join [u'ix' table name] + list column names table table schema table name session columns [getattr table c column for column in column names]try Index index name *columns create bind session bind except Operational Error log debug u' Errorcreatingindex '... | def create_index table_name session *column_names index_name u'_' join [u'ix' table_name] + list column_names table table_schema table_name session columns [getattr table c column for column in column_names]try Index index_name *columns create bind session bind except OperationalError log debug u'Errorcreatingindex ' e... | 55 |
python-test-267 | python | What do a string represent ? | a base and a policy | def split policy string policy string if '-' in policy string base policy index policy string rsplit '-' 1 else base policy index policy string None policy POLICIES get by index policy index if get policy string base policy policy string raise Policy Error ' Unknownpolicy' index policy index return base policy | def split_policy_string policy_string if '-' in policy_string base policy_index policy_string rsplit '-' 1 else base policy_index policy_string None policy POLICIES get_by_index policy_index if get_policy_string base policy policy_string raise PolicyError 'Unknownpolicy' index policy_index return base policy | 52 |
python-test-268 | python | What do inputs convert ? | to float arrays | def convert input x y z None n models 1 model set axis 0 x np asarray x dtype np float y np asarray y dtype np float if z is not None z np asarray z dtype np float if n models > 1 if z is None if y shape[model set axis] n models raise Value Error u' Numberofdatasets yarrayisexpectedtoequalthenumberofparametersets ' y n... | def _convert_input x y z None n_models 1 model_set_axis 0 x np asarray x dtype np float y np asarray y dtype np float if z is not None z np asarray z dtype np float if n_models > 1 if z is None if y shape[model_set_axis] n_models raise ValueError u'Numberofdatasets yarrayisexpectedtoequalthenumberofparametersets ' y np... | 116 |
python-test-269 | python | What does the code generate ? | a gaussian random partition graph | def gaussian random partition graph n s v p in p out directed False seed None if s > n raise nx Network X Error 'smustbe< n' assigned 0sizes []while True size int random normalvariate s float s / v + 0 5 if size < 1 continueif assigned + size > n sizes append n - assigned breakassigned + sizesizes append size return ra... | def gaussian_random_partition_graph n s v p_in p_out directed False seed None if s > n raise nx NetworkXError 'smustbe< n' assigned 0sizes []while True size int random normalvariate s float s / v + 0 5 if size < 1 continueif assigned + size > n sizes append n - assigned breakassigned + sizesizes append size return rand... | 74 |
python-test-272 | python | What does the code turn into a single multipleseqalignment object ? | an alignment file | def read handle format seq count None alphabet None iterator parse handle format seq count alphabet try first next iterator except Stop Iteration first Noneif first is None raise Value Error ' Norecordsfoundinhandle' try second next iterator except Stop Iteration second Noneif second is not None raise Value Error ' Mor... | def read handle format seq_count None alphabet None iterator parse handle format seq_count alphabet try first next iterator except StopIteration first Noneif first is None raise ValueError 'Norecordsfoundinhandle' try second next iterator except StopIteration second Noneif second is not None raise ValueError 'Morethano... | 61 |
python-test-273 | python | For what purpose does the code change the local state ? | to match the given desired state | def change node state deployer desired configuration state persister In Memory State Persister def converge d deployer discover state Deployment State nodes { Node State hostname deployer hostname uuid deployer node uuid applications [] manifestations {} paths {} devices {} } persistent state state persister get state ... | def change_node_state deployer desired_configuration state_persister InMemoryStatePersister def converge d deployer discover_state DeploymentState nodes {NodeState hostname deployer hostname uuid deployer node_uuid applications [] manifestations {} paths {} devices {} } persistent_state state_persister get_state def go... | 119 |
python-test-276 | python | What does it remove from the input ? | all html tags | def break long words value max word length 8 tagless django utils html strip tags value re capitalized word re compile ' [A-Z][a-z][a-z]+ ' re UNICODE words re capitalized word split tagless re too many letters in a row re compile ' [\\w]{%d} [ \\ ^/] ' % max word length re UNICODE broken words []for word in words if w... | def break_long_words value max_word_length 8 tagless django utils html strip_tags value re_capitalized_word re compile ' [A-Z][a-z][a-z]+ ' re UNICODE words re_capitalized_word split tagless re_too_many_letters_in_a_row re compile ' [\\w]{%d} [ \\_^/] ' % max_word_length re UNICODE broken_words []for word in words if w... | 88 |
python-test-277 | python | What does this filter do ? | two things | def break long words value max word length 8 tagless django utils html strip tags value re capitalized word re compile ' [A-Z][a-z][a-z]+ ' re UNICODE words re capitalized word split tagless re too many letters in a row re compile ' [\\w]{%d} [ \\ ^/] ' % max word length re UNICODE broken words []for word in words if w... | def break_long_words value max_word_length 8 tagless django utils html strip_tags value re_capitalized_word re compile ' [A-Z][a-z][a-z]+ ' re UNICODE words re_capitalized_word split tagless re_too_many_letters_in_a_row re compile ' [\\w]{%d} [ \\_^/] ' % max_word_length re UNICODE broken_words []for word in words if w... | 88 |
python-test-279 | python | What does the code start ? | a superset worker for async sql query execution | @manager commanddef worker print u' Starting SQL Celeryworker ' if config get u'CELERY CONFIG' print u' Celerybrokerurl ' print config get u'CELERY CONFIG' BROKER URL application celery current app get current object c worker celery worker worker app application options {u'broker' config get u'CELERY CONFIG' BROKER URL... | @manager commanddef worker print u'StartingSQLCeleryworker ' if config get u'CELERY_CONFIG' print u'Celerybrokerurl ' print config get u'CELERY_CONFIG' BROKER_URL application celery current_app _get_current_object c_worker celery_worker worker app application options {u'broker' config get u'CELERY_CONFIG' BROKER_URL u'... | 54 |
python-test-281 | python | What does the code find ? | all steps in data from a stim channel | def find stim steps raw pad start None pad stop None merge 0 stim channel None stim channel get stim channel stim channel raw info picks pick channels raw info['ch names'] include stim channel if len picks 0 raise Value Error ' Nostimchannelfoundtoextracteventtriggers ' data raw[picks ]if np any data < 0 warn ' Trigger... | def find_stim_steps raw pad_start None pad_stop None merge 0 stim_channel None stim_channel _get_stim_channel stim_channel raw info picks pick_channels raw info['ch_names'] include stim_channel if len picks 0 raise ValueError 'Nostimchannelfoundtoextracteventtriggers ' data _ raw[picks ]if np any data < 0 warn 'Trigger... | 84 |
python-test-283 | python | What do tests hit ? | known bugs | def skip because *args **kwargs def decorator f @functools wraps f def wrapper self *func args **func kwargs skip Falseif 'condition' in kwargs if kwargs['condition'] is True skip Trueelse skip Trueif 'bug' in kwargs and skip is True if not kwargs['bug'] isdigit raise Value Error 'bugmustbeavalidbugnumber' msg ' Skippe... | def skip_because *args **kwargs def decorator f @functools wraps f def wrapper self *func_args **func_kwargs skip Falseif 'condition' in kwargs if kwargs['condition'] is True skip Trueelse skip Trueif 'bug' in kwargs and skip is True if not kwargs['bug'] isdigit raise ValueError 'bugmustbeavalidbugnumber' msg 'Skippedu... | 71 |
python-test-284 | python | What do a decorator skip ? | tests hitting known bugs | def skip because *args **kwargs def decorator f @functools wraps f def wrapper self *func args **func kwargs skip Falseif 'condition' in kwargs if kwargs['condition'] is True skip Trueelse skip Trueif 'bug' in kwargs and skip is True if not kwargs['bug'] isdigit raise Value Error 'bugmustbeavalidbugnumber' msg ' Skippe... | def skip_because *args **kwargs def decorator f @functools wraps f def wrapper self *func_args **func_kwargs skip Falseif 'condition' in kwargs if kwargs['condition'] is True skip Trueelse skip Trueif 'bug' in kwargs and skip is True if not kwargs['bug'] isdigit raise ValueError 'bugmustbeavalidbugnumber' msg 'Skippedu... | 71 |
python-test-285 | python | What does the code create ? | all tuples of the links for the hosts | def print all links res rules r []for host in res host name apply rules host rules print '%s esxhostname %s' % host name host name print '%s isesxhost 1' % host name for vm in res[host] vm name apply rules vm rules print '%s vmname %s' % vm name vm name print '%s isesxvm 1' % vm name print '%s esxhost %s' % vm name hos... | def print_all_links res rules r []for host in res host_name _apply_rules host rules print '%s esxhostname %s' % host_name host_name print '%s isesxhost 1' % host_name for vm in res[host] vm_name _apply_rules vm rules print '%s vmname %s' % vm_name vm_name print '%s isesxvm 1' % vm_name print '%s esxhost %s' % vm_name h... | 70 |
python-test-289 | python | How do a donut pie chart test ? | with multiserie | def test multiseries donut chart Pie inner radius 0 3 pretty print True chart title ' Browserusagebyversionin February 2012 in% 'chart add 'IE' [5 7 10 2 2 6 1] chart add ' Firefox' [0 6 16 8 7 4 2 2 1 2 1 1 1 1 4 3 1] chart add ' Chrome' [0 3 0 9 17 1 15 3 0 6 0 5 1 6] chart add ' Safari' [4 4 0 1] chart add ' Opera' ... | def test_multiseries_donut chart Pie inner_radius 0 3 pretty_print True chart title 'BrowserusagebyversioninFebruary2012 in% 'chart add 'IE' [5 7 10 2 2 6 1] chart add 'Firefox' [0 6 16 8 7 4 2 2 1 2 1 1 1 1 4 3 1] chart add 'Chrome' [0 3 0 9 17 1 15 3 0 6 0 5 1 6] chart add 'Safari' [4 4 0 1] chart add 'Opera' [0 1 1 ... | 92 |
python-test-290 | python | What does the code setup ? | the lg webos tv platform | def setup platform hass config add devices discovery info None if discovery info is not None host urlparse discovery info[ 1 ] hostnameelse host config get CONF HOST if host is None LOGGER error ' No T Vfoundinconfigurationfileorwithdiscovery' return Falseif host in CONFIGURING returnmac config get CONF MAC name config... | def setup_platform hass config add_devices discovery_info None if discovery_info is not None host urlparse discovery_info[1] hostnameelse host config get CONF_HOST if host is None _LOGGER error 'NoTVfoundinconfigurationfileorwithdiscovery' return Falseif host in _CONFIGURING returnmac config get CONF_MAC name config ge... | 67 |
python-test-292 | python | What does the code create ? | a node of type node_type | def add node workflow name node type parents attrs {} Node Class NODE TYPES[node type]node Node Class workflow workflow node type node type name name for attr in attrs setattr node attr attrs[attr] node save if parents for parent in parents name 'ok'if parent node type 'start' or parent node type 'join' name 'to'elif p... | def add_node workflow name node_type parents attrs {} NodeClass NODE_TYPES[node_type]node NodeClass workflow workflow node_type node_type name name for attr in attrs setattr node attr attrs[attr] node save if parents for parent in parents name 'ok'if parent node_type 'start' or parent node_type 'join' name 'to'elif par... | 104 |
python-test-293 | python | What does the code associate ? | the listed parents | def add node workflow name node type parents attrs {} Node Class NODE TYPES[node type]node Node Class workflow workflow node type node type name name for attr in attrs setattr node attr attrs[attr] node save if parents for parent in parents name 'ok'if parent node type 'start' or parent node type 'join' name 'to'elif p... | def add_node workflow name node_type parents attrs {} NodeClass NODE_TYPES[node_type]node NodeClass workflow workflow node_type node_type name name for attr in attrs setattr node attr attrs[attr] node save if parents for parent in parents name 'ok'if parent node_type 'start' or parent node_type 'join' name 'to'elif par... | 104 |
python-test-294 | python | What does the code notify ? | a list_user_unsubscribed event | def notify list user unsubscribed e target e['target']if target['screen name'] c['original name'] returnsource e['source']target object [e['target object']]created at e['created at']source user cycle color source['name'] + color func c['NOTIFICATION']['source nick'] '@' + source['screen name'] notify color func c['NOTI... | def notify_list_user_unsubscribed e target e['target']if target['screen_name'] c['original_name'] returnsource e['source']target_object [e['target_object']]created_at e['created_at']source_user cycle_color source['name'] + color_func c['NOTIFICATION']['source_nick'] '@' + source['screen_name'] notify color_func c['NOTI... | 89 |
python-test-296 | python | What does the code generate ? | an arg list marking tupleargs | def generate Arg List arglist args []extra []count 0for i in range len arglist elt arglist[i]if isinstance elt str args append elt elif isinstance elt tuple args append Tuple Arg i * 2 elt extra extend misc flatten elt count count + 1 else raise Value Error 'unexpectargumenttype ' eltreturn args + extra count | def generateArgList arglist args []extra []count 0for i in range len arglist elt arglist[i]if isinstance elt str args append elt elif isinstance elt tuple args append TupleArg i * 2 elt extra extend misc flatten elt count count + 1 else raise ValueError 'unexpectargumenttype ' eltreturn args + extra count | 54 |
python-test-297 | python | What do an arg list mark ? | tupleargs | def generate Arg List arglist args []extra []count 0for i in range len arglist elt arglist[i]if isinstance elt str args append elt elif isinstance elt tuple args append Tuple Arg i * 2 elt extra extend misc flatten elt count count + 1 else raise Value Error 'unexpectargumenttype ' eltreturn args + extra count | def generateArgList arglist args []extra []count 0for i in range len arglist elt arglist[i]if isinstance elt str args append elt elif isinstance elt tuple args append TupleArg i * 2 elt extra extend misc flatten elt count count + 1 else raise ValueError 'unexpectargumenttype ' eltreturn args + extra count | 54 |
python-test-298 | python | What is marking tupleargs ? | an arg list | def generate Arg List arglist args []extra []count 0for i in range len arglist elt arglist[i]if isinstance elt str args append elt elif isinstance elt tuple args append Tuple Arg i * 2 elt extra extend misc flatten elt count count + 1 else raise Value Error 'unexpectargumenttype ' eltreturn args + extra count | def generateArgList arglist args []extra []count 0for i in range len arglist elt arglist[i]if isinstance elt str args append elt elif isinstance elt tuple args append TupleArg i * 2 elt extra extend misc flatten elt count count + 1 else raise ValueError 'unexpectargumenttype ' eltreturn args + extra count | 54 |
python-test-304 | python | What does the code count ? | the number of parameters in a list of layers | def count total params layers layer set None if layer set is None layer set set trainable count 0non trainable count 0for layer in layers if layer in layer set continuelayer set add layer if isinstance layer Model Sequential t nt count total params layer layers layer set trainable count + tnon trainable count + ntelse ... | def count_total_params layers layer_set None if layer_set is None layer_set set trainable_count 0non_trainable_count 0for layer in layers if layer in layer_set continuelayer_set add layer if isinstance layer Model Sequential t nt count_total_params layer layers layer_set trainable_count + tnon_trainable_count + ntelse ... | 92 |
python-test-305 | python | What does the code take ? | a config key for a database connection url | def parse db config config key 'sqlalchemy url' from ckan common import configurl config[config key]regex ['^\\s* ?P<db type>\\w* ' ' //' ' ?P<db user>[^ ]* ' ' ?' ' ?P<db pass>[^@]* ' '@' ' ?P<db host>[^/ ]* ' ' ?' ' ?P<db port>[^/]* ' '/' ' ?P<db name>[\\w -]* ']db details match re match '' join regex url if not db d... | def parse_db_config config_key 'sqlalchemy url' from ckan common import configurl config[config_key]regex ['^\\s* ?P<db_type>\\w* ' ' //' ' ?P<db_user>[^ ]* ' ' ?' ' ?P<db_pass>[^@]* ' '@' ' ?P<db_host>[^/ ]* ' ' ?' ' ?P<db_port>[^/]* ' '/' ' ?P<db_name>[\\w -]* ']db_details_match re match '' join regex url if not db_d... | 79 |
python-test-306 | python | What does the code create ? | a new collection | def create collection committer id collection commit message commit cmds collection validate strict False rights manager create new collection rights collection id committer id model collection models Collection Model id collection id category collection category title collection title objective collection objective la... | def _create_collection committer_id collection commit_message commit_cmds collection validate strict False rights_manager create_new_collection_rights collection id committer_id model collection_models CollectionModel id collection id category collection category title collection title objective collection objective la... | 83 |
python-test-307 | python | How do the save topic method test ? | with creating and editing a topic | def test topic save forum user post Post content ' Test Content' topic Topic title ' Test Title' assert forum last post id is None assert forum post count 0 assert forum topic count 0 topic save forum forum post post user user assert topic title ' Test Title' topic title ' Test Edit Title'topic save assert topic title ... | def test_topic_save forum user post Post content 'TestContent' topic Topic title 'TestTitle' assert forum last_post_id is None assert forum post_count 0 assert forum topic_count 0 topic save forum forum post post user user assert topic title 'TestTitle' topic title 'TestEditTitle'topic save assert topic title 'TestEdit... | 94 |
python-test-309 | python | What does the code get ? | reader for data_format | def get reader data format data class readers [ fmt cls for fmt cls in readers if fmt data format ]for reader format reader class in readers if is best match data class reader class readers return readers[ reader format reader class ]else format table str get format table str data class u' Read' raise IO Registry Error... | def get_reader data_format data_class readers [ fmt cls for fmt cls in _readers if fmt data_format ]for reader_format reader_class in readers if _is_best_match data_class reader_class readers return _readers[ reader_format reader_class ]else format_table_str _get_format_table_str data_class u'Read' raise IORegistryErro... | 78 |
python-test-316 | python | What do a string contain ? | information useful in bug - reports | def bugreport app import billiardimport celeryimport kombutry conn app connection driver v u'{ 0 } {1 }' format conn transport driver name conn transport driver version transport conn transport clsexcept Exception transport driver v u''return BUGREPORT INFO format system platform system arch u' ' join x for x in platfo... | def bugreport app import billiardimport celeryimport kombutry conn app connection driver_v u'{0} {1}' format conn transport driver_name conn transport driver_version transport conn transport_clsexcept Exception transport driver_v u''return BUGREPORT_INFO format system _platform system arch u' ' join x for x in _platfor... | 100 |
python-test-317 | python | What does the code show ? | a small info window with an ok button | def show Info text parent False help '' type 'info' title ' Anki' if parent is False parent aqt mw app active Window or aqt mw if type 'warning' icon Q Message Box Warningelif type 'critical' icon Q Message Box Criticalelse icon Q Message Box Informationmb Q Message Box parent mb set Text text mb set Icon icon mb set W... | def showInfo text parent False help '' type 'info' title 'Anki' if parent is False parent aqt mw app activeWindow or aqt mw if type 'warning' icon QMessageBox Warningelif type 'critical' icon QMessageBox Criticalelse icon QMessageBox Informationmb QMessageBox parent mb setText text mb setIcon icon mb setWindowModality ... | 107 |
python-test-320 | python | Till when do this nt effect the text colored_text = color_text colored_text = color_text ? | until it is printed to the terminal | def color text text color color mapping {u'black' u' 0 30 ' u'red' u' 0 31 ' u'green' u' 0 32 ' u'brown' u' 0 33 ' u'blue' u' 0 34 ' u'magenta' u' 0 35 ' u'cyan' u' 0 36 ' u'lightgrey' u' 0 37 ' u'default' u' 0 39 ' u'darkgrey' u' 1 30 ' u'lightred' u' 1 31 ' u'lightgreen' u' 1 32 ' u'yellow' u' 1 33 ' u'lightblue' u' ... | def _color_text text color color_mapping {u'black' u'0 30' u'red' u'0 31' u'green' u'0 32' u'brown' u'0 33' u'blue' u'0 34' u'magenta' u'0 35' u'cyan' u'0 36' u'lightgrey' u'0 37' u'default' u'0 39' u'darkgrey' u'1 30' u'lightred' u'1 31' u'lightgreen' u'1 32' u'yellow' u'1 33' u'lightblue' u'1 34' u'lightmagenta' u'1 ... | 129 |
python-test-321 | python | Do this effect the text colored_text = color_text colored_text = color_text until it is printed to the terminal ? | No | def color text text color color mapping {u'black' u' 0 30 ' u'red' u' 0 31 ' u'green' u' 0 32 ' u'brown' u' 0 33 ' u'blue' u' 0 34 ' u'magenta' u' 0 35 ' u'cyan' u' 0 36 ' u'lightgrey' u' 0 37 ' u'default' u' 0 39 ' u'darkgrey' u' 1 30 ' u'lightred' u' 1 31 ' u'lightgreen' u' 1 32 ' u'yellow' u' 1 33 ' u'lightblue' u' ... | def _color_text text color color_mapping {u'black' u'0 30' u'red' u'0 31' u'green' u'0 32' u'brown' u'0 33' u'blue' u'0 34' u'magenta' u'0 35' u'cyan' u'0 36' u'lightgrey' u'0 37' u'default' u'0 39' u'darkgrey' u'1 30' u'lightred' u'1 31' u'lightgreen' u'1 32' u'yellow' u'1 33' u'lightblue' u'1 34' u'lightmagenta' u'1 ... | 129 |
python-test-322 | python | What nt effects the text colored_text = color_text colored_text = color_text until it is printed to the terminal ? | this | def color text text color color mapping {u'black' u' 0 30 ' u'red' u' 0 31 ' u'green' u' 0 32 ' u'brown' u' 0 33 ' u'blue' u' 0 34 ' u'magenta' u' 0 35 ' u'cyan' u' 0 36 ' u'lightgrey' u' 0 37 ' u'default' u' 0 39 ' u'darkgrey' u' 1 30 ' u'lightred' u' 1 31 ' u'lightgreen' u' 1 32 ' u'yellow' u' 1 33 ' u'lightblue' u' ... | def _color_text text color color_mapping {u'black' u'0 30' u'red' u'0 31' u'green' u'0 32' u'brown' u'0 33' u'blue' u'0 34' u'magenta' u'0 35' u'cyan' u'0 36' u'lightgrey' u'0 37' u'default' u'0 39' u'darkgrey' u'1 30' u'lightred' u'1 31' u'lightgreen' u'1 32' u'yellow' u'1 33' u'lightblue' u'1 34' u'lightmagenta' u'1 ... | 129 |
python-test-323 | python | Where do the text color ? | in a terminal | def color text text color color mapping {u'black' u' 0 30 ' u'red' u' 0 31 ' u'green' u' 0 32 ' u'brown' u' 0 33 ' u'blue' u' 0 34 ' u'magenta' u' 0 35 ' u'cyan' u' 0 36 ' u'lightgrey' u' 0 37 ' u'default' u' 0 39 ' u'darkgrey' u' 1 30 ' u'lightred' u' 1 31 ' u'lightgreen' u' 1 32 ' u'yellow' u' 1 33 ' u'lightblue' u' ... | def _color_text text color color_mapping {u'black' u'0 30' u'red' u'0 31' u'green' u'0 32' u'brown' u'0 33' u'blue' u'0 34' u'magenta' u'0 35' u'cyan' u'0 36' u'lightgrey' u'0 37' u'default' u'0 39' u'darkgrey' u'1 30' u'lightred' u'1 31' u'lightgreen' u'1 32' u'yellow' u'1 33' u'lightblue' u'1 34' u'lightmagenta' u'1 ... | 129 |
python-test-324 | python | What do this nt effect colored_text = color_text colored_text = color_text until it is printed to the terminal ? | the text | def color text text color color mapping {u'black' u' 0 30 ' u'red' u' 0 31 ' u'green' u' 0 32 ' u'brown' u' 0 33 ' u'blue' u' 0 34 ' u'magenta' u' 0 35 ' u'cyan' u' 0 36 ' u'lightgrey' u' 0 37 ' u'default' u' 0 39 ' u'darkgrey' u' 1 30 ' u'lightred' u' 1 31 ' u'lightgreen' u' 1 32 ' u'yellow' u' 1 33 ' u'lightblue' u' ... | def _color_text text color color_mapping {u'black' u'0 30' u'red' u'0 31' u'green' u'0 32' u'brown' u'0 33' u'blue' u'0 34' u'magenta' u'0 35' u'cyan' u'0 36' u'lightgrey' u'0 37' u'default' u'0 39' u'darkgrey' u'1 30' u'lightred' u'1 31' u'lightgreen' u'1 32' u'yellow' u'1 33' u'lightblue' u'1 34' u'lightmagenta' u'1 ... | 129 |
python-test-325 | python | What is coloring in a terminal ? | the text | def color text text color color mapping {u'black' u' 0 30 ' u'red' u' 0 31 ' u'green' u' 0 32 ' u'brown' u' 0 33 ' u'blue' u' 0 34 ' u'magenta' u' 0 35 ' u'cyan' u' 0 36 ' u'lightgrey' u' 0 37 ' u'default' u' 0 39 ' u'darkgrey' u' 1 30 ' u'lightred' u' 1 31 ' u'lightgreen' u' 1 32 ' u'yellow' u' 1 33 ' u'lightblue' u' ... | def _color_text text color color_mapping {u'black' u'0 30' u'red' u'0 31' u'green' u'0 32' u'brown' u'0 33' u'blue' u'0 34' u'magenta' u'0 35' u'cyan' u'0 36' u'lightgrey' u'0 37' u'default' u'0 39' u'darkgrey' u'1 30' u'lightred' u'1 31' u'lightgreen' u'1 32' u'yellow' u'1 33' u'lightblue' u'1 34' u'lightmagenta' u'1 ... | 129 |
python-test-328 | python | What does the code update ? | a keys description | def update key description key id description region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile r {}try conn update key description key id description r['result'] Trueexcept boto exception Boto Server Error as e r['result'] Falser['error'] utils ['boto get erro... | def update_key_description key_id description region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile r {}try conn update_key_description key_id description r['result'] Trueexcept boto exception BotoServerError as e r['result'] Falser['error'] __utils__['boto get_er... | 53 |
python-test-332 | python | For what purpose does the tf session return ? | to be used by the backend | def get session global SESSIO Nif tf get default session is not None session tf get default session else if SESSION is None if not os environ get 'OMP NUM THREADS' config tf Config Proto allow soft placement True else nb thread int os environ get 'OMP NUM THREADS' config tf Config Proto intra op parallelism threads nb ... | def get_session global _SESSIONif tf get_default_session is not None session tf get_default_session else if _SESSION is None if not os environ get 'OMP_NUM_THREADS' config tf ConfigProto allow_soft_placement True else nb_thread int os environ get 'OMP_NUM_THREADS' config tf ConfigProto intra_op_parallelism_threads nb_t... | 79 |
python-test-336 | python | What does the code execute ? | a powershell query | def exec query ps cmd fields if not WINDOWS returnps sp Popen [conf prog powershell] + cmd + [' ' 'select%s' % ' ' join fields ' ' 'fl'] stdout sp PIPE universal newlines True l []for line in ps stdout if not line strip continuesl line split ' ' 1 if len sl 1 l[ -1 ] + sl[ 0 ] strip continueelse l append sl[ 1 ] strip ... | def _exec_query_ps cmd fields if not WINDOWS returnps sp Popen [conf prog powershell] + cmd + [' ' 'select%s' % ' ' join fields ' ' 'fl'] stdout sp PIPE universal_newlines True l []for line in ps stdout if not line strip continuesl line split ' ' 1 if len sl 1 l[ -1 ] + sl[0] strip continueelse l append sl[1] strip if ... | 79 |
python-test-340 | python | What will it rebuild whenever a file is edited ? | the documentation | def serve config file None dev addr None strict None theme None theme dir None livereload u'livereload' tempdir tempfile mkdtemp def builder log info u' Buildingdocumentation ' config load config config file config file dev addr dev addr strict strict theme theme theme dir theme dir config[u'site dir'] tempdirlive serv... | def serve config_file None dev_addr None strict None theme None theme_dir None livereload u'livereload' tempdir tempfile mkdtemp def builder log info u'Buildingdocumentation ' config load_config config_file config_file dev_addr dev_addr strict strict theme theme theme_dir theme_dir config[u'site_dir'] tempdirlive_serve... | 98 |
python-test-341 | python | What will it serve ? | the documentation on URL | def serve config file None dev addr None strict None theme None theme dir None livereload u'livereload' tempdir tempfile mkdtemp def builder log info u' Buildingdocumentation ' config load config config file config file dev addr dev addr strict strict theme theme theme dir theme dir config[u'site dir'] tempdirlive serv... | def serve config_file None dev_addr None strict None theme None theme_dir None livereload u'livereload' tempdir tempfile mkdtemp def builder log info u'Buildingdocumentation ' config load_config config_file config_file dev_addr dev_addr strict strict theme theme theme_dir theme_dir config[u'site_dir'] tempdirlive_serve... | 98 |
python-test-342 | python | When will it rebuild the documentation ? | whenever a file is edited | def serve config file None dev addr None strict None theme None theme dir None livereload u'livereload' tempdir tempfile mkdtemp def builder log info u' Buildingdocumentation ' config load config config file config file dev addr dev addr strict strict theme theme theme dir theme dir config[u'site dir'] tempdirlive serv... | def serve config_file None dev_addr None strict None theme None theme_dir None livereload u'livereload' tempdir tempfile mkdtemp def builder log info u'Buildingdocumentation ' config load_config config_file config_file dev_addr dev_addr strict strict theme theme theme_dir theme_dir config[u'site_dir'] tempdirlive_serve... | 98 |
python-test-343 | python | What does the code start by default ? | the mkdocs development server | def serve config file None dev addr None strict None theme None theme dir None livereload u'livereload' tempdir tempfile mkdtemp def builder log info u' Buildingdocumentation ' config load config config file config file dev addr dev addr strict strict theme theme theme dir theme dir config[u'site dir'] tempdirlive serv... | def serve config_file None dev_addr None strict None theme None theme_dir None livereload u'livereload' tempdir tempfile mkdtemp def builder log info u'Buildingdocumentation ' config load_config config_file config_file dev_addr dev_addr strict strict theme theme theme_dir theme_dir config[u'site_dir'] tempdirlive_serve... | 98 |
python-test-354 | python | What does the code add ? | attachment_specs table | def upgrade migrate engine meta Meta Data meta bind migrate engine Table 'volume attachment' meta autoload True attachment specs Table 'attachment specs' meta Column 'created at' Date Time timezone False Column 'updated at' Date Time timezone False Column 'deleted at' Date Time timezone False Column 'deleted' Boolean d... | def upgrade migrate_engine meta MetaData meta bind migrate_engineTable 'volume_attachment' meta autoload True attachment_specs Table 'attachment_specs' meta Column 'created_at' DateTime timezone False Column 'updated_at' DateTime timezone False Column 'deleted_at' DateTime timezone False Column 'deleted' Boolean defaul... | 90 |
python-test-355 | python | What does the code get ? | path to local copy of eegmmi dataset url | @verbosedef data path url path None force update False update path None verbose None key 'MNE DATASETS EEGBCI PATH'name 'EEGBCI'path get path path key name destination url to local path url op join path 'MNE-eegbci-data' destinations [destination]if not op isfile destination or force update if op isfile destination os ... | @verbosedef data_path url path None force_update False update_path None verbose None key 'MNE_DATASETS_EEGBCI_PATH'name 'EEGBCI'path _get_path path key name destination _url_to_local_path url op join path 'MNE-eegbci-data' destinations [destination]if not op isfile destination or force_update if op isfile destination o... | 80 |
python-test-356 | python | What does the code get ? | the coupon information to display in the pop up form | @require POST@login requireddef get coupon info request course id coupon id request POST get 'id' None if not coupon id return Json Response {'message' 'couponidnotfound' } status 400 try coupon Coupon objects get id coupon id except Object Does Not Exist return Json Response {'message' 'couponwiththecouponid {coupon i... | @require_POST@login_requireddef get_coupon_info request course_id coupon_id request POST get 'id' None if not coupon_id return JsonResponse {'message' _ 'couponidnotfound' } status 400 try coupon Coupon objects get id coupon_id except ObjectDoesNotExist return JsonResponse {'message' _ 'couponwiththecouponid {coupon_id... | 125 |
python-test-357 | python | What contain draft comments ? | diffsets in the review | def diffsets with comments review current pair if not review returndiffsets Diff Set objects filter files comments review review diffsets diffsets filter files comments interfilediff isnull True diffsets diffsets distinct for diffset in diffsets yield {u'diffset' diffset u'is current' current pair[ 0 ] diffset and curr... | def diffsets_with_comments review current_pair if not review returndiffsets DiffSet objects filter files__comments__review review diffsets diffsets filter files__comments__interfilediff__isnull True diffsets diffsets distinct for diffset in diffsets yield {u'diffset' diffset u'is_current' current_pair[0] diffset and cu... | 52 |
python-test-358 | python | What does the code perform on the sample ? | an static analysis | def binskim sample signature check challenge signature if len re findall ' [a-f\\d]{ 32 } ' sample 0 return ' Wrong Input 'binskim path config['binskim']['file x64 ']command 'analyze'path config[' Mob SF']['samples'] + sample output p '-o'output d config[' Mob SF']['samples'] + sample + ' binskim' policy p '--config'po... | def binskim sample signature _check_challenge signature if len re findall ' [a-f\\d]{32} ' sample 0 return 'WrongInput 'binskim_path config['binskim']['file_x64']command 'analyze'path config['MobSF']['samples'] + sample output_p '-o'output_d config['MobSF']['samples'] + sample + '_binskim' policy_p '--config'policy_d '... | 80 |
python-test-359 | python | What does the code subtract from each image channel ? | the given means | def mean image subtraction image means if image get shape ndims 3 raise Value Error ' Inputmustbeofsize[height width C> 0 ]' num channels image get shape as list [ -1 ]if len means num channels raise Value Error 'len means mustmatchthenumberofchannels' channels tf split 2 num channels image for i in range num channels ... | def _mean_image_subtraction image means if image get_shape ndims 3 raise ValueError 'Inputmustbeofsize[height width C>0]' num_channels image get_shape as_list [ -1 ]if len means num_channels raise ValueError 'len means mustmatchthenumberofchannels' channels tf split 2 num_channels image for i in range num_channels chan... | 61 |
python-test-376 | python | What does the code add ? | two 1d kernel arrays of different size | def add kernel arrays 1D array 1 array 2 if array 1 size > array 2 size new array array 1 copy center array 1 size // 2 slice slice center - array 2 size // 2 center + array 2 size // 2 + 1 new array[slice ] + array 2return new arrayelif array 2 size > array 1 size new array array 2 copy center array 2 size // 2 slice ... | def add_kernel_arrays_1D array_1 array_2 if array_1 size > array_2 size new_array array_1 copy center array_1 size // 2 slice_ slice center - array_2 size // 2 center + array_2 size // 2 + 1 new_array[slice_] + array_2return new_arrayelif array_2 size > array_1 size new_array array_2 copy center array_2 size // 2 slice... | 103 |
python-test-377 | python | What does the code apply ? | fixes needed for web fonts | def apply web specific fixes font unhinted family name hhea font['hhea']hhea ascent 1900 hhea descent -500 os 2 font['OS/ 2 ']os 2 s Typo Ascender 1536 os 2 s Typo Descender -512 os 2 s Typo Line Gap 102 os 2 us Win Ascent 1946 os 2 us Win Descent 512 apply web cros common fixes font unhinted family name | def apply_web_specific_fixes font unhinted family_name hhea font['hhea']hhea ascent 1900hhea descent -500 os2 font['OS/2']os2 sTypoAscender 1536os2 sTypoDescender -512 os2 sTypoLineGap 102os2 usWinAscent 1946os2 usWinDescent 512apply_web_cros_common_fixes font unhinted family_name | 60 |
python-test-378 | python | For what purpose did fixes need ? | for web fonts | def apply web specific fixes font unhinted family name hhea font['hhea']hhea ascent 1900 hhea descent -500 os 2 font['OS/ 2 ']os 2 s Typo Ascender 1536 os 2 s Typo Descender -512 os 2 s Typo Line Gap 102 os 2 us Win Ascent 1946 os 2 us Win Descent 512 apply web cros common fixes font unhinted family name | def apply_web_specific_fixes font unhinted family_name hhea font['hhea']hhea ascent 1900hhea descent -500 os2 font['OS/2']os2 sTypoAscender 1536os2 sTypoDescender -512 os2 sTypoLineGap 102os2 usWinAscent 1946os2 usWinDescent 512apply_web_cros_common_fixes font unhinted family_name | 60 |
python-test-386 | python | What does the code make ? | boxplot trace for decreasing candlesticks | def make decreasing candle open high low close dates **kwargs decrease x decrease y Candlestick open high low close dates **kwargs get candle decrease if 'line' in kwargs kwargs setdefault 'fillcolor' kwargs['line']['color'] else kwargs setdefault 'fillcolor' DEFAULT DECREASING COLOR kwargs setdefault 'showlegend' Fals... | def make_decreasing_candle open high low close dates **kwargs decrease_x decrease_y _Candlestick open high low close dates **kwargs get_candle_decrease if 'line' in kwargs kwargs setdefault 'fillcolor' kwargs['line']['color'] else kwargs setdefault 'fillcolor' _DEFAULT_DECREASING_COLOR kwargs setdefault 'showlegend' Fa... | 77 |
python-test-391 | python | How does the code generate the page context ? | by extending the global context and adding page specific variables | def get page context page content toc meta config if config[u'site url'] page set canonical url config[u'site url'] if config[u'repo url'] page set edit url config[u'repo url'] config[u'edit uri'] page content contentpage toc tocpage meta metaif page is homepage or page title is None page title Noneelse page title page... | def get_page_context page content toc meta config if config[u'site_url'] page set_canonical_url config[u'site_url'] if config[u'repo_url'] page set_edit_url config[u'repo_url'] config[u'edit_uri'] page content contentpage toc tocpage meta metaif page is_homepage or page title is None page_title Noneelse page_title page... | 95 |
python-test-392 | python | What does the code generate by extending the global context and adding page specific variables ? | the page context | def get page context page content toc meta config if config[u'site url'] page set canonical url config[u'site url'] if config[u'repo url'] page set edit url config[u'repo url'] config[u'edit uri'] page content contentpage toc tocpage meta metaif page is homepage or page title is None page title Noneelse page title page... | def get_page_context page content toc meta config if config[u'site_url'] page set_canonical_url config[u'site_url'] if config[u'repo_url'] page set_edit_url config[u'repo_url'] config[u'edit_uri'] page content contentpage toc tocpage meta metaif page is_homepage or page title is None page_title Noneelse page_title page... | 95 |
python-test-397 | python | For what purpose do detail show ? | for a single oauth application | @must be logged indef oauth application detail auth **kwargs client id kwargs get 'client id' try record Api O Auth 2 Application find one Q 'client id' 'eq' client id except No Results Found raise HTTP Error http NOT FOUND except Value Error raise HTTP Error http NOT FOUND if record owner auth user raise HTTP Error ht... | @must_be_logged_indef oauth_application_detail auth **kwargs client_id kwargs get 'client_id' try record ApiOAuth2Application find_one Q 'client_id' 'eq' client_id except NoResultsFound raise HTTPError http NOT_FOUND except ValueError raise HTTPError http NOT_FOUND if record owner auth user raise HTTPError http FORBIDD... | 91 |
python-test-399 | python | What does the code install into a virtualenv using pip ? | the flocker client | def task cli pip install venv name 'flocker-client' package source Package Source url 'https //{bucket} s3 amazonaws com/{key}/ Flocker-{version}-py 2 -none-any whl' format bucket ARCHIVE BUCKET key 'python' version get wheel version package source return sequence [run from args ['virtualenv' '--python /usr/bin/python ... | def task_cli_pip_install venv_name 'flocker-client' package_source PackageSource url 'https //{bucket} s3 amazonaws com/{key}/Flocker-{version}-py2-none-any whl' format bucket ARCHIVE_BUCKET key 'python' version _get_wheel_version package_source return sequence [run_from_args ['virtualenv' '--python /usr/bin/python2 7'... | 69 |
python-test-401 | python | What does the code create ? | a brand new name | def get valid name layer name name clean string layer name proposed name namecount 1while Layer objects filter name proposed name exists proposed name '%s %d' % name count count count + 1 logger info ' Requestednamealreadyused adjustingname[%s] >[%s]' layer name proposed name else logger info ' Usingnameasrequested' re... | def get_valid_name layer_name name _clean_string layer_name proposed_name namecount 1while Layer objects filter name proposed_name exists proposed_name '%s_%d' % name count count count + 1 logger info 'Requestednamealreadyused adjustingname[%s] >[%s]' layer_name proposed_name else logger info 'Usingnameasrequested' ret... | 51 |
python-test-402 | python | What indicates whether the domain was renewed successfully amount charged for reactivation orderid unique integer value for the order transactionid unique integer value for the transaction cli example ? | the following information in a dictionary issuccess bool | def reactivate domain name opts salt utils namecheap get opts 'namecheap domains reactivate' opts[' Domain Name'] domain nameresponse xml salt utils namecheap post request opts if response xml is None return {}domainreactivateresult response xml get Elements By Tag Name ' Domain Reactivate Result' [0 ]return salt utils... | def reactivate domain_name opts salt utils namecheap get_opts 'namecheap domains reactivate' opts['DomainName'] domain_nameresponse_xml salt utils namecheap post_request opts if response_xml is None return {}domainreactivateresult response_xml getElementsByTagName 'DomainReactivateResult' [0]return salt utils namecheap... | 52 |
python-test-403 | python | What does the following information in a dictionary issuccess bool indicate ? | whether the domain was renewed successfully amount charged for reactivation orderid unique integer value for the order transactionid unique integer value for the transaction cli example | def reactivate domain name opts salt utils namecheap get opts 'namecheap domains reactivate' opts[' Domain Name'] domain nameresponse xml salt utils namecheap post request opts if response xml is None return {}domainreactivateresult response xml get Elements By Tag Name ' Domain Reactivate Result' [0 ]return salt utils... | def reactivate domain_name opts salt utils namecheap get_opts 'namecheap domains reactivate' opts['DomainName'] domain_nameresponse_xml salt utils namecheap post_request opts if response_xml is None return {}domainreactivateresult response_xml getElementsByTagName 'DomainReactivateResult' [0]return salt utils namecheap... | 52 |
python-test-404 | python | What converts to color array ? | user string or hex color | def string to rgb color if not color startswith '#' if color lower not in color dict raise Value Error ' Color"%s"unknown' % color color color dict[color]assert color[ 0 ] '#' color color[ 1 ]lc len color if lc in 3 4 color '' join c + c for c in color lc len color if lc not in 6 8 raise Value Error ' Hexcolormusthavee... | def _string_to_rgb color if not color startswith '#' if color lower not in _color_dict raise ValueError 'Color"%s"unknown' % color color _color_dict[color]assert color[0] '#' color color[1 ]lc len color if lc in 3 4 color '' join c + c for c in color lc len color if lc not in 6 8 raise ValueError 'Hexcolormusthaveexact... | 90 |
python-test-405 | python | What do user string or hex color convert ? | to color array | def string to rgb color if not color startswith '#' if color lower not in color dict raise Value Error ' Color"%s"unknown' % color color color dict[color]assert color[ 0 ] '#' color color[ 1 ]lc len color if lc in 3 4 color '' join c + c for c in color lc len color if lc not in 6 8 raise Value Error ' Hexcolormusthavee... | def _string_to_rgb color if not color startswith '#' if color lower not in _color_dict raise ValueError 'Color"%s"unknown' % color color _color_dict[color]assert color[0] '#' color color[1 ]lc len color if lc in 3 4 color '' join c + c for c in color lc len color if lc not in 6 8 raise ValueError 'Hexcolormusthaveexact... | 90 |
python-test-408 | python | What does the code ensure ? | that the virtualbox guest additions are installed | def additions installed name reboot False upgrade os False ret {'name' name 'changes' {} 'result' False 'comment' ''}current state salt ['vbox guest additions version'] if current state ret['result'] Trueret['comment'] ' Systemalreadyinthecorrectstate'return retif opts ['test'] ret['comment'] ' Thestateof Virtual Box G... | def additions_installed name reboot False upgrade_os False ret {'name' name 'changes' {} 'result' False 'comment' ''}current_state __salt__['vbox_guest additions_version'] if current_state ret['result'] Trueret['comment'] 'Systemalreadyinthecorrectstate'return retif __opts__['test'] ret['comment'] 'ThestateofVirtualBox... | 80 |
python-test-409 | python | What does the code parse ? | the value of extra_model_fields | def parse extra model fields extra model fields fields defaultdict list for entry in extra model fields model key field name parse field path entry[ 0 ] field class import field entry[ 1 ] field args field kwargs entry[ 2 ]try field field class *field args **field kwargs except Type Error as e raise Improperly Configur... | def parse_extra_model_fields extra_model_fields fields defaultdict list for entry in extra_model_fields model_key field_name parse_field_path entry[0] field_class import_field entry[1] field_args field_kwargs entry[2 ]try field field_class *field_args **field_kwargs except TypeError as e raise ImproperlyConfigured u"Th... | 76 |
python-test-422 | python | What disappears on the given page ? | the " mini - notification " | def wait for notification page def is saving ' Whetherornotthenotificationiscurrentlyshowing 'return page q css ' wrapper-notification-mini is-shown' presentdef is saving done ' Whetherornotthenotificationisfinishedshowing 'return page q css ' wrapper-notification-mini is-hiding' present Empty Promise is saving ' Notif... | def wait_for_notification page def _is_saving 'Whetherornotthenotificationiscurrentlyshowing 'return page q css ' wrapper-notification-mini is-shown' presentdef _is_saving_done 'Whetherornotthenotificationisfinishedshowing 'return page q css ' wrapper-notification-mini is-hiding' presentEmptyPromise _is_saving 'Notific... | 60 |
python-test-428 | python | What did the code give ? | two tp instances | def same TP Params tp 1 tp 2 result Truefor param in ['number Of Cols' 'cells Per Column' 'initial Perm' 'connected Perm' 'min Threshold' 'new Synapse Count' 'permanence Inc' 'permanence Dec' 'permanence Max' 'global Decay' 'activation Threshold' 'do Pooling' 'seg Update Valid Duration' 'seed' 'burn In' 'pam Length' 'm... | def sameTPParams tp1 tp2 result Truefor param in ['numberOfCols' 'cellsPerColumn' 'initialPerm' 'connectedPerm' 'minThreshold' 'newSynapseCount' 'permanenceInc' 'permanenceDec' 'permanenceMax' 'globalDecay' 'activationThreshold' 'doPooling' 'segUpdateValidDuration' 'seed' 'burnIn' 'pamLength' 'maxAge'] if getattr tp1 p... | 74 |
python-test-429 | python | What does the code check ? | the strength of the password entered by the user | def check password strength password password unicode password n math log len set password num re search '[ 0 - 9 ]' password is not None and re match '^[ 0 - 9 ]*$' password is None caps password password upper and password password lower extra re match '^[a-z A-Z 0 - 9 ]*$' password is None score len password * n + c... | def check_password_strength password password unicode password n math log len set password num re search '[0-9]' password is not None and re match '^[0-9]*$' password is None caps password password upper and password password lower extra re match '^[a-zA-Z0-9]*$' password is None score len password * n + caps + num + e... | 91 |
python-test-430 | python | What does the code update from configuration files specified in the environment ? | a config dictionary | def update config from env config env srcdir os path join os path dirname os path realpath file ' ' if env in ['prod' 'staging'] base cfg path ['/etc/inboxapp/secrets yml' '/etc/inboxapp/config json']else v {'env' env 'srcdir' srcdir}base cfg path ['{srcdir}/etc/secrets-{env} yml' format **v '{srcdir}/etc/config-{env} ... | def _update_config_from_env config env srcdir os path join os path dirname os path realpath __file__ ' ' if env in ['prod' 'staging'] base_cfg_path ['/etc/inboxapp/secrets yml' '/etc/inboxapp/config json']else v {'env' env 'srcdir' srcdir}base_cfg_path ['{srcdir}/etc/secrets-{env} yml' format **v '{srcdir}/etc/config-{... | 122 |
python-test-439 | python | What does the code get ? | interesting info about some | def get eip address info addresses None allocation ids None region None key None keyid None profile None if type addresses type 'string' addresses [addresses]if type allocation ids type 'string' allocation ids [allocation ids]ret get all eip addresses addresses addresses allocation ids allocation ids region region key ... | def get_eip_address_info addresses None allocation_ids None region None key None keyid None profile None if type addresses type 'string' addresses [addresses]if type allocation_ids type 'string' allocation_ids [allocation_ids]ret _get_all_eip_addresses addresses addresses allocation_ids allocation_ids region region key... | 86 |
python-test-441 | python | What did client define ? | formatting rules | def format by pattern numobj number format user defined formats country code numobj country codensn national significant number numobj if not has valid country calling code country code return nsnregion code region code for country code country code metadata Phone Metadata metadata for region or calling code country co... | def format_by_pattern numobj number_format user_defined_formats country_code numobj country_codensn national_significant_number numobj if not _has_valid_country_calling_code country_code return nsnregion_code region_code_for_country_code country_code metadata PhoneMetadata metadata_for_region_or_calling_code country_co... | 190 |
python-test-443 | python | How do directory merge a ? | to directory b | def mergetreejinja src dst context for item in os listdir src s os path join src item d os path join dst item if os path isdir s log info ' Copyingfolder{ 0 }to{ 1 }' format s d if os path exists d mergetreejinja s d context else os mkdir d mergetreejinja s d context elif item TEMPLATE FILE NAME d Template d render con... | def _mergetreejinja src dst context for item in os listdir src s os path join src item d os path join dst item if os path isdir s log info 'Copyingfolder{0}to{1}' format s d if os path exists d _mergetreejinja s d context else os mkdir d _mergetreejinja s d context elif item TEMPLATE_FILE_NAME d Template d render conte... | 112 |
python-test-444 | python | How does the code run ? | pylama | def hg hook ui repo node None **kwargs seen set paths []if len repo for rev in range repo[node] len repo for file in repo[rev] files file op join repo root file if file in seen or not op exists file continueseen add file paths append file options parse options setup logger options if paths process paths options candida... | def hg_hook ui repo node None **kwargs seen set paths []if len repo for rev in range repo[node] len repo for file_ in repo[rev] files file_ op join repo root file_ if file_ in seen or not op exists file_ continueseen add file_ paths append file_ options parse_options setup_logger options if paths process_paths options ... | 60 |
python-test-450 | python | What does the code restrict ? | the characters that are allowed in text | def sanitize text text valid characters valid chars character map mapped chars invalid character 'X' if isinstance text list return [sanitize text x valid characters valid characters character map character map invalid character invalid character for x in text]if not isinstance text string types text smart str text ret... | def sanitize_text text valid_characters valid_chars character_map mapped_chars invalid_character 'X' if isinstance text list return [sanitize_text x valid_characters valid_characters character_map character_map invalid_character invalid_character for x in text]if not isinstance text string_types text smart_str text ret... | 61 |
python-test-451 | python | What does the code accept ? | both strings and lists of strings | def sanitize text text valid characters valid chars character map mapped chars invalid character 'X' if isinstance text list return [sanitize text x valid characters valid characters character map character map invalid character invalid character for x in text]if not isinstance text string types text smart str text ret... | def sanitize_text text valid_characters valid_chars character_map mapped_chars invalid_character 'X' if isinstance text list return [sanitize_text x valid_characters valid_characters character_map character_map invalid_character invalid_character for x in text]if not isinstance text string_types text smart_str text ret... | 61 |
python-test-452 | python | What do it do also ? | some basic import validation | def get request ip resolver module attribute get cms setting 'REQUEST IP RESOLVER' rsplit ' ' 1 try ip resolver module importlib import module module ip resolver getattr ip resolver module attribute except Import Error raise Improperly Configured ' Unabletofindthespecified CMS REQUEST IP RESOLVE Rmodule "{ 0 }" ' forma... | def get_request_ip_resolver module attribute get_cms_setting 'REQUEST_IP_RESOLVER' rsplit ' ' 1 try ip_resolver_module importlib import_module module ip_resolver getattr ip_resolver_module attribute except ImportError raise ImproperlyConfigured _ 'UnabletofindthespecifiedCMS_REQUEST_IP_RESOLVERmodule "{0}" ' format mod... | 76 |
python-test-455 | python | How do task message create ? | in protocol 1 format | def Task Message 1 name id None args kwargs {} callbacks None errbacks None chain None **options from celery import uuidfrom kombu serialization import dumpsid id or uuid message Mock name u' Task Message-{ 0 }' format id message headers {}message payload {u'task' name u'id' id u'args' args u'kwargs' kwargs u'callbacks... | def TaskMessage1 name id None args kwargs {} callbacks None errbacks None chain None **options from celery import uuidfrom kombu serialization import dumpsid id or uuid message Mock name u'TaskMessage-{0}' format id message headers {}message payload {u'task' name u'id' id u'args' args u'kwargs' kwargs u'callbacks' call... | 70 |
python-test-457 | python | What supports ipv6 functionality ? | keepalived | def keepalived ipv 6 supported br name ha port gw port common utils get related rand device names ['ka-test-' ha router HA DEV PREFIX namespaces INTERNAL DEV PREFIX] gw vip 'fdf 8 f53 b 82 e 4 10 / 64 'expected default gw 'fe 80 f816 1'with ovs lib OVS Bridge br name as br with Keepalived I Pv 6 Test ha port gw port gw... | def keepalived_ipv6_supported br_name ha_port gw_port common_utils get_related_rand_device_names ['ka-test-' ha_router HA_DEV_PREFIX namespaces INTERNAL_DEV_PREFIX] gw_vip 'fdf8 f53b 82e4 10/64'expected_default_gw 'fe80 f816 1'with ovs_lib OVSBridge br_name as br with KeepalivedIPv6Test ha_port gw_port gw_vip expected_... | 162 |
python-test-458 | python | What do keepalived support ? | ipv6 functionality | def keepalived ipv 6 supported br name ha port gw port common utils get related rand device names ['ka-test-' ha router HA DEV PREFIX namespaces INTERNAL DEV PREFIX] gw vip 'fdf 8 f53 b 82 e 4 10 / 64 'expected default gw 'fe 80 f816 1'with ovs lib OVS Bridge br name as br with Keepalived I Pv 6 Test ha port gw port gw... | def keepalived_ipv6_supported br_name ha_port gw_port common_utils get_related_rand_device_names ['ka-test-' ha_router HA_DEV_PREFIX namespaces INTERNAL_DEV_PREFIX] gw_vip 'fdf8 f53b 82e4 10/64'expected_default_gw 'fe80 f816 1'with ovs_lib OVSBridge br_name as br with KeepalivedIPv6Test ha_port gw_port gw_vip expected_... | 162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.