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-459
python
What does a compatibility function provide ?
the logic for nspawn
@ ensure existsdef stop name kill False if sd version > 219 if kill action 'terminate'else action 'poweroff'ret machinectl '{ 0 }{ 1 }' format action name else cmd 'systemctlstopsystemd-nspawn@{ 0 }' format name ret salt ['cmd run all'] cmd python shell False if ret['retcode'] 0 context ['retcode'] salt defaults exitco...
@_ensure_existsdef stop name kill False if _sd_version > 219 if kill action 'terminate'else action 'poweroff'ret _machinectl '{0}{1}' format action name else cmd 'systemctlstopsystemd-nspawn@{0}' format name ret __salt__['cmd run_all'] cmd python_shell False if ret['retcode'] 0 __context__['retcode'] salt defaults exit...
56
python-test-464
python
What does the user own ?
a given file symlinks
def get uid path follow symlinks True if not os path exists path return Falseif follow symlinks and sys getwindowsversion major > 6 path resolve symlink path try secdesc win 32 security Get File Security path win 32 security OWNER SECURITY INFORMATION except Memory Error return 'S- 1 - 1 - 0 'except pywinerror as exc i...
def get_uid path follow_symlinks True if not os path exists path return Falseif follow_symlinks and sys getwindowsversion major > 6 path _resolve_symlink path try secdesc win32security GetFileSecurity path win32security OWNER_SECURITY_INFORMATION except MemoryError return 'S-1-1-0'except pywinerror as exc if exc winerr...
89
python-test-466
python
How did a file open elsewhere already ?
in read - only mode
def test read hdf multiply open pytest importorskip 'tables' df pd Data Frame {'x' ['a' 'b' 'c' 'd'] 'y' [1 2 3 4]} index [1 0 2 0 3 0 4 0] with tmpfile 'h 5 ' as fn df to hdf fn '/data' format 'table' with pd HDF Store fn mode 'r' dd read hdf fn '/data' chunksize 2 mode 'r'
def test_read_hdf_multiply_open pytest importorskip 'tables' df pd DataFrame {'x' ['a' 'b' 'c' 'd'] 'y' [1 2 3 4]} index [1 0 2 0 3 0 4 0] with tmpfile 'h5' as fn df to_hdf fn '/data' format 'table' with pd HDFStore fn mode 'r' dd read_hdf fn '/data' chunksize 2 mode 'r'
62
python-test-470
python
What does mongo - db build wrapper initaliz while running the build ?
a mongodb database
def mongo db registry xml parent data mongodb XML Sub Element xml parent 'org jenkinsci plugins mongodb Mongo Build Wrapper' mongodb set 'plugin' 'mongodb' mapping [ 'name' 'mongodb Name' None 'port' 'port' '' 'data-directory' 'dbpath' '' 'startup-params' 'parameters' '' 'start-timeout' 'start Timeout' 0 ]convert mappi...
def mongo_db registry xml_parent data mongodb XML SubElement xml_parent 'org jenkinsci plugins mongodb MongoBuildWrapper' mongodb set 'plugin' 'mongodb' mapping [ 'name' 'mongodbName' None 'port' 'port' '' 'data-directory' 'dbpath' '' 'startup-params' 'parameters' '' 'start-timeout' 'startTimeout' 0 ]convert_mapping_to...
53
python-test-471
python
When does mongo - db build wrapper initaliz a mongodb database ?
while running the build
def mongo db registry xml parent data mongodb XML Sub Element xml parent 'org jenkinsci plugins mongodb Mongo Build Wrapper' mongodb set 'plugin' 'mongodb' mapping [ 'name' 'mongodb Name' None 'port' 'port' '' 'data-directory' 'dbpath' '' 'startup-params' 'parameters' '' 'start-timeout' 'start Timeout' 0 ]convert mappi...
def mongo_db registry xml_parent data mongodb XML SubElement xml_parent 'org jenkinsci plugins mongodb MongoBuildWrapper' mongodb set 'plugin' 'mongodb' mapping [ 'name' 'mongodbName' None 'port' 'port' '' 'data-directory' 'dbpath' '' 'startup-params' 'parameters' '' 'start-timeout' 'startTimeout' 0 ]convert_mapping_to...
53
python-test-485
python
What do lib2to3 use ?
to refactor the source
def refactor with 2to 3 source text fixer names filename u'' from lib 2 to 3 refactor import Refactoring Toolfixers [ u'lib 2 to 3 fixes fix ' + name for name in fixer names]tool Refactoring Tool fixer names fixers explicit fixers from lib 2 to 3 pgen 2 import tokenize as lib 2 to 3 tokenizetry return unicode tool refa...
def refactor_with_2to3 source_text fixer_names filename u'' from lib2to3 refactor import RefactoringToolfixers [ u'lib2to3 fixes fix_' + name for name in fixer_names]tool RefactoringTool fixer_names fixers explicit fixers from lib2to3 pgen2 import tokenize as lib2to3_tokenizetry return unicode tool refactor_string sour...
77
python-test-486
python
What use to refactor the source ?
lib2to3
def refactor with 2to 3 source text fixer names filename u'' from lib 2 to 3 refactor import Refactoring Toolfixers [ u'lib 2 to 3 fixes fix ' + name for name in fixer names]tool Refactoring Tool fixer names fixers explicit fixers from lib 2 to 3 pgen 2 import tokenize as lib 2 to 3 tokenizetry return unicode tool refa...
def refactor_with_2to3 source_text fixer_names filename u'' from lib2to3 refactor import RefactoringToolfixers [ u'lib2to3 fixes fix_' + name for name in fixer_names]tool RefactoringTool fixer_names fixers explicit fixers from lib2to3 pgen2 import tokenize as lib2to3_tokenizetry return unicode tool refactor_string sour...
77
python-test-488
python
What does the code find ?
the node that has an op of of type cls in v
def find node v cls ignore clients False if v owner is not None and ignore clients or len v clients 1 if isinstance v owner op cls return v ownerelif isinstance v owner op Gpu From Host and v owner inputs[ 0 ] owner is not None and ignore clients or len v owner inputs[ 0 ] clients 1 and isinstance v owner inputs[ 0 ] o...
def find_node v cls ignore_clients False if v owner is not None and ignore_clients or len v clients 1 if isinstance v owner op cls return v ownerelif isinstance v owner op GpuFromHost and v owner inputs[0] owner is not None and ignore_clients or len v owner inputs[0] clients 1 and isinstance v owner inputs[0] owner op ...
88
python-test-489
python
What does the node have ?
an op of of type cls in v
def find node v cls ignore clients False if v owner is not None and ignore clients or len v clients 1 if isinstance v owner op cls return v ownerelif isinstance v owner op Gpu From Host and v owner inputs[ 0 ] owner is not None and ignore clients or len v owner inputs[ 0 ] clients 1 and isinstance v owner inputs[ 0 ] o...
def find_node v cls ignore_clients False if v owner is not None and ignore_clients or len v clients 1 if isinstance v owner op cls return v ownerelif isinstance v owner op GpuFromHost and v owner inputs[0] owner is not None and ignore_clients or len v owner inputs[0] clients 1 and isinstance v owner inputs[0] owner op ...
88
python-test-492
python
How does the code make schema ?
by getting all valid combinations and making sure that all keys are available
def make full schema data schema flattened schema flatten schema schema key combinations get all key combinations data flattened schema full schema {}for combination in key combinations sub schema schemafor key in combination[ 2] sub schema sub schema[key]for key value in sub schema iteritems if isinstance value list f...
def make_full_schema data schema flattened_schema flatten_schema schema key_combinations get_all_key_combinations data flattened_schema full_schema {}for combination in key_combinations sub_schema schemafor key in combination[ 2] sub_schema sub_schema[key]for key value in sub_schema iteritems if isinstance value list f...
57
python-test-494
python
What requires the jenkins : jenkins - wiki : slack plugin < slack+plugin > when using slack plugin version < 2 ?
slack
def slack registry xml parent data logger logging get Logger name plugin info registry get plugin info ' Slack Notification Plugin' plugin ver pkg resources parse version plugin info get 'version' '0 ' if plugin ver > pkg resources parse version '2 0' logger warn 'propertiessectionisnotusedwithpluginversion> 2 0' mappi...
def slack registry xml_parent data logger logging getLogger __name__ plugin_info registry get_plugin_info 'SlackNotificationPlugin' plugin_ver pkg_resources parse_version plugin_info get 'version' '0' if plugin_ver > pkg_resources parse_version '2 0' logger warn 'propertiessectionisnotusedwithpluginversion> 2 0' mappin...
144
python-test-495
python
What does slack require ?
the jenkins : jenkins - wiki : slack plugin < slack+plugin > when using slack plugin version < 2
def slack registry xml parent data logger logging get Logger name plugin info registry get plugin info ' Slack Notification Plugin' plugin ver pkg resources parse version plugin info get 'version' '0 ' if plugin ver > pkg resources parse version '2 0' logger warn 'propertiessectionisnotusedwithpluginversion> 2 0' mappi...
def slack registry xml_parent data logger logging getLogger __name__ plugin_info registry get_plugin_info 'SlackNotificationPlugin' plugin_ver pkg_resources parse_version plugin_info get 'version' '0' if plugin_ver > pkg_resources parse_version '2 0' logger warn 'propertiessectionisnotusedwithpluginversion> 2 0' mappin...
144
python-test-496
python
What does the code get ?
information about the defined api deployments
def describe api deployments rest Api Id region None key None keyid None profile None try conn get conn region region key key keyid keyid profile profile deployments [] deployments conn get deployments rest Api Id rest Api Id while True if deployments deployments deployments + deployments['items'] if 'position' not in ...
def describe_api_deployments restApiId region None key None keyid None profile None try conn _get_conn region region key key keyid keyid profile profile deployments []_deployments conn get_deployments restApiId restApiId while True if _deployments deployments deployments + _deployments['items'] if 'position' not in _de...
90
python-test-497
python
What does the code write ?
optional metadata tag to stream
def write metadata tag stream metadata SCRIPT TAG '\x 12 'FLV TAG HEADER LEN 11 if metadata stream write SCRIPT TAG write unsigned int 24 stream len metadata stream write '\x 00 \x 00 \x 00 \x 00 \x 00 \x 00 \x 00 ' stream write metadata write unsigned int stream FLV TAG HEADER LEN + len metadata
def write_metadata_tag stream metadata SCRIPT_TAG '\x12'FLV_TAG_HEADER_LEN 11if metadata stream write SCRIPT_TAG write_unsigned_int_24 stream len metadata stream write '\x00\x00\x00\x00\x00\x00\x00' stream write metadata write_unsigned_int stream FLV_TAG_HEADER_LEN + len metadata
59
python-test-498
python
What do users not have on new_node ?
permissions
def users to remove source event source node new node Notification Subscription apps get model 'osf Notification Subscription' removed users {key [] for key in constants NOTIFICATION TYPES}if source node new node return removed usersold sub Notification Subscription load to subscription key source node id source event ...
def users_to_remove source_event source_node new_node NotificationSubscription apps get_model 'osf NotificationSubscription' removed_users {key [] for key in constants NOTIFICATION_TYPES}if source_node new_node return removed_usersold_sub NotificationSubscription load to_subscription_key source_node _id source_event ol...
127
python-test-499
python
Where do users not have permissions ?
on new_node
def users to remove source event source node new node Notification Subscription apps get model 'osf Notification Subscription' removed users {key [] for key in constants NOTIFICATION TYPES}if source node new node return removed usersold sub Notification Subscription load to subscription key source node id source event ...
def users_to_remove source_event source_node new_node NotificationSubscription apps get_model 'osf NotificationSubscription' removed_users {key [] for key in constants NOTIFICATION_TYPES}if source_node new_node return removed_usersold_sub NotificationSubscription load to_subscription_key source_node _id source_event ol...
127
python-test-500
python
What do not have permissions on new_node ?
users
def users to remove source event source node new node Notification Subscription apps get model 'osf Notification Subscription' removed users {key [] for key in constants NOTIFICATION TYPES}if source node new node return removed usersold sub Notification Subscription load to subscription key source node id source event ...
def users_to_remove source_event source_node new_node NotificationSubscription apps get_model 'osf NotificationSubscription' removed_users {key [] for key in constants NOTIFICATION_TYPES}if source_node new_node return removed_usersold_sub NotificationSubscription load to_subscription_key source_node _id source_event ol...
127
python-test-501
python
Do users have permissions on new_node ?
No
def users to remove source event source node new node Notification Subscription apps get model 'osf Notification Subscription' removed users {key [] for key in constants NOTIFICATION TYPES}if source node new node return removed usersold sub Notification Subscription load to subscription key source node id source event ...
def users_to_remove source_event source_node new_node NotificationSubscription apps get_model 'osf NotificationSubscription' removed_users {key [] for key in constants NOTIFICATION_TYPES}if source_node new_node return removed_usersold_sub NotificationSubscription load to_subscription_key source_node _id source_event ol...
127
python-test-504
python
What does the code ensure ?
roundtripping
def test predefined string roundtrip with u magnitude zero points enable assert u Unit u S Tmag to string u S Tmag assert u Unit u A Bmag to string u A Bmag assert u Unit u M bol to string u M bol assert u Unit u m bol to string u m bol
def test_predefined_string_roundtrip with u magnitude_zero_points enable assert u Unit u STmag to_string u STmag assert u Unit u ABmag to_string u ABmag assert u Unit u M_bol to_string u M_bol assert u Unit u m_bol to_string u m_bol
55
python-test-505
python
What splits into two separate segment divided at * t * ?
a bezier segment defined by its controlpoints * beta *
def split de casteljau beta t beta np asarray beta beta list [beta]while True beta de casteljau 1 beta t beta list append beta if len beta 1 breakleft beta [beta[ 0 ] for beta in beta list]right beta [beta[ -1 ] for beta in reversed beta list ]return left beta right beta
def split_de_casteljau beta t beta np asarray beta beta_list [beta]while True beta _de_casteljau1 beta t beta_list append beta if len beta 1 breakleft_beta [beta[0] for beta in beta_list]right_beta [beta[ -1 ] for beta in reversed beta_list ]return left_beta right_beta
53
python-test-506
python
What do a bezier segment defined by its controlpoints * beta * split ?
into two separate segment divided at * t *
def split de casteljau beta t beta np asarray beta beta list [beta]while True beta de casteljau 1 beta t beta list append beta if len beta 1 breakleft beta [beta[ 0 ] for beta in beta list]right beta [beta[ -1 ] for beta in reversed beta list ]return left beta right beta
def split_de_casteljau beta t beta np asarray beta beta_list [beta]while True beta _de_casteljau1 beta t beta_list append beta if len beta 1 breakleft_beta [beta[0] for beta in beta_list]right_beta [beta[ -1 ] for beta in reversed beta_list ]return left_beta right_beta
53
python-test-509
python
For what purpose do the revision rev ?
to update to force : false force an update user
def update cwd rev force False user None cmd ['hg' 'update' '{ 0 }' format rev ]if force cmd append '-C' ret salt ['cmd run all'] cmd cwd cwd runas user python shell False if ret['retcode'] 0 raise Command Execution Error ' Hgcommandfailed {0 }' format ret get 'stderr' ret['stdout'] return ret['stdout']
def update cwd rev force False user None cmd ['hg' 'update' '{0}' format rev ]if force cmd append '-C' ret __salt__['cmd run_all'] cmd cwd cwd runas user python_shell False if ret['retcode'] 0 raise CommandExecutionError 'Hgcommandfailed {0}' format ret get 'stderr' ret['stdout'] return ret['stdout']
52
python-test-511
python
What does the code make ?
dask
def intersect chunks old chunks new chunks cmo cumdims label old chunks 'o' cmn cumdims label new chunks 'n' sums [sum o for o in old chunks]sums 2 [sum n for n in old chunks]if not sums sums 2 raise Value Error ' Cannotchangedimensionsfromto%r' % sums 2 old to new [ intersect 1d breakpoints cm[ 0 ] cm[ 1 ] for cm in z...
def intersect_chunks old_chunks new_chunks cmo cumdims_label old_chunks 'o' cmn cumdims_label new_chunks 'n' sums [sum o for o in old_chunks]sums2 [sum n for n in old_chunks]if not sums sums2 raise ValueError 'Cannotchangedimensionsfromto%r' % sums2 old_to_new [_intersect_1d _breakpoints cm[0] cm[1] for cm in zip cmo c...
84
python-test-524
python
What does the code mutate according to its : attr : strategy attribute as described in [ beyer2002 ] ?
an evolution strategy
def mut ES Log Normal individual c indpb size len individual t c / math sqrt 2 0 * math sqrt size t0 c / math sqrt 2 0 * size n random gauss 0 1 t0 n t0 * n for indx in xrange size if random random < indpb individual strategy[indx] * math exp t0 n + t * random gauss 0 1 individual[indx] + individual strategy[indx] * ra...
def mutESLogNormal individual c indpb size len individual t c / math sqrt 2 0 * math sqrt size t0 c / math sqrt 2 0 * size n random gauss 0 1 t0_n t0 * n for indx in xrange size if random random < indpb individual strategy[indx] * math exp t0_n + t * random gauss 0 1 individual[indx] + individual strategy[indx] * rando...
76
python-test-525
python
How does the code mutate an evolution strategy ?
according to its : attr : strategy attribute as described in [ beyer2002 ]
def mut ES Log Normal individual c indpb size len individual t c / math sqrt 2 0 * math sqrt size t0 c / math sqrt 2 0 * size n random gauss 0 1 t0 n t0 * n for indx in xrange size if random random < indpb individual strategy[indx] * math exp t0 n + t * random gauss 0 1 individual[indx] + individual strategy[indx] * ra...
def mutESLogNormal individual c indpb size len individual t c / math sqrt 2 0 * math sqrt size t0 c / math sqrt 2 0 * size n random gauss 0 1 t0_n t0 * n for indx in xrange size if random random < indpb individual strategy[indx] * math exp t0_n + t * random gauss 0 1 individual[indx] + individual strategy[indx] * rando...
76
python-test-540
python
What provides the given package ?
the address from the given addressfamilies
@printing funcdef select package address jvm package name address families addresses [address for address family in address families for address in address family addressables keys ]if len addresses 0 raise Value Error u' Notargetsexistedin{}toprovide{}' format address families jvm package name elif len addresses > 1 r...
@printing_funcdef select_package_address jvm_package_name address_families addresses [address for address_family in address_families for address in address_family addressables keys ]if len addresses 0 raise ValueError u'Notargetsexistedin{}toprovide{}' format address_families jvm_package_name elif len addresses > 1 rai...
67
python-test-541
python
What does the address from the given addressfamilies provide ?
the given package
@printing funcdef select package address jvm package name address families addresses [address for address family in address families for address in address family addressables keys ]if len addresses 0 raise Value Error u' Notargetsexistedin{}toprovide{}' format address families jvm package name elif len addresses > 1 r...
@printing_funcdef select_package_address jvm_package_name address_families addresses [address for address_family in address_families for address in address_family addressables keys ]if len addresses 0 raise ValueError u'Notargetsexistedin{}toprovide{}' format address_families jvm_package_name elif len addresses > 1 rai...
67
python-test-542
python
For what purpose does all series_fields populate based on parser ?
for given entry
def populate entry fields entry parser config entry[u'series parser'] copy parser entry[u'series name'] parser nameif u'quality' in entry and entry[u'quality'] parser quality log verbose u' Founddifferentqualityfor%s Was%s overridingwith%s ' % entry[u'title'] entry[u'quality'] parser quality entry[u'quality'] parser qu...
def populate_entry_fields entry parser config entry[u'series_parser'] copy parser entry[u'series_name'] parser nameif u'quality' in entry and entry[u'quality'] parser quality log verbose u'Founddifferentqualityfor%s Was%s overridingwith%s ' % entry[u'title'] entry[u'quality'] parser quality entry[u'quality'] parser qua...
124
python-test-550
python
What does the code add to the given namespace ?
a new mako template lookup directory
def add lookup namespace directory package None prepend False templates LOOKUP get namespace if not templates LOOKUP[namespace] templates Dynamic Template Lookup module directory settings MAKO MODULE DIR output encoding 'utf- 8 ' input encoding 'utf- 8 ' default filters ['decode utf 8 '] encoding errors 'replace' if pa...
def add_lookup namespace directory package None prepend False templates LOOKUP get namespace if not templates LOOKUP[namespace] templates DynamicTemplateLookup module_directory settings MAKO_MODULE_DIR output_encoding 'utf-8' input_encoding 'utf-8' default_filters ['decode utf8'] encoding_errors 'replace' if package di...
61
python-test-551
python
What does the code create ?
a permalinked map
def snapshot create request conf request bodyif isinstance conf basestring config json loads conf snapshot Map Snapshot objects create config clean config conf map Map objects get id config['id'] return Http Response num encode snapshot id content type 'text/plain' else return Http Response ' Invalid JSON' content type...
def snapshot_create request conf request bodyif isinstance conf basestring config json loads conf snapshot MapSnapshot objects create config clean_config conf map Map objects get id config['id'] return HttpResponse num_encode snapshot id content_type 'text/plain' else return HttpResponse 'InvalidJSON' content_type 'tex...
51
python-test-556
python
Where does the code play a movie ?
in a window
def play Movie In Window the Window the File movie Box the Movie load Movie the File the Movie Set Movie Box movie Box the Movie Go To Beginning Of Movie the Movie Movies Task 0 the Movie Start Movie while not the Movie Is Movie Done and not Evt Button the Movie Movies Task 0
def playMovieInWindow theWindow theFile movieBox theMovie loadMovie theFile theMovie SetMovieBox movieBox theMovie GoToBeginningOfMovie theMovie MoviesTask 0 theMovie StartMovie while not theMovie IsMovieDone and not Evt Button theMovie MoviesTask 0
56
python-test-567
python
What does a mugshot for a user upload ?
to the userena_mugshot_path
def upload to mugshot instance filename extension filename split ' ' [ -1 ] lower salt hash generate sha 1 instance pk path userena settings USERENA MUGSHOT PATH % {'username' instance user username 'id' instance user id 'date' instance user date joined 'date now' get datetime now date } return '% path s% hash s % exte...
def upload_to_mugshot instance filename extension filename split ' ' [ -1 ] lower salt hash generate_sha1 instance pk path userena_settings USERENA_MUGSHOT_PATH % {'username' instance user username 'id' instance user id 'date' instance user date_joined 'date_now' get_datetime_now date } return '% path s% hash s % exten...
67
python-test-568
python
How does it save for the image ?
under unique hash
def upload to mugshot instance filename extension filename split ' ' [ -1 ] lower salt hash generate sha 1 instance pk path userena settings USERENA MUGSHOT PATH % {'username' instance user username 'id' instance user id 'date' instance user date joined 'date now' get datetime now date } return '% path s% hash s % exte...
def upload_to_mugshot instance filename extension filename split ' ' [ -1 ] lower salt hash generate_sha1 instance pk path userena_settings USERENA_MUGSHOT_PATH % {'username' instance user username 'id' instance user id 'date' instance user date_joined 'date_now' get_datetime_now date } return '% path s% hash s % exten...
67
python-test-569
python
What uploads to the userena_mugshot_path ?
a mugshot for a user
def upload to mugshot instance filename extension filename split ' ' [ -1 ] lower salt hash generate sha 1 instance pk path userena settings USERENA MUGSHOT PATH % {'username' instance user username 'id' instance user id 'date' instance user date joined 'date now' get datetime now date } return '% path s% hash s % exte...
def upload_to_mugshot instance filename extension filename split ' ' [ -1 ] lower salt hash generate_sha1 instance pk path userena_settings USERENA_MUGSHOT_PATH % {'username' instance user username 'id' instance user id 'date' instance user date_joined 'date_now' get_datetime_now date } return '% path s% hash s % exten...
67
python-test-572
python
What does the code ensure ?
a job is absent from the schedule name the unique name that is given to the scheduled job
def absent name **kwargs ret {'name' name 'result' True 'changes' {} 'comment' []}current schedule salt ['schedule list'] show all True return yaml False if name in current schedule if 'test' in opts and opts ['test'] kwargs['test'] Trueresult salt ['schedule delete'] name **kwargs ret['comment'] append result['comment...
def absent name **kwargs ret {'name' name 'result' True 'changes' {} 'comment' []}current_schedule __salt__['schedule list'] show_all True return_yaml False if name in current_schedule if 'test' in __opts__ and __opts__['test'] kwargs['test'] Trueresult __salt__['schedule delete'] name **kwargs ret['comment'] append re...
82
python-test-574
python
What did the code set ?
callback to be passed the containing class upon creation
def add Class Advisor callback depth 2 frame sys getframe depth kind module caller locals caller globals get Frame Info frame previous Metaclass caller locals get ' metaclass ' if python 3 default Metaclass caller globals get ' metaclass ' type else default Metaclass caller globals get ' metaclass ' Class Type def advi...
def addClassAdvisor callback depth 2 frame sys _getframe depth kind module caller_locals caller_globals getFrameInfo frame previousMetaclass caller_locals get '__metaclass__' if __python3 defaultMetaclass caller_globals get '__metaclass__' type else defaultMetaclass caller_globals get '__metaclass__' ClassType def advi...
116
python-test-575
python
How did an " advising " function execute ?
in a class suite
def add Class Advisor callback depth 2 frame sys getframe depth kind module caller locals caller globals get Frame Info frame previous Metaclass caller locals get ' metaclass ' if python 3 default Metaclass caller globals get ' metaclass ' type else default Metaclass caller globals get ' metaclass ' Class Type def advi...
def addClassAdvisor callback depth 2 frame sys _getframe depth kind module caller_locals caller_globals getFrameInfo frame previousMetaclass caller_locals get '__metaclass__' if __python3 defaultMetaclass caller_globals get '__metaclass__' type else defaultMetaclass caller_globals get '__metaclass__' ClassType def advi...
116
python-test-576
python
What is this function designed ?
to be called by an " advising " function executed in a class suite
def add Class Advisor callback depth 2 frame sys getframe depth kind module caller locals caller globals get Frame Info frame previous Metaclass caller locals get ' metaclass ' if python 3 default Metaclass caller globals get ' metaclass ' type else default Metaclass caller globals get ' metaclass ' Class Type def advi...
def addClassAdvisor callback depth 2 frame sys _getframe depth kind module caller_locals caller_globals getFrameInfo frame previousMetaclass caller_locals get '__metaclass__' if __python3 defaultMetaclass caller_globals get '__metaclass__' type else defaultMetaclass caller_globals get '__metaclass__' ClassType def advi...
116
python-test-577
python
For what purpose does the code check the environment ?
for reasons libnotify
def diagnose try import pynotifyexcept Import Error return u'<p> Error pynotifyisn\'tinstalled On Ubuntu/ Debian installthe<ahref "apt python-notify">python-notify</a>package 'if 'DISPLAY' not in os environ and 'DBUS SESSION BUS ADDRESS' not in os environ return u"<p> Error Environmentvariables DISPLA Yand DBUS SESSION...
def diagnose try import pynotifyexcept ImportError return u'<p>Error pynotifyisn\'tinstalled OnUbuntu/Debian installthe<ahref "apt python-notify">python-notify</a>package 'if 'DISPLAY' not in os environ and 'DBUS_SESSION_BUS_ADDRESS' not in os environ return u"<p>Error EnvironmentvariablesDISPLAYandDBUS_SESSION_BUS_ADD...
111
python-test-578
python
What does the code separate into two pieces ?
a complex summary
def fancify summary expr seen names clear name dict clear exprs pipe expr values map Expr traverse concat filter lambda x isinstance x Reduction set one summary **dict name expr expr for expr in exprs two dict name expr symbol name expr datashape var * expr dshape for expr in exprs d dict expr two[ name expr ] for expr...
def fancify_summary expr seen_names clear name_dict clear exprs pipe expr values map Expr _traverse concat filter lambda x isinstance x Reduction set one summary **dict _name expr expr for expr in exprs two dict _name expr symbol _name expr datashape var * expr dshape for expr in exprs d dict expr two[_name expr ] for ...
81
python-test-579
python
What does the code help compute_by on summaries ?
pandas
def fancify summary expr seen names clear name dict clear exprs pipe expr values map Expr traverse concat filter lambda x isinstance x Reduction set one summary **dict name expr expr for expr in exprs two dict name expr symbol name expr datashape var * expr dshape for expr in exprs d dict expr two[ name expr ] for expr...
def fancify_summary expr seen_names clear name_dict clear exprs pipe expr values map Expr _traverse concat filter lambda x isinstance x Reduction set one summary **dict _name expr expr for expr in exprs two dict _name expr symbol _name expr datashape var * expr dshape for expr in exprs d dict expr two[_name expr ] for ...
81
python-test-584
python
What did the code read in specified format ?
data in admin folder
@synchronized IO LOCK def load admin id remove False do pickle True silent False path os path join cfg admin dir get path id logging info ' Loadingdatafor%sfrom%s' id path if not os path exists path logging info '%smissing' path return Nonetry f open path 'rb' if do pickle data c Pickle load f else data f read f close ...
@synchronized IO_LOCK def load_admin _id remove False do_pickle True silent False path os path join cfg admin_dir get_path _id logging info 'Loadingdatafor%sfrom%s' _id path if not os path exists path logging info '%smissing' path return Nonetry f open path 'rb' if do_pickle data cPickle load f else data f read f close...
94
python-test-589
python
What does the code ensure ?
that only the given hostnames are associated with the given ip address
def only name hostnames ret {'name' name 'changes' {} 'result' None 'comment' ''}if isinstance hostnames six string types hostnames [hostnames]old '' join salt ['hosts get alias'] name new '' join x strip for x in hostnames if old new ret['comment'] 'I Paddress{ 0 }alreadysetto"{ 1 }"' format name new ret['result'] Tru...
def only name hostnames ret {'name' name 'changes' {} 'result' None 'comment' ''}if isinstance hostnames six string_types hostnames [hostnames]old '' join __salt__['hosts get_alias'] name new '' join x strip for x in hostnames if old new ret['comment'] 'IPaddress{0}alreadysetto"{1}"' format name new ret['result'] Truer...
114
python-test-590
python
What does the code apply ?
some temporary fixes
def apply temporary fixes font is for cros False font name font data font name font weight noto fonts parse weight font name weight number noto fonts WEIGHTS[weight]if is for cros and weight ' Thin' weight number 100 font['OS/ 2 '] us Weight Class weight numbername records font data get name records font family name na...
def apply_temporary_fixes font is_for_cros False font_name font_data font_name font weight noto_fonts parse_weight font_name weight_number noto_fonts WEIGHTS[weight]if is_for_cros and weight 'Thin' weight_number 100font['OS/2'] usWeightClass weight_numbername_records font_data get_name_records font family_name name_rec...
88
python-test-596
python
What does the code convert as returned from self ?
a twisted address
def peer 2 str addr if isinstance addr I Pv 4 Address res u'tcp 4 {0 } {1 }' format addr host addr port elif HAS IPV 6 and isinstance addr I Pv 6 Address res u'tcp 6 {0 } {1 }' format addr host addr port elif isinstance addr UNIX Address res u'unix {0 }' format addr name elif isinstance addr Pipe Address res u'<pipe>'e...
def peer2str addr if isinstance addr IPv4Address res u'tcp4 {0} {1}' format addr host addr port elif _HAS_IPV6 and isinstance addr IPv6Address res u'tcp6 {0} {1}' format addr host addr port elif isinstance addr UNIXAddress res u'unix {0}' format addr name elif isinstance addr PipeAddress res u'<pipe>'else res u'? {0}' ...
74
python-test-600
python
What does the code update ?
the attributes of a group
@pick context manager writerdef instance group update context group uuid values group model query context models Instance Group filter by uuid group uuid first if not group raise exception Instance Group Not Found group uuid group uuid policies values get 'policies' if policies is not None instance group policies add c...
@pick_context_manager_writerdef instance_group_update context group_uuid values group model_query context models InstanceGroup filter_by uuid group_uuid first if not group raise exception InstanceGroupNotFound group_uuid group_uuid policies values get 'policies' if policies is not None _instance_group_policies_add cont...
91
python-test-604
python
How do logger create ?
according to provided configuration
def create logger common config use daemon threads True ext u' unknown ' import paths None imported modules None stream None logger logging Logger u'powerline' level getattr logging common config[u'log level'] logger set Level level pl Powerline Logger use daemon threads logger ext get module attr gen module attr gette...
def create_logger common_config use_daemon_threads True ext u'__unknown__' import_paths None imported_modules None stream None logger logging Logger u'powerline' level getattr logging common_config[u'log_level'] logger setLevel level pl PowerlineLogger use_daemon_threads logger ext get_module_attr gen_module_attr_gette...
78
python-test-605
python
What does the code convert into a dictionary ?
the coord data
def convert coord data to dict data coord header data['coord'][ 0 ]coords data['coord'][ 1 ]pct var data['coord'][ 3 ]coords dict {}pct var dict {}coords dict['pcvectornumber'] coord headerfor x in range len coords coords dict[str x + 1 ] coords[ 0 x]pct var dict[str x + 1 ] pct var[x]return coords dict pct var dict
def convert_coord_data_to_dict data coord_header data['coord'][0]coords data['coord'][1]pct_var data['coord'][3]coords_dict {}pct_var_dict {}coords_dict['pcvectornumber'] coord_headerfor x in range len coords coords_dict[str x + 1 ] coords[0 x]pct_var_dict[str x + 1 ] pct_var[x]return coords_dict pct_var_dict
54
python-test-606
python
What can influence a unit on layer ?
the data layer
def get max data extent net layer rc is conv if is conv conv size net blobs[layer] data shape[ 2 4]layer slice middle conv size[ 0 ] / 2 conv size[ 0 ] / 2 + 1 conv size[ 1 ] / 2 conv size[ 1 ] / 2 + 1 data slice rc convert region layer 'data' layer slice middle return data slice[ 1 ] - data slice[ 0 ] data slice[ 3 ] ...
def get_max_data_extent net layer rc is_conv if is_conv conv_size net blobs[layer] data shape[2 4]layer_slice_middle conv_size[0] / 2 conv_size[0] / 2 + 1 conv_size[1] / 2 conv_size[1] / 2 + 1 data_slice rc convert_region layer 'data' layer_slice_middle return data_slice[1] - data_slice[0] data_slice[3] - data_slice[2]...
88
python-test-607
python
What does the code get ?
the maximum size of the data layer that can influence a unit on layer
def get max data extent net layer rc is conv if is conv conv size net blobs[layer] data shape[ 2 4]layer slice middle conv size[ 0 ] / 2 conv size[ 0 ] / 2 + 1 conv size[ 1 ] / 2 conv size[ 1 ] / 2 + 1 data slice rc convert region layer 'data' layer slice middle return data slice[ 1 ] - data slice[ 0 ] data slice[ 3 ] ...
def get_max_data_extent net layer rc is_conv if is_conv conv_size net blobs[layer] data shape[2 4]layer_slice_middle conv_size[0] / 2 conv_size[0] / 2 + 1 conv_size[1] / 2 conv_size[1] / 2 + 1 data_slice rc convert_region layer 'data' layer_slice_middle return data_slice[1] - data_slice[0] data_slice[3] - data_slice[2]...
88
python-test-608
python
What can the data layer influence ?
a unit on layer
def get max data extent net layer rc is conv if is conv conv size net blobs[layer] data shape[ 2 4]layer slice middle conv size[ 0 ] / 2 conv size[ 0 ] / 2 + 1 conv size[ 1 ] / 2 conv size[ 1 ] / 2 + 1 data slice rc convert region layer 'data' layer slice middle return data slice[ 1 ] - data slice[ 0 ] data slice[ 3 ] ...
def get_max_data_extent net layer rc is_conv if is_conv conv_size net blobs[layer] data shape[2 4]layer_slice_middle conv_size[0] / 2 conv_size[0] / 2 + 1 conv_size[1] / 2 conv_size[1] / 2 + 1 data_slice rc convert_region layer 'data' layer_slice_middle return data_slice[1] - data_slice[0] data_slice[3] - data_slice[2]...
88
python-test-611
python
Where does the code perform a few cleanup routines ?
on a classification network
def cleaned Up Classification Network original network num categories network caffe pb 2 Net Parameter network Copy From original network for i layer in enumerate network layer if ' Data' in layer type assert layer type in [' Data' 'HDF 5 Data'] ' Unsupporteddatalayertype%s' % layer type elif layer type ' Input' del ne...
def cleanedUpClassificationNetwork original_network num_categories network caffe_pb2 NetParameter network CopyFrom original_network for i layer in enumerate network layer if 'Data' in layer type assert layer type in ['Data' 'HDF5Data'] 'Unsupporteddatalayertype%s' % layer type elif layer type 'Input' del network layer[...
103
python-test-612
python
What does the code return ?
a new netparameter
def cleaned Up Classification Network original network num categories network caffe pb 2 Net Parameter network Copy From original network for i layer in enumerate network layer if ' Data' in layer type assert layer type in [' Data' 'HDF 5 Data'] ' Unsupporteddatalayertype%s' % layer type elif layer type ' Input' del ne...
def cleanedUpClassificationNetwork original_network num_categories network caffe_pb2 NetParameter network CopyFrom original_network for i layer in enumerate network layer if 'Data' in layer type assert layer type in ['Data' 'HDF5Data'] 'Unsupporteddatalayertype%s' % layer type elif layer type 'Input' del network layer[...
103
python-test-616
python
What sends on the instance ?
versioned notification about the volume swap action
def notify about volume swap context instance host action phase old volume id new volume id exception None ips get instance ips instance flavor flavor notification Flavor Payload instance flavor fault priority get fault and priority from exc exception payload instance notification Instance Action Volume Swap Payload in...
def notify_about_volume_swap context instance host action phase old_volume_id new_volume_id exception None ips _get_instance_ips instance flavor flavor_notification FlavorPayload instance flavor fault priority _get_fault_and_priority_from_exc exception payload instance_notification InstanceActionVolumeSwapPayload insta...
106
python-test-619
python
What does the code check ?
either registration is blocked or not
def is course blocked request redeemed registration codes course key blocked Falsefor redeemed registration in redeemed registration codes if redeemed registration invoice item if not redeemed registration invoice item invoice is valid blocked True Optout objects get or create user request user course id course key log...
def is_course_blocked request redeemed_registration_codes course_key blocked Falsefor redeemed_registration in redeemed_registration_codes if redeemed_registration invoice_item if not redeemed_registration invoice_item invoice is_valid blocked TrueOptout objects get_or_create user request user course_id course_key log ...
82
python-test-634
python
What replaces in the expression ?
the given variables
def replace new vars expr id to new var if expr type lo VARIABLE and expr data in id to new var return id to new var[expr data]else new args []for arg in expr args new args append replace new vars arg id to new var return lo Lin Op expr type expr size new args expr data
def replace_new_vars expr id_to_new_var if expr type lo VARIABLE and expr data in id_to_new_var return id_to_new_var[expr data]else new_args []for arg in expr args new_args append replace_new_vars arg id_to_new_var return lo LinOp expr type expr size new_args expr data
58
python-test-637
python
What does the code ensure ?
the rackspace queue exists
def present name provider ret {'name' name 'result' True 'comment' '' 'changes' {}}is present list salt ['cloud action'] 'queues exists' provider provider name name [provider] values [0 ]if not is present if opts ['test'] msg ' Rackspacequeue{ 0 }issettobecreated ' format name ret['comment'] msgret['result'] Nonereturn...
def present name provider ret {'name' name 'result' True 'comment' '' 'changes' {}}is_present list __salt__['cloud action'] 'queues_exists' provider provider name name [provider] values [0]if not is_present if __opts__['test'] msg 'Rackspacequeue{0}issettobecreated ' format name ret['comment'] msgret['result'] Noneretu...
92
python-test-638
python
What do file contents write ?
to output root
def write files output root contents generated suffix map None ensure dir output root to delete set file basename for file in output root files - set contents keys if generated suffix map for output file in contents keys for suffix generated suffix in generated suffix map items if output file endswith suffix to delete ...
def _write_files output_root contents generated_suffix_map None _ensure_dir output_root to_delete set file basename for file in output_root files - set contents keys if generated_suffix_map for output_file in contents keys for suffix generated_suffix in generated_suffix_map items if output_file endswith suffix to_delet...
132
python-test-639
python
What writes to output root ?
file contents
def write files output root contents generated suffix map None ensure dir output root to delete set file basename for file in output root files - set contents keys if generated suffix map for output file in contents keys for suffix generated suffix in generated suffix map items if output file endswith suffix to delete ...
def _write_files output_root contents generated_suffix_map None _ensure_dir output_root to_delete set file basename for file in output_root files - set contents keys if generated_suffix_map for output_file in contents keys for suffix generated_suffix in generated_suffix_map items if output_file endswith suffix to_delet...
132
python-test-640
python
What does the code concatenate alongside the specified axis ?
a list of tensors
def concatenate tensors axis -1 if axis < 0 dims ndim tensors[ 0 ] if dims axis axis % dims else axis 0if py all [is sparse x for x in tensors] return tf sparse concat axis tensors else try return tf concat v2 [to dense x for x in tensors] axis except Attribute Error return tf concat axis [to dense x for x in tensors]
def concatenate tensors axis -1 if axis < 0 dims ndim tensors[0] if dims axis axis % dims else axis 0if py_all [is_sparse x for x in tensors] return tf sparse_concat axis tensors else try return tf concat_v2 [to_dense x for x in tensors] axis except AttributeError return tf concat axis [to_dense x for x in tensors]
66
python-test-642
python
What should this be called correctly ?
select largest disjoint sets
def set partition ssli part []for s in sorted list set ssli key len [ -1 ] s set s copy if not any set s intersection set t for t in part part append s missing list set i for ll in ssli for i in ll - set i for ll in part for i in ll return part missing
def set_partition ssli part []for s in sorted list set ssli key len [ -1 ] s_ set s copy if not any set s_ intersection set t for t in part part append s missing list set i for ll in ssli for i in ll - set i for ll in part for i in ll return part missing
62
python-test-643
python
What calculates certain changes in a certain circumstance ?
applicationnodedeployer
def assert application calculated changes case node state node config nonmanifest datasets expected changes additional node states frozenset additional node config frozenset deployer Application Node Deployer hostname node state hostname node uuid node state uuid docker client Fake Docker Client return assert calculate...
def assert_application_calculated_changes case node_state node_config nonmanifest_datasets expected_changes additional_node_states frozenset additional_node_config frozenset deployer ApplicationNodeDeployer hostname node_state hostname node_uuid node_state uuid docker_client FakeDockerClient return assert_calculated_ch...
69
python-test-645
python
What does the code grab from the firebase config snippet ?
the databaseurl
@lru cache def get firebase db url regex re compile '\\bdatabase URL\\b *?["\\\'] [^"\\\']+ ' cwd os path dirname file try with open os path join cwd 'templates' FIREBASE CONFIG as f url next regex search line for line in f if regex search line except Stop Iteration raise Value Error ' Errorparsingdatabase URL Pleaseco...
@lru_cache def _get_firebase_db_url regex re compile '\\bdatabaseURL\\b *?["\\\'] [^"\\\']+ ' cwd os path dirname __file__ try with open os path join cwd 'templates' _FIREBASE_CONFIG as f url next regex search line for line in f if regex search line except StopIteration raise ValueError 'ErrorparsingdatabaseURL Pleasec...
63
python-test-646
python
What does the code render ?
a bootstrap alert
def render alert content alert type None dismissable True button u''if not alert type alert type u'info'css classes [u'alert' u'alert-' + text value alert type ]if dismissable css classes append u'alert-dismissable' button u'<buttontype "button"class "close"' + u'data-dismiss "alert"aria-hidden "true">&times </button>'...
def render_alert content alert_type None dismissable True button u''if not alert_type alert_type u'info'css_classes [u'alert' u'alert-' + text_value alert_type ]if dismissable css_classes append u'alert-dismissable' button u'<buttontype "button"class "close"' + u'data-dismiss "alert"aria-hidden "true">&times </button>'...
68
python-test-650
python
What does the code get ?
a list of tuples sorted descending by visits
def get locales by visit start date end date cache key 'locales sorted by visits {start} {end}' format start start date end end date sorted locales cache get cache key if sorted locales is None try results visitors by locale start date end date locales and visits results items sorted locales list reversed sorted locale...
def get_locales_by_visit start_date end_date cache_key 'locales_sorted_by_visits {start} {end}' format start start_date end end_date sorted_locales cache get cache_key if sorted_locales is None try results visitors_by_locale start_date end_date locales_and_visits results items sorted_locales list reversed sorted locale...
104
python-test-653
python
What does openshift - img - tagger require ?
the jenkins : jenkins - wiki : openshift pipeline plugin < openshift+pipeline+plugin >
def openshift img tagger registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Image Tagger' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'test-tag' 'test Tag' 'origin-nodejs-sample latest' 'prod-tag' 'prod Tag' 'origin-nodejs-sample pr...
def openshift_img_tagger registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftImageTagger' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'test-tag' 'testTag' 'origin-nodejs-sample latest' 'prod-tag' 'prodTag' 'origin-nodejs-sample prod' 'na...
64
python-test-654
python
For what purpose does openshift - img - tagger perform the equivalent of an oc tag command invocation ?
in order to manipulate tags for images in openshift imagestreams requires
def openshift img tagger registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Image Tagger' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'test-tag' 'test Tag' 'origin-nodejs-sample latest' 'prod-tag' 'prod Tag' 'origin-nodejs-sample pr...
def openshift_img_tagger registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftImageTagger' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'test-tag' 'testTag' 'origin-nodejs-sample latest' 'prod-tag' 'prodTag' 'origin-nodejs-sample prod' 'na...
64
python-test-655
python
What does openshift - img - tagger perform in order to manipulate tags for images in openshift imagestreams requires ?
the equivalent of an oc tag command invocation
def openshift img tagger registry xml parent data osb XML Sub Element xml parent 'com openshift jenkins plugins pipeline Open Shift Image Tagger' mapping [ 'api-url' 'api URL' 'https //openshift default svc cluster local' 'test-tag' 'test Tag' 'origin-nodejs-sample latest' 'prod-tag' 'prod Tag' 'origin-nodejs-sample pr...
def openshift_img_tagger registry xml_parent data osb XML SubElement xml_parent 'com openshift jenkins plugins pipeline OpenShiftImageTagger' mapping [ 'api-url' 'apiURL' 'https //openshift default svc cluster local' 'test-tag' 'testTag' 'origin-nodejs-sample latest' 'prod-tag' 'prodTag' 'origin-nodejs-sample prod' 'na...
64
python-test-656
python
What does the code install ?
a python implementation
def install python python runas None python re sub '^python-' '' python env Noneenv list []if grains ['os'] in ' Free BSD' ' Net BSD' ' Open BSD' env list append 'MAKE gmake' if salt ['config option'] 'pyenv build env' env list append salt ['config option'] 'pyenv build env' if env list env '' join env list ret {}ret p...
def install_python python runas None python re sub '^python-' '' python env Noneenv_list []if __grains__['os'] in 'FreeBSD' 'NetBSD' 'OpenBSD' env_list append 'MAKE gmake' if __salt__['config option'] 'pyenv build_env' env_list append __salt__['config option'] 'pyenv build_env' if env_list env '' join env_list ret {}re...
84
python-test-663
python
When should jedi follow imports ?
in certain conditions
@cwd at ' ' def test completion docstring def docstr src result c Script src completions [0 ]assert c docstring raw True fast False cleandoc result c Script 'importjedi\njed' completions [0 ]assert c docstring fast False cleandoc jedi doc docstr 'importjedi\njedi Scr' cleandoc Script doc docstr 'abcd 3 abcd' '' docstr ...
@cwd_at ' ' def test_completion_docstring def docstr src result c Script src completions [0]assert c docstring raw True fast False cleandoc result c Script 'importjedi\njed' completions [0]assert c docstring fast False cleandoc jedi_doc docstr 'importjedi\njedi Scr' cleandoc Script __doc__ docstr 'abcd 3 abcd' '' docst...
64
python-test-666
python
What is containing a simple kroneckerdelta ?
the first add
@cacheitdef expand delta expr index if not expr is Mul return exprdelta Nonefunc Addterms [S 1 ]for h in expr args if delta is None and h is Add and has simple delta h index delta Truefunc h functerms [ terms[ 0 ] * t for t in h args]else terms [ t * h for t in terms]return func *terms
@cacheitdef _expand_delta expr index if not expr is_Mul return exprdelta Nonefunc Addterms [S 1 ]for h in expr args if delta is None and h is_Add and _has_simple_delta h index delta Truefunc h functerms [ terms[0] * t for t in h args]else terms [ t * h for t in terms]return func *terms
61
python-test-667
python
What does the code expand ?
the first add containing a simple kroneckerdelta
@cacheitdef expand delta expr index if not expr is Mul return exprdelta Nonefunc Addterms [S 1 ]for h in expr args if delta is None and h is Add and has simple delta h index delta Truefunc h functerms [ terms[ 0 ] * t for t in h args]else terms [ t * h for t in terms]return func *terms
@cacheitdef _expand_delta expr index if not expr is_Mul return exprdelta Nonefunc Addterms [S 1 ]for h in expr args if delta is None and h is_Add and _has_simple_delta h index delta Truefunc h functerms [ terms[0] * t for t in h args]else terms [ t * h for t in terms]return func *terms
61
python-test-671
python
What localized in locale ?
available languages
def get languages for locale locale locale locale replace '-' ' ' if locale not in AVAILABLE LANGUAGES try local lang babel Locale locale languagesexcept babel Unknown Locale Error return AVAILABLE LANGUAGES['en']diff [lc for lc in REFERENCE LANGUAGE keys if lc not in local lang keys ]for lc in diff local lang[lc] REFE...
def get_languages_for_locale locale locale locale replace '-' '_' if locale not in AVAILABLE_LANGUAGES try local_lang babel Locale locale languagesexcept babel UnknownLocaleError return AVAILABLE_LANGUAGES['en']diff [lc for lc in REFERENCE_LANGUAGE keys if lc not in local_lang keys ]for lc in diff local_lang[lc] REFERE...
94
python-test-672
python
What does this method return ?
available languages localized in locale
def get languages for locale locale locale locale replace '-' ' ' if locale not in AVAILABLE LANGUAGES try local lang babel Locale locale languagesexcept babel Unknown Locale Error return AVAILABLE LANGUAGES['en']diff [lc for lc in REFERENCE LANGUAGE keys if lc not in local lang keys ]for lc in diff local lang[lc] REFE...
def get_languages_for_locale locale locale locale replace '-' '_' if locale not in AVAILABLE_LANGUAGES try local_lang babel Locale locale languagesexcept babel UnknownLocaleError return AVAILABLE_LANGUAGES['en']diff [lc for lc in REFERENCE_LANGUAGE keys if lc not in local_lang keys ]for lc in diff local_lang[lc] REFERE...
94
python-test-674
python
What is not used in linux implementation ?
realtime arg
def rush value True realtime False if import Ctypes Failed return Falseif value sched Params Sched Params sched Params sched priority c sched get priority max SCHED RR err c sched setscheduler 0 SCHED RR ctypes byref sched Params if err -1 logging warning warn Max % sys executable sys executable else sched Params Sched...
def rush value True realtime False if importCtypesFailed return Falseif value schedParams _SchedParams schedParams sched_priority c sched_get_priority_max SCHED_RR err c sched_setscheduler 0 SCHED_RR ctypes byref schedParams if err -1 logging warning warnMax % sys executable sys executable else schedParams _SchedParams...
90
python-test-675
python
Is realtime arg used in linux implementation ?
No
def rush value True realtime False if import Ctypes Failed return Falseif value sched Params Sched Params sched Params sched priority c sched get priority max SCHED RR err c sched setscheduler 0 SCHED RR ctypes byref sched Params if err -1 logging warning warn Max % sys executable sys executable else sched Params Sched...
def rush value True realtime False if importCtypesFailed return Falseif value schedParams _SchedParams schedParams sched_priority c sched_get_priority_max SCHED_RR err c sched_setscheduler 0 SCHED_RR ctypes byref schedParams if err -1 logging warning warnMax % sys executable sys executable else schedParams _SchedParams...
90
python-test-676
python
Where is realtime arg not used ?
in linux implementation
def rush value True realtime False if import Ctypes Failed return Falseif value sched Params Sched Params sched Params sched priority c sched get priority max SCHED RR err c sched setscheduler 0 SCHED RR ctypes byref sched Params if err -1 logging warning warn Max % sys executable sys executable else sched Params Sched...
def rush value True realtime False if importCtypesFailed return Falseif value schedParams _SchedParams schedParams sched_priority c sched_get_priority_max SCHED_RR err c sched_setscheduler 0 SCHED_RR ctypes byref schedParams if err -1 logging warning warnMax % sys executable sys executable else schedParams _SchedParams...
90
python-test-677
python
What does the code raise ?
the priority of the current thread / process using - sched_setscheduler realtime arg
def rush value True realtime False if import Ctypes Failed return Falseif value sched Params Sched Params sched Params sched priority c sched get priority max SCHED RR err c sched setscheduler 0 SCHED RR ctypes byref sched Params if err -1 logging warning warn Max % sys executable sys executable else sched Params Sched...
def rush value True realtime False if importCtypesFailed return Falseif value schedParams _SchedParams schedParams sched_priority c sched_get_priority_max SCHED_RR err c sched_setscheduler 0 SCHED_RR ctypes byref schedParams if err -1 logging warning warnMax % sys executable sys executable else schedParams _SchedParams...
90
python-test-694
python
What do internal helper extract ?
the default arguments
def get defaults func code func code pos count code co argcountarg names code co varnamesarg names arg names[ pos count]defaults func defaults or kwdefaults func kwdefaults res dict kwdefaults if kwdefaults else {} pos offset pos count - len defaults for name value in zip arg names[pos offset ] defaults assert name not...
def _get_defaults func code func __code__pos_count code co_argcountarg_names code co_varnamesarg_names arg_names[ pos_count]defaults func __defaults__ or kwdefaults func __kwdefaults__res dict kwdefaults if kwdefaults else {} pos_offset pos_count - len defaults for name value in zip arg_names[pos_offset ] defaults asse...
59
python-test-695
python
What does the code update ?
the global list of line error - suppressions
def Parse Nolint Suppressions filename raw line linenum error matched Search '\\b NOLINT NEXTLINE ?\\b \\ [^ ]+\\ ?' raw line if matched if matched group 1 suppressed line linenum + 1 else suppressed line linenumcategory matched group 2 if category in None ' * ' error suppressions setdefault None set add suppressed lin...
def ParseNolintSuppressions filename raw_line linenum error matched Search '\\bNOLINT NEXTLINE ?\\b \\ [^ ]+\\ ?' raw_line if matched if matched group 1 suppressed_line linenum + 1 else suppressed_line linenumcategory matched group 2 if category in None ' * ' _error_suppressions setdefault None set add suppressed_line ...
100
python-test-698
python
What does the code get ?
the description for multiply
def get Description Multiply lines activate Multiply String get Setting String lines 'multiply' ' Activate Multiply' if activate Multiply String None or activate Multiply String ' False' return ''columns String get Setting String lines 'multiply' ' Numberof Columns' rows String get Setting String lines 'multiply' ' Num...
def getDescriptionMultiply lines activateMultiplyString getSettingString lines 'multiply' 'ActivateMultiply' if activateMultiplyString None or activateMultiplyString 'False' return ''columnsString getSettingString lines 'multiply' 'NumberofColumns' rowsString getSettingString lines 'multiply' 'NumberofRows' if columnsS...
67
python-test-701
python
What do bear directories have ?
a matching kind
@yield oncedef icollect bears bear dir glob bear globs kinds log printer for bear dir dir glob in filter lambda x os path isdir x[ 0 ] icollect bear dir glob bear dir glob escape bear dir for bear glob in bear globs for matching file in iglob os path join bear dir bear glob + ' py' try for bear in import bears matching...
@yield_oncedef icollect_bears bear_dir_glob bear_globs kinds log_printer for bear_dir dir_glob in filter lambda x os path isdir x[0] icollect bear_dir_glob bear_dir glob_escape bear_dir for bear_glob in bear_globs for matching_file in iglob os path join bear_dir bear_glob + ' py' try for bear in _import_bears matching_...
123
python-test-702
python
What does the code compute ?
a series of _ idiffchange s to turn set_a into set_b assuming that these sets are at current_path inside a nested pyrsistent object
def create diffs for sets current path set a set b resulting diffs pvector [] evolver for item in set a difference set b resulting diffs append Remove path current path item item for item in set b difference set a resulting diffs append Add path current path item item return resulting diffs persistent
def _create_diffs_for_sets current_path set_a set_b resulting_diffs pvector [] evolver for item in set_a difference set_b resulting_diffs append _Remove path current_path item item for item in set_b difference set_a resulting_diffs append _Add path current_path item item return resulting_diffs persistent
54
python-test-703
python
Where did the timestamps list ?
in the vhd footer
def validate footer timestamp vdi path check cmd 'vhd-utilcheck-n% vdi path s-p' % locals check proc make subprocess check cmd stdout True stderr True out err finish subprocess check proc check cmd ok exit codes [0 22 ] first line out splitlines [0 ] strip if 'primaryfooterinvalid' in first line raise Exception "VDI'% ...
def _validate_footer_timestamp vdi_path check_cmd 'vhd-utilcheck-n% vdi_path s-p' % locals check_proc make_subprocess check_cmd stdout True stderr True out err finish_subprocess check_proc check_cmd ok_exit_codes [0 22] first_line out splitlines [0] strip if 'primaryfooterinvalid' in first_line raise Exception "VDI'% v...
72
python-test-704
python
What are this check ensures ?
that the timestamps listed in the vhd footer are nt in the future
def validate footer timestamp vdi path check cmd 'vhd-utilcheck-n% vdi path s-p' % locals check proc make subprocess check cmd stdout True stderr True out err finish subprocess check proc check cmd ok exit codes [0 22 ] first line out splitlines [0 ] strip if 'primaryfooterinvalid' in first line raise Exception "VDI'% ...
def _validate_footer_timestamp vdi_path check_cmd 'vhd-utilcheck-n% vdi_path s-p' % locals check_proc make_subprocess check_cmd stdout True stderr True out err finish_subprocess check_proc check_cmd ok_exit_codes [0 22] first_line out splitlines [0] strip if 'primaryfooterinvalid' in first_line raise Exception "VDI'% v...
72
python-test-705
python
What listed in the vhd footer ?
the timestamps
def validate footer timestamp vdi path check cmd 'vhd-utilcheck-n% vdi path s-p' % locals check proc make subprocess check cmd stdout True stderr True out err finish subprocess check proc check cmd ok exit codes [0 22 ] first line out splitlines [0 ] strip if 'primaryfooterinvalid' in first line raise Exception "VDI'% ...
def _validate_footer_timestamp vdi_path check_cmd 'vhd-utilcheck-n% vdi_path s-p' % locals check_proc make_subprocess check_cmd stdout True stderr True out err finish_subprocess check_proc check_cmd ok_exit_codes [0 22] first_line out splitlines [0] strip if 'primaryfooterinvalid' in first_line raise Exception "VDI'% v...
72
python-test-708
python
What does this function check ?
that the builtin sites registry is consistent with the remote registry
def check builtin matches remote download url True builtin registry Earth Location get site registry force builtin True dl registry Earth Location get site registry force download download url in dl {}matches {}for name in builtin registry names in dl[name] name in dl registry if in dl[name] matches[name] quantity allc...
def check_builtin_matches_remote download_url True builtin_registry EarthLocation _get_site_registry force_builtin True dl_registry EarthLocation _get_site_registry force_download download_url in_dl {}matches {}for name in builtin_registry names in_dl[name] name in dl_registry if in_dl[name] matches[name] quantity_allc...
106
python-test-712
python
What is a : class : figure instance where ?
h
def close *args if len args 0 fig Manager pylab helpers Gcf get active if fig Manager is None returnelse fig Manager canvas mpl disconnect fig Manager cidgcf pylab helpers Gcf destroy fig Manager num elif len args 1 arg args[ 0 ]if arg 'all' for manager in pylab helpers Gcf get all fig managers manager canvas mpl disco...
def close *args if len args 0 figManager _pylab_helpers Gcf get_active if figManager is None returnelse figManager canvas mpl_disconnect figManager _cidgcf _pylab_helpers Gcf destroy figManager num elif len args 1 arg args[0]if arg 'all' for manager in _pylab_helpers Gcf get_all_fig_managers manager canvas mpl_disconne...
125
python-test-713
python
What does the code ensure ?
fn is usable as a spir kernel
def set hsa kernel fn mod fn modulefn calling convention CC SPIR KERNE Locl kernels mod get or insert named metadata 'opencl kernels' ocl kernels add lc Meta Data get mod [fn gen arg addrspace md fn gen arg access qual md fn gen arg type fn gen arg type qual fn gen arg base type fn ] make constant lambda x lc Constant ...
def set_hsa_kernel fn mod fn modulefn calling_convention CC_SPIR_KERNELocl_kernels mod get_or_insert_named_metadata 'opencl kernels' ocl_kernels add lc MetaData get mod [fn gen_arg_addrspace_md fn gen_arg_access_qual_md fn gen_arg_type fn gen_arg_type_qual fn gen_arg_base_type fn ] make_constant lambda x lc Constant in...
133
python-test-714
python
What does the code produce ?
a generator that feeds lists of arrays to any gradient test
def correlation row generator bt pmf category data array [i for i in bt iter data axis 'observation' ] try cat vect array [pmf[s][category] for s in bt ids ] dtype float return row cat vect for row in data except Value Error raise Value Error " Mappingfilecategorycontaineddatathatcouldn't" + "beconvertedtofloat Can'tco...
def correlation_row_generator bt pmf category data array [i for i in bt iter_data axis 'observation' ] try cat_vect array [pmf[s][category] for s in bt ids ] dtype float return row cat_vect for row in data except ValueError raise ValueError "Mappingfilecategorycontaineddatathatcouldn't" + "beconvertedtofloat Can'tconti...
52
python-test-720
python
What adds environment variables to the whole build process ?
env - script
def env script registry xml parent data el XML Sub Element xml parent 'com lookout jenkins Environment Script' XML Sub Element el 'script' text data get 'script-content' '' valid script types {'unix-script' 'unix Script' 'power-shell' 'power Shell' 'batch-script' 'batch Script'}script type data get 'script-type' 'unix-...
def env_script registry xml_parent data el XML SubElement xml_parent 'com lookout jenkins EnvironmentScript' XML SubElement el 'script' text data get 'script-content' '' valid_script_types {'unix-script' 'unixScript' 'power-shell' 'powerShell' 'batch-script' 'batchScript'}script_type data get 'script-type' 'unix-script...
94
python-test-723
python
What does the code get ?
all associations of given qos specs
def get associations context qos specs id try types objects Volume Type List get all types for qos context qos specs id except db exc DB Error LOG exception LE 'D Berror ' msg ' Failedtogetallassociationsofqosspecs%s' % qos specs id LOG warning msg raise exception Cinder Exception message msg result []for vol type in t...
def get_associations context qos_specs_id try types objects VolumeTypeList get_all_types_for_qos context qos_specs_id except db_exc DBError LOG exception _LE 'DBerror ' msg _ 'Failedtogetallassociationsofqosspecs%s' % qos_specs_id LOG warning msg raise exception CinderException message msg result []for vol_type in type...
71
python-test-725
python
What did the code generate ?
variables that require params to be known
def Calculate Variables default variables params generator flags params get 'generator flags' {} msvs version MSVS Version Select Visual Studio Version generator flags get 'msvs version' 'auto' params['msvs version'] msvs versiondefault variables['MSVS VERSION'] msvs version Short Name if os environ get 'PROCESSOR ARCH...
def CalculateVariables default_variables params generator_flags params get 'generator_flags' {} msvs_version MSVSVersion SelectVisualStudioVersion generator_flags get 'msvs_version' 'auto' params['msvs_version'] msvs_versiondefault_variables['MSVS_VERSION'] msvs_version ShortName if os environ get 'PROCESSOR_ARCHITECTU...
89
python-test-726
python
What do variables require params ?
to be known
def Calculate Variables default variables params generator flags params get 'generator flags' {} msvs version MSVS Version Select Visual Studio Version generator flags get 'msvs version' 'auto' params['msvs version'] msvs versiondefault variables['MSVS VERSION'] msvs version Short Name if os environ get 'PROCESSOR ARCH...
def CalculateVariables default_variables params generator_flags params get 'generator_flags' {} msvs_version MSVSVersion SelectVisualStudioVersion generator_flags get 'msvs_version' 'auto' params['msvs_version'] msvs_versiondefault_variables['MSVS_VERSION'] msvs_version ShortName if os environ get 'PROCESSOR_ARCHITECTU...
89
python-test-730
python
What do cache directory store ?
data cache files
def get data cache dir data dir subdir None data cache dir os environ get 'NEON DATA CACHE DIR' if data cache dir is None data cache dir data dirif subdir subdir subdir if isinstance subdir list else [subdir] data cache dir os path join data cache dir *subdir if not os path exists data cache dir os makedirs data cache ...
def get_data_cache_dir data_dir subdir None data_cache_dir os environ get 'NEON_DATA_CACHE_DIR' if data_cache_dir is None data_cache_dir data_dirif subdir subdir subdir if isinstance subdir list else [subdir] data_cache_dir os path join data_cache_dir *subdir if not os path exists data_cache_dir os makedirs data_cache_...
66
python-test-746
python
What does the code create ?
a master key
def create key policy None description None key usage None region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile r {} policy json serialize policy try key metadata conn create key policy description description key usage key usage r['key metadata'] key metadata[' K...
def create_key policy None description None key_usage None region None key None keyid None profile None conn _get_conn region region key key keyid keyid profile profile r {}_policy json serialize policy try key_metadata conn create_key _policy description description key_usage key_usage r['key_metadata'] key_metadata['...
69
python-test-747
python
What does the code retrieve as a dictionary keyed with object ids ?
the votes cast by a user on a list of objects
def do votes by user parser token bits token contents split if len bits 6 raise template Template Syntax Error "'%s'tagtakesexactlyfourarguments" % bits[ 0 ] if bits[ 2 ] 'on' raise template Template Syntax Error "secondargumentto'%s'tagmustbe'on'" % bits[ 0 ] if bits[ 4 ] 'as' raise template Template Syntax Error "fou...
def do_votes_by_user parser token bits token contents split if len bits 6 raise template TemplateSyntaxError "'%s'tagtakesexactlyfourarguments" % bits[0] if bits[2] 'on' raise template TemplateSyntaxError "secondargumentto'%s'tagmustbe'on'" % bits[0] if bits[4] 'as' raise template TemplateSyntaxError "fourthargumentto'...
69
python-test-748
python
Where did by a user cast the votes ?
on a list of objects
def do votes by user parser token bits token contents split if len bits 6 raise template Template Syntax Error "'%s'tagtakesexactlyfourarguments" % bits[ 0 ] if bits[ 2 ] 'on' raise template Template Syntax Error "secondargumentto'%s'tagmustbe'on'" % bits[ 0 ] if bits[ 4 ] 'as' raise template Template Syntax Error "fou...
def do_votes_by_user parser token bits token contents split if len bits 6 raise template TemplateSyntaxError "'%s'tagtakesexactlyfourarguments" % bits[0] if bits[2] 'on' raise template TemplateSyntaxError "secondargumentto'%s'tagmustbe'on'" % bits[0] if bits[4] 'as' raise template TemplateSyntaxError "fourthargumentto'...
69
python-test-755
python
What is holding critical data for the given service ?
file names
def get snapshot paths service file list []if service 'cassandra' return file listlook for 'snapshots'data dir '{ 0 }/{ 1 }' format APPSCALE DATA DIR service for full path file in os walk data dir if look for in full path file list append full path logging debug " Listofdatapathsfor'{ 0 }' {1 }" format service file lis...
def get_snapshot_paths service file_list []if service 'cassandra' return file_listlook_for 'snapshots'data_dir '{0}/{1}' format APPSCALE_DATA_DIR service for full_path _ file in os walk data_dir if look_for in full_path file_list append full_path logging debug "Listofdatapathsfor'{0}' {1}" format service file_list retu...
61
python-test-756
python
What do file names hold ?
critical data for the given service
def get snapshot paths service file list []if service 'cassandra' return file listlook for 'snapshots'data dir '{ 0 }/{ 1 }' format APPSCALE DATA DIR service for full path file in os walk data dir if look for in full path file list append full path logging debug " Listofdatapathsfor'{ 0 }' {1 }" format service file lis...
def get_snapshot_paths service file_list []if service 'cassandra' return file_listlook_for 'snapshots'data_dir '{0}/{1}' format APPSCALE_DATA_DIR service for full_path _ file in os walk data_dir if look_for in full_path file_list append full_path logging debug "Listofdatapathsfor'{0}' {1}" format service file_list retu...
61