labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2 values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4 values | answer stringlengths 2 905 | src stringclasses 3 values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does the code get from attribute dictionary by arguments ?
| def getGeometryOutputByArguments(arguments, xmlElement):
evaluate.setAttributeDictionaryByArguments(['start', 'end', 'step'], arguments, xmlElement)
return getGeometryOutput(None, xmlElement)
| null | null | null | vector3 vertexes
| codeqa | def get Geometry Output By Arguments arguments xml Element evaluate set Attribute Dictionary By Arguments ['start' 'end' 'step'] arguments xml Element return get Geometry Output None xml Element
| null | null | null | null | Question:
What does the code get from attribute dictionary by arguments ?
Code:
def getGeometryOutputByArguments(arguments, xmlElement):
evaluate.setAttributeDictionaryByArguments(['start', 'end', 'step'], arguments, xmlElement)
return getGeometryOutput(None, xmlElement)
|
null | null | null | How do a python script run ?
| def outputFromPythonScript(script, *args):
with open(devnull, 'rb') as nullInput:
with open(devnull, 'wb') as nullError:
process = Popen(([executable, script.path] + list(args)), stdout=PIPE, stderr=nullError, stdin=nullInput)
stdout = process.communicate()[0]
return stdout
| null | null | null | synchronously
| codeqa | def output From Python Script script *args with open devnull 'rb' as null Input with open devnull 'wb' as null Error process Popen [executable script path] + list args stdout PIPE stderr null Error stdin null Input stdout process communicate [0 ]return stdout
| null | null | null | null | Question:
How do a python script run ?
Code:
def outputFromPythonScript(script, *args):
with open(devnull, 'rb') as nullInput:
with open(devnull, 'wb') as nullError:
process = Popen(([executable, script.path] + list(args)), stdout=PIPE, stderr=nullError, stdin=nullInput)
stdout = process.communicate()[0]
return stdout
|
null | null | null | What does the code add to a team with team_name ?
| def add_team_repo(repo_name, team_name, profile='github', permission=None):
team = get_team(team_name, profile=profile)
if (not team):
log.error('Team {0} does not exist'.format(team_name))
return False
try:
client = _get_client(profile)
organization = client.get_organization(_get_config_value(profile, 'org_name'))
team = organization.get_team(team['id'])
repo = organization.get_repo(repo_name)
except UnknownObjectException as e:
log.exception('Resource not found: {0}'.format(team['id']))
return False
params = None
if (permission is not None):
params = {'permission': permission}
(headers, data) = team._requester.requestJsonAndCheck('PUT', ((team.url + '/repos/') + repo._identity), input=params)
list_team_repos(team_name, profile=profile, ignore_cache=True)
return True
| null | null | null | a repository
| codeqa | def add team repo repo name team name profile 'github' permission None team get team team name profile profile if not team log error ' Team{ 0 }doesnotexist' format team name return Falsetry client get client profile organization client get organization get config value profile 'org name' team organization get team team['id'] repo organization get repo repo name except Unknown Object Exception as e log exception ' Resourcenotfound {0 }' format team['id'] return Falseparams Noneif permission is not None params {'permission' permission} headers data team requester request Json And Check 'PUT' team url + '/repos/' + repo identity input params list team repos team name profile profile ignore cache True return True
| null | null | null | null | Question:
What does the code add to a team with team_name ?
Code:
def add_team_repo(repo_name, team_name, profile='github', permission=None):
team = get_team(team_name, profile=profile)
if (not team):
log.error('Team {0} does not exist'.format(team_name))
return False
try:
client = _get_client(profile)
organization = client.get_organization(_get_config_value(profile, 'org_name'))
team = organization.get_team(team['id'])
repo = organization.get_repo(repo_name)
except UnknownObjectException as e:
log.exception('Resource not found: {0}'.format(team['id']))
return False
params = None
if (permission is not None):
params = {'permission': permission}
(headers, data) = team._requester.requestJsonAndCheck('PUT', ((team.url + '/repos/') + repo._identity), input=params)
list_team_repos(team_name, profile=profile, ignore_cache=True)
return True
|
null | null | null | What does the code write to the sublime text console ?
| def console_write(string, params=None, strip=True, indent=None, prefix=True):
string = text.format(str_cls(string), params, strip=strip, indent=indent)
if (sys.version_info < (3,)):
if isinstance(string, str_cls):
string = string.encode('UTF-8')
if prefix:
sys.stdout.write('Package Control: ')
print string
| null | null | null | a value
| codeqa | def console write string params None strip True indent None prefix True string text format str cls string params strip strip indent indent if sys version info < 3 if isinstance string str cls string string encode 'UTF- 8 ' if prefix sys stdout write ' Package Control ' print string
| null | null | null | null | Question:
What does the code write to the sublime text console ?
Code:
def console_write(string, params=None, strip=True, indent=None, prefix=True):
string = text.format(str_cls(string), params, strip=strip, indent=indent)
if (sys.version_info < (3,)):
if isinstance(string, str_cls):
string = string.encode('UTF-8')
if prefix:
sys.stdout.write('Package Control: ')
print string
|
null | null | null | What does the code add to a queue ?
| def insert(queue, items, backend='sqlite'):
queue_funcs = salt.loader.queues(__opts__)
cmd = '{0}.insert'.format(backend)
if (cmd not in queue_funcs):
raise SaltInvocationError('Function "{0}" is not available'.format(cmd))
ret = queue_funcs[cmd](items=items, queue=queue)
return ret
| null | null | null | an item or items
| codeqa | def insert queue items backend 'sqlite' queue funcs salt loader queues opts cmd '{ 0 } insert' format backend if cmd not in queue funcs raise Salt Invocation Error ' Function"{ 0 }"isnotavailable' format cmd ret queue funcs[cmd] items items queue queue return ret
| null | null | null | null | Question:
What does the code add to a queue ?
Code:
def insert(queue, items, backend='sqlite'):
queue_funcs = salt.loader.queues(__opts__)
cmd = '{0}.insert'.format(backend)
if (cmd not in queue_funcs):
raise SaltInvocationError('Function "{0}" is not available'.format(cmd))
ret = queue_funcs[cmd](items=items, queue=queue)
return ret
|
null | null | null | What does the code add to an existing declarative class ?
| def _add_attribute(cls, key, value):
if ('__mapper__' in cls.__dict__):
if isinstance(value, Column):
_undefer_column_name(key, value)
cls.__table__.append_column(value)
cls.__mapper__.add_property(key, value)
elif isinstance(value, ColumnProperty):
for col in value.columns:
if (isinstance(col, Column) and (col.table is None)):
_undefer_column_name(key, col)
cls.__table__.append_column(col)
cls.__mapper__.add_property(key, value)
elif isinstance(value, MapperProperty):
cls.__mapper__.add_property(key, clsregistry._deferred_relationship(cls, value))
elif (isinstance(value, QueryableAttribute) and (value.key != key)):
value = synonym(value.key)
cls.__mapper__.add_property(key, clsregistry._deferred_relationship(cls, value))
else:
type.__setattr__(cls, key, value)
else:
type.__setattr__(cls, key, value)
| null | null | null | an attribute
| codeqa | def add attribute cls key value if ' mapper ' in cls dict if isinstance value Column undefer column name key value cls table append column value cls mapper add property key value elif isinstance value Column Property for col in value columns if isinstance col Column and col table is None undefer column name key col cls table append column col cls mapper add property key value elif isinstance value Mapper Property cls mapper add property key clsregistry deferred relationship cls value elif isinstance value Queryable Attribute and value key key value synonym value key cls mapper add property key clsregistry deferred relationship cls value else type setattr cls key value else type setattr cls key value
| null | null | null | null | Question:
What does the code add to an existing declarative class ?
Code:
def _add_attribute(cls, key, value):
if ('__mapper__' in cls.__dict__):
if isinstance(value, Column):
_undefer_column_name(key, value)
cls.__table__.append_column(value)
cls.__mapper__.add_property(key, value)
elif isinstance(value, ColumnProperty):
for col in value.columns:
if (isinstance(col, Column) and (col.table is None)):
_undefer_column_name(key, col)
cls.__table__.append_column(col)
cls.__mapper__.add_property(key, value)
elif isinstance(value, MapperProperty):
cls.__mapper__.add_property(key, clsregistry._deferred_relationship(cls, value))
elif (isinstance(value, QueryableAttribute) and (value.key != key)):
value = synonym(value.key)
cls.__mapper__.add_property(key, clsregistry._deferred_relationship(cls, value))
else:
type.__setattr__(cls, key, value)
else:
type.__setattr__(cls, key, value)
|
null | null | null | What describe its properties ?
| def describe(DomainName, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
domain = conn.describe_elasticsearch_domain_config(DomainName=DomainName)
if (domain and ('DomainConfig' in domain)):
domain = domain['DomainConfig']
keys = ('ElasticsearchClusterConfig', 'EBSOptions', 'AccessPolicies', 'SnapshotOptions', 'AdvancedOptions')
return {'domain': dict([(k, domain.get(k, {}).get('Options')) for k in keys if (k in domain)])}
else:
return {'domain': None}
except ClientError as e:
return {'error': salt.utils.boto3.get_error(e)}
| null | null | null | a domain name
| codeqa | def describe Domain Name region None key None keyid None profile None conn get conn region region key key keyid keyid profile profile try domain conn describe elasticsearch domain config Domain Name Domain Name if domain and ' Domain Config' in domain domain domain[' Domain Config']keys ' Elasticsearch Cluster Config' 'EBS Options' ' Access Policies' ' Snapshot Options' ' Advanced Options' return {'domain' dict [ k domain get k {} get ' Options' for k in keys if k in domain ] }else return {'domain' None}except Client Error as e return {'error' salt utils boto 3 get error e }
| null | null | null | null | Question:
What describe its properties ?
Code:
def describe(DomainName, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
domain = conn.describe_elasticsearch_domain_config(DomainName=DomainName)
if (domain and ('DomainConfig' in domain)):
domain = domain['DomainConfig']
keys = ('ElasticsearchClusterConfig', 'EBSOptions', 'AccessPolicies', 'SnapshotOptions', 'AdvancedOptions')
return {'domain': dict([(k, domain.get(k, {}).get('Options')) for k in keys if (k in domain)])}
else:
return {'domain': None}
except ClientError as e:
return {'error': salt.utils.boto3.get_error(e)}
|
null | null | null | Where did the locator and course module calculate for the view functions ?
| def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | in this file
| codeqa | def get course and check access course key user depth 0 if not has studio read access user course key raise Permission Denied course module modulestore get course course key depth depth return course module
| null | null | null | null | Question:
Where did the locator and course module calculate for the view functions ?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | What did internal method use ?
| def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | to calculate and return the locator and course module for the view functions in this file
| codeqa | def get course and check access course key user depth 0 if not has studio read access user course key raise Permission Denied course module modulestore get course course key depth depth return course module
| null | null | null | null | Question:
What did internal method use ?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | What used to calculate and return the locator and course module for the view functions in this file ?
| def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | internal method
| codeqa | def get course and check access course key user depth 0 if not has studio read access user course key raise Permission Denied course module modulestore get course course key depth depth return course module
| null | null | null | null | Question:
What used to calculate and return the locator and course module for the view functions in this file ?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | Where do the locator and course module return for the view functions ?
| def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | in this file
| codeqa | def get course and check access course key user depth 0 if not has studio read access user course key raise Permission Denied course module modulestore get course course key depth depth return course module
| null | null | null | null | Question:
Where do the locator and course module return for the view functions ?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | What calculates in this file ?
| def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | the locator and course module
| codeqa | def get course and check access course key user depth 0 if not has studio read access user course key raise Permission Denied course module modulestore get course course key depth depth return course module
| null | null | null | null | Question:
What calculates in this file ?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | For what purpose did the locator and course module calculate in this file ?
| def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | for the view functions
| codeqa | def get course and check access course key user depth 0 if not has studio read access user course key raise Permission Denied course module modulestore get course course key depth depth return course module
| null | null | null | null | Question:
For what purpose did the locator and course module calculate in this file ?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | For what purpose do the locator and course module return in this file ?
| def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | for the view functions
| codeqa | def get course and check access course key user depth 0 if not has studio read access user course key raise Permission Denied course module modulestore get course course key depth depth return course module
| null | null | null | null | Question:
For what purpose do the locator and course module return in this file ?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | What returns in this file ?
| def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
| null | null | null | the locator and course module
| codeqa | def get course and check access course key user depth 0 if not has studio read access user course key raise Permission Denied course module modulestore get course course key depth depth return course module
| null | null | null | null | Question:
What returns in this file ?
Code:
def get_course_and_check_access(course_key, user, depth=0):
if (not has_studio_read_access(user, course_key)):
raise PermissionDenied()
course_module = modulestore().get_course(course_key, depth=depth)
return course_module
|
null | null | null | What do source field use ?
| def backwards_move_org_source(apps, schema_editor):
RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization')
SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount')
for account in SocialAccount.objects.all():
rows = account.remote_organizations.update(account=None, source=account.provider)
| null | null | null | to set organization account
| codeqa | def backwards move org source apps schema editor Remote Organization apps get model u'oauth' u' Remote Organization' Social Account apps get model u'socialaccount' u' Social Account' for account in Social Account objects all rows account remote organizations update account None source account provider
| null | null | null | null | Question:
What do source field use ?
Code:
def backwards_move_org_source(apps, schema_editor):
RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization')
SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount')
for account in SocialAccount.objects.all():
rows = account.remote_organizations.update(account=None, source=account.provider)
|
null | null | null | What uses to set organization account ?
| def backwards_move_org_source(apps, schema_editor):
RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization')
SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount')
for account in SocialAccount.objects.all():
rows = account.remote_organizations.update(account=None, source=account.provider)
| null | null | null | source field
| codeqa | def backwards move org source apps schema editor Remote Organization apps get model u'oauth' u' Remote Organization' Social Account apps get model u'socialaccount' u' Social Account' for account in Social Account objects all rows account remote organizations update account None source account provider
| null | null | null | null | Question:
What uses to set organization account ?
Code:
def backwards_move_org_source(apps, schema_editor):
RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization')
SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount')
for account in SocialAccount.objects.all():
rows = account.remote_organizations.update(account=None, source=account.provider)
|
null | null | null | For what purpose does the translation object fetch ?
| def activate(language):
if (isinstance(language, basestring) and (language == 'no')):
warnings.warn("The use of the language code 'no' is deprecated. Please use the 'nb' translation instead.", DeprecationWarning)
_active.value = translation(language)
| null | null | null | for a given tuple of application name and language
| codeqa | def activate language if isinstance language basestring and language 'no' warnings warn " Theuseofthelanguagecode'no'isdeprecated Pleaseusethe'nb'translationinstead " Deprecation Warning active value translation language
| null | null | null | null | Question:
For what purpose does the translation object fetch ?
Code:
def activate(language):
if (isinstance(language, basestring) and (language == 'no')):
warnings.warn("The use of the language code 'no' is deprecated. Please use the 'nb' translation instead.", DeprecationWarning)
_active.value = translation(language)
|
null | null | null | What does this function handle ?
| def _split_digest_auth(data):
values = []
curdata = []
state = 0
for char in data:
if (state == 0):
if (char == ','):
values.append(''.join(curdata).strip())
curdata = []
else:
if (char == '"'):
state = 1
curdata.append(char)
elif (state == 1):
if (char == '"'):
state = 0
curdata.append(char)
values.append(''.join(curdata).strip())
if ((state == 1) and config.DEBUG):
sys.stderr.write(('IVRE: WARNING: could not parse Digest auth data [%r]' % data))
return values
| null | null | null | authorization
| codeqa | def split digest auth data values []curdata []state 0for char in data if state 0 if char ' ' values append '' join curdata strip curdata []else if char '"' state 1curdata append char elif state 1 if char '"' state 0curdata append char values append '' join curdata strip if state 1 and config DEBUG sys stderr write 'IVRE WARNING couldnotparse Digestauthdata[%r]' % data return values
| null | null | null | null | Question:
What does this function handle ?
Code:
def _split_digest_auth(data):
values = []
curdata = []
state = 0
for char in data:
if (state == 0):
if (char == ','):
values.append(''.join(curdata).strip())
curdata = []
else:
if (char == '"'):
state = 1
curdata.append(char)
elif (state == 1):
if (char == '"'):
state = 0
curdata.append(char)
values.append(''.join(curdata).strip())
if ((state == 1) and config.DEBUG):
sys.stderr.write(('IVRE: WARNING: could not parse Digest auth data [%r]' % data))
return values
|
null | null | null | Where did the code set a value ?
| def sdb_set(uri, value, opts):
if (not isinstance(uri, string_types)):
return False
if (not uri.startswith('sdb://')):
return False
sdlen = len('sdb://')
indx = uri.find('/', sdlen)
if ((indx == (-1)) or (len(uri[(indx + 1):]) == 0)):
return False
profile = opts.get(uri[sdlen:indx], {})
if (not profile):
profile = opts.get('pillar', {}).get(uri[sdlen:indx], {})
if ('driver' not in profile):
return False
fun = '{0}.set'.format(profile['driver'])
query = uri[(indx + 1):]
loaded_db = salt.loader.sdb(opts, fun)
return loaded_db[fun](query, value, profile=profile)
| null | null | null | in a db
| codeqa | def sdb set uri value opts if not isinstance uri string types return Falseif not uri startswith 'sdb //' return Falsesdlen len 'sdb //' indx uri find '/' sdlen if indx -1 or len uri[ indx + 1 ] 0 return Falseprofile opts get uri[sdlen indx] {} if not profile profile opts get 'pillar' {} get uri[sdlen indx] {} if 'driver' not in profile return Falsefun '{ 0 } set' format profile['driver'] query uri[ indx + 1 ]loaded db salt loader sdb opts fun return loaded db[fun] query value profile profile
| null | null | null | null | Question:
Where did the code set a value ?
Code:
def sdb_set(uri, value, opts):
if (not isinstance(uri, string_types)):
return False
if (not uri.startswith('sdb://')):
return False
sdlen = len('sdb://')
indx = uri.find('/', sdlen)
if ((indx == (-1)) or (len(uri[(indx + 1):]) == 0)):
return False
profile = opts.get(uri[sdlen:indx], {})
if (not profile):
profile = opts.get('pillar', {}).get(uri[sdlen:indx], {})
if ('driver' not in profile):
return False
fun = '{0}.set'.format(profile['driver'])
query = uri[(indx + 1):]
loaded_db = salt.loader.sdb(opts, fun)
return loaded_db[fun](query, value, profile=profile)
|
null | null | null | What did the code set in a db ?
| def sdb_set(uri, value, opts):
if (not isinstance(uri, string_types)):
return False
if (not uri.startswith('sdb://')):
return False
sdlen = len('sdb://')
indx = uri.find('/', sdlen)
if ((indx == (-1)) or (len(uri[(indx + 1):]) == 0)):
return False
profile = opts.get(uri[sdlen:indx], {})
if (not profile):
profile = opts.get('pillar', {}).get(uri[sdlen:indx], {})
if ('driver' not in profile):
return False
fun = '{0}.set'.format(profile['driver'])
query = uri[(indx + 1):]
loaded_db = salt.loader.sdb(opts, fun)
return loaded_db[fun](query, value, profile=profile)
| null | null | null | a value
| codeqa | def sdb set uri value opts if not isinstance uri string types return Falseif not uri startswith 'sdb //' return Falsesdlen len 'sdb //' indx uri find '/' sdlen if indx -1 or len uri[ indx + 1 ] 0 return Falseprofile opts get uri[sdlen indx] {} if not profile profile opts get 'pillar' {} get uri[sdlen indx] {} if 'driver' not in profile return Falsefun '{ 0 } set' format profile['driver'] query uri[ indx + 1 ]loaded db salt loader sdb opts fun return loaded db[fun] query value profile profile
| null | null | null | null | Question:
What did the code set in a db ?
Code:
def sdb_set(uri, value, opts):
if (not isinstance(uri, string_types)):
return False
if (not uri.startswith('sdb://')):
return False
sdlen = len('sdb://')
indx = uri.find('/', sdlen)
if ((indx == (-1)) or (len(uri[(indx + 1):]) == 0)):
return False
profile = opts.get(uri[sdlen:indx], {})
if (not profile):
profile = opts.get('pillar', {}).get(uri[sdlen:indx], {})
if ('driver' not in profile):
return False
fun = '{0}.set'.format(profile['driver'])
query = uri[(indx + 1):]
loaded_db = salt.loader.sdb(opts, fun)
return loaded_db[fun](query, value, profile=profile)
|
null | null | null | What does the code create ?
| def create_port(context, port_id, network_id, physical_interface, vlan_id, tenant_id, admin_state_up):
port_id = port_id[0:11]
session = context.session
with session.begin(subtransactions=True):
port = BrocadePort(port_id=port_id, network_id=network_id, physical_interface=physical_interface, vlan_id=vlan_id, admin_state_up=admin_state_up, tenant_id=tenant_id)
session.add(port)
return port
| null | null | null | a brocade specific port
| codeqa | def create port context port id network id physical interface vlan id tenant id admin state up port id port id[ 0 11 ]session context sessionwith session begin subtransactions True port Brocade Port port id port id network id network id physical interface physical interface vlan id vlan id admin state up admin state up tenant id tenant id session add port return port
| null | null | null | null | Question:
What does the code create ?
Code:
def create_port(context, port_id, network_id, physical_interface, vlan_id, tenant_id, admin_state_up):
port_id = port_id[0:11]
session = context.session
with session.begin(subtransactions=True):
port = BrocadePort(port_id=port_id, network_id=network_id, physical_interface=physical_interface, vlan_id=vlan_id, admin_state_up=admin_state_up, tenant_id=tenant_id)
session.add(port)
return port
|
null | null | null | How does two strings compare for equality ?
| def _cryptovariables_equal(x, y):
return (_hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, x) == _hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, y))
| null | null | null | securely
| codeqa | def cryptovariables equal x y return hmac sha 256 CRYPTOVARIABLE EQUALITY COMPARISON NONCE x hmac sha 256 CRYPTOVARIABLE EQUALITY COMPARISON NONCE y
| null | null | null | null | Question:
How does two strings compare for equality ?
Code:
def _cryptovariables_equal(x, y):
return (_hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, x) == _hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, y))
|
null | null | null | What does the code convert ?
| def _media_size_to_long(maxSize):
if (len(maxSize) < 2):
return 0
units = maxSize[(-2):].upper()
multiplier = MULTIPLIERS.get(units, 0)
if multiplier:
return (int(maxSize[:(-2)]) * multiplier)
else:
return int(maxSize)
| null | null | null | a string media size
| codeqa | def media size to long max Size if len max Size < 2 return 0units max Size[ -2 ] upper multiplier MULTIPLIERS get units 0 if multiplier return int max Size[ -2 ] * multiplier else return int max Size
| null | null | null | null | Question:
What does the code convert ?
Code:
def _media_size_to_long(maxSize):
if (len(maxSize) < 2):
return 0
units = maxSize[(-2):].upper()
multiplier = MULTIPLIERS.get(units, 0)
if multiplier:
return (int(maxSize[:(-2)]) * multiplier)
else:
return int(maxSize)
|
null | null | null | How does temporary file object move temporary file object upon exiting ?
| @contextmanager
def open_atomic(filepath, *args, **kwargs):
fsync = kwargs.pop('fsync', False)
with _tempfile(dir=os.path.dirname(filepath)) as tmppath:
with open(tmppath, *args, **kwargs) as f:
(yield f)
if fsync:
f.flush()
os.fsync(file.fileno())
os.rename(tmppath, filepath)
| null | null | null | atomically
| codeqa | @contextmanagerdef open atomic filepath *args **kwargs fsync kwargs pop 'fsync' False with tempfile dir os path dirname filepath as tmppath with open tmppath *args **kwargs as f yield f if fsync f flush os fsync file fileno os rename tmppath filepath
| null | null | null | null | Question:
How does temporary file object move temporary file object upon exiting ?
Code:
@contextmanager
def open_atomic(filepath, *args, **kwargs):
fsync = kwargs.pop('fsync', False)
with _tempfile(dir=os.path.dirname(filepath)) as tmppath:
with open(tmppath, *args, **kwargs) as f:
(yield f)
if fsync:
f.flush()
os.fsync(file.fileno())
os.rename(tmppath, filepath)
|
null | null | null | When does temporary file object move temporary file object atomically ?
| @contextmanager
def open_atomic(filepath, *args, **kwargs):
fsync = kwargs.pop('fsync', False)
with _tempfile(dir=os.path.dirname(filepath)) as tmppath:
with open(tmppath, *args, **kwargs) as f:
(yield f)
if fsync:
f.flush()
os.fsync(file.fileno())
os.rename(tmppath, filepath)
| null | null | null | upon exiting
| codeqa | @contextmanagerdef open atomic filepath *args **kwargs fsync kwargs pop 'fsync' False with tempfile dir os path dirname filepath as tmppath with open tmppath *args **kwargs as f yield f if fsync f flush os fsync file fileno os rename tmppath filepath
| null | null | null | null | Question:
When does temporary file object move temporary file object atomically ?
Code:
@contextmanager
def open_atomic(filepath, *args, **kwargs):
fsync = kwargs.pop('fsync', False)
with _tempfile(dir=os.path.dirname(filepath)) as tmppath:
with open(tmppath, *args, **kwargs) as f:
(yield f)
if fsync:
f.flush()
os.fsync(file.fileno())
os.rename(tmppath, filepath)
|
null | null | null | What does the code get ?
| def get_mem_info_linux():
info = {}
with open('/proc/meminfo', 'r') as f:
for line in f:
p = line.split()
info[p[0].strip(':').lower()] = (float(p[1]) * 1000.0)
return info
| null | null | null | information about available memory
| codeqa | def get mem info linux info {}with open '/proc/meminfo' 'r' as f for line in f p line split info[p[ 0 ] strip ' ' lower ] float p[ 1 ] * 1000 0 return info
| null | null | null | null | Question:
What does the code get ?
Code:
def get_mem_info_linux():
info = {}
with open('/proc/meminfo', 'r') as f:
for line in f:
p = line.split()
info[p[0].strip(':').lower()] = (float(p[1]) * 1000.0)
return info
|
null | null | null | What support transactions ?
| def connections_support_transactions():
return all((conn.settings_dict['SUPPORTS_TRANSACTIONS'] for conn in connections.all()))
| null | null | null | all connections
| codeqa | def connections support transactions return all conn settings dict['SUPPORTS TRANSACTIONS'] for conn in connections all
| null | null | null | null | Question:
What support transactions ?
Code:
def connections_support_transactions():
return all((conn.settings_dict['SUPPORTS_TRANSACTIONS'] for conn in connections.all()))
|
null | null | null | What do a string contain ?
| def get_python_version():
return sys.version[:3]
| null | null | null | the major and minor python version
| codeqa | def get python version return sys version[ 3]
| null | null | null | null | Question:
What do a string contain ?
Code:
def get_python_version():
return sys.version[:3]
|
null | null | null | What is containing the major and minor python version ?
| def get_python_version():
return sys.version[:3]
| null | null | null | a string
| codeqa | def get python version return sys version[ 3]
| null | null | null | null | Question:
What is containing the major and minor python version ?
Code:
def get_python_version():
return sys.version[:3]
|
null | null | null | What does this function patch by adding all keyword arguments to it ?
| def patch_cache_control(response, **kwargs):
def dictitem(s):
t = s.split('=', 1)
if (len(t) > 1):
return (t[0].lower().replace('-', '_'), t[1])
else:
return (t[0].lower().replace('-', '_'), True)
def dictvalue(t):
if (t[1] == True):
return t[0]
else:
return ((t[0] + '=') + str(t[1]))
if response.has_header('Cache-Control'):
cc = cc_delim_re.split(response['Cache-Control'])
cc = dict([dictitem(el) for el in cc])
else:
cc = {}
for (k, v) in kwargs.items():
cc[k.replace('_', '-')] = v
cc = ', '.join([dictvalue(el) for el in cc.items()])
response['Cache-Control'] = cc
| null | null | null | the cache - control header
| codeqa | def patch cache control response **kwargs def dictitem s t s split ' ' 1 if len t > 1 return t[ 0 ] lower replace '-' ' ' t[ 1 ] else return t[ 0 ] lower replace '-' ' ' True def dictvalue t if t[ 1 ] True return t[ 0 ]else return t[ 0 ] + ' ' + str t[ 1 ] if response has header ' Cache- Control' cc cc delim re split response[' Cache- Control'] cc dict [dictitem el for el in cc] else cc {}for k v in kwargs items cc[k replace ' ' '-' ] vcc ' ' join [dictvalue el for el in cc items ] response[' Cache- Control'] cc
| null | null | null | null | Question:
What does this function patch by adding all keyword arguments to it ?
Code:
def patch_cache_control(response, **kwargs):
def dictitem(s):
t = s.split('=', 1)
if (len(t) > 1):
return (t[0].lower().replace('-', '_'), t[1])
else:
return (t[0].lower().replace('-', '_'), True)
def dictvalue(t):
if (t[1] == True):
return t[0]
else:
return ((t[0] + '=') + str(t[1]))
if response.has_header('Cache-Control'):
cc = cc_delim_re.split(response['Cache-Control'])
cc = dict([dictitem(el) for el in cc])
else:
cc = {}
for (k, v) in kwargs.items():
cc[k.replace('_', '-')] = v
cc = ', '.join([dictvalue(el) for el in cc.items()])
response['Cache-Control'] = cc
|
null | null | null | How does this function patch the cache - control header ?
| def patch_cache_control(response, **kwargs):
def dictitem(s):
t = s.split('=', 1)
if (len(t) > 1):
return (t[0].lower().replace('-', '_'), t[1])
else:
return (t[0].lower().replace('-', '_'), True)
def dictvalue(t):
if (t[1] == True):
return t[0]
else:
return ((t[0] + '=') + str(t[1]))
if response.has_header('Cache-Control'):
cc = cc_delim_re.split(response['Cache-Control'])
cc = dict([dictitem(el) for el in cc])
else:
cc = {}
for (k, v) in kwargs.items():
cc[k.replace('_', '-')] = v
cc = ', '.join([dictvalue(el) for el in cc.items()])
response['Cache-Control'] = cc
| null | null | null | by adding all keyword arguments to it
| codeqa | def patch cache control response **kwargs def dictitem s t s split ' ' 1 if len t > 1 return t[ 0 ] lower replace '-' ' ' t[ 1 ] else return t[ 0 ] lower replace '-' ' ' True def dictvalue t if t[ 1 ] True return t[ 0 ]else return t[ 0 ] + ' ' + str t[ 1 ] if response has header ' Cache- Control' cc cc delim re split response[' Cache- Control'] cc dict [dictitem el for el in cc] else cc {}for k v in kwargs items cc[k replace ' ' '-' ] vcc ' ' join [dictvalue el for el in cc items ] response[' Cache- Control'] cc
| null | null | null | null | Question:
How does this function patch the cache - control header ?
Code:
def patch_cache_control(response, **kwargs):
def dictitem(s):
t = s.split('=', 1)
if (len(t) > 1):
return (t[0].lower().replace('-', '_'), t[1])
else:
return (t[0].lower().replace('-', '_'), True)
def dictvalue(t):
if (t[1] == True):
return t[0]
else:
return ((t[0] + '=') + str(t[1]))
if response.has_header('Cache-Control'):
cc = cc_delim_re.split(response['Cache-Control'])
cc = dict([dictitem(el) for el in cc])
else:
cc = {}
for (k, v) in kwargs.items():
cc[k.replace('_', '-')] = v
cc = ', '.join([dictvalue(el) for el in cc.items()])
response['Cache-Control'] = cc
|
null | null | null | For what purpose does the current active catalog return ?
| def catalog():
global _default, _active
t = _active.get(currentThread(), None)
if (t is not None):
return t
if (_default is None):
from django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
return _default
| null | null | null | for further processing
| codeqa | def catalog global default activet active get current Thread None if t is not None return tif default is None from django conf import settings default translation settings LANGUAGE CODE return default
| null | null | null | null | Question:
For what purpose does the current active catalog return ?
Code:
def catalog():
global _default, _active
t = _active.get(currentThread(), None)
if (t is not None):
return t
if (_default is None):
from django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
return _default
|
null | null | null | What does the code build ?
| def Assign(target, source):
if (not isinstance(target, list)):
target = [target]
if (not isinstance(source, list)):
source.prefix = ' '
source = [source]
return Node(syms.atom, ((target + [Leaf(token.EQUAL, '=', prefix=' ')]) + source))
| null | null | null | an assignment statement
| codeqa | def Assign target source if not isinstance target list target [target]if not isinstance source list source prefix ''source [source]return Node syms atom target + [ Leaf token EQUAL ' ' prefix '' ] + source
| null | null | null | null | Question:
What does the code build ?
Code:
def Assign(target, source):
if (not isinstance(target, list)):
target = [target]
if (not isinstance(source, list)):
source.prefix = ' '
source = [source]
return Node(syms.atom, ((target + [Leaf(token.EQUAL, '=', prefix=' ')]) + source))
|
null | null | null | What does the code get by degrees ?
| def getCylindrical(azimuthDegrees, radius=1.0, z=0.0):
return getCylindricalByRadians(math.radians(azimuthDegrees), radius, z)
| null | null | null | the cylindrical vector3
| codeqa | def get Cylindrical azimuth Degrees radius 1 0 z 0 0 return get Cylindrical By Radians math radians azimuth Degrees radius z
| null | null | null | null | Question:
What does the code get by degrees ?
Code:
def getCylindrical(azimuthDegrees, radius=1.0, z=0.0):
return getCylindricalByRadians(math.radians(azimuthDegrees), radius, z)
|
null | null | null | How does the code get the cylindrical vector3 ?
| def getCylindrical(azimuthDegrees, radius=1.0, z=0.0):
return getCylindricalByRadians(math.radians(azimuthDegrees), radius, z)
| null | null | null | by degrees
| codeqa | def get Cylindrical azimuth Degrees radius 1 0 z 0 0 return get Cylindrical By Radians math radians azimuth Degrees radius z
| null | null | null | null | Question:
How does the code get the cylindrical vector3 ?
Code:
def getCylindrical(azimuthDegrees, radius=1.0, z=0.0):
return getCylindricalByRadians(math.radians(azimuthDegrees), radius, z)
|
null | null | null | What did the code split ?
| def split_path(path_):
path = path_.lstrip('/')
(first, _, rest) = path.partition('/')
lang = first.lower()
if (lang in settings.LANGUAGE_URL_MAP):
return (settings.LANGUAGE_URL_MAP[lang], rest)
else:
supported = find_supported(first)
if len(supported):
return (supported[0], rest)
else:
return ('', path)
| null | null | null | the requested path into
| codeqa | def split path path path path lstrip '/' first rest path partition '/' lang first lower if lang in settings LANGUAGE URL MAP return settings LANGUAGE URL MAP[lang] rest else supported find supported first if len supported return supported[ 0 ] rest else return '' path
| null | null | null | null | Question:
What did the code split ?
Code:
def split_path(path_):
path = path_.lstrip('/')
(first, _, rest) = path.partition('/')
lang = first.lower()
if (lang in settings.LANGUAGE_URL_MAP):
return (settings.LANGUAGE_URL_MAP[lang], rest)
else:
supported = find_supported(first)
if len(supported):
return (supported[0], rest)
else:
return ('', path)
|
null | null | null | What does the code authorize ?
| def groups_for_user(environ, username):
UserModel = auth.get_user_model()
db.reset_queries()
try:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
return []
if (not user.is_active):
return []
return [force_bytes(group.name) for group in user.groups.all()]
finally:
db.close_connection()
| null | null | null | a user based on groups
| codeqa | def groups for user environ username User Model auth get user model db reset queries try try user User Model default manager get by natural key username except User Model Does Not Exist return []if not user is active return []return [force bytes group name for group in user groups all ]finally db close connection
| null | null | null | null | Question:
What does the code authorize ?
Code:
def groups_for_user(environ, username):
UserModel = auth.get_user_model()
db.reset_queries()
try:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
return []
if (not user.is_active):
return []
return [force_bytes(group.name) for group in user.groups.all()]
finally:
db.close_connection()
|
null | null | null | How did specific permutation combinations filter ?
| def permutationFilter(perm):
limit = int(os.environ.get('NTA_TEST_maxvalFilter', 300))
if (perm['modelParams']['sensorParams']['encoders']['consumption']['maxval'] > limit):
return False
return True
| null | null | null | selectively
| codeqa | def permutation Filter perm limit int os environ get 'NTA TEST maxval Filter' 300 if perm['model Params']['sensor Params']['encoders']['consumption']['maxval'] > limit return Falsereturn True
| null | null | null | null | Question:
How did specific permutation combinations filter ?
Code:
def permutationFilter(perm):
limit = int(os.environ.get('NTA_TEST_maxvalFilter', 300))
if (perm['modelParams']['sensorParams']['encoders']['consumption']['maxval'] > limit):
return False
return True
|
null | null | null | What can this function be used ?
| def permutationFilter(perm):
limit = int(os.environ.get('NTA_TEST_maxvalFilter', 300))
if (perm['modelParams']['sensorParams']['encoders']['consumption']['maxval'] > limit):
return False
return True
| null | null | null | to selectively filter out specific permutation combinations
| codeqa | def permutation Filter perm limit int os environ get 'NTA TEST maxval Filter' 300 if perm['model Params']['sensor Params']['encoders']['consumption']['maxval'] > limit return Falsereturn True
| null | null | null | null | Question:
What can this function be used ?
Code:
def permutationFilter(perm):
limit = int(os.environ.get('NTA_TEST_maxvalFilter', 300))
if (perm['modelParams']['sensorParams']['encoders']['consumption']['maxval'] > limit):
return False
return True
|
null | null | null | How does the code run ?
| def time_openpyxl_optimised():
start_time = clock()
workbook = openpyxl.workbook.Workbook(optimized_write=True)
worksheet = workbook.create_sheet()
for row in range((row_max // 2)):
string_data = [('Row: %d Col: %d' % (row, col)) for col in range(col_max)]
worksheet.append(string_data)
num_data = [(row + col) for col in range(col_max)]
worksheet.append(num_data)
workbook.save('openpyxl_opt.xlsx')
elapsed = (clock() - start_time)
print_elapsed_time('openpyxl (optimised)', elapsed)
| null | null | null | openpyxl
| codeqa | def time openpyxl optimised start time clock workbook openpyxl workbook Workbook optimized write True worksheet workbook create sheet for row in range row max // 2 string data [ ' Row %d Col %d' % row col for col in range col max ]worksheet append string data num data [ row + col for col in range col max ]worksheet append num data workbook save 'openpyxl opt xlsx' elapsed clock - start time print elapsed time 'openpyxl optimised ' elapsed
| null | null | null | null | Question:
How does the code run ?
Code:
def time_openpyxl_optimised():
start_time = clock()
workbook = openpyxl.workbook.Workbook(optimized_write=True)
worksheet = workbook.create_sheet()
for row in range((row_max // 2)):
string_data = [('Row: %d Col: %d' % (row, col)) for col in range(col_max)]
worksheet.append(string_data)
num_data = [(row + col) for col in range(col_max)]
worksheet.append(num_data)
workbook.save('openpyxl_opt.xlsx')
elapsed = (clock() - start_time)
print_elapsed_time('openpyxl (optimised)', elapsed)
|
null | null | null | In which direction can the name be parsed to its original form for both single and multi episodes ?
| def check_valid_naming(pattern=None, multi=None, anime_type=None):
if (pattern is None):
pattern = sickbeard.NAMING_PATTERN
if (anime_type is None):
anime_type = sickbeard.NAMING_ANIME
logger.log(((u'Checking whether the pattern ' + pattern) + u' is valid for a single episode'), logger.DEBUG)
valid = validate_name(pattern, None, anime_type)
if (multi is not None):
logger.log(((u'Checking whether the pattern ' + pattern) + u' is valid for a multi episode'), logger.DEBUG)
valid = (valid and validate_name(pattern, multi, anime_type))
return valid
| null | null | null | back
| codeqa | def check valid naming pattern None multi None anime type None if pattern is None pattern sickbeard NAMING PATTER Nif anime type is None anime type sickbeard NAMING ANIM Elogger log u' Checkingwhetherthepattern' + pattern + u'isvalidforasingleepisode' logger DEBUG valid validate name pattern None anime type if multi is not None logger log u' Checkingwhetherthepattern' + pattern + u'isvalidforamultiepisode' logger DEBUG valid valid and validate name pattern multi anime type return valid
| null | null | null | null | Question:
In which direction can the name be parsed to its original form for both single and multi episodes ?
Code:
def check_valid_naming(pattern=None, multi=None, anime_type=None):
if (pattern is None):
pattern = sickbeard.NAMING_PATTERN
if (anime_type is None):
anime_type = sickbeard.NAMING_ANIME
logger.log(((u'Checking whether the pattern ' + pattern) + u' is valid for a single episode'), logger.DEBUG)
valid = validate_name(pattern, None, anime_type)
if (multi is not None):
logger.log(((u'Checking whether the pattern ' + pattern) + u' is valid for a multi episode'), logger.DEBUG)
valid = (valid and validate_name(pattern, multi, anime_type))
return valid
|
null | null | null | When were just assets were alive ?
| def only_active_assets(reference_date_value, assets):
return [a for a in assets if was_active(reference_date_value, a)]
| null | null | null | at the time
| codeqa | def only active assets reference date value assets return [a for a in assets if was active reference date value a ]
| null | null | null | null | Question:
When were just assets were alive ?
Code:
def only_active_assets(reference_date_value, assets):
return [a for a in assets if was_active(reference_date_value, a)]
|
null | null | null | What does the code initialize ?
| def init_params(options):
params = OrderedDict()
params['Wemb'] = norm_weight(options['n_words'], options['dim_word'])
params = get_layer(options['encoder'])[0](options, params, prefix='encoder', nin=options['dim_word'], dim=options['dim'])
params = get_layer(options['decoder'])[0](options, params, prefix='decoder_f', nin=options['dim_word'], dim=options['dim'])
params = get_layer(options['decoder'])[0](options, params, prefix='decoder_b', nin=options['dim_word'], dim=options['dim'])
params = get_layer('ff')[0](options, params, prefix='ff_logit', nin=options['dim'], nout=options['n_words'])
return params
| null | null | null | all parameters
| codeqa | def init params options params Ordered Dict params[' Wemb'] norm weight options['n words'] options['dim word'] params get layer options['encoder'] [0 ] options params prefix 'encoder' nin options['dim word'] dim options['dim'] params get layer options['decoder'] [0 ] options params prefix 'decoder f' nin options['dim word'] dim options['dim'] params get layer options['decoder'] [0 ] options params prefix 'decoder b' nin options['dim word'] dim options['dim'] params get layer 'ff' [0 ] options params prefix 'ff logit' nin options['dim'] nout options['n words'] return params
| null | null | null | null | Question:
What does the code initialize ?
Code:
def init_params(options):
params = OrderedDict()
params['Wemb'] = norm_weight(options['n_words'], options['dim_word'])
params = get_layer(options['encoder'])[0](options, params, prefix='encoder', nin=options['dim_word'], dim=options['dim'])
params = get_layer(options['decoder'])[0](options, params, prefix='decoder_f', nin=options['dim_word'], dim=options['dim'])
params = get_layer(options['decoder'])[0](options, params, prefix='decoder_b', nin=options['dim_word'], dim=options['dim'])
params = get_layer('ff')[0](options, params, prefix='ff_logit', nin=options['dim'], nout=options['n_words'])
return params
|
null | null | null | How does files open ?
| def main():
(option_parser, opts, args) = parse_command_line_parameters(**script_info)
data = {}
fasta_file = opts.input_fasta_fp
data['aln'] = SequenceCollection.from_fasta_records(parse_fasta(open(fasta_file)), DNA)
otu_path = opts.otu_map_fp
otu_f = open(otu_path, 'U')
otus = fields_to_dict(otu_f)
otu_f.close()
data['otus'] = otus
if opts.samples_to_extract:
prefs = process_extract_samples(opts.samples_to_extract)
filepath = opts.input_fasta_fp
filename = filepath.strip().split('/')[(-1)]
filename = filename.split('.')[0]
if opts.output_dir:
if os.path.exists(opts.output_dir):
dir_path = opts.output_dir
else:
try:
os.mkdir(opts.output_dir)
dir_path = opts.output_dir
except OSError:
pass
else:
dir_path = './'
try:
action = filter_samples
except NameError:
action = None
if action:
action(prefs, data, dir_path, filename)
| null | null | null | as necessary
| codeqa | def main option parser opts args parse command line parameters **script info data {}fasta file opts input fasta fpdata['aln'] Sequence Collection from fasta records parse fasta open fasta file DNA otu path opts otu map fpotu f open otu path 'U' otus fields to dict otu f otu f close data['otus'] otusif opts samples to extract prefs process extract samples opts samples to extract filepath opts input fasta fpfilename filepath strip split '/' [ -1 ]filename filename split ' ' [0 ]if opts output dir if os path exists opts output dir dir path opts output direlse try os mkdir opts output dir dir path opts output direxcept OS Error passelse dir path ' /'try action filter samplesexcept Name Error action Noneif action action prefs data dir path filename
| null | null | null | null | Question:
How does files open ?
Code:
def main():
(option_parser, opts, args) = parse_command_line_parameters(**script_info)
data = {}
fasta_file = opts.input_fasta_fp
data['aln'] = SequenceCollection.from_fasta_records(parse_fasta(open(fasta_file)), DNA)
otu_path = opts.otu_map_fp
otu_f = open(otu_path, 'U')
otus = fields_to_dict(otu_f)
otu_f.close()
data['otus'] = otus
if opts.samples_to_extract:
prefs = process_extract_samples(opts.samples_to_extract)
filepath = opts.input_fasta_fp
filename = filepath.strip().split('/')[(-1)]
filename = filename.split('.')[0]
if opts.output_dir:
if os.path.exists(opts.output_dir):
dir_path = opts.output_dir
else:
try:
os.mkdir(opts.output_dir)
dir_path = opts.output_dir
except OSError:
pass
else:
dir_path = './'
try:
action = filter_samples
except NameError:
action = None
if action:
action(prefs, data, dir_path, filename)
|
null | null | null | Till when should it be not changed ?
| def device_to_device(dst, src, size, stream=0):
varargs = []
if stream:
assert isinstance(stream, Stream)
fn = driver.cuMemcpyDtoDAsync
varargs.append(stream.handle)
else:
fn = driver.cuMemcpyDtoD
fn(device_pointer(dst), device_pointer(src), size, *varargs)
| null | null | null | until the operation which can be asynchronous completes
| codeqa | def device to device dst src size stream 0 varargs []if stream assert isinstance stream Stream fn driver cu Memcpy Dto D Asyncvarargs append stream handle else fn driver cu Memcpy Dto Dfn device pointer dst device pointer src size *varargs
| null | null | null | null | Question:
Till when should it be not changed ?
Code:
def device_to_device(dst, src, size, stream=0):
varargs = []
if stream:
assert isinstance(stream, Stream)
fn = driver.cuMemcpyDtoDAsync
varargs.append(stream.handle)
else:
fn = driver.cuMemcpyDtoD
fn(device_pointer(dst), device_pointer(src), size, *varargs)
|
null | null | null | How do a node and each of its children display ?
| def DisplayTree(node, children, level=0):
value = ''
node_type = ''
if ('caseValue' in node):
case_value = node['caseValue']
node_type = case_value['ProductDimension.Type']
if (node_type == 'ProductCanonicalCondition'):
value = (case_value['condition'] if ('condition' in case_value) else 'OTHER')
elif (node_type == 'ProductBiddingCategory'):
value = ('%s(%s)' % (case_value['type'], (case_value['value'] if ('value' in case_value) else 'OTHER')))
else:
value = (case_value['value'] if ('value' in case_value) else 'OTHER')
print ('%sid: %s, node_type: %s, value: %s\n' % ((' ' * level), node['id'], node_type, value))
for child_node in children[node['id']]:
DisplayTree(child_node, children, (level + 1))
| null | null | null | recursively
| codeqa | def Display Tree node children level 0 value ''node type ''if 'case Value' in node case value node['case Value']node type case value[' Product Dimension Type']if node type ' Product Canonical Condition' value case value['condition'] if 'condition' in case value else 'OTHER' elif node type ' Product Bidding Category' value '%s %s ' % case value['type'] case value['value'] if 'value' in case value else 'OTHER' else value case value['value'] if 'value' in case value else 'OTHER' print '%sid %s node type %s value %s\n' % '' * level node['id'] node type value for child node in children[node['id']] Display Tree child node children level + 1
| null | null | null | null | Question:
How do a node and each of its children display ?
Code:
def DisplayTree(node, children, level=0):
value = ''
node_type = ''
if ('caseValue' in node):
case_value = node['caseValue']
node_type = case_value['ProductDimension.Type']
if (node_type == 'ProductCanonicalCondition'):
value = (case_value['condition'] if ('condition' in case_value) else 'OTHER')
elif (node_type == 'ProductBiddingCategory'):
value = ('%s(%s)' % (case_value['type'], (case_value['value'] if ('value' in case_value) else 'OTHER')))
else:
value = (case_value['value'] if ('value' in case_value) else 'OTHER')
print ('%sid: %s, node_type: %s, value: %s\n' % ((' ' * level), node['id'], node_type, value))
for child_node in children[node['id']]:
DisplayTree(child_node, children, (level + 1))
|
null | null | null | What logs on the root logger ?
| def error(msg, *args, **kwargs):
if (len(root.handlers) == 0):
basicConfig()
root.error(*((msg,) + args), **kwargs)
| null | null | null | a message with severity error
| codeqa | def error msg *args **kwargs if len root handlers 0 basic Config root error * msg + args **kwargs
| null | null | null | null | Question:
What logs on the root logger ?
Code:
def error(msg, *args, **kwargs):
if (len(root.handlers) == 0):
basicConfig()
root.error(*((msg,) + args), **kwargs)
|
null | null | null | Where do a message with severity error log ?
| def error(msg, *args, **kwargs):
if (len(root.handlers) == 0):
basicConfig()
root.error(*((msg,) + args), **kwargs)
| null | null | null | on the root logger
| codeqa | def error msg *args **kwargs if len root handlers 0 basic Config root error * msg + args **kwargs
| null | null | null | null | Question:
Where do a message with severity error log ?
Code:
def error(msg, *args, **kwargs):
if (len(root.handlers) == 0):
basicConfig()
root.error(*((msg,) + args), **kwargs)
|
null | null | null | What does the code turn into a dict with major / minor/ ?
| def version_dict(version):
match = version_re.match((version or ''))
letters = 'alpha pre'.split()
numbers = 'major minor1 minor2 minor3 alpha_ver pre_ver'.split()
if match:
d = match.groupdict()
for letter in letters:
d[letter] = (d[letter] if d[letter] else None)
for num in numbers:
if (d[num] == '*'):
d[num] = 99
else:
d[num] = (int(d[num]) if d[num] else None)
else:
d = dict(((k, None) for k in numbers))
d.update(((k, None) for k in letters))
return d
| null | null | null | a version string
| codeqa | def version dict version match version re match version or '' letters 'alphapre' split numbers 'majorminor 1 minor 2 minor 3 alpha verpre ver' split if match d match groupdict for letter in letters d[letter] d[letter] if d[letter] else None for num in numbers if d[num] '*' d[num] 99 else d[num] int d[num] if d[num] else None else d dict k None for k in numbers d update k None for k in letters return d
| null | null | null | null | Question:
What does the code turn into a dict with major / minor/ ?
Code:
def version_dict(version):
match = version_re.match((version or ''))
letters = 'alpha pre'.split()
numbers = 'major minor1 minor2 minor3 alpha_ver pre_ver'.split()
if match:
d = match.groupdict()
for letter in letters:
d[letter] = (d[letter] if d[letter] else None)
for num in numbers:
if (d[num] == '*'):
d[num] = 99
else:
d[num] = (int(d[num]) if d[num] else None)
else:
d = dict(((k, None) for k in numbers))
d.update(((k, None) for k in letters))
return d
|
null | null | null | What do links extend ?
| @command(usage='parse links')
def extend_links(args):
args = parse_command_line(args, [], ['name'])
import lixian_tasks_extended
for x in (lixian_tasks_extended.extend_links if (not args.name) else lixian_tasks_extended.extend_links_name)(args):
print x
| null | null | null | urls
| codeqa | @command usage 'parselinks' def extend links args args parse command line args [] ['name'] import lixian tasks extendedfor x in lixian tasks extended extend links if not args name else lixian tasks extended extend links name args print x
| null | null | null | null | Question:
What do links extend ?
Code:
@command(usage='parse links')
def extend_links(args):
args = parse_command_line(args, [], ['name'])
import lixian_tasks_extended
for x in (lixian_tasks_extended.extend_links if (not args.name) else lixian_tasks_extended.extend_links_name)(args):
print x
|
null | null | null | In which direction did the code flip ?
| def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement):
flipPoints(loop, prefix, xmlElement)
if getShouldReverse(xmlElement):
loop.reverse()
return [loop]
| null | null | null | loop
| codeqa | def get Manipulated Paths close loop prefix side Length xml Element flip Points loop prefix xml Element if get Should Reverse xml Element loop reverse return [loop]
| null | null | null | null | Question:
In which direction did the code flip ?
Code:
def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement):
flipPoints(loop, prefix, xmlElement)
if getShouldReverse(xmlElement):
loop.reverse()
return [loop]
|
null | null | null | What did the code set ?
| def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=True, argv=None, usage=default_usage, description=default_description):
pub = Publisher(reader, parser, writer, settings=settings)
pub.set_components(reader_name, parser_name, writer_name)
output = pub.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status)
return output
| null | null | null | a publisher for command - line - based file i / o
| codeqa | def publish cmdline reader None reader name 'standalone' parser None parser name 'restructuredtext' writer None writer name 'pseudoxml' settings None settings spec None settings overrides None config section None enable exit status True argv None usage default usage description default description pub Publisher reader parser writer settings settings pub set components reader name parser name writer name output pub publish argv usage description settings spec settings overrides config section config section enable exit status enable exit status return output
| null | null | null | null | Question:
What did the code set ?
Code:
def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=True, argv=None, usage=default_usage, description=default_description):
pub = Publisher(reader, parser, writer, settings=settings)
pub.set_components(reader_name, parser_name, writer_name)
output = pub.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status)
return output
|
null | null | null | For what purpose did the code run a publisher ?
| def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=True, argv=None, usage=default_usage, description=default_description):
pub = Publisher(reader, parser, writer, settings=settings)
pub.set_components(reader_name, parser_name, writer_name)
output = pub.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status)
return output
| null | null | null | for command - line - based file i / o
| codeqa | def publish cmdline reader None reader name 'standalone' parser None parser name 'restructuredtext' writer None writer name 'pseudoxml' settings None settings spec None settings overrides None config section None enable exit status True argv None usage default usage description default description pub Publisher reader parser writer settings settings pub set components reader name parser name writer name output pub publish argv usage description settings spec settings overrides config section config section enable exit status enable exit status return output
| null | null | null | null | Question:
For what purpose did the code run a publisher ?
Code:
def publish_cmdline(reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name='pseudoxml', settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=True, argv=None, usage=default_usage, description=default_description):
pub = Publisher(reader, parser, writer, settings=settings)
pub.set_components(reader_name, parser_name, writer_name)
output = pub.publish(argv, usage, description, settings_spec, settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status)
return output
|
null | null | null | For what purpose does the code update the glance metadata ?
| def volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id):
return IMPL.volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id)
| null | null | null | for a volume
| codeqa | def volume glance metadata copy from volume to volume context src volume id volume id return IMPL volume glance metadata copy from volume to volume context src volume id volume id
| null | null | null | null | Question:
For what purpose does the code update the glance metadata ?
Code:
def volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id):
return IMPL.volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id)
|
null | null | null | What does the code update for a volume ?
| def volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id):
return IMPL.volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id)
| null | null | null | the glance metadata
| codeqa | def volume glance metadata copy from volume to volume context src volume id volume id return IMPL volume glance metadata copy from volume to volume context src volume id volume id
| null | null | null | null | Question:
What does the code update for a volume ?
Code:
def volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id):
return IMPL.volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id)
|
null | null | null | How do spectral norm of the difference of two complex matrices estimate ?
| def idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its=20):
return _id.idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its)
| null | null | null | by the randomized power method
| codeqa | def idz diffsnorm m n matveca matveca 2 matvec matvec 2 its 20 return id idz diffsnorm m n matveca matveca 2 matvec matvec 2 its
| null | null | null | null | Question:
How do spectral norm of the difference of two complex matrices estimate ?
Code:
def idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its=20):
return _id.idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its)
|
null | null | null | What does the code create ?
| def create_cache_cluster(name, wait=600, security_groups=None, region=None, key=None, keyid=None, profile=None, **args):
if security_groups:
if (not isinstance(security_groups, list)):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region, key=key, keyid=keyid, profile=profile)
if ('SecurityGroupIds' not in args):
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for (k, v) in args.items() if (not k.startswith('_'))])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster', res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus', region=region, key=key, keyid=keyid, profile=profile, **args)
| null | null | null | a cache cluster
| codeqa | def create cache cluster name wait 600 security groups None region None key None keyid None profile None **args if security groups if not isinstance security groups list security groups [security groups]sgs salt ['boto secgroup convert to group ids'] groups security groups region region key key keyid keyid profile profile if ' Security Group Ids' not in args args[' Security Group Ids'] []args[' Security Group Ids'] + sgsargs dict [ k v for k v in args items if not k startswith ' ' ] return create resource name name param ' Cache Cluster Id' desc 'cachecluster' res type 'cache cluster' wait wait status param ' Cache Cluster Status' region region key key keyid keyid profile profile **args
| null | null | null | null | Question:
What does the code create ?
Code:
def create_cache_cluster(name, wait=600, security_groups=None, region=None, key=None, keyid=None, profile=None, **args):
if security_groups:
if (not isinstance(security_groups, list)):
security_groups = [security_groups]
sgs = __salt__['boto_secgroup.convert_to_group_ids'](groups=security_groups, region=region, key=key, keyid=keyid, profile=profile)
if ('SecurityGroupIds' not in args):
args['SecurityGroupIds'] = []
args['SecurityGroupIds'] += sgs
args = dict([(k, v) for (k, v) in args.items() if (not k.startswith('_'))])
return _create_resource(name, name_param='CacheClusterId', desc='cache cluster', res_type='cache_cluster', wait=wait, status_param='CacheClusterStatus', region=region, key=key, keyid=keyid, profile=profile, **args)
|
null | null | null | When did its symbol pass ?
| def _op_maker(op_class, op_symbol):
def f(self, node, *args, **kwargs):
'Return a partial function with an Op subclass with an operator\n already passed.\n\n Returns\n -------\n f : callable\n '
return partial(op_class, op_symbol, *args, **kwargs)
return f
| null | null | null | already
| codeqa | def op maker op class op symbol def f self node *args **kwargs ' Returnapartialfunctionwithan Opsubclasswithanoperator\nalreadypassed \n\n Returns\n-------\nf callable\n'return partial op class op symbol *args **kwargs return f
| null | null | null | null | Question:
When did its symbol pass ?
Code:
def _op_maker(op_class, op_symbol):
def f(self, node, *args, **kwargs):
'Return a partial function with an Op subclass with an operator\n already passed.\n\n Returns\n -------\n f : callable\n '
return partial(op_class, op_symbol, *args, **kwargs)
return f
|
null | null | null | What does the code create ?
| def create_virtualenv(venv=VENV):
print 'Creating venv...',
run_command(['virtualenv', '-q', '--no-site-packages', VENV])
print 'done.'
print 'Installing pip in virtualenv...',
if (not run_command([WITH_VENV, 'easy_install', 'pip']).strip()):
die('Failed to install pip.')
print 'done.'
print 'Installing distribute in virtualenv...'
pip_install('distribute>=0.6.24')
print 'done.'
| null | null | null | the virtual environment
| codeqa | def create virtualenv venv VENV print ' Creatingvenv ' run command ['virtualenv' '-q' '--no-site-packages' VENV] print 'done 'print ' Installingpipinvirtualenv ' if not run command [WITH VENV 'easy install' 'pip'] strip die ' Failedtoinstallpip ' print 'done 'print ' Installingdistributeinvirtualenv 'pip install 'distribute> 0 6 24 ' print 'done '
| null | null | null | null | Question:
What does the code create ?
Code:
def create_virtualenv(venv=VENV):
print 'Creating venv...',
run_command(['virtualenv', '-q', '--no-site-packages', VENV])
print 'done.'
print 'Installing pip in virtualenv...',
if (not run_command([WITH_VENV, 'easy_install', 'pip']).strip()):
die('Failed to install pip.')
print 'done.'
print 'Installing distribute in virtualenv...'
pip_install('distribute>=0.6.24')
print 'done.'
|
null | null | null | How do an executing test skip ?
| def skip(msg=u''):
__tracebackhide__ = True
if is_called_from_pytest():
import pytest
pytest.skip(msg)
else:
from nose import SkipTest
raise SkipTest(msg)
| null | null | null | with the given message
| codeqa | def skip msg u'' tracebackhide Trueif is called from pytest import pytestpytest skip msg else from nose import Skip Testraise Skip Test msg
| null | null | null | null | Question:
How do an executing test skip ?
Code:
def skip(msg=u''):
__tracebackhide__ = True
if is_called_from_pytest():
import pytest
pytest.skip(msg)
else:
from nose import SkipTest
raise SkipTest(msg)
|
null | null | null | What did the code require ?
| def register(linter):
linter.register_checker(BasicErrorChecker(linter))
linter.register_checker(BasicChecker(linter))
linter.register_checker(NameChecker(linter))
linter.register_checker(DocStringChecker(linter))
linter.register_checker(PassChecker(linter))
linter.register_checker(LambdaForComprehensionChecker(linter))
| null | null | null | method to auto register this checker
| codeqa | def register linter linter register checker Basic Error Checker linter linter register checker Basic Checker linter linter register checker Name Checker linter linter register checker Doc String Checker linter linter register checker Pass Checker linter linter register checker Lambda For Comprehension Checker linter
| null | null | null | null | Question:
What did the code require ?
Code:
def register(linter):
linter.register_checker(BasicErrorChecker(linter))
linter.register_checker(BasicChecker(linter))
linter.register_checker(NameChecker(linter))
linter.register_checker(DocStringChecker(linter))
linter.register_checker(PassChecker(linter))
linter.register_checker(LambdaForComprehensionChecker(linter))
|
null | null | null | What runs the user ?
| def list_(runas=None):
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile('^[= ]([*> ]) ([^- ]+)-([^ ]+) \\[ (.*) \\]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([match.group(2), match.group(3), (match.group(1) == '*')])
return rubies
| null | null | null | rvm
| codeqa | def list runas None rubies []output rvm ['list'] runas runas if output regex re compile '^[ ] [*>] [^-]+ - [^]+ \\[ * \\]' for line in output splitlines match regex match line if match rubies append [match group 2 match group 3 match group 1 '*' ] return rubies
| null | null | null | null | Question:
What runs the user ?
Code:
def list_(runas=None):
rubies = []
output = _rvm(['list'], runas=runas)
if output:
regex = re.compile('^[= ]([*> ]) ([^- ]+)-([^ ]+) \\[ (.*) \\]')
for line in output.splitlines():
match = regex.match(line)
if match:
rubies.append([match.group(2), match.group(3), (match.group(1) == '*')])
return rubies
|
null | null | null | What does the code initialize ?
| def setUpModule():
global hass
hass = get_test_home_assistant()
bootstrap.setup_component(hass, http.DOMAIN, {http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD, http.CONF_SERVER_PORT: SERVER_PORT}})
bootstrap.setup_component(hass, 'api')
hass.http.app[KEY_BANNED_IPS] = [IpBan(banned_ip) for banned_ip in BANNED_IPS]
hass.start()
| null | null | null | a home assistant server
| codeqa | def set Up Module global hasshass get test home assistant bootstrap setup component hass http DOMAIN {http DOMAIN {http CONF API PASSWORD API PASSWORD http CONF SERVER PORT SERVER PORT}} bootstrap setup component hass 'api' hass http app[KEY BANNED IPS] [ Ip Ban banned ip for banned ip in BANNED IPS]hass start
| null | null | null | null | Question:
What does the code initialize ?
Code:
def setUpModule():
global hass
hass = get_test_home_assistant()
bootstrap.setup_component(hass, http.DOMAIN, {http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD, http.CONF_SERVER_PORT: SERVER_PORT}})
bootstrap.setup_component(hass, 'api')
hass.http.app[KEY_BANNED_IPS] = [IpBan(banned_ip) for banned_ip in BANNED_IPS]
hass.start()
|
null | null | null | What does the code create ?
| @route(bp, '/', methods=['POST'])
def new():
form = NewStoreForm()
if form.validate_on_submit():
return _stores.create(**request.json)
raise OverholtFormError(form.errors)
| null | null | null | a new store
| codeqa | @route bp '/' methods ['POST'] def new form New Store Form if form validate on submit return stores create **request json raise Overholt Form Error form errors
| null | null | null | null | Question:
What does the code create ?
Code:
@route(bp, '/', methods=['POST'])
def new():
form = NewStoreForm()
if form.validate_on_submit():
return _stores.create(**request.json)
raise OverholtFormError(form.errors)
|
null | null | null | What does the code get ?
| def getNewRepository():
return PolyfileRepository()
| null | null | null | the repository constructor
| codeqa | def get New Repository return Polyfile Repository
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewRepository():
return PolyfileRepository()
|
null | null | null | What does the code run ?
| def main():
parser = argparse.ArgumentParser(description='ansible-role-requirements.yml CLI editor', epilog='Licensed "Apache 2.0"')
parser.add_argument('-f', '--file', help='<Required> ansible-role-requirements.yml file location', required=True)
parser.add_argument('-n', '--name', help='<Required> The name of the Ansible role to edit', required=True)
parser.add_argument('-v', '--version', help='<Required> The version to set for the Ansible role', required=True)
parser.add_argument('-s', '--src', help='<Optional> The source URL to set for the Ansible role', required=False)
args = parser.parse_args()
with open(args.file, 'r') as role_req_file:
reqs = yaml.safe_load(role_req_file)
for role_data in reqs:
if (role_data['name'] == args.name):
role_data['version'] = args.version
if args.src:
role_data['src'] = args.src
with open(args.file, 'w') as role_req_file:
try:
yaml.dump(reqs, role_req_file, default_flow_style=False)
except yaml.YAMLError as exc:
print(exc)
| null | null | null | the main application
| codeqa | def main parser argparse Argument Parser description 'ansible-role-requirements yml CL Ieditor' epilog ' Licensed" Apache 2 0"' parser add argument '-f' '--file' help '< Required>ansible-role-requirements ymlfilelocation' required True parser add argument '-n' '--name' help '< Required> Thenameofthe Ansibleroletoedit' required True parser add argument '-v' '--version' help '< Required> Theversiontosetforthe Ansiblerole' required True parser add argument '-s' '--src' help '< Optional> Thesource UR Ltosetforthe Ansiblerole' required False args parser parse args with open args file 'r' as role req file reqs yaml safe load role req file for role data in reqs if role data['name'] args name role data['version'] args versionif args src role data['src'] args srcwith open args file 'w' as role req file try yaml dump reqs role req file default flow style False except yaml YAML Error as exc print exc
| null | null | null | null | Question:
What does the code run ?
Code:
def main():
parser = argparse.ArgumentParser(description='ansible-role-requirements.yml CLI editor', epilog='Licensed "Apache 2.0"')
parser.add_argument('-f', '--file', help='<Required> ansible-role-requirements.yml file location', required=True)
parser.add_argument('-n', '--name', help='<Required> The name of the Ansible role to edit', required=True)
parser.add_argument('-v', '--version', help='<Required> The version to set for the Ansible role', required=True)
parser.add_argument('-s', '--src', help='<Optional> The source URL to set for the Ansible role', required=False)
args = parser.parse_args()
with open(args.file, 'r') as role_req_file:
reqs = yaml.safe_load(role_req_file)
for role_data in reqs:
if (role_data['name'] == args.name):
role_data['version'] = args.version
if args.src:
role_data['src'] = args.src
with open(args.file, 'w') as role_req_file:
try:
yaml.dump(reqs, role_req_file, default_flow_style=False)
except yaml.YAMLError as exc:
print(exc)
|
null | null | null | What does the code get from a dictionary ?
| def _extract(d, k, default=_NoDefault):
try:
retval = d[k]
except KeyError:
if (default is _NoDefault):
raise
return default
del d[k]
return retval
| null | null | null | an item
| codeqa | def extract d k default No Default try retval d[k]except Key Error if default is No Default raisereturn defaultdel d[k]return retval
| null | null | null | null | Question:
What does the code get from a dictionary ?
Code:
def _extract(d, k, default=_NoDefault):
try:
retval = d[k]
except KeyError:
if (default is _NoDefault):
raise
return default
del d[k]
return retval
|
null | null | null | When do any email notifications for the given user return ?
| def get_notifications(user_dict, since):
notifications = []
for function in _notifications_functions:
notifications.extend(function(user_dict, since))
return notifications
| null | null | null | since since
| codeqa | def get notifications user dict since notifications []for function in notifications functions notifications extend function user dict since return notifications
| null | null | null | null | Question:
When do any email notifications for the given user return ?
Code:
def get_notifications(user_dict, since):
notifications = []
for function in _notifications_functions:
notifications.extend(function(user_dict, since))
return notifications
|
null | null | null | What does a step definition call with behave_as when ?
| @with_setup(step_runner_environ)
def test_successful_behave_as_step_doesnt_fail():
runnable_step = Step.from_string('Given I have a step which calls the "define a step" step with behave_as')
runnable_step.run(True)
assert_false(runnable_step.failed)
| null | null | null | another step definition
| codeqa | @with setup step runner environ def test successful behave as step doesnt fail runnable step Step from string ' Given Ihaveastepwhichcallsthe"defineastep"stepwithbehave as' runnable step run True assert false runnable step failed
| null | null | null | null | Question:
What does a step definition call with behave_as when ?
Code:
@with_setup(step_runner_environ)
def test_successful_behave_as_step_doesnt_fail():
runnable_step = Step.from_string('Given I have a step which calls the "define a step" step with behave_as')
runnable_step.run(True)
assert_false(runnable_step.failed)
|
null | null | null | What calls another step definition with behave_as when ?
| @with_setup(step_runner_environ)
def test_successful_behave_as_step_doesnt_fail():
runnable_step = Step.from_string('Given I have a step which calls the "define a step" step with behave_as')
runnable_step.run(True)
assert_false(runnable_step.failed)
| null | null | null | a step definition
| codeqa | @with setup step runner environ def test successful behave as step doesnt fail runnable step Step from string ' Given Ihaveastepwhichcallsthe"defineastep"stepwithbehave as' runnable step run True assert false runnable step failed
| null | null | null | null | Question:
What calls another step definition with behave_as when ?
Code:
@with_setup(step_runner_environ)
def test_successful_behave_as_step_doesnt_fail():
runnable_step = Step.from_string('Given I have a step which calls the "define a step" step with behave_as')
runnable_step.run(True)
assert_false(runnable_step.failed)
|
null | null | null | What does the code add to the beginning of every non - blank line in s ?
| def _indent(s, indent=4):
if (not PY3):
if isinstance(s, unicode):
s = s.encode(pdoctest._encoding, 'backslashreplace')
return re.sub('(?m)^(?!$)', (indent * ' '), s)
| null | null | null | the given number of space characters
| codeqa | def indent s indent 4 if not PY 3 if isinstance s unicode s s encode pdoctest encoding 'backslashreplace' return re sub ' ?m ^ ? $ ' indent * '' s
| null | null | null | null | Question:
What does the code add to the beginning of every non - blank line in s ?
Code:
def _indent(s, indent=4):
if (not PY3):
if isinstance(s, unicode):
s = s.encode(pdoctest._encoding, 'backslashreplace')
return re.sub('(?m)^(?!$)', (indent * ' '), s)
|
null | null | null | What do strings represent ?
| def getdata(im, offset=(0, 0), **params):
class Collector(object, ):
data = []
def write(self, data):
self.data.append(data)
im.load()
fp = Collector()
try:
im.encoderinfo = params
_get_local_header(fp, im, offset, 0)
ImageFile._save(im, fp, [('gif', ((0, 0) + im.size), 0, RAWMODE[im.mode])])
fp.write('\x00')
finally:
del im.encoderinfo
return fp.data
| null | null | null | this image
| codeqa | def getdata im offset 0 0 **params class Collector object data []def write self data self data append data im load fp Collector try im encoderinfo params get local header fp im offset 0 Image File save im fp [ 'gif' 0 0 + im size 0 RAWMODE[im mode] ] fp write '\x 00 ' finally del im encoderinforeturn fp data
| null | null | null | null | Question:
What do strings represent ?
Code:
def getdata(im, offset=(0, 0), **params):
class Collector(object, ):
data = []
def write(self, data):
self.data.append(data)
im.load()
fp = Collector()
try:
im.encoderinfo = params
_get_local_header(fp, im, offset, 0)
ImageFile._save(im, fp, [('gif', ((0, 0) + im.size), 0, RAWMODE[im.mode])])
fp.write('\x00')
finally:
del im.encoderinfo
return fp.data
|
null | null | null | What is representing this image ?
| def getdata(im, offset=(0, 0), **params):
class Collector(object, ):
data = []
def write(self, data):
self.data.append(data)
im.load()
fp = Collector()
try:
im.encoderinfo = params
_get_local_header(fp, im, offset, 0)
ImageFile._save(im, fp, [('gif', ((0, 0) + im.size), 0, RAWMODE[im.mode])])
fp.write('\x00')
finally:
del im.encoderinfo
return fp.data
| null | null | null | strings
| codeqa | def getdata im offset 0 0 **params class Collector object data []def write self data self data append data im load fp Collector try im encoderinfo params get local header fp im offset 0 Image File save im fp [ 'gif' 0 0 + im size 0 RAWMODE[im mode] ] fp write '\x 00 ' finally del im encoderinforeturn fp data
| null | null | null | null | Question:
What is representing this image ?
Code:
def getdata(im, offset=(0, 0), **params):
class Collector(object, ):
data = []
def write(self, data):
self.data.append(data)
im.load()
fp = Collector()
try:
im.encoderinfo = params
_get_local_header(fp, im, offset, 0)
ImageFile._save(im, fp, [('gif', ((0, 0) + im.size), 0, RAWMODE[im.mode])])
fp.write('\x00')
finally:
del im.encoderinfo
return fp.data
|
null | null | null | What is concerning an instance ?
| def show_instance(name, call=None):
if (call != 'action'):
raise SaltCloudSystemExit('The show_instance action must be called with -a or --action.')
nodes = list_nodes_full()
if (name not in nodes):
return {}
if ('name' not in nodes[name]):
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
| null | null | null | the provider
| codeqa | def show instance name call None if call 'action' raise Salt Cloud System Exit ' Theshow instanceactionmustbecalledwith-aor--action ' nodes list nodes full if name not in nodes return {}if 'name' not in nodes[name] nodes[name]['name'] nodes[name]['id']try utils ['cloud cache node'] nodes[name] active provider name opts except Type Error log warning ' Unabletoshowcachenodedata thismaybebecausethenodehasbeendeleted' return nodes[name]
| null | null | null | null | Question:
What is concerning an instance ?
Code:
def show_instance(name, call=None):
if (call != 'action'):
raise SaltCloudSystemExit('The show_instance action must be called with -a or --action.')
nodes = list_nodes_full()
if (name not in nodes):
return {}
if ('name' not in nodes[name]):
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
|
null | null | null | What does the code show ?
| def show_instance(name, call=None):
if (call != 'action'):
raise SaltCloudSystemExit('The show_instance action must be called with -a or --action.')
nodes = list_nodes_full()
if (name not in nodes):
return {}
if ('name' not in nodes[name]):
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
| null | null | null | the details from the provider concerning an instance
| codeqa | def show instance name call None if call 'action' raise Salt Cloud System Exit ' Theshow instanceactionmustbecalledwith-aor--action ' nodes list nodes full if name not in nodes return {}if 'name' not in nodes[name] nodes[name]['name'] nodes[name]['id']try utils ['cloud cache node'] nodes[name] active provider name opts except Type Error log warning ' Unabletoshowcachenodedata thismaybebecausethenodehasbeendeleted' return nodes[name]
| null | null | null | null | Question:
What does the code show ?
Code:
def show_instance(name, call=None):
if (call != 'action'):
raise SaltCloudSystemExit('The show_instance action must be called with -a or --action.')
nodes = list_nodes_full()
if (name not in nodes):
return {}
if ('name' not in nodes[name]):
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
|
null | null | null | What does the code locate ?
| def which(file, mode=(F_OK | X_OK), path=None, pathext=None):
try:
return iter(which_files(file, mode, path, pathext)).next()
except StopIteration:
try:
from errno import ENOENT
except ImportError:
ENOENT = 2
raise IOError(ENOENT, ('%s not found' % (((mode & X_OK) and 'command') or 'file')), file)
| null | null | null | a file in a path supplied as a part of the file name
| codeqa | def which file mode F OK X OK path None pathext None try return iter which files file mode path pathext next except Stop Iteration try from errno import ENOEN Texcept Import Error ENOENT 2raise IO Error ENOENT '%snotfound' % mode & X OK and 'command' or 'file' file
| null | null | null | null | Question:
What does the code locate ?
Code:
def which(file, mode=(F_OK | X_OK), path=None, pathext=None):
try:
return iter(which_files(file, mode, path, pathext)).next()
except StopIteration:
try:
from errno import ENOENT
except ImportError:
ENOENT = 2
raise IOError(ENOENT, ('%s not found' % (((mode & X_OK) and 'command') or 'file')), file)
|
null | null | null | What is running in the docker - compose file ?
| def stop(path, service_names=None):
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if ((service_names is None) or (container.get('Name')[1:] in service_names)):
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
| null | null | null | containers
| codeqa | def stop path service names None project load project path debug ret {}result {}if isinstance project dict return projectelse try project stop service names if debug for container in project containers stopped True if service names is None or container get ' Name' [1 ] in service names container inspect if not inspected debug ret[container get ' Name' ] container inspect result[container get ' Name' ] 'stopped'except Exception as inst return handle except inst return standardize result True ' Stoppingcontainersviadocker-compose' result debug ret
| null | null | null | null | Question:
What is running in the docker - compose file ?
Code:
def stop(path, service_names=None):
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if ((service_names is None) or (container.get('Name')[1:] in service_names)):
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
|
null | null | null | What stops in the docker - compose file ?
| def stop(path, service_names=None):
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if ((service_names is None) or (container.get('Name')[1:] in service_names)):
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
| null | null | null | running containers
| codeqa | def stop path service names None project load project path debug ret {}result {}if isinstance project dict return projectelse try project stop service names if debug for container in project containers stopped True if service names is None or container get ' Name' [1 ] in service names container inspect if not inspected debug ret[container get ' Name' ] container inspect result[container get ' Name' ] 'stopped'except Exception as inst return handle except inst return standardize result True ' Stoppingcontainersviadocker-compose' result debug ret
| null | null | null | null | Question:
What stops in the docker - compose file ?
Code:
def stop(path, service_names=None):
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if ((service_names is None) or (container.get('Name')[1:] in service_names)):
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
|
null | null | null | Where do running containers stop ?
| def stop(path, service_names=None):
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if ((service_names is None) or (container.get('Name')[1:] in service_names)):
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
| null | null | null | in the docker - compose file
| codeqa | def stop path service names None project load project path debug ret {}result {}if isinstance project dict return projectelse try project stop service names if debug for container in project containers stopped True if service names is None or container get ' Name' [1 ] in service names container inspect if not inspected debug ret[container get ' Name' ] container inspect result[container get ' Name' ] 'stopped'except Exception as inst return handle except inst return standardize result True ' Stoppingcontainersviadocker-compose' result debug ret
| null | null | null | null | Question:
Where do running containers stop ?
Code:
def stop(path, service_names=None):
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if ((service_names is None) or (container.get('Name')[1:] in service_names)):
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
|
null | null | null | Where do containers run ?
| def stop(path, service_names=None):
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if ((service_names is None) or (container.get('Name')[1:] in service_names)):
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
| null | null | null | in the docker - compose file
| codeqa | def stop path service names None project load project path debug ret {}result {}if isinstance project dict return projectelse try project stop service names if debug for container in project containers stopped True if service names is None or container get ' Name' [1 ] in service names container inspect if not inspected debug ret[container get ' Name' ] container inspect result[container get ' Name' ] 'stopped'except Exception as inst return handle except inst return standardize result True ' Stoppingcontainersviadocker-compose' result debug ret
| null | null | null | null | Question:
Where do containers run ?
Code:
def stop(path, service_names=None):
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if ((service_names is None) or (container.get('Name')[1:] in service_names)):
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
|
null | null | null | What does the code get from attributes ?
| def getGeometryOutput(derivation, elementNode):
if (derivation == None):
derivation = TextDerivation(elementNode)
if (derivation.textString == ''):
print 'Warning, textString is empty in getGeometryOutput in text for:'
print elementNode
return []
geometryOutput = []
for textComplexLoop in svg_reader.getTextComplexLoops(derivation.fontFamily, derivation.fontSize, derivation.textString):
textComplexLoop.reverse()
vector3Path = euclidean.getVector3Path(textComplexLoop)
sideLoop = lineation.SideLoop(vector3Path)
sideLoop.rotate(elementNode)
geometryOutput += lineation.getGeometryOutputByManipulation(elementNode, sideLoop)
return geometryOutput
| null | null | null | vector3 vertexes
| codeqa | def get Geometry Output derivation element Node if derivation None derivation Text Derivation element Node if derivation text String '' print ' Warning text Stringisemptyinget Geometry Outputintextfor 'print element Nodereturn []geometry Output []for text Complex Loop in svg reader get Text Complex Loops derivation font Family derivation font Size derivation text String text Complex Loop reverse vector 3 Path euclidean get Vector 3 Path text Complex Loop side Loop lineation Side Loop vector 3 Path side Loop rotate element Node geometry Output + lineation get Geometry Output By Manipulation element Node side Loop return geometry Output
| null | null | null | null | Question:
What does the code get from attributes ?
Code:
def getGeometryOutput(derivation, elementNode):
if (derivation == None):
derivation = TextDerivation(elementNode)
if (derivation.textString == ''):
print 'Warning, textString is empty in getGeometryOutput in text for:'
print elementNode
return []
geometryOutput = []
for textComplexLoop in svg_reader.getTextComplexLoops(derivation.fontFamily, derivation.fontSize, derivation.textString):
textComplexLoop.reverse()
vector3Path = euclidean.getVector3Path(textComplexLoop)
sideLoop = lineation.SideLoop(vector3Path)
sideLoop.rotate(elementNode)
geometryOutput += lineation.getGeometryOutputByManipulation(elementNode, sideLoop)
return geometryOutput
|
null | null | null | What does the code display ?
| def display_menu(stdscr, menu_y):
erase_menu(stdscr, menu_y)
if curses.has_colors():
stdscr.attrset(curses.color_pair(1))
stdscr.addstr(menu_y, 4, 'Use the cursor keys to move, and space or Enter to toggle a cell.')
stdscr.addstr((menu_y + 1), 4, 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit')
stdscr.attrset(0)
| null | null | null | the menu of possible keystroke commands
| codeqa | def display menu stdscr menu y erase menu stdscr menu y if curses has colors stdscr attrset curses color pair 1 stdscr addstr menu y 4 ' Usethecursorkeystomove andspaceor Entertotoggleacell ' stdscr addstr menu y + 1 4 'E rasetheboard R andomfill S teponceor C ontinuously Q uit' stdscr attrset 0
| null | null | null | null | Question:
What does the code display ?
Code:
def display_menu(stdscr, menu_y):
erase_menu(stdscr, menu_y)
if curses.has_colors():
stdscr.attrset(curses.color_pair(1))
stdscr.addstr(menu_y, 4, 'Use the cursor keys to move, and space or Enter to toggle a cell.')
stdscr.addstr((menu_y + 1), 4, 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit')
stdscr.attrset(0)
|
null | null | null | What does the code run ?
| def _test():
import doctest
doctest.testmod(verbose=1)
| null | null | null | the bio
| codeqa | def test import doctestdoctest testmod verbose 1
| null | null | null | null | Question:
What does the code run ?
Code:
def _test():
import doctest
doctest.testmod(verbose=1)
|
null | null | null | When does the complementary error function return ?
| def erfc(x):
z = abs(x)
t = (1.0 / (1 + (0.5 * z)))
r = 0.0
for y in (0.17087277, (-0.82215223), 1.48851587, (-1.13520398), 0.27886807, (-0.18628806), 0.09678418, 0.37409196, 1.00002368, (-1.26551223)):
r = (y + (t * r))
r = (t * exp(((- (z ** 2)) + r)))
if (x >= 0):
return r
return (2.0 - r)
| null | null | null | at x
| codeqa | def erfc x z abs x t 1 0 / 1 + 0 5 * z r 0 0for y in 0 17087277 -0 82215223 1 48851587 -1 13520398 0 27886807 -0 18628806 0 09678418 0 37409196 1 00002368 -1 26551223 r y + t * r r t * exp - z ** 2 + r if x > 0 return rreturn 2 0 - r
| null | null | null | null | Question:
When does the complementary error function return ?
Code:
def erfc(x):
z = abs(x)
t = (1.0 / (1 + (0.5 * z)))
r = 0.0
for y in (0.17087277, (-0.82215223), 1.48851587, (-1.13520398), 0.27886807, (-0.18628806), 0.09678418, 0.37409196, 1.00002368, (-1.26551223)):
r = (y + (t * r))
r = (t * exp(((- (z ** 2)) + r)))
if (x >= 0):
return r
return (2.0 - r)
|
null | null | null | What does the code write ?
| def _write_file_network(data, filename):
with salt.utils.fopen(filename, 'w') as fp_:
fp_.write(data)
| null | null | null | a file to disk
| codeqa | def write file network data filename with salt utils fopen filename 'w' as fp fp write data
| null | null | null | null | Question:
What does the code write ?
Code:
def _write_file_network(data, filename):
with salt.utils.fopen(filename, 'w') as fp_:
fp_.write(data)
|
null | null | null | What does the code get ?
| def getInsetLoopsFromVector3Loop(loop, radius, thresholdRatio=0.9):
if (len(loop) < 2):
return [loop]
loopComplex = euclidean.getComplexPath(loop)
loopComplexes = getInsetLoopsFromLoop(loopComplex, radius)
return euclidean.getVector3Paths(loopComplexes, loop[0].z)
| null | null | null | the inset loops from vector3 loop
| codeqa | def get Inset Loops From Vector 3 Loop loop radius threshold Ratio 0 9 if len loop < 2 return [loop]loop Complex euclidean get Complex Path loop loop Complexes get Inset Loops From Loop loop Complex radius return euclidean get Vector 3 Paths loop Complexes loop[ 0 ] z
| null | null | null | null | Question:
What does the code get ?
Code:
def getInsetLoopsFromVector3Loop(loop, radius, thresholdRatio=0.9):
if (len(loop) < 2):
return [loop]
loopComplex = euclidean.getComplexPath(loop)
loopComplexes = getInsetLoopsFromLoop(loopComplex, radius)
return euclidean.getVector3Paths(loopComplexes, loop[0].z)
|
null | null | null | What do we have ?
| def _test_basics(backend):
with use_log_level('error', print_msg=False):
gl.use_gl(backend)
with Canvas():
_test_setting_parameters()
_test_enabling_disabling()
_test_setting_stuff()
_test_object_creation_and_deletion()
_test_fbo()
gl.glFinish()
| null | null | null | a context
| codeqa | def test basics backend with use log level 'error' print msg False gl use gl backend with Canvas test setting parameters test enabling disabling test setting stuff test object creation and deletion test fbo gl gl Finish
| null | null | null | null | Question:
What do we have ?
Code:
def _test_basics(backend):
with use_log_level('error', print_msg=False):
gl.use_gl(backend)
with Canvas():
_test_setting_parameters()
_test_enabling_disabling()
_test_setting_stuff()
_test_object_creation_and_deletion()
_test_fbo()
gl.glFinish()
|
null | null | null | For what purpose have app and canvas create ?
| def _test_basics(backend):
with use_log_level('error', print_msg=False):
gl.use_gl(backend)
with Canvas():
_test_setting_parameters()
_test_enabling_disabling()
_test_setting_stuff()
_test_object_creation_and_deletion()
_test_fbo()
gl.glFinish()
| null | null | null | so we have a context
| codeqa | def test basics backend with use log level 'error' print msg False gl use gl backend with Canvas test setting parameters test enabling disabling test setting stuff test object creation and deletion test fbo gl gl Finish
| null | null | null | null | Question:
For what purpose have app and canvas create ?
Code:
def _test_basics(backend):
with use_log_level('error', print_msg=False):
gl.use_gl(backend)
with Canvas():
_test_setting_parameters()
_test_enabling_disabling()
_test_setting_stuff()
_test_object_creation_and_deletion()
_test_fbo()
gl.glFinish()
|
null | null | null | What does the code get ?
| def get_stack(context=1):
frame = sys._getframe(1)
framelist = []
while frame:
framelist.append(((frame,) + getframeinfo(frame, context)))
frame = frame.f_back
return framelist
| null | null | null | a list of records for a frame and all higher frames
| codeqa | def get stack context 1 frame sys getframe 1 framelist []while frame framelist append frame + getframeinfo frame context frame frame f backreturn framelist
| null | null | null | null | Question:
What does the code get ?
Code:
def get_stack(context=1):
frame = sys._getframe(1)
framelist = []
while frame:
framelist.append(((frame,) + getframeinfo(frame, context)))
frame = frame.f_back
return framelist
|
null | null | null | What does the code add to negatives and positives ?
| def addNegativesPositives(derivation, negatives, paths, positives):
for path in paths:
endMultiplier = None
normal = euclidean.getNormalByPath(path)
if (normal.dot(derivation.normal) < 0.0):
endMultiplier = 1.000001
loopListsByPath = getLoopListsByPath(derivation, endMultiplier, path)
geometryOutput = triangle_mesh.getPillarsOutput(loopListsByPath)
if (endMultiplier == None):
positives.append(geometryOutput)
else:
negatives.append(geometryOutput)
| null | null | null | pillars output
| codeqa | def add Negatives Positives derivation negatives paths positives for path in paths end Multiplier Nonenormal euclidean get Normal By Path path if normal dot derivation normal < 0 0 end Multiplier 1 000001 loop Lists By Path get Loop Lists By Path derivation end Multiplier path geometry Output triangle mesh get Pillars Output loop Lists By Path if end Multiplier None positives append geometry Output else negatives append geometry Output
| null | null | null | null | Question:
What does the code add to negatives and positives ?
Code:
def addNegativesPositives(derivation, negatives, paths, positives):
for path in paths:
endMultiplier = None
normal = euclidean.getNormalByPath(path)
if (normal.dot(derivation.normal) < 0.0):
endMultiplier = 1.000001
loopListsByPath = getLoopListsByPath(derivation, endMultiplier, path)
geometryOutput = triangle_mesh.getPillarsOutput(loopListsByPath)
if (endMultiplier == None):
positives.append(geometryOutput)
else:
negatives.append(geometryOutput)
|
null | null | null | What wraps at ?
| def wordwrap(value, arg):
from django.utils.text import wrap
return wrap(value, int(arg))
| null | null | null | the text
| codeqa | def wordwrap value arg from django utils text import wrapreturn wrap value int arg
| null | null | null | null | Question:
What wraps at ?
Code:
def wordwrap(value, arg):
from django.utils.text import wrap
return wrap(value, int(arg))
|
null | null | null | What list on this system ?
| def list_upgrades(refresh=False, root=None, **kwargs):
upgrades = {}
cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v']
if (root is not None):
cmd.extend(('-r', root))
if refresh:
cmd.append('-y')
call = __salt__['cmd.run_all'](cmd, python_shell=False, output_loglevel='trace')
if (call['retcode'] != 0):
comment = ''
if ('stderr' in call):
comment += call['stderr']
if ('stdout' in call):
comment += call['stdout']
if comment:
comment = (': ' + comment)
raise CommandExecutionError(('Error listing upgrades' + comment))
else:
out = call['stdout']
for line in salt.utils.itertools.split(out, '\n'):
try:
(pkgname, pkgver) = line.split()
except ValueError:
continue
if ((pkgname.lower() == 'downloading') and ('.db' in pkgver.lower())):
continue
upgrades[pkgname] = pkgver
return upgrades
| null | null | null | all available package upgrades
| codeqa | def list upgrades refresh False root None **kwargs upgrades {}cmd ['pacman' '-S' '-p' '-u' '--print-format' '%n%v']if root is not None cmd extend '-r' root if refresh cmd append '-y' call salt ['cmd run all'] cmd python shell False output loglevel 'trace' if call['retcode'] 0 comment ''if 'stderr' in call comment + call['stderr']if 'stdout' in call comment + call['stdout']if comment comment ' ' + comment raise Command Execution Error ' Errorlistingupgrades' + comment else out call['stdout']for line in salt utils itertools split out '\n' try pkgname pkgver line split except Value Error continueif pkgname lower 'downloading' and ' db' in pkgver lower continueupgrades[pkgname] pkgverreturn upgrades
| null | null | null | null | Question:
What list on this system ?
Code:
def list_upgrades(refresh=False, root=None, **kwargs):
upgrades = {}
cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v']
if (root is not None):
cmd.extend(('-r', root))
if refresh:
cmd.append('-y')
call = __salt__['cmd.run_all'](cmd, python_shell=False, output_loglevel='trace')
if (call['retcode'] != 0):
comment = ''
if ('stderr' in call):
comment += call['stderr']
if ('stdout' in call):
comment += call['stdout']
if comment:
comment = (': ' + comment)
raise CommandExecutionError(('Error listing upgrades' + comment))
else:
out = call['stdout']
for line in salt.utils.itertools.split(out, '\n'):
try:
(pkgname, pkgver) = line.split()
except ValueError:
continue
if ((pkgname.lower() == 'downloading') and ('.db' in pkgver.lower())):
continue
upgrades[pkgname] = pkgver
return upgrades
|
null | null | null | Where do all available package upgrades list ?
| def list_upgrades(refresh=False, root=None, **kwargs):
upgrades = {}
cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v']
if (root is not None):
cmd.extend(('-r', root))
if refresh:
cmd.append('-y')
call = __salt__['cmd.run_all'](cmd, python_shell=False, output_loglevel='trace')
if (call['retcode'] != 0):
comment = ''
if ('stderr' in call):
comment += call['stderr']
if ('stdout' in call):
comment += call['stdout']
if comment:
comment = (': ' + comment)
raise CommandExecutionError(('Error listing upgrades' + comment))
else:
out = call['stdout']
for line in salt.utils.itertools.split(out, '\n'):
try:
(pkgname, pkgver) = line.split()
except ValueError:
continue
if ((pkgname.lower() == 'downloading') and ('.db' in pkgver.lower())):
continue
upgrades[pkgname] = pkgver
return upgrades
| null | null | null | on this system
| codeqa | def list upgrades refresh False root None **kwargs upgrades {}cmd ['pacman' '-S' '-p' '-u' '--print-format' '%n%v']if root is not None cmd extend '-r' root if refresh cmd append '-y' call salt ['cmd run all'] cmd python shell False output loglevel 'trace' if call['retcode'] 0 comment ''if 'stderr' in call comment + call['stderr']if 'stdout' in call comment + call['stdout']if comment comment ' ' + comment raise Command Execution Error ' Errorlistingupgrades' + comment else out call['stdout']for line in salt utils itertools split out '\n' try pkgname pkgver line split except Value Error continueif pkgname lower 'downloading' and ' db' in pkgver lower continueupgrades[pkgname] pkgverreturn upgrades
| null | null | null | null | Question:
Where do all available package upgrades list ?
Code:
def list_upgrades(refresh=False, root=None, **kwargs):
upgrades = {}
cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v']
if (root is not None):
cmd.extend(('-r', root))
if refresh:
cmd.append('-y')
call = __salt__['cmd.run_all'](cmd, python_shell=False, output_loglevel='trace')
if (call['retcode'] != 0):
comment = ''
if ('stderr' in call):
comment += call['stderr']
if ('stdout' in call):
comment += call['stdout']
if comment:
comment = (': ' + comment)
raise CommandExecutionError(('Error listing upgrades' + comment))
else:
out = call['stdout']
for line in salt.utils.itertools.split(out, '\n'):
try:
(pkgname, pkgver) = line.split()
except ValueError:
continue
if ((pkgname.lower() == 'downloading') and ('.db' in pkgver.lower())):
continue
upgrades[pkgname] = pkgver
return upgrades
|
null | null | null | Where do contents file ?
| def write_file(path, contents):
(dirname, name) = os.path.split(path)
if (not os.path.exists(dirname)):
try:
os.makedirs(dirname)
except OSError as err:
if (err.errno == errno.EACCES):
sys.exit(('Unable to create %s. Running as non-root?' % dirname))
with open(path, 'w') as f:
f.write(('%s' % contents))
| null | null | null | at path
| codeqa | def write file path contents dirname name os path split path if not os path exists dirname try os makedirs dirname except OS Error as err if err errno errno EACCES sys exit ' Unabletocreate%s Runningasnon-root?' % dirname with open path 'w' as f f write '%s' % contents
| null | null | null | null | Question:
Where do contents file ?
Code:
def write_file(path, contents):
(dirname, name) = os.path.split(path)
if (not os.path.exists(dirname)):
try:
os.makedirs(dirname)
except OSError as err:
if (err.errno == errno.EACCES):
sys.exit(('Unable to create %s. Running as non-root?' % dirname))
with open(path, 'w') as f:
f.write(('%s' % contents))
|
null | null | null | What files at path ?
| def write_file(path, contents):
(dirname, name) = os.path.split(path)
if (not os.path.exists(dirname)):
try:
os.makedirs(dirname)
except OSError as err:
if (err.errno == errno.EACCES):
sys.exit(('Unable to create %s. Running as non-root?' % dirname))
with open(path, 'w') as f:
f.write(('%s' % contents))
| null | null | null | contents
| codeqa | def write file path contents dirname name os path split path if not os path exists dirname try os makedirs dirname except OS Error as err if err errno errno EACCES sys exit ' Unabletocreate%s Runningasnon-root?' % dirname with open path 'w' as f f write '%s' % contents
| null | null | null | null | Question:
What files at path ?
Code:
def write_file(path, contents):
(dirname, name) = os.path.split(path)
if (not os.path.exists(dirname)):
try:
os.makedirs(dirname)
except OSError as err:
if (err.errno == errno.EACCES):
sys.exit(('Unable to create %s. Running as non-root?' % dirname))
with open(path, 'w') as f:
f.write(('%s' % contents))
|
null | null | null | What does the code get ?
| def getnode():
global _node
if (_node is not None):
return _node
import sys
if (sys.platform == 'win32'):
getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode]
else:
getters = [_unixdll_getnode, _ifconfig_getnode, _ip_getnode, _arp_getnode, _lanscan_getnode, _netstat_getnode]
for getter in (getters + [_random_getnode]):
try:
_node = getter()
except:
continue
if (_node is not None):
return _node
| null | null | null | the hardware address
| codeqa | def getnode global nodeif node is not None return nodeimport sysif sys platform 'win 32 ' getters [ windll getnode netbios getnode ipconfig getnode]else getters [ unixdll getnode ifconfig getnode ip getnode arp getnode lanscan getnode netstat getnode]for getter in getters + [ random getnode] try node getter except continueif node is not None return node
| null | null | null | null | Question:
What does the code get ?
Code:
def getnode():
global _node
if (_node is not None):
return _node
import sys
if (sys.platform == 'win32'):
getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode]
else:
getters = [_unixdll_getnode, _ifconfig_getnode, _ip_getnode, _arp_getnode, _lanscan_getnode, _netstat_getnode]
for getter in (getters + [_random_getnode]):
try:
_node = getter()
except:
continue
if (_node is not None):
return _node
|
null | null | null | What does the code get ?
| def server_console_output(request, instance_id, tail_length=None):
return novaclient(request).servers.get_console_output(instance_id, length=tail_length)
| null | null | null | console output of an instance
| codeqa | def server console output request instance id tail length None return novaclient request servers get console output instance id length tail length
| null | null | null | null | Question:
What does the code get ?
Code:
def server_console_output(request, instance_id, tail_length=None):
return novaclient(request).servers.get_console_output(instance_id, length=tail_length)
|
null | null | null | What does decorator call ?
| def permalink(func):
import warnings
from functools import wraps
from django.urls import reverse
from django.utils.deprecation import RemovedInDjango21Warning
warnings.warn('permalink() is deprecated in favor of calling django.urls.reverse() in the decorated method.', RemovedInDjango21Warning)
@wraps(func)
def inner(*args, **kwargs):
bits = func(*args, **kwargs)
return reverse(bits[0], None, *bits[1:3])
return inner
| null | null | null | urls
| codeqa | def permalink func import warningsfrom functools import wrapsfrom django urls import reversefrom django utils deprecation import Removed In Django 21 Warningwarnings warn 'permalink isdeprecatedinfavorofcallingdjango urls reverse inthedecoratedmethod ' Removed In Django 21 Warning @wraps func def inner *args **kwargs bits func *args **kwargs return reverse bits[ 0 ] None *bits[ 1 3] return inner
| null | null | null | null | Question:
What does decorator call ?
Code:
def permalink(func):
import warnings
from functools import wraps
from django.urls import reverse
from django.utils.deprecation import RemovedInDjango21Warning
warnings.warn('permalink() is deprecated in favor of calling django.urls.reverse() in the decorated method.', RemovedInDjango21Warning)
@wraps(func)
def inner(*args, **kwargs):
bits = func(*args, **kwargs)
return reverse(bits[0], None, *bits[1:3])
return inner
|
null | null | null | What does the code create ?
| def create_channel(client_id, duration_minutes=None):
client_id = _ValidateClientId(client_id)
request = channel_service_pb.CreateChannelRequest()
response = channel_service_pb.CreateChannelResponse()
request.set_application_key(client_id)
try:
apiproxy_stub_map.MakeSyncCall(_GetService(), 'CreateChannel', request, response)
except apiproxy_errors.ApplicationError as e:
raise _ToChannelError(e)
return response.token()
| null | null | null | a channel
| codeqa | def create channel client id duration minutes None client id Validate Client Id client id request channel service pb Create Channel Request response channel service pb Create Channel Response request set application key client id try apiproxy stub map Make Sync Call Get Service ' Create Channel' request response except apiproxy errors Application Error as e raise To Channel Error e return response token
| null | null | null | null | Question:
What does the code create ?
Code:
def create_channel(client_id, duration_minutes=None):
client_id = _ValidateClientId(client_id)
request = channel_service_pb.CreateChannelRequest()
response = channel_service_pb.CreateChannelResponse()
request.set_application_key(client_id)
try:
apiproxy_stub_map.MakeSyncCall(_GetService(), 'CreateChannel', request, response)
except apiproxy_errors.ApplicationError as e:
raise _ToChannelError(e)
return response.token()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.