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-3461 | python | What does the code create with a given schema in a given api ? | a new model | def create api model rest Api Id model Name model Description schema content Type 'application/json' region None key None keyid None profile None try schema json json dumps schema if isinstance schema dict else schema conn get conn region region key key keyid keyid profile profile model conn create model rest Api Id re... | def create_api_model restApiId modelName modelDescription schema contentType 'application/json' region None key None keyid None profile None try schema_json json dumps schema if isinstance schema dict else schema conn _get_conn region region key key keyid keyid profile profile model conn create_model restApiId restApiI... | 94 |
python-test-3462 | python | When does the code create a new model with a given schema ? | in a given api | def create api model rest Api Id model Name model Description schema content Type 'application/json' region None key None keyid None profile None try schema json json dumps schema if isinstance schema dict else schema conn get conn region region key key keyid keyid profile profile model conn create model rest Api Id re... | def create_api_model restApiId modelName modelDescription schema contentType 'application/json' region None key None keyid None profile None try schema_json json dumps schema if isinstance schema dict else schema conn _get_conn region region key key keyid keyid profile profile model conn create_model restApiId restApiI... | 94 |
python-test-3463 | python | What are available in the configuration file ? | all the types | def get block types from json file xblock json file if not os path isfile xblock json file print 'x Blockconfigurationfiledoesnotexist %s' % xblock json file sys exit 2 with open xblock json file 'r' as json file type set set try json data json loads json file read except Value Error as e print 'x Blockconfigurationfil... | def _get_block_types_from_json_file xblock_json_file if not os path isfile xblock_json_file print 'xBlockconfigurationfiledoesnotexist %s' % xblock_json_file sys exit 2 with open xblock_json_file 'r' as json_file type_set set try json_data json loads json_file read except ValueError as e print 'xBlockconfigurationfiled... | 99 |
python-test-3464 | python | What do request have ? | no permission to access info of the task with i d task_id | def get public task data request task id try task state info get task data task id except Task Not Found raise Task No Permission task id if not hasattr task 'check permission' raise Task No Permission task id context info get 'context' {} if not task check permission request state context raise Task No Permission task... | def get_public_task_data request task_id try task state info get_task_data task_id except TaskNotFound raise TaskNoPermission task_id if not hasattr task 'check_permission' raise TaskNoPermission task_id context info get 'context' {} if not task check_permission request state context raise TaskNoPermission task_id publ... | 75 |
python-test-3465 | python | What will tuple has raise if request has no permission to access info of the task with i d task_id ? | tasknopermission | def get public task data request task id try task state info get task data task id except Task Not Found raise Task No Permission task id if not hasattr task 'check permission' raise Task No Permission task id context info get 'context' {} if not task check permission request state context raise Task No Permission task... | def get_public_task_data request task_id try task state info get_task_data task_id except TaskNotFound raise TaskNoPermission task_id if not hasattr task 'check_permission' raise TaskNoPermission task_id context info get 'context' {} if not task check_permission request state context raise TaskNoPermission task_id publ... | 75 |
python-test-3466 | python | How do info of the task access ? | with i d task_id | def get public task data request task id try task state info get task data task id except Task Not Found raise Task No Permission task id if not hasattr task 'check permission' raise Task No Permission task id context info get 'context' {} if not task check permission request state context raise Task No Permission task... | def get_public_task_data request task_id try task state info get_task_data task_id except TaskNotFound raise TaskNoPermission task_id if not hasattr task 'check_permission' raise TaskNoPermission task_id context info get 'context' {} if not task check_permission request state context raise TaskNoPermission task_id publ... | 75 |
python-test-3473 | python | Where do gjr garch process parameters simulate ? | ar : array_like | def generate gjrgarch nobs ar ma mu 1 0 scale 0 1 varinnovation None if varinnovation is None eta scale * np random randn nobs else eta varinnovationetax np empty nobs 3 etax[ 0] muetax[ 1 ] eta ** 2 [ None]etax[ eta > 0 2 ] 0h miso lfilter ar ma etax [0 ]err np sqrt h[ len eta ] * eta return err h etax | def generate_gjrgarch nobs ar ma mu 1 0 scale 0 1 varinnovation None if varinnovation is None eta scale * np random randn nobs else eta varinnovationetax np empty nobs 3 etax[ 0] muetax[ 1 ] eta ** 2 [ None]etax[ eta > 0 2 ] 0h miso_lfilter ar ma etax [0]err np sqrt h[ len eta ] * eta return err h etax | 67 |
python-test-3474 | python | What simulate ar : array_like ? | gjr garch process parameters | def generate gjrgarch nobs ar ma mu 1 0 scale 0 1 varinnovation None if varinnovation is None eta scale * np random randn nobs else eta varinnovationetax np empty nobs 3 etax[ 0] muetax[ 1 ] eta ** 2 [ None]etax[ eta > 0 2 ] 0h miso lfilter ar ma etax [0 ]err np sqrt h[ len eta ] * eta return err h etax | def generate_gjrgarch nobs ar ma mu 1 0 scale 0 1 varinnovation None if varinnovation is None eta scale * np random randn nobs else eta varinnovationetax np empty nobs 3 etax[ 0] muetax[ 1 ] eta ** 2 [ None]etax[ eta > 0 2 ] 0h miso_lfilter ar ma etax [0]err np sqrt h[ len eta ] * eta return err h etax | 67 |
python-test-3475 | python | How does this function train a student ? | using predictions made by an ensemble of teachers | def train student dataset nb teachers assert input create dir if needed FLAGS train dir stdnt dataset prepare student data dataset nb teachers save True stdnt data stdnt labels stdnt test data stdnt test labels stdnt datasetif FLAGS deeper ckpt path FLAGS train dir + '/' + str dataset + ' ' + str nb teachers + ' studen... | def train_student dataset nb_teachers assert input create_dir_if_needed FLAGS train_dir stdnt_dataset prepare_student_data dataset nb_teachers save True stdnt_data stdnt_labels stdnt_test_data stdnt_test_labels stdnt_datasetif FLAGS deeper ckpt_path FLAGS train_dir + '/' + str dataset + '_' + str nb_teachers + '_studen... | 136 |
python-test-3476 | python | What do a student use ? | predictions made by an ensemble of teachers | def train student dataset nb teachers assert input create dir if needed FLAGS train dir stdnt dataset prepare student data dataset nb teachers save True stdnt data stdnt labels stdnt test data stdnt test labels stdnt datasetif FLAGS deeper ckpt path FLAGS train dir + '/' + str dataset + ' ' + str nb teachers + ' studen... | def train_student dataset nb_teachers assert input create_dir_if_needed FLAGS train_dir stdnt_dataset prepare_student_data dataset nb_teachers save True stdnt_data stdnt_labels stdnt_test_data stdnt_test_labels stdnt_datasetif FLAGS deeper ckpt_path FLAGS train_dir + '/' + str dataset + '_' + str nb_teachers + '_studen... | 136 |
python-test-3477 | python | What does the code validate ? | the inputs to the actions in a target | def Validate Actions In Target target target dict build file target name target dict get 'target name' actions target dict get 'actions' [] for action in actions action name action get 'action name' if not action name raise Gyp Error " Anonymousactionintarget%s Anactionmusthavean'action name'field " % target name input... | def ValidateActionsInTarget target target_dict build_file target_name target_dict get 'target_name' actions target_dict get 'actions' [] for action in actions action_name action get 'action_name' if not action_name raise GypError "Anonymousactionintarget%s Anactionmusthavean'action_name'field " % target_name inputs act... | 89 |
python-test-3478 | python | How did sample ids sort from mapping file ? | by ascending value | def sort sample ids by mapping value mapping file field field type f float data headers comments parse mapping file mapping file try column headers index field except Value Error raise Value Error ' Column %s notfoundinmappingfileheaders \n%s' % field '' join headers results [ e[ 0 ] field type f e[column] for e in dat... | def sort_sample_ids_by_mapping_value mapping_file field field_type_f float data headers comments parse_mapping_file mapping_file try column headers index field except ValueError raise ValueError 'Column %s notfoundinmappingfileheaders \n%s' % field '' join headers results [ e[0] field_type_f e[column] for e in data]res... | 62 |
python-test-3479 | python | For what purpose do short_urls create ? | for a list of docs | @task@timeitdef add short links doc ids base url 'https //{ 0 }%s' format Site objects get current domain docs Document objects filter id in doc ids try pin this thread for doc in docs endpoint django reverse 'wiki document' args [doc slug] doc update share link generate short url base url % endpoint statsd incr 'wiki ... | @task@timeitdef add_short_links doc_ids base_url 'https //{0}%s' format Site objects get_current domain docs Document objects filter id__in doc_ids try pin_this_thread for doc in docs endpoint django_reverse 'wiki document' args [doc slug] doc update share_link generate_short_url base_url % endpoint statsd incr 'wiki a... | 77 |
python-test-3482 | python | What does the code ensure ? | that the named group is absent name the groupname of the group to remove user system user all operations should be performed on behalf of | def absent name user None maintenance db None db password None db host None db port None db user None ret {'name' name 'changes' {} 'result' True 'comment' ''}db args {'maintenance db' maintenance db 'runas' user 'host' db host 'user' db user 'port' db port 'password' db password}if salt ['postgres user exists'] name *... | def absent name user None maintenance_db None db_password None db_host None db_port None db_user None ret {'name' name 'changes' {} 'result' True 'comment' ''}db_args {'maintenance_db' maintenance_db 'runas' user 'host' db_host 'user' db_user 'port' db_port 'password' db_password}if __salt__['postgres user_exists'] nam... | 96 |
python-test-3483 | python | For what purpose is the named group absent name the groupname of the group ? | to remove user system user | def absent name user None maintenance db None db password None db host None db port None db user None ret {'name' name 'changes' {} 'result' True 'comment' ''}db args {'maintenance db' maintenance db 'runas' user 'host' db host 'user' db user 'port' db port 'password' db password}if salt ['postgres user exists'] name *... | def absent name user None maintenance_db None db_password None db_host None db_port None db_user None ret {'name' name 'changes' {} 'result' True 'comment' ''}db_args {'maintenance_db' maintenance_db 'runas' user 'host' db_host 'user' db_user 'port' db_port 'password' db_password}if __salt__['postgres user_exists'] nam... | 96 |
python-test-3486 | python | For what purpose do detail show ? | for a specified raid device cli example | def detail device '/dev/md 0 ' ret {}ret['members'] {}if not os path exists device msg " Device{ 0 }doesn'texist "raise Command Execution Error msg format device cmd ['mdadm' '--detail' device]for line in salt ['cmd run stdout'] cmd python shell False splitlines if line startswith device continueif '' not in line conti... | def detail device '/dev/md0' ret {}ret['members'] {}if not os path exists device msg "Device{0}doesn'texist "raise CommandExecutionError msg format device cmd ['mdadm' '--detail' device]for line in __salt__['cmd run_stdout'] cmd python_shell False splitlines if line startswith device continueif '' not in line continuei... | 132 |
python-test-3488 | python | What does the code evaluate ? | a python tuple literal source where the elements are constrained to be int | def tuple eval source node ast parse source '<source>' mode 'eval' if not isinstance node body ast Tuple raise Value Error '%risnotatupleliteral' % source if not all isinstance el ast Str ast Num or isinstance el ast Unary Op and isinstance el op ast U Add ast U Sub and isinstance el operand ast Num for el in node body... | def tuple_eval source node ast parse source '<source>' mode 'eval' if not isinstance node body ast Tuple raise ValueError '%risnotatupleliteral' % source if not all isinstance el ast Str ast Num or isinstance el ast UnaryOp and isinstance el op ast UAdd ast USub and isinstance el operand ast Num for el in node body elt... | 70 |
python-test-3489 | python | Where are the elements constrained ? | a python tuple literal source | def tuple eval source node ast parse source '<source>' mode 'eval' if not isinstance node body ast Tuple raise Value Error '%risnotatupleliteral' % source if not all isinstance el ast Str ast Num or isinstance el ast Unary Op and isinstance el op ast U Add ast U Sub and isinstance el operand ast Num for el in node body... | def tuple_eval source node ast parse source '<source>' mode 'eval' if not isinstance node body ast Tuple raise ValueError '%risnotatupleliteral' % source if not all isinstance el ast Str ast Num or isinstance el ast UnaryOp and isinstance el op ast UAdd ast USub and isinstance el operand ast Num for el in node body elt... | 70 |
python-test-3494 | python | What does the code ensure ? | an apache site is disabled | def disabled name ret {'name' name 'result' True 'comment' '' 'changes' {}}is enabled salt ['apache check site enabled'] name if is enabled if opts ['test'] msg ' Apachesite{ 0 }issettobedisabled ' format name ret['comment'] msgret['changes']['old'] nameret['changes']['new'] Noneret['result'] Nonereturn retstatus salt ... | def disabled name ret {'name' name 'result' True 'comment' '' 'changes' {}}is_enabled __salt__['apache check_site_enabled'] name if is_enabled if __opts__['test'] msg 'Apachesite{0}issettobedisabled ' format name ret['comment'] msgret['changes']['old'] nameret['changes']['new'] Noneret['result'] Nonereturn retstatus __... | 92 |
python-test-3495 | python | What does the code add to a virtual service ? | a real server | def add server protocol None service address None server address None packet forward method 'dr' weight 1 **kwargs cmd '{ 0 }-a{ 1 }' format detect os build cmd protocol protocol service address service address server address server address packet forward method packet forward method weight weight **kwargs out salt ['c... | def add_server protocol None service_address None server_address None packet_forward_method 'dr' weight 1 **kwargs cmd '{0}-a{1}' format __detect_os _build_cmd protocol protocol service_address service_address server_address server_address packet_forward_method packet_forward_method weight weight **kwargs out __salt__[... | 66 |
python-test-3497 | python | What does the code get ? | ancestor random variables of input | def get ancestors x collection None if collection is None collection random variables node dict {node value node for node in collection}output set [] nodes set [x] while nodes node nodes pop if isinstance node Random Variable node node value candidate node node dict get node None if candidate node and candidate node x ... | def get_ancestors x collection None if collection is None collection random_variables node_dict {node value node for node in collection}output set [] nodes set [x] while nodes node nodes pop if isinstance node RandomVariable node node value candidate_node node_dict get node None if candidate_node and candidate_node x o... | 66 |
python-test-3504 | python | What do central convert ? | to non - central moments | def mc 2 mnc mc n len mc mean mc[ 0 ]mc [1 ] + list mc mc[ 1 ] 0mnc [1 mean]for nn m in enumerate mc[ 2 ] n nn + 2 mnc append 0 for k in range n + 1 mnc[n] + comb n k exact 1 * mc[k] * mean ** n - k return mnc[ 1 ] | def mc2mnc mc n len mc mean mc[0]mc [1] + list mc mc[1] 0mnc [1 mean]for nn m in enumerate mc[2 ] n nn + 2 mnc append 0 for k in range n + 1 mnc[n] + comb n k exact 1 * mc[k] * mean ** n - k return mnc[1 ] | 63 |
python-test-3505 | python | What converts to non - central moments ? | central | def mc 2 mnc mc n len mc mean mc[ 0 ]mc [1 ] + list mc mc[ 1 ] 0mnc [1 mean]for nn m in enumerate mc[ 2 ] n nn + 2 mnc append 0 for k in range n + 1 mnc[n] + comb n k exact 1 * mc[k] * mean ** n - k return mnc[ 1 ] | def mc2mnc mc n len mc mean mc[0]mc [1] + list mc mc[1] 0mnc [1 mean]for nn m in enumerate mc[2 ] n nn + 2 mnc append 0 for k in range n + 1 mnc[n] + comb n k exact 1 * mc[k] * mean ** n - k return mnc[1 ] | 63 |
python-test-3510 | python | What does the code convert to human readable string ? | a binary uuid | def uuid bin to str uuid block 1 block 2 block 3 struct unpack '<LHH' uuid[ 8] block 4 block 5 block 6 struct unpack '>HHL' uuid[ 8 16 ] return '% 08 x-% 04 x-% 04 x-% 04 x-% 04 x% 08 x' % block 1 block 2 block 3 block 4 block 5 block 6 | def uuid_bin_to_str uuid block1 block2 block3 struct unpack '<LHH' uuid[ 8] block4 block5 block6 struct unpack '>HHL' uuid[8 16] return '%08x-%04x-%04x-%04x-%04x%08x' % block1 block2 block3 block4 block5 block6 | 57 |
python-test-3511 | python | What does the code parse ? | the facebooklocales | def build locale table filename or file from xml dom minidom import parsedom parse filename or file reps dom get Elements By Tag Name 'representation' locs map lambda r r child Nodes[ 0 ] data reps locale map {}for loc in locs lang reg loc partition ' ' lang map locale map setdefault lang {'regs' [] 'default' reg} lang... | def _build_locale_table filename_or_file from xml dom minidom import parsedom parse filename_or_file reps dom getElementsByTagName 'representation' locs map lambda r r childNodes[0] data reps locale_map {}for loc in locs lang _ reg loc partition '_' lang_map locale_map setdefault lang {'regs' [] 'default' reg} lang_map... | 75 |
python-test-3513 | python | What does trial division use ? | to find prime factors of n | def trial division n prime factors []if n < 2 return prime factorsfor p in eratosthenes int n ** 0 5 + 1 if p * p > n breakwhile n % p 0 prime factors append p n // pif n > 1 prime factors append n return prime factors | def trial_division n prime_factors []if n < 2 return prime_factorsfor p in eratosthenes int n ** 0 5 + 1 if p * p > n breakwhile n % p 0 prime_factors append p n // pif n > 1 prime_factors append n return prime_factors | 51 |
python-test-3514 | python | What uses to find prime factors of n ? | trial division | def trial division n prime factors []if n < 2 return prime factorsfor p in eratosthenes int n ** 0 5 + 1 if p * p > n breakwhile n % p 0 prime factors append p n // pif n > 1 prime factors append n return prime factors | def trial_division n prime_factors []if n < 2 return prime_factorsfor p in eratosthenes int n ** 0 5 + 1 if p * p > n breakwhile n % p 0 prime_factors append p n // pif n > 1 prime_factors append n return prime_factors | 51 |
python-test-3515 | python | What does the code apply ? | a linear filter with coefficients a | def apply Filter data b a padding 100 bidir True try import scipy signalexcept Import Error raise Exception 'apply Filter requiresthepackagescipy signal ' d1 data view np ndarray if padding > 0 d1 np hstack [d 1 [ padding] d1 d1 [ - padding ]] if bidir d1 scipy signal lfilter b a scipy signal lfilter b a d1 [ -1 ] [ -1... | def applyFilter data b a padding 100 bidir True try import scipy signalexcept ImportError raise Exception 'applyFilter requiresthepackagescipy signal ' d1 data view np ndarray if padding > 0 d1 np hstack [d1[ padding] d1 d1[ - padding ]] if bidir d1 scipy signal lfilter b a scipy signal lfilter b a d1 [ -1 ] [ -1 ]else... | 102 |
python-test-3518 | python | What does the code remove ? | a provisioning block for an object with triggering a callback | @db api retry if session inactive def remove provisioning component context object id object type entity standard attr id None with context session begin subtransactions True standard attr id standard attr id or get standard attr id context object id object type if not standard attr id return Falserecord context sessio... | @db_api retry_if_session_inactive def remove_provisioning_component context object_id object_type entity standard_attr_id None with context session begin subtransactions True standard_attr_id standard_attr_id or _get_standard_attr_id context object_id object_type if not standard_attr_id return Falserecord context sessi... | 76 |
python-test-3523 | python | What does the code convert to add to signatures ? | the signature spec in module_info | def expand sig sig if isinstance sig tuple if len sig 3 num pos only func keyword only sigassert isinstance sig[ -1 ] tuple else num pos only func sigkeyword only sigspec signature or spec func else func sigsigspec signature or spec func num pos only num pos args sigspec keyword only keyword exclude get exclude keyword... | def expand_sig sig if isinstance sig tuple if len sig 3 num_pos_only func keyword_only sigassert isinstance sig[ -1 ] tuple else num_pos_only func sigkeyword_only sigspec signature_or_spec func else func sigsigspec signature_or_spec func num_pos_only num_pos_args sigspec keyword_only keyword_exclude get_exclude_keyword... | 72 |
python-test-3524 | python | What does the code convert the signature spec in module_info ? | to add to signatures | def expand sig sig if isinstance sig tuple if len sig 3 num pos only func keyword only sigassert isinstance sig[ -1 ] tuple else num pos only func sigkeyword only sigspec signature or spec func else func sigsigspec signature or spec func num pos only num pos args sigspec keyword only keyword exclude get exclude keyword... | def expand_sig sig if isinstance sig tuple if len sig 3 num_pos_only func keyword_only sigassert isinstance sig[ -1 ] tuple else num_pos_only func sigkeyword_only sigspec signature_or_spec func else func sigsigspec signature_or_spec func num_pos_only num_pos_args sigspec keyword_only keyword_exclude get_exclude_keyword... | 72 |
python-test-3527 | python | What does the code turn into a dict ? | a single repo file | def parse repo file filename repos {}header ''repo ''with salt utils fopen filename 'r' as rfile for line in rfile if line startswith '[' repo line strip replace '[' '' replace ']' '' repos[repo] {}if not line if not repo header + lineif line startswith '#' if not repo header + lineelse if 'comments' not in repos[repo]... | def _parse_repo_file filename repos {}header ''repo ''with salt utils fopen filename 'r' as rfile for line in rfile if line startswith '[' repo line strip replace '[' '' replace ']' '' repos[repo] {}if not line if not repo header + lineif line startswith '#' if not repo header + lineelse if 'comments' not in repos[repo... | 111 |
python-test-3528 | python | What does presend have ? | two functions | def welcome osf 4 m email from website files models import Osf Storage File Nodeif email user date last login if email user date last login > timezone now - settings WELCOME OSF 4 M WAIT TIME GRACE return Falseupload Osf Storage File Node load email data['fid'] if upload email data['downloads'] upload get download coun... | def welcome_osf4m email from website files models import OsfStorageFileNodeif email user date_last_login if email user date_last_login > timezone now - settings WELCOME_OSF4M_WAIT_TIME_GRACE return Falseupload OsfStorageFileNode load email data['fid'] if upload email data['downloads'] upload get_download_count else ema... | 62 |
python-test-3529 | python | What has two functions ? | presend | def welcome osf 4 m email from website files models import Osf Storage File Nodeif email user date last login if email user date last login > timezone now - settings WELCOME OSF 4 M WAIT TIME GRACE return Falseupload Osf Storage File Node load email data['fid'] if upload email data['downloads'] upload get download coun... | def welcome_osf4m email from website files models import OsfStorageFileNodeif email user date_last_login if email user date_last_login > timezone now - settings WELCOME_OSF4M_WAIT_TIME_GRACE return Falseupload OsfStorageFileNode load email data['fid'] if upload email data['downloads'] upload get_download_count else ema... | 62 |
python-test-3533 | python | What does the code add to multiple users ? | new media | def user addmedia userids active mediatypeid period sendto severity **connection args conn args login **connection args try if conn args method 'user addmedia'params {'users' []}if not isinstance userids list userids [userids]for user in userids params['users'] append {'userid' user} params['medias'] [{'active' active ... | def user_addmedia userids active mediatypeid period sendto severity **connection_args conn_args _login **connection_args try if conn_args method 'user addmedia'params {'users' []}if not isinstance userids list userids [userids]for user in userids params['users'] append {'userid' user} params['medias'] [{'active' active... | 65 |
python-test-3534 | python | What does the code get ? | the default domain object to use when creating identity object | def get default domain request get name True domain id request session get 'domain context' None domain name request session get 'domain context name' None if VERSIONS active > 3 and domain id is None domain id request user user domain iddomain name request user user domain nameif get name and not request user is feder... | def get_default_domain request get_name True domain_id request session get 'domain_context' None domain_name request session get 'domain_context_name' None if VERSIONS active > 3 and domain_id is None domain_id request user user_domain_iddomain_name request user user_domain_nameif get_name and not request user is_feder... | 110 |
python-test-3535 | python | For what purpose do string output return ? | for the sql to be run | def run executor sql join False expanded False pgspecial None exception formatter None results executor run sql pgspecial exception formatter formatted []for title rows headers status sql success in results formatted extend format output title rows headers status 'psql' dcmlfmt 'd' floatfmt 'g' expanded expanded if joi... | def run executor sql join False expanded False pgspecial None exception_formatter None results executor run sql pgspecial exception_formatter formatted []for title rows headers status sql success in results formatted extend format_output title rows headers status 'psql' dcmlfmt 'd' floatfmt 'g' expanded expanded if joi... | 53 |
python-test-3536 | python | What does the code return on the cloud provider ? | a dict of all custom vm images | def list custom images call None if call 'function' raise Salt Cloud System Exit ' Thelist vlansfunctionmustbecalledwith-for--function ' ret {}conn get conn ' Soft Layer Account' response conn get Block Device Template Groups for image in response if 'global Identifier' not in image continueret[image['name']] {'id' ima... | def list_custom_images call None if call 'function' raise SaltCloudSystemExit 'Thelist_vlansfunctionmustbecalledwith-for--function ' ret {}conn get_conn 'SoftLayer_Account' response conn getBlockDeviceTemplateGroups for image in response if 'globalIdentifier' not in image continueret[image['name']] {'id' image['id'] 'n... | 58 |
python-test-3537 | python | What does the code find in the given node where the given attribute has the given value ? | subnodes | def locate Nodes node List key value no Nesting 1 return List []if not isinstance node List type [] return locate Nodes node List child Nodes key value no Nesting for child Node in node List if not hasattr child Node 'get Attribute' continueif str child Node get Attribute key value return List append child Node if no N... | def locateNodes nodeList key value noNesting 1 returnList []if not isinstance nodeList type [] return locateNodes nodeList childNodes key value noNesting for childNode in nodeList if not hasattr childNode 'getAttribute' continueif str childNode getAttribute key value returnList append childNode if noNesting continueret... | 73 |
python-test-3538 | python | Where does the code find subnodes ? | in the given node where the given attribute has the given value | def locate Nodes node List key value no Nesting 1 return List []if not isinstance node List type [] return locate Nodes node List child Nodes key value no Nesting for child Node in node List if not hasattr child Node 'get Attribute' continueif str child Node get Attribute key value return List append child Node if no N... | def locateNodes nodeList key value noNesting 1 returnList []if not isinstance nodeList type [] return locateNodes nodeList childNodes key value noNesting for childNode in nodeList if not hasattr childNode 'getAttribute' continueif str childNode getAttribute key value returnList append childNode if noNesting continueret... | 73 |
python-test-3539 | python | What does the code calculate ? | the residual sum of squares | def fit eval rd B B2 fwd svd None fwd data None whitener None if fwd svd is None fwd dipole forwards fwd data whitener rd[np newaxis ] [0 ] uu sing vv linalg svd fwd overwrite a True full matrices False else uu sing vv fwd svdgof dipole gof uu sing vv B B2 [0 ]return 1 0 - gof | def _fit_eval rd B B2 fwd_svd None fwd_data None whitener None if fwd_svd is None fwd _dipole_forwards fwd_data whitener rd[np newaxis ] [0] uu sing vv linalg svd fwd overwrite_a True full_matrices False else uu sing vv fwd_svdgof _dipole_gof uu sing vv B B2 [0]return 1 0 - gof | 61 |
python-test-3540 | python | What does the code evaluate ? | the hyperbolic cos of an interval | def cosh x np import module 'numpy' if isinstance x int float return interval np cosh x np cosh x elif isinstance x interval if x start < 0 and x end > 0 end max np cosh x start np cosh x end return interval 1 end is valid x is valid else start np cosh x start end np cosh x end return interval start end is valid x is v... | def cosh x np import_module 'numpy' if isinstance x int float return interval np cosh x np cosh x elif isinstance x interval if x start < 0 and x end > 0 end max np cosh x start np cosh x end return interval 1 end is_valid x is_valid else start np cosh x start end np cosh x end return interval start end is_valid x is_v... | 78 |
python-test-3549 | python | What does the code prepare ? | a django query to be returned via rpc as a sequence of nested dictionaries | def prepare rows as nested dicts query nested dict column names all dicts []for row in query select related row dict row get object dict for column in nested dict column names if row dict[column] is not None row dict[column] getattr row column get object dict all dicts append row dict return prepare for serialization a... | def prepare_rows_as_nested_dicts query nested_dict_column_names all_dicts []for row in query select_related row_dict row get_object_dict for column in nested_dict_column_names if row_dict[column] is not None row_dict[column] getattr row column get_object_dict all_dicts append row_dict return prepare_for_serialization a... | 57 |
python-test-3552 | python | What does this function implement on the integer n ? | shors factoring algorithm | def shor N a random randrange N - 2 + 2 if igcd N a 1 print 'gotluckywithrand' return igcd N a print 'a ' a print 'N ' N r period find a N print 'r ' r if r % 2 1 print 'risnoteven beginagain' shor N answer igcd a ** r / 2 - 1 N igcd a ** r / 2 + 1 N return answer | def shor N a random randrange N - 2 + 2 if igcd N a 1 print 'gotluckywithrand' return igcd N a print 'a ' a print 'N ' N r period_find a N print 'r ' r if r % 2 1 print 'risnoteven beginagain' shor N answer igcd a ** r / 2 - 1 N igcd a ** r / 2 + 1 N return answer | 70 |
python-test-3553 | python | How does the algorithm start ? | by picking a random number ( a ) and seeing if it is coprime with n | def shor N a random randrange N - 2 + 2 if igcd N a 1 print 'gotluckywithrand' return igcd N a print 'a ' a print 'N ' N r period find a N print 'r ' r if r % 2 1 print 'risnoteven beginagain' shor N answer igcd a ** r / 2 - 1 N igcd a ** r / 2 + 1 N return answer | def shor N a random randrange N - 2 + 2 if igcd N a 1 print 'gotluckywithrand' return igcd N a print 'a ' a print 'N ' N r period_find a N print 'r ' r if r % 2 1 print 'risnoteven beginagain' shor N answer igcd a ** r / 2 - 1 N igcd a ** r / 2 + 1 N return answer | 70 |
python-test-3554 | python | What do the algorithm pick ? | a random number ( a ) | def shor N a random randrange N - 2 + 2 if igcd N a 1 print 'gotluckywithrand' return igcd N a print 'a ' a print 'N ' N r period find a N print 'r ' r if r % 2 1 print 'risnoteven beginagain' shor N answer igcd a ** r / 2 - 1 N igcd a ** r / 2 + 1 N return answer | def shor N a random randrange N - 2 + 2 if igcd N a 1 print 'gotluckywithrand' return igcd N a print 'a ' a print 'N ' N r period_find a N print 'r ' r if r % 2 1 print 'risnoteven beginagain' shor N answer igcd a ** r / 2 - 1 N igcd a ** r / 2 + 1 N return answer | 70 |
python-test-3555 | python | What is factoring algorithm on the integer n ? | shors | def shor N a random randrange N - 2 + 2 if igcd N a 1 print 'gotluckywithrand' return igcd N a print 'a ' a print 'N ' N r period find a N print 'r ' r if r % 2 1 print 'risnoteven beginagain' shor N answer igcd a ** r / 2 - 1 N igcd a ** r / 2 + 1 N return answer | def shor N a random randrange N - 2 + 2 if igcd N a 1 print 'gotluckywithrand' return igcd N a print 'a ' a print 'N ' N r period_find a N print 'r ' r if r % 2 1 print 'risnoteven beginagain' shor N answer igcd a ** r / 2 - 1 N igcd a ** r / 2 + 1 N return answer | 70 |
python-test-3556 | python | What does the code get ? | name of a caller in the format module | def caller name skip 2 stack inspect stack start 0 + skip if len stack < start + 1 return ''parentframe stack[start][ 0 ]name []module inspect getmodule parentframe if module name append module name if 'self' in parentframe f locals name append parentframe f locals['self'] class name codename parentframe f code co name... | def caller_name skip 2 stack inspect stack start 0 + skip if len stack < start + 1 return ''parentframe stack[start][0]name []module inspect getmodule parentframe if module name append module __name__ if 'self' in parentframe f_locals name append parentframe f_locals['self'] __class__ __name__ codename parentframe f_co... | 64 |
python-test-3560 | python | What does the code get ? | the query to retrieve the volume | @require contextdef volume get query context session None project only False joined load True if not joined load return model query context models Volume session session project only project only if is admin context context return model query context models Volume session session project only project only options joine... | @require_contextdef _volume_get_query context session None project_only False joined_load True if not joined_load return model_query context models Volume session session project_only project_only if is_admin_context context return model_query context models Volume session session project_only project_only options join... | 101 |
python-test-3562 | python | What matches the theano implementation ? | a numpy implementation | def test correctness model MLP layers [ Linear dim 10 layer name 'linear' irange 1 0 Softmax n classes 2 layer name 'softmax' irange 1 0 ] batch size 10 nvis 10 cost Lp Penalty variables model get params p 2 penalty cost expr model None penalty function theano function inputs [] outputs penalty p penalty function actua... | def test_correctness model MLP layers [Linear dim 10 layer_name 'linear' irange 1 0 Softmax n_classes 2 layer_name 'softmax' irange 1 0 ] batch_size 10 nvis 10 cost LpPenalty variables model get_params p 2 penalty cost expr model None penalty_function theano function inputs [] outputs penalty p penalty_function actual_... | 81 |
python-test-3563 | python | What does a numpy implementation match ? | the theano implementation | def test correctness model MLP layers [ Linear dim 10 layer name 'linear' irange 1 0 Softmax n classes 2 layer name 'softmax' irange 1 0 ] batch size 10 nvis 10 cost Lp Penalty variables model get params p 2 penalty cost expr model None penalty function theano function inputs [] outputs penalty p penalty function actua... | def test_correctness model MLP layers [Linear dim 10 layer_name 'linear' irange 1 0 Softmax n_classes 2 layer_name 'softmax' irange 1 0 ] batch_size 10 nvis 10 cost LpPenalty variables model get_params p 2 penalty cost expr model None penalty_function theano function inputs [] outputs penalty p penalty_function actual_... | 81 |
python-test-3567 | python | What does the code write ? | the cache represented by entries to a stream | def write cache entries stream extension data None Sha Stream Cls Index File SHA 1 Writer stream Sha Stream Cls stream tell stream tellwrite stream writeversion 2write 'DIRC' write pack '>LL' version len entries for entry in entries beginoffset tell write entry[ 4 ] write entry[ 5 ] path entry[ 3 ]path force bytes path... | def write_cache entries stream extension_data None ShaStreamCls IndexFileSHA1Writer stream ShaStreamCls stream tell stream tellwrite stream writeversion 2write 'DIRC' write pack '>LL' version len entries for entry in entries beginoffset tell write entry[4] write entry[5] path entry[3]path force_bytes path encoding defe... | 146 |
python-test-3574 | python | What updated on upgrade ? | submodules | @pytest mark skipif "sys platform 'win 32 '" @pytest mark networkdef test check submodule addition script module path submodule path create test package with submodule script install result script pip 'install' '-e' 'git+' + module path + '#egg version pkg' assert script venv / 'src/version-pkg/testpkg/static/testfile'... | @pytest mark skipif "sys platform 'win32'" @pytest mark networkdef test_check_submodule_addition script module_path submodule_path _create_test_package_with_submodule script install_result script pip 'install' '-e' 'git+' + module_path + '#egg version_pkg' assert script venv / 'src/version-pkg/testpkg/static/testfile' ... | 96 |
python-test-3575 | python | Where did submodules update ? | on upgrade | @pytest mark skipif "sys platform 'win 32 '" @pytest mark networkdef test check submodule addition script module path submodule path create test package with submodule script install result script pip 'install' '-e' 'git+' + module path + '#egg version pkg' assert script venv / 'src/version-pkg/testpkg/static/testfile'... | @pytest mark skipif "sys platform 'win32'" @pytest mark networkdef test_check_submodule_addition script module_path submodule_path _create_test_package_with_submodule script install_result script pip 'install' '-e' 'git+' + module_path + '#egg version_pkg' assert script venv / 'src/version-pkg/testpkg/static/testfile' ... | 96 |
python-test-3576 | python | How are submodules pulled in ? | on install | @pytest mark skipif "sys platform 'win 32 '" @pytest mark networkdef test check submodule addition script module path submodule path create test package with submodule script install result script pip 'install' '-e' 'git+' + module path + '#egg version pkg' assert script venv / 'src/version-pkg/testpkg/static/testfile'... | @pytest mark skipif "sys platform 'win32'" @pytest mark networkdef test_check_submodule_addition script module_path submodule_path _create_test_package_with_submodule script install_result script pip 'install' '-e' 'git+' + module_path + '#egg version_pkg' assert script venv / 'src/version-pkg/testpkg/static/testfile' ... | 96 |
python-test-3577 | python | What does the code delete based on the network_acl_id or network_acl_name provided ? | a network acl | def delete network acl network acl id None network acl name None disassociate False region None key None keyid None profile None if disassociate network acl get resource 'network acl' name network acl name region region key key keyid keyid profile profile if network acl and network acl associations subnet id network ac... | def delete_network_acl network_acl_id None network_acl_name None disassociate False region None key None keyid None profile None if disassociate network_acl _get_resource 'network_acl' name network_acl_name region region key key keyid keyid profile profile if network_acl and network_acl associations subnet_id network_a... | 102 |
python-test-3578 | python | How does the code delete a network acl ? | based on the network_acl_id or network_acl_name provided | def delete network acl network acl id None network acl name None disassociate False region None key None keyid None profile None if disassociate network acl get resource 'network acl' name network acl name region region key key keyid keyid profile profile if network acl and network acl associations subnet id network ac... | def delete_network_acl network_acl_id None network_acl_name None disassociate False region None key None keyid None profile None if disassociate network_acl _get_resource 'network_acl' name network_acl_name region region key key keyid keyid profile profile if network_acl and network_acl associations subnet_id network_a... | 102 |
python-test-3584 | python | Where did items describe ? | in autosummary | def process autosummary toc app doctree env app builder envcrawled {}def crawl toc node depth 1 crawled[node] Truefor j subnode in enumerate node try if isinstance subnode autosummary toc and isinstance subnode[ 0 ] addnodes toctree env note toctree env docname subnode[ 0 ] continueexcept Index Error continueif not isi... | def process_autosummary_toc app doctree env app builder envcrawled {}def crawl_toc node depth 1 crawled[node] Truefor j subnode in enumerate node try if isinstance subnode autosummary_toc and isinstance subnode[0] addnodes toctree env note_toctree env docname subnode[0] continueexcept IndexError continueif not isinstan... | 67 |
python-test-3586 | python | What marks subs ? | locator | def sub labels axis subs fmt axis get minor formatter minor tlocs axis get minorticklocs fmt set locs minor tlocs coefs minor tlocs / 10 ** np floor np log 10 minor tlocs label expected [ np round c in subs for c in coefs]label test [ fmt x u'' for x in minor tlocs]assert label test label expected | def _sub_labels axis subs fmt axis get_minor_formatter minor_tlocs axis get_minorticklocs fmt set_locs minor_tlocs coefs minor_tlocs / 10 ** np floor np log10 minor_tlocs label_expected [ np round c in subs for c in coefs]label_test [ fmt x u'' for x in minor_tlocs]assert label_test label_expected | 59 |
python-test-3588 | python | What does the code generate ? | a csv file containing a summary of the xblock usage arguments | def write block summary report course data block summary counts unique course counts get block summary totals course data with open 'xblock summary counts csv' 'wb' as csvfile summary writer csv writer csvfile delimiter ' ' quotechar '"' quoting csv QUOTE MINIMAL summary writer writerow ['XBLOCK NAME' 'UNIQUE COURSES' ... | def write_block_summary_report course_data block_summary_counts unique_course_counts _get_block_summary_totals course_data with open 'xblock_summary_counts csv' 'wb' as csvfile summary_writer csv writer csvfile delimiter ' ' quotechar '"' quoting csv QUOTE_MINIMAL summary_writer writerow ['XBLOCK_NAME' 'UNIQUE_COURSES'... | 84 |
python-test-3589 | python | What do a csv file contain ? | a summary of the xblock usage arguments | def write block summary report course data block summary counts unique course counts get block summary totals course data with open 'xblock summary counts csv' 'wb' as csvfile summary writer csv writer csvfile delimiter ' ' quotechar '"' quoting csv QUOTE MINIMAL summary writer writerow ['XBLOCK NAME' 'UNIQUE COURSES' ... | def write_block_summary_report course_data block_summary_counts unique_course_counts _get_block_summary_totals course_data with open 'xblock_summary_counts csv' 'wb' as csvfile summary_writer csv writer csvfile delimiter ' ' quotechar '"' quoting csv QUOTE_MINIMAL summary_writer writerow ['XBLOCK_NAME' 'UNIQUE_COURSES'... | 84 |
python-test-3594 | python | What does the code select ? | the best path based on origin attribute | def cmp by origin path 1 path 2 def get origin pref origin if origin value BGP ATTR ORIGIN IGP return 3elif origin value BGP ATTR ORIGIN EGP return 2elif origin value BGP ATTR ORIGIN INCOMPLETE return 1else LOG error ' Invalidoriginvalueencountered%s ' origin return 0origin 1 path 1 get pattr BGP ATTR TYPE ORIGIN origi... | def _cmp_by_origin path1 path2 def get_origin_pref origin if origin value BGP_ATTR_ORIGIN_IGP return 3elif origin value BGP_ATTR_ORIGIN_EGP return 2elif origin value BGP_ATTR_ORIGIN_INCOMPLETE return 1else LOG error 'Invalidoriginvalueencountered%s ' origin return 0origin1 path1 get_pattr BGP_ATTR_TYPE_ORIGIN origin2 p... | 117 |
python-test-3595 | python | What does the code generate ? | the dihedral group of order 2n | def dihedral n if n 1 yield Permutation [0 1] yield Permutation [1 0] elif n 2 yield Permutation [0 1 2 3] yield Permutation [1 0 3 2] yield Permutation [2 3 0 1] yield Permutation [3 2 1 0] else gen list range n for i in range n yield Permutation gen yield Permutation gen[ -1 ] gen rotate left gen 1 | def dihedral n if n 1 yield Permutation [0 1] yield Permutation [1 0] elif n 2 yield Permutation [0 1 2 3] yield Permutation [1 0 3 2] yield Permutation [2 3 0 1] yield Permutation [3 2 1 0] else gen list range n for i in range n yield Permutation gen yield Permutation gen[ -1 ] gen rotate_left gen 1 | 64 |
python-test-3598 | python | What does the code get ? | the actor of a given action based on presence of a transmit to action | def get actor tr chamber actor tr[ 0 ] text content strip if actor startswith 'H' or actor startswith 'S' actor actor[ 0 ]return {'H' 'lower' 'S' 'upper'}[actor]else h or s tr xpath 'ancestor table[ 1 ]/preceding-sibling ' + 'table/tr/td/b[contains text "TRANSMITTO" ]' if h or s h or s h or s[ -1 ] text content strip a... | def get_actor tr chamber actor tr[0] text_content strip if actor startswith 'H' or actor startswith 'S' actor actor[0]return {'H' 'lower' 'S' 'upper'}[actor]else h_or_s tr xpath 'ancestor table[1]/preceding-sibling ' + 'table/tr/td/b[contains text "TRANSMITTO" ]' if h_or_s h_or_s h_or_s[ -1 ] text_content strip actor '... | 73 |
python-test-3599 | python | What iterates in a file ? | over the extra - info descriptors | def parse file descriptor file is bridge False validate False **kwargs while True if not is bridge extrainfo content read until keywords 'router-signature' descriptor file block end prefix PGP BLOCK END split '' 1 [0 ]extrainfo content + read until keywords block end prefix descriptor file True else extrainfo content r... | def _parse_file descriptor_file is_bridge False validate False **kwargs while True if not is_bridge extrainfo_content _read_until_keywords 'router-signature' descriptor_file block_end_prefix PGP_BLOCK_END split '' 1 [0]extrainfo_content + _read_until_keywords block_end_prefix descriptor_file True else extrainfo_content... | 102 |
python-test-3600 | python | What does the code get ? | the vmotion enabled status for a given host or a list of host_names | @depends HAS PYVMOMI def get vmotion enabled host username password protocol None port None host names None service instance salt utils vmware get service instance host host username username password password protocol protocol port port host names check hosts service instance host host names ret {}for host name in hos... | @depends HAS_PYVMOMI def get_vmotion_enabled host username password protocol None port None host_names None service_instance salt utils vmware get_service_instance host host username username password password protocol protocol port port host_names _check_hosts service_instance host host_names ret {}for host_name in ho... | 96 |
python-test-3608 | python | What does flat to matrix notes need ? | to be overwritten by subclass | def gjrconvertparams self params nar nma p q nar nma ar np concatenate [1 ] params[ p] ma np zeros q + 1 3 ma[ 0 0 ] params[ -1 ]ma[ 1] np concatenate [0 ] params[p p + q ] ma[ 2] np concatenate [0 ] params[ p + q p + 2 * q ] mu params[ -1 ]params 2 ar ma return paramsclass | def gjrconvertparams self params nar nma p q nar nma ar np concatenate [1] params[ p] ma np zeros q + 1 3 ma[ 0 0 ] params[ -1 ]ma[ 1] np concatenate [0] params[p p + q ] ma[ 2] np concatenate [0] params[ p + q p + 2 * q ] mu params[ -1 ]params2 ar ma return paramsclass | 66 |
python-test-3609 | python | What needs to be overwritten by subclass ? | flat to matrix notes | def gjrconvertparams self params nar nma p q nar nma ar np concatenate [1 ] params[ p] ma np zeros q + 1 3 ma[ 0 0 ] params[ -1 ]ma[ 1] np concatenate [0 ] params[p p + q ] ma[ 2] np concatenate [0 ] params[ p + q p + 2 * q ] mu params[ -1 ]params 2 ar ma return paramsclass | def gjrconvertparams self params nar nma p q nar nma ar np concatenate [1] params[ p] ma np zeros q + 1 3 ma[ 0 0 ] params[ -1 ]ma[ 1] np concatenate [0] params[p p + q ] ma[ 2] np concatenate [0] params[ p + q p + 2 * q ] mu params[ -1 ]params2 ar ma return paramsclass | 66 |
python-test-3611 | python | What are visible here ? | all inbound tweets | def twitter inbox if not auth s3 logged in session error T ' Requires Login ' redirect URL c 'default' f 'user' args 'login' tablename 'msg twitter'table s3 db msg twitters 3 filter table inbound True table inbound readable Falses 3 crud strings[tablename] Storage title display T ' Tweet Details' title list T ' Twitter... | def twitter_inbox if not auth s3_logged_in session error T 'RequiresLogin ' redirect URL c 'default' f 'user' args 'login' tablename 'msg_twitter'table s3db msg_twitters3 filter table inbound True table inbound readable Falses3 crud_strings[tablename] Storage title_display T 'TweetDetails' title_list T 'TwitterInBox' l... | 109 |
python-test-3614 | python | What does a class provide ? | standard = = and ! = behavior | def make comparison tests klass kwargs 1 kwargs 2 def instance kwargs if isinstance kwargs dict return klass **kwargs return klass **kwargs class Tests Test Case def test equality self '\n Instanceswiththesameargumentsareequal \n'self assert True instance kwargs 1 instance kwargs 1 self assert False instance kwargs 1 i... | def make_comparison_tests klass kwargs1 kwargs2 def instance kwargs if isinstance kwargs dict return klass **kwargs return klass **kwargs class Tests TestCase def test_equality self '\nInstanceswiththesameargumentsareequal \n'self assertTrue instance kwargs1 instance kwargs1 self assertFalse instance kwargs1 instance k... | 84 |
python-test-3616 | python | How do access allow ? | via virtual - hosting style | def check dns name bucket name if ' ' in bucket name return Falsen len bucket name if n < 3 or n > 63 return Falseif n 1 if not bucket name isalnum return Falsematch LABEL RE match bucket name if match is None or match end len bucket name return Falsereturn True | def check_dns_name bucket_name if ' ' in bucket_name return Falsen len bucket_name if n < 3 or n > 63 return Falseif n 1 if not bucket_name isalnum return Falsematch LABEL_RE match bucket_name if match is None or match end len bucket_name return Falsereturn True | 54 |
python-test-3617 | python | What does the code ensure ? | storage pool is absent on the system name | def absent name export False force False ret {'name' name 'changes' {} 'result' None 'comment' ''}log debug 'zpool absent {0 } config force {1 }' format name force log debug 'zpool absent {0 } config export {1 }' format name export if salt ['zpool exists'] name ret['result'] Falseif export if opts ['test'] ret['result'... | def absent name export False force False ret {'name' name 'changes' {} 'result' None 'comment' ''}log debug 'zpool absent {0} config force {1}' format name force log debug 'zpool absent {0} config export {1}' format name export if __salt__['zpool exists'] name ret['result'] Falseif export if __opts__['test'] ret['resul... | 110 |
python-test-3620 | python | What does the code parse ? | the compiler output | def solc parse output compiler output result yaml safe load compiler output ['contracts']if 'bin' in tuple result values [0 ] for value in result values value['bin hex'] value['bin']try value['bin'] decode hex value['bin hex'] except Type Error passfor json data in 'abi' 'devdoc' 'userdoc' if json data not in tuple res... | def solc_parse_output compiler_output result yaml safe_load compiler_output ['contracts']if 'bin' in tuple result values [0] for value in result values value['bin_hex'] value['bin']try value['bin'] decode_hex value['bin_hex'] except TypeError passfor json_data in 'abi' 'devdoc' 'userdoc' if json_data not in tuple resul... | 67 |
python-test-3622 | python | What uses to check for a handshake ? | pyrit | def has handshake pyrit target capfile if not program exists 'pyrit' return Falsecmd ['pyrit' '-r' capfile 'analyze']proc Popen cmd stdout PIPE stderr DN proc wait hit essid Falsefor line in proc communicate [0 ] split '\n' if line '' or line None continueif line find ' Access Point' -1 hit essid line find " '" + targe... | def has_handshake_pyrit target capfile if not program_exists 'pyrit' return Falsecmd ['pyrit' '-r' capfile 'analyze']proc Popen cmd stdout PIPE stderr DN proc wait hit_essid Falsefor line in proc communicate [0] split '\n' if line '' or line None continueif line find 'AccessPoint' -1 hit_essid line find " '" + target s... | 90 |
python-test-3624 | python | What did code set ? | channel access | def set channel access channel 14 access update mode 'non volatile' alerting False per msg auth False user level auth False access mode 'always' privilege update mode 'non volatile' privilege level 'administrator' **kwargs with Ipmi Command **kwargs as s return s set channel access channel access update mode alerting p... | def set_channel_access channel 14 access_update_mode 'non_volatile' alerting False per_msg_auth False user_level_auth False access_mode 'always' privilege_update_mode 'non_volatile' privilege_level 'administrator' **kwargs with _IpmiCommand **kwargs as s return s set_channel_access channel access_update_mode alerting p... | 62 |
python-test-3625 | python | For what purpose does the md5 checksum return in hex ? | for the given content | def get checksum content encoding 'utf 8 ' block size 8192 md hashlib md 5 def safe update txt try md update txt except Unicode Encode Error md update txt encode encoding try isfile os path isfile content except Type Error isfile Falseif isfile with open content 'rb' as ff txt ff read block size while txt safe update t... | def get_checksum content encoding 'utf8' block_size 8192 md hashlib md5 def safe_update txt try md update txt except UnicodeEncodeError md update txt encode encoding try isfile os path isfile content except TypeError isfile Falseif isfile with open content 'rb' as ff txt ff read block_size while txt safe_update txt txt... | 100 |
python-test-3626 | python | What does the code get from the account server directly ? | listings | def direct get account node part account marker None limit None prefix None delimiter None conn timeout 5 response timeout 15 end marker None reverse None path '/' + account return get direct account container path ' Account' node part marker marker limit limit prefix prefix delimiter delimiter end marker end marker re... | def direct_get_account node part account marker None limit None prefix None delimiter None conn_timeout 5 response_timeout 15 end_marker None reverse None path '/' + account return _get_direct_account_container path 'Account' node part marker marker limit limit prefix prefix delimiter delimiter end_marker end_marker re... | 62 |
python-test-3637 | python | For what purpose do analytics event send ? | for a vote on a thread or response | def track voted event request course obj vote value undo vote False if isinstance obj cc Thread obj type 'thread'else obj type 'response'event name EVENT NAME TEMPLATE format obj type obj type action name 'voted' event data {'commentable id' obj commentable id 'target username' obj get 'username' 'undo vote' undo vote ... | def track_voted_event request course obj vote_value undo_vote False if isinstance obj cc Thread obj_type 'thread'else obj_type 'response'event_name _EVENT_NAME_TEMPLATE format obj_type obj_type action_name 'voted' event_data {'commentable_id' obj commentable_id 'target_username' obj get 'username' 'undo_vote' undo_vote... | 64 |
python-test-3638 | python | How did a bokeh application build for a file or directory ? | using a single handler | def build single handler application path argv None argv argv or [] path os path abspath path if os path isdir path handler Directory Handler filename path argv argv elif path endswith ' ipynb' handler Notebook Handler filename path argv argv elif path endswith ' py' if path endswith 'main py' warnings warn DIRSTYLE MA... | def build_single_handler_application path argv None argv argv or [] path os path abspath path if os path isdir path handler DirectoryHandler filename path argv argv elif path endswith ' ipynb' handler NotebookHandler filename path argv argv elif path endswith ' py' if path endswith 'main py' warnings warn DIRSTYLE_MAIN... | 96 |
python-test-3639 | python | What do it have ? | 2x2 blocks of block matrices | def reblock 2x 2 B if not isinstance B Block Matrix or not all d > 2 for d in B blocks shape return BBM Block Matrixreturn BM [[B blocks[ 0 0 ] BM B blocks[ 0 1 ] ] [BM B blocks[ 1 0] BM B blocks[ 1 1 ] ]] | def reblock_2x2 B if not isinstance B BlockMatrix or not all d > 2 for d in B blocks shape return BBM BlockMatrixreturn BM [[B blocks[ 0 0 ] BM B blocks[0 1 ] ] [BM B blocks[1 0] BM B blocks[1 1 ] ]] | 52 |
python-test-3640 | python | For what purpose has a blockmatrix reblock ? | so that it has 2x2 blocks of block matrices | def reblock 2x 2 B if not isinstance B Block Matrix or not all d > 2 for d in B blocks shape return BBM Block Matrixreturn BM [[B blocks[ 0 0 ] BM B blocks[ 0 1 ] ] [BM B blocks[ 1 0] BM B blocks[ 1 1 ] ]] | def reblock_2x2 B if not isinstance B BlockMatrix or not all d > 2 for d in B blocks shape return BBM BlockMatrixreturn BM [[B blocks[ 0 0 ] BM B blocks[0 1 ] ] [BM B blocks[1 0] BM B blocks[1 1 ] ]] | 52 |
python-test-3644 | python | For what purpose do sitewide totals aggregate ? | for self - serve promotion traffic | def totals cls interval time points get time points interval q Session query cls date sum cls pageview count label 'sum' filter cls interval interval filter cls date in time points filter cls codename startswith Link type prefix group by cls date order by desc cls date return fill gaps time points q 'sum' | def totals cls interval time_points get_time_points interval q Session query cls date sum cls pageview_count label 'sum' filter cls interval interval filter cls date in_ time_points filter cls codename startswith Link _type_prefix group_by cls date order_by desc cls date return fill_gaps time_points q 'sum' | 54 |
python-test-3645 | python | What iterates in a package ? | over all modules | def iter modules path import osimport pkgutilif hasattr pkgutil 'iter modules' for importer modname ispkg in pkgutil iter modules path yield modname ispkg returnfrom inspect import getmodulenamefrom pydoc import ispackagefound set for path in path for filename in os listdir path p os path join path filename modname get... | def _iter_modules path import osimport pkgutilif hasattr pkgutil 'iter_modules' for importer modname ispkg in pkgutil iter_modules path yield modname ispkg returnfrom inspect import getmodulenamefrom pydoc import ispackagefound set for path in path for filename in os listdir path p os path join path filename modname ge... | 69 |
python-test-3648 | python | For what purpose has a view function modifies ? | so that its response has the x - frame - options http header set to deny if the request http referrer is not from a whitelisted hostname | def xframe allow whitelisted view func def wrapped view request *args **kwargs ' Modifytheresponsewiththecorrect X- Frame- Options 'resp view func request *args **kwargs x frame option 'DENY'if settings FEATURES['ENABLE THIRD PARTY AUTH'] referer request META get 'HTTP REFERER' if referer is not None parsed url urlpars... | def xframe_allow_whitelisted view_func def wrapped_view request *args **kwargs 'ModifytheresponsewiththecorrectX-Frame-Options 'resp view_func request *args **kwargs x_frame_option 'DENY'if settings FEATURES['ENABLE_THIRD_PARTY_AUTH'] referer request META get 'HTTP_REFERER' if referer is not None parsed_url urlparse re... | 84 |
python-test-3649 | python | What does the code compute ? | the gcd of two polynomials in trivial cases | def trivial gcd f g ring f ringif not f or g return ring zero ring zero ring zero elif not f if g LC < ring domain zero return - g ring zero - ring one else return g ring zero ring one elif not g if f LC < ring domain zero return - f - ring one ring zero else return f ring one ring zero return None | def _trivial_gcd f g ring f ringif not f or g return ring zero ring zero ring zero elif not f if g LC < ring domain zero return - g ring zero - ring one else return g ring zero ring one elif not g if f LC < ring domain zero return - f - ring one ring zero else return f ring one ring zero return None | 71 |
python-test-3650 | python | What does an ordereddict map to its headers in the final report ? | a scorable blocks i d | def graded scorable blocks to header course key scorable blocks map Ordered Dict grading context grading context for course course key for assignment type name subsection infos in grading context['all graded subsections by type'] iteritems for subsection index subsection info in enumerate subsection infos start 1 for s... | def _graded_scorable_blocks_to_header course_key scorable_blocks_map OrderedDict grading_context grading_context_for_course course_key for assignment_type_name subsection_infos in grading_context['all_graded_subsections_by_type'] iteritems for subsection_index subsection_info in enumerate subsection_infos start 1 for s... | 108 |
python-test-3651 | python | Where does an ordereddict map a scorable blocks i d to its headers ? | in the final report | def graded scorable blocks to header course key scorable blocks map Ordered Dict grading context grading context for course course key for assignment type name subsection infos in grading context['all graded subsections by type'] iteritems for subsection index subsection info in enumerate subsection infos start 1 for s... | def _graded_scorable_blocks_to_header course_key scorable_blocks_map OrderedDict grading_context grading_context_for_course course_key for assignment_type_name subsection_infos in grading_context['all_graded_subsections_by_type'] iteritems for subsection_index subsection_info in enumerate subsection_infos start 1 for s... | 108 |
python-test-3653 | python | What do emails send ? | to notify the given recipients about new suggestion | def send suggestion email exploration title exploration id author id recipient list email subject ' Newsuggestionfor"%s"' % exploration title email body template ' Hi%s <br>%shassubmittedanewsuggestionforyour Oppiaexploration <ahref "https //www oppia org/create/%s">"%s"</a> <br> Youcanacceptorrejectthissuggestionbyvis... | def send_suggestion_email exploration_title exploration_id author_id recipient_list email_subject 'Newsuggestionfor"%s"' % exploration_title email_body_template 'Hi%s <br>%shassubmittedanewsuggestionforyourOppiaexploration <ahref "https //www oppia org/create/%s">"%s"</a> <br>Youcanacceptorrejectthissuggestionbyvisitin... | 157 |
python-test-3654 | python | What do emails notify about new suggestion ? | the given recipients | def send suggestion email exploration title exploration id author id recipient list email subject ' Newsuggestionfor"%s"' % exploration title email body template ' Hi%s <br>%shassubmittedanewsuggestionforyour Oppiaexploration <ahref "https //www oppia org/create/%s">"%s"</a> <br> Youcanacceptorrejectthissuggestionbyvis... | def send_suggestion_email exploration_title exploration_id author_id recipient_list email_subject 'Newsuggestionfor"%s"' % exploration_title email_body_template 'Hi%s <br>%shassubmittedanewsuggestionforyourOppiaexploration <ahref "https //www oppia org/create/%s">"%s"</a> <br>Youcanacceptorrejectthissuggestionbyvisitin... | 157 |
python-test-3655 | python | What describe the removal of each respective results affected code ? | all files in file_dict | def remove result ranges diffs result list file dict result diff dict dict {}for original result in result list mod file dict copy deepcopy file dict source ranges []previous Nonefor source range in sorted original result affected code reverse True if previous is not None and source range overlaps previous combined sr ... | def remove_result_ranges_diffs result_list file_dict result_diff_dict_dict {}for original_result in result_list mod_file_dict copy deepcopy file_dict source_ranges []previous Nonefor source_range in sorted original_result affected_code reverse True if previous is not None and source_range overlaps previous combined_sr ... | 137 |
python-test-3656 | python | What does the code calculate ? | the diffs to all files in file_dict that describe the removal of each respective results affected code | def remove result ranges diffs result list file dict result diff dict dict {}for original result in result list mod file dict copy deepcopy file dict source ranges []previous Nonefor source range in sorted original result affected code reverse True if previous is not None and source range overlaps previous combined sr ... | def remove_result_ranges_diffs result_list file_dict result_diff_dict_dict {}for original_result in result_list mod_file_dict copy deepcopy file_dict source_ranges []previous Nonefor source_range in sorted original_result affected_code reverse True if previous is not None and source_range overlaps previous combined_sr ... | 137 |
python-test-3657 | python | What do all files in file_dict describe ? | the removal of each respective results affected code | def remove result ranges diffs result list file dict result diff dict dict {}for original result in result list mod file dict copy deepcopy file dict source ranges []previous Nonefor source range in sorted original result affected code reverse True if previous is not None and source range overlaps previous combined sr ... | def remove_result_ranges_diffs result_list file_dict result_diff_dict_dict {}for original_result in result_list mod_file_dict copy deepcopy file_dict source_ranges []previous Nonefor source_range in sorted original_result affected_code reverse True if previous is not None and source_range overlaps previous combined_sr ... | 137 |
python-test-3658 | python | What does the code collect ? | some data : number of open shards | def get info for reshard stream details min hash key 0max hash key 0stream details[' Open Shards'] []for shard in stream details[' Shards'] shard id shard[' Shard Id']if ' Ending Sequence Number' in shard[' Sequence Number Range'] log debug 'skippingclosedshard{ 0 }' format shard id continuestream details[' Open Shards... | def get_info_for_reshard stream_details min_hash_key 0max_hash_key 0stream_details['OpenShards'] []for shard in stream_details['Shards'] shard_id shard['ShardId']if 'EndingSequenceNumber' in shard['SequenceNumberRange'] log debug 'skippingclosedshard{0}' format shard_id continuestream_details['OpenShards'] append shard... | 151 |
python-test-3660 | python | What do you want ? | to deploy to | def get deployment engine class provider engine path PROVIDER MAPPING get provider None logger debug ' Loading Deployment Enginefor%s %s' provider engine path if engine path is None return None module engine engine path rsplit ' ' 1 try mod import module fromlist [engine] except Import Error as e logger error ' Unablet... | def get_deployment_engine_class provider engine_path PROVIDER_MAPPING get provider None logger debug 'LoadingDeploymentEnginefor%s %s' provider engine_path if engine_path is None return None module engine engine_path rsplit ' ' 1 try _mod __import__ module fromlist [engine] except ImportError as e logger error 'Unablet... | 73 |
python-test-3663 | python | What does the code see ? | approx_fprime | def approx fprime helper xk f epsilon args f0 None if f0 is None f0 f * xk + args grad numpy zeros len xk float ei numpy zeros len xk float for k in range len xk ei[k] 1 0d epsilon * ei grad[k] f * xk + d + args - f0 / d[k] ei[k] 0 0return grad | def _approx_fprime_helper xk f epsilon args f0 None if f0 is None f0 f * xk + args grad numpy zeros len xk float ei numpy zeros len xk float for k in range len xk ei[k] 1 0d epsilon * ei grad[k] f * xk + d + args - f0 / d[k] ei[k] 0 0return grad | 60 |
python-test-3664 | python | Will this method raise the indices ? | No | def substitute indices t *index tuples if not isinstance t Tens Expr return tfree t freefree 1 []for j ipos cpos in free for i v in index tuples if i name j name and i tensortype j tensortype if i is up j is up free 1 append v ipos cpos else free 1 append - v ipos cpos breakelse free 1 append j ipos cpos t Tens Mul fro... | def substitute_indices t *index_tuples if not isinstance t TensExpr return tfree t freefree1 []for j ipos cpos in free for i v in index_tuples if i _name j _name and i _tensortype j _tensortype if i _is_up j _is_up free1 append v ipos cpos else free1 append - v ipos cpos breakelse free1 append j ipos cpos t TensMul fro... | 82 |
python-test-3665 | python | What will this method neither raise ? | the indices | def substitute indices t *index tuples if not isinstance t Tens Expr return tfree t freefree 1 []for j ipos cpos in free for i v in index tuples if i name j name and i tensortype j tensortype if i is up j is up free 1 append v ipos cpos else free 1 append - v ipos cpos breakelse free 1 append j ipos cpos t Tens Mul fro... | def substitute_indices t *index_tuples if not isinstance t TensExpr return tfree t freefree1 []for j ipos cpos in free for i v in index_tuples if i _name j _name and i _tensortype j _tensortype if i _is_up j _is_up free1 append v ipos cpos else free1 append - v ipos cpos breakelse free1 append j ipos cpos t TensMul fro... | 82 |
python-test-3667 | python | How does decorator check the fixture ? | with a product set of dtypes | def for dtypes combination types names 'dtype' full None if full is None full int os environ get 'CUPY TEST FULL COMBINATION' '0 ' 0 if full combination parameterized product {name types for name in names} else ts []for in range len names t list types random shuffle t ts append t combination [dict zip names typs for ty... | def for_dtypes_combination types names 'dtype' full None if full is None full int os environ get 'CUPY_TEST_FULL_COMBINATION' '0' 0 if full combination parameterized product {name types for name in names} else ts []for _ in range len names t list types random shuffle t ts append t combination [dict zip names typs for t... | 100 |
python-test-3676 | python | What do a coverage file load ? | from an open file object | def load coverage F header length 6 dtype np int 16 header [F readline for i in range header length ]make tuple lambda t t split [0 ] float t split [1 ] header dict [make tuple line for line in header] M np loadtxt F dtype dtype nodata int header['NODATA value'] if nodata -9999 M[nodata] -9999 return M | def _load_coverage F header_length 6 dtype np int16 header [F readline for i in range header_length ]make_tuple lambda t t split [0] float t split [1] header dict [make_tuple line for line in header] M np loadtxt F dtype dtype nodata int header['NODATA_value'] if nodata -9999 M[nodata] -9999 return M | 59 |
python-test-3677 | python | What loads from an open file object ? | a coverage file | def load coverage F header length 6 dtype np int 16 header [F readline for i in range header length ]make tuple lambda t t split [0 ] float t split [1 ] header dict [make tuple line for line in header] M np loadtxt F dtype dtype nodata int header['NODATA value'] if nodata -9999 M[nodata] -9999 return M | def _load_coverage F header_length 6 dtype np int16 header [F readline for i in range header_length ]make_tuple lambda t t split [0] float t split [1] header dict [make_tuple line for line in header] M np loadtxt F dtype dtype nodata int header['NODATA_value'] if nodata -9999 M[nodata] -9999 return M | 59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.