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 | When is * cluster_summary bootstrapping ?
| def _is_cluster_bootstrapping(cluster_summary):
return ((cluster_summary.status.state != 'STARTING') and (not hasattr(cluster_summary.status.timeline, 'readydatetime')))
| null | null | null | currently
| codeqa | def is cluster bootstrapping cluster summary return cluster summary status state 'STARTING' and not hasattr cluster summary status timeline 'readydatetime'
| null | null | null | null | Question:
When is * cluster_summary bootstrapping ?
Code:
def _is_cluster_bootstrapping(cluster_summary):
return ((cluster_summary.status.state != 'STARTING') and (not hasattr(cluster_summary.status.timeline, 'readydatetime')))
|
null | null | null | What did the code set ?
| def set_sysctl(key, value):
run_as_root(('/sbin/sysctl -n -e -w %(key)s=%(value)s' % locals()))
| null | null | null | a kernel parameter
| codeqa | def set sysctl key value run as root '/sbin/sysctl-n-e-w% key s % value s' % locals
| null | null | null | null | Question:
What did the code set ?
Code:
def set_sysctl(key, value):
run_as_root(('/sbin/sysctl -n -e -w %(key)s=%(value)s' % locals()))
|
null | null | null | What sets the icon of object ?
| def icon(object, icondata=None):
fsr = Carbon.File.FSRef(object)
object_alias = fsr.FSNewAliasMinimal()
if (icondata is None):
return _geticon(object_alias)
return _seticon(object_alias, icondata)
| null | null | null | icon
| codeqa | def icon object icondata None fsr Carbon File FS Ref object object alias fsr FS New Alias Minimal if icondata is None return geticon object alias return seticon object alias icondata
| null | null | null | null | Question:
What sets the icon of object ?
Code:
def icon(object, icondata=None):
fsr = Carbon.File.FSRef(object)
object_alias = fsr.FSNewAliasMinimal()
if (icondata is None):
return _geticon(object_alias)
return _seticon(object_alias, icondata)
|
null | null | null | What does icon set ?
| def icon(object, icondata=None):
fsr = Carbon.File.FSRef(object)
object_alias = fsr.FSNewAliasMinimal()
if (icondata is None):
return _geticon(object_alias)
return _seticon(object_alias, icondata)
| null | null | null | the icon of object
| codeqa | def icon object icondata None fsr Carbon File FS Ref object object alias fsr FS New Alias Minimal if icondata is None return geticon object alias return seticon object alias icondata
| null | null | null | null | Question:
What does icon set ?
Code:
def icon(object, icondata=None):
fsr = Carbon.File.FSRef(object)
object_alias = fsr.FSNewAliasMinimal()
if (icondata is None):
return _geticon(object_alias)
return _seticon(object_alias, icondata)
|
null | null | null | When did the command arguments render ?
| @salt.utils.decorators.which('gzip')
def gzip(sourcefile, template=None, runas=None, options=None):
cmd = ['gzip']
if options:
cmd.append(options)
cmd.append('{0}'.format(sourcefile))
return __salt__['cmd.run'](cmd, template=template, runas=runas, python_shell=False).splitlines()
| null | null | null | before execution
| codeqa | @salt utils decorators which 'gzip' def gzip sourcefile template None runas None options None cmd ['gzip']if options cmd append options cmd append '{ 0 }' format sourcefile return salt ['cmd run'] cmd template template runas runas python shell False splitlines
| null | null | null | null | Question:
When did the command arguments render ?
Code:
@salt.utils.decorators.which('gzip')
def gzip(sourcefile, template=None, runas=None, options=None):
cmd = ['gzip']
if options:
cmd.append(options)
cmd.append('{0}'.format(sourcefile))
return __salt__['cmd.run'](cmd, template=template, runas=runas, python_shell=False).splitlines()
|
null | null | null | What does the code get from salt ?
| def _get_options(ret=None):
defaults = {'level': 'LOG_INFO', 'facility': 'LOG_USER', 'options': []}
attrs = {'level': 'level', 'facility': 'facility', 'tag': 'tag', 'options': 'options'}
_options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults)
return _options
| null | null | null | the returner options
| codeqa | def get options ret None defaults {'level' 'LOG INFO' 'facility' 'LOG USER' 'options' []}attrs {'level' 'level' 'facility' 'facility' 'tag' 'tag' 'options' 'options'} options salt returners get returner options virtualname ret attrs salt salt opts opts defaults defaults return options
| null | null | null | null | Question:
What does the code get from salt ?
Code:
def _get_options(ret=None):
defaults = {'level': 'LOG_INFO', 'facility': 'LOG_USER', 'options': []}
attrs = {'level': 'level', 'facility': 'facility', 'tag': 'tag', 'options': 'options'}
_options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults)
return _options
|
null | null | null | What does the code find ?
| def get_service_by_id_or_name(consul_api, service_id_or_name):
for (name, service) in consul_api.agent.services().items():
if ((service['ID'] == service_id_or_name) or (service['Service'] == service_id_or_name)):
return ConsulService(loaded=service)
| null | null | null | one with the given i d
| codeqa | def get service by id or name consul api service id or name for name service in consul api agent services items if service['ID'] service id or name or service[' Service'] service id or name return Consul Service loaded service
| null | null | null | null | Question:
What does the code find ?
Code:
def get_service_by_id_or_name(consul_api, service_id_or_name):
for (name, service) in consul_api.agent.services().items():
if ((service['ID'] == service_id_or_name) or (service['Service'] == service_id_or_name)):
return ConsulService(loaded=service)
|
null | null | null | What does the code iterate ?
| def get_service_by_id_or_name(consul_api, service_id_or_name):
for (name, service) in consul_api.agent.services().items():
if ((service['ID'] == service_id_or_name) or (service['Service'] == service_id_or_name)):
return ConsulService(loaded=service)
| null | null | null | the registered services
| codeqa | def get service by id or name consul api service id or name for name service in consul api agent services items if service['ID'] service id or name or service[' Service'] service id or name return Consul Service loaded service
| null | null | null | null | Question:
What does the code iterate ?
Code:
def get_service_by_id_or_name(consul_api, service_id_or_name):
for (name, service) in consul_api.agent.services().items():
if ((service['ID'] == service_id_or_name) or (service['Service'] == service_id_or_name)):
return ConsulService(loaded=service)
|
null | null | null | Where is string interpolation delayed ?
| def check_delayed_string_interpolation(logical_line, physical_line, filename):
if ('nova/tests' in filename):
return
if pep8.noqa(physical_line):
return
if log_string_interpolation.match(logical_line):
(yield (logical_line.index('%'), "N354: String interpolation should be delayed to be handled by the logging code, rather than being done at the point of the logging call. Use ',' instead of '%'."))
| null | null | null | at logging calls not correct
| codeqa | def check delayed string interpolation logical line physical line filename if 'nova/tests' in filename returnif pep 8 noqa physical line returnif log string interpolation match logical line yield logical line index '%' "N 354 Stringinterpolationshouldbedelayedtobehandledbytheloggingcode ratherthanbeingdoneatthepointoftheloggingcall Use' 'insteadof'%' "
| null | null | null | null | Question:
Where is string interpolation delayed ?
Code:
def check_delayed_string_interpolation(logical_line, physical_line, filename):
if ('nova/tests' in filename):
return
if pep8.noqa(physical_line):
return
if log_string_interpolation.match(logical_line):
(yield (logical_line.index('%'), "N354: String interpolation should be delayed to be handled by the logging code, rather than being done at the point of the logging call. Use ',' instead of '%'."))
|
null | null | null | What is delayed at logging calls not correct ?
| def check_delayed_string_interpolation(logical_line, physical_line, filename):
if ('nova/tests' in filename):
return
if pep8.noqa(physical_line):
return
if log_string_interpolation.match(logical_line):
(yield (logical_line.index('%'), "N354: String interpolation should be delayed to be handled by the logging code, rather than being done at the point of the logging call. Use ',' instead of '%'."))
| null | null | null | string interpolation
| codeqa | def check delayed string interpolation logical line physical line filename if 'nova/tests' in filename returnif pep 8 noqa physical line returnif log string interpolation match logical line yield logical line index '%' "N 354 Stringinterpolationshouldbedelayedtobehandledbytheloggingcode ratherthanbeingdoneatthepointoftheloggingcall Use' 'insteadof'%' "
| null | null | null | null | Question:
What is delayed at logging calls not correct ?
Code:
def check_delayed_string_interpolation(logical_line, physical_line, filename):
if ('nova/tests' in filename):
return
if pep8.noqa(physical_line):
return
if log_string_interpolation.match(logical_line):
(yield (logical_line.index('%'), "N354: String interpolation should be delayed to be handled by the logging code, rather than being done at the point of the logging call. Use ',' instead of '%'."))
|
null | null | null | What does the code create ?
| def new(key, *args, **kwargs):
return RC2Cipher(key, *args, **kwargs)
| null | null | null | a new rc2 cipher
| codeqa | def new key *args **kwargs return RC 2 Cipher key *args **kwargs
| null | null | null | null | Question:
What does the code create ?
Code:
def new(key, *args, **kwargs):
return RC2Cipher(key, *args, **kwargs)
|
null | null | null | How do to file write ?
| def write_file(file, data):
fp = open(file, 'w')
fp.write(data)
fp.close()
| null | null | null | simple
| codeqa | def write file file data fp open file 'w' fp write data fp close
| null | null | null | null | Question:
How do to file write ?
Code:
def write_file(file, data):
fp = open(file, 'w')
fp.write(data)
fp.close()
|
null | null | null | How do learning rates scale ?
| def rmsprop(loss_or_grads, params, learning_rate=1.0, rho=0.9, epsilon=1e-06):
grads = get_or_compute_grads(loss_or_grads, params)
updates = OrderedDict()
one = T.constant(1)
for (param, grad) in zip(params, grads):
value = param.get_value(borrow=True)
accu = theano.shared(np.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable)
accu_new = ((rho * accu) + ((one - rho) * (grad ** 2)))
updates[accu] = accu_new
updates[param] = (param - ((learning_rate * grad) / T.sqrt((accu_new + epsilon))))
return updates
| null | null | null | by dividing with the moving average of the root mean squared gradients
| codeqa | def rmsprop loss or grads params learning rate 1 0 rho 0 9 epsilon 1e- 06 grads get or compute grads loss or grads params updates Ordered Dict one T constant 1 for param grad in zip params grads value param get value borrow True accu theano shared np zeros value shape dtype value dtype broadcastable param broadcastable accu new rho * accu + one - rho * grad ** 2 updates[accu] accu newupdates[param] param - learning rate * grad / T sqrt accu new + epsilon return updates
| null | null | null | null | Question:
How do learning rates scale ?
Code:
def rmsprop(loss_or_grads, params, learning_rate=1.0, rho=0.9, epsilon=1e-06):
grads = get_or_compute_grads(loss_or_grads, params)
updates = OrderedDict()
one = T.constant(1)
for (param, grad) in zip(params, grads):
value = param.get_value(borrow=True)
accu = theano.shared(np.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable)
accu_new = ((rho * accu) + ((one - rho) * (grad ** 2)))
updates[accu] = accu_new
updates[param] = (param - ((learning_rate * grad) / T.sqrt((accu_new + epsilon))))
return updates
|
null | null | null | What does the code return ?
| def findall(dir=os.curdir):
from stat import ST_MODE, S_ISREG, S_ISDIR, S_ISLNK
list = []
stack = [dir]
pop = stack.pop
push = stack.append
while stack:
dir = pop()
names = os.listdir(dir)
for name in names:
if (dir != os.curdir):
fullname = os.path.join(dir, name)
else:
fullname = name
stat = os.stat(fullname)
mode = stat[ST_MODE]
if S_ISREG(mode):
list.append(fullname)
elif (S_ISDIR(mode) and (not S_ISLNK(mode))):
push(fullname)
return list
| null | null | null | the list of full filenames
| codeqa | def findall dir os curdir from stat import ST MODE S ISREG S ISDIR S ISLN Klist []stack [dir]pop stack poppush stack appendwhile stack dir pop names os listdir dir for name in names if dir os curdir fullname os path join dir name else fullname namestat os stat fullname mode stat[ST MODE]if S ISREG mode list append fullname elif S ISDIR mode and not S ISLNK mode push fullname return list
| null | null | null | null | Question:
What does the code return ?
Code:
def findall(dir=os.curdir):
from stat import ST_MODE, S_ISREG, S_ISDIR, S_ISLNK
list = []
stack = [dir]
pop = stack.pop
push = stack.append
while stack:
dir = pop()
names = os.listdir(dir)
for name in names:
if (dir != os.curdir):
fullname = os.path.join(dir, name)
else:
fullname = name
stat = os.stat(fullname)
mode = stat[ST_MODE]
if S_ISREG(mode):
list.append(fullname)
elif (S_ISDIR(mode) and (not S_ISLNK(mode))):
push(fullname)
return list
|
null | null | null | What does the code generate in directory ?
| def generate_configuration(directory):
conf = osp.join(get_module_source_path('spyder.utils.help'), 'conf.py')
layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html')
os.makedirs(osp.join(directory, 'templates'))
os.makedirs(osp.join(directory, 'static'))
shutil.copy(conf, directory)
shutil.copy(layout, osp.join(directory, 'templates'))
open(osp.join(directory, '__init__.py'), 'w').write('')
open(osp.join(directory, 'static', 'empty'), 'w').write('')
| null | null | null | a sphinx configuration
| codeqa | def generate configuration directory conf osp join get module source path 'spyder utils help' 'conf py' layout osp join osp join CONFDIR PATH 'templates' 'layout html' os makedirs osp join directory 'templates' os makedirs osp join directory 'static' shutil copy conf directory shutil copy layout osp join directory 'templates' open osp join directory ' init py' 'w' write '' open osp join directory 'static' 'empty' 'w' write ''
| null | null | null | null | Question:
What does the code generate in directory ?
Code:
def generate_configuration(directory):
conf = osp.join(get_module_source_path('spyder.utils.help'), 'conf.py')
layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html')
os.makedirs(osp.join(directory, 'templates'))
os.makedirs(osp.join(directory, 'static'))
shutil.copy(conf, directory)
shutil.copy(layout, osp.join(directory, 'templates'))
open(osp.join(directory, '__init__.py'), 'w').write('')
open(osp.join(directory, 'static', 'empty'), 'w').write('')
|
null | null | null | Where does the code generate a sphinx configuration ?
| def generate_configuration(directory):
conf = osp.join(get_module_source_path('spyder.utils.help'), 'conf.py')
layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html')
os.makedirs(osp.join(directory, 'templates'))
os.makedirs(osp.join(directory, 'static'))
shutil.copy(conf, directory)
shutil.copy(layout, osp.join(directory, 'templates'))
open(osp.join(directory, '__init__.py'), 'w').write('')
open(osp.join(directory, 'static', 'empty'), 'w').write('')
| null | null | null | in directory
| codeqa | def generate configuration directory conf osp join get module source path 'spyder utils help' 'conf py' layout osp join osp join CONFDIR PATH 'templates' 'layout html' os makedirs osp join directory 'templates' os makedirs osp join directory 'static' shutil copy conf directory shutil copy layout osp join directory 'templates' open osp join directory ' init py' 'w' write '' open osp join directory 'static' 'empty' 'w' write ''
| null | null | null | null | Question:
Where does the code generate a sphinx configuration ?
Code:
def generate_configuration(directory):
conf = osp.join(get_module_source_path('spyder.utils.help'), 'conf.py')
layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html')
os.makedirs(osp.join(directory, 'templates'))
os.makedirs(osp.join(directory, 'static'))
shutil.copy(conf, directory)
shutil.copy(layout, osp.join(directory, 'templates'))
open(osp.join(directory, '__init__.py'), 'w').write('')
open(osp.join(directory, 'static', 'empty'), 'w').write('')
|
null | null | null | What fails to import correctly when ?
| def _import_fail_message(module, version):
_dict = {'which': which[0], 'module': module, 'specific': (version + module)}
print ('\nThe import of the %(which)s version of the %(module)s module,\n%(specific)s, failed. This is is either because %(which)s was\nunavailable when matplotlib was compiled, because a dependency of\n%(specific)s could not be satisfied, or because the build flag for\nthis module was turned off in setup.py. If it appears that\n%(specific)s was not built, make sure you have a working copy of\n%(which)s and then re-install matplotlib. Otherwise, the following\ntraceback gives more details:\n' % _dict)
| null | null | null | the array package specific version of an extension
| codeqa | def import fail message module version dict {'which' which[ 0 ] 'module' module 'specific' version + module }print '\n Theimportofthe% which sversionofthe% module smodule \n% specific s failed Thisisiseitherbecause% which swas\nunavailablewhenmatplotlibwascompiled becauseadependencyof\n% specific scouldnotbesatisfied orbecausethebuildflagfor\nthismodulewasturnedoffinsetup py Ifitappearsthat\n% specific swasnotbuilt makesureyouhaveaworkingcopyof\n% which sandthenre-installmatplotlib Otherwise thefollowing\ntracebackgivesmoredetails \n' % dict
| null | null | null | null | Question:
What fails to import correctly when ?
Code:
def _import_fail_message(module, version):
_dict = {'which': which[0], 'module': module, 'specific': (version + module)}
print ('\nThe import of the %(which)s version of the %(module)s module,\n%(specific)s, failed. This is is either because %(which)s was\nunavailable when matplotlib was compiled, because a dependency of\n%(specific)s could not be satisfied, or because the build flag for\nthis module was turned off in setup.py. If it appears that\n%(specific)s was not built, make sure you have a working copy of\n%(which)s and then re-install matplotlib. Otherwise, the following\ntraceback gives more details:\n' % _dict)
|
null | null | null | When does a message print ?
| def _import_fail_message(module, version):
_dict = {'which': which[0], 'module': module, 'specific': (version + module)}
print ('\nThe import of the %(which)s version of the %(module)s module,\n%(specific)s, failed. This is is either because %(which)s was\nunavailable when matplotlib was compiled, because a dependency of\n%(specific)s could not be satisfied, or because the build flag for\nthis module was turned off in setup.py. If it appears that\n%(specific)s was not built, make sure you have a working copy of\n%(which)s and then re-install matplotlib. Otherwise, the following\ntraceback gives more details:\n' % _dict)
| null | null | null | when the array package specific version of an extension fails to import correctly
| codeqa | def import fail message module version dict {'which' which[ 0 ] 'module' module 'specific' version + module }print '\n Theimportofthe% which sversionofthe% module smodule \n% specific s failed Thisisiseitherbecause% which swas\nunavailablewhenmatplotlibwascompiled becauseadependencyof\n% specific scouldnotbesatisfied orbecausethebuildflagfor\nthismodulewasturnedoffinsetup py Ifitappearsthat\n% specific swasnotbuilt makesureyouhaveaworkingcopyof\n% which sandthenre-installmatplotlib Otherwise thefollowing\ntracebackgivesmoredetails \n' % dict
| null | null | null | null | Question:
When does a message print ?
Code:
def _import_fail_message(module, version):
_dict = {'which': which[0], 'module': module, 'specific': (version + module)}
print ('\nThe import of the %(which)s version of the %(module)s module,\n%(specific)s, failed. This is is either because %(which)s was\nunavailable when matplotlib was compiled, because a dependency of\n%(specific)s could not be satisfied, or because the build flag for\nthis module was turned off in setup.py. If it appears that\n%(specific)s was not built, make sure you have a working copy of\n%(which)s and then re-install matplotlib. Otherwise, the following\ntraceback gives more details:\n' % _dict)
|
null | null | null | What does the array package specific version of an extension fail when ?
| def _import_fail_message(module, version):
_dict = {'which': which[0], 'module': module, 'specific': (version + module)}
print ('\nThe import of the %(which)s version of the %(module)s module,\n%(specific)s, failed. This is is either because %(which)s was\nunavailable when matplotlib was compiled, because a dependency of\n%(specific)s could not be satisfied, or because the build flag for\nthis module was turned off in setup.py. If it appears that\n%(specific)s was not built, make sure you have a working copy of\n%(which)s and then re-install matplotlib. Otherwise, the following\ntraceback gives more details:\n' % _dict)
| null | null | null | to import correctly
| codeqa | def import fail message module version dict {'which' which[ 0 ] 'module' module 'specific' version + module }print '\n Theimportofthe% which sversionofthe% module smodule \n% specific s failed Thisisiseitherbecause% which swas\nunavailablewhenmatplotlibwascompiled becauseadependencyof\n% specific scouldnotbesatisfied orbecausethebuildflagfor\nthismodulewasturnedoffinsetup py Ifitappearsthat\n% specific swasnotbuilt makesureyouhaveaworkingcopyof\n% which sandthenre-installmatplotlib Otherwise thefollowing\ntracebackgivesmoredetails \n' % dict
| null | null | null | null | Question:
What does the array package specific version of an extension fail when ?
Code:
def _import_fail_message(module, version):
_dict = {'which': which[0], 'module': module, 'specific': (version + module)}
print ('\nThe import of the %(which)s version of the %(module)s module,\n%(specific)s, failed. This is is either because %(which)s was\nunavailable when matplotlib was compiled, because a dependency of\n%(specific)s could not be satisfied, or because the build flag for\nthis module was turned off in setup.py. If it appears that\n%(specific)s was not built, make sure you have a working copy of\n%(which)s and then re-install matplotlib. Otherwise, the following\ntraceback gives more details:\n' % _dict)
|
null | null | null | What does the code get ?
| def getProfileBaseName(repository):
return getProfileName(repository.baseName, repository)
| null | null | null | the profile base file name
| codeqa | def get Profile Base Name repository return get Profile Name repository base Name repository
| null | null | null | null | Question:
What does the code get ?
Code:
def getProfileBaseName(repository):
return getProfileName(repository.baseName, repository)
|
null | null | null | What does a context manager silence ?
| @contextlib.contextmanager
def _silence():
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
sys.stderr = _DummyFile()
exception_occurred = False
try:
(yield)
except:
exception_occurred = True
sys.stdout = old_stdout
sys.stderr = old_stderr
raise
if (not exception_occurred):
sys.stdout = old_stdout
sys.stderr = old_stderr
| null | null | null | sys
| codeqa | @contextlib contextmanagerdef silence old stdout sys stdoutold stderr sys stderrsys stdout Dummy File sys stderr Dummy File exception occurred Falsetry yield except exception occurred Truesys stdout old stdoutsys stderr old stderrraiseif not exception occurred sys stdout old stdoutsys stderr old stderr
| null | null | null | null | Question:
What does a context manager silence ?
Code:
@contextlib.contextmanager
def _silence():
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
sys.stderr = _DummyFile()
exception_occurred = False
try:
(yield)
except:
exception_occurred = True
sys.stdout = old_stdout
sys.stderr = old_stderr
raise
if (not exception_occurred):
sys.stdout = old_stdout
sys.stderr = old_stderr
|
null | null | null | What does the code sanitize ?
| def sanitize_file_name2(name, substitute='_'):
if isbytestring(name):
return sanitize_file_name(name, substitute=substitute)
return sanitize_file_name_unicode(name, substitute=substitute)
| null | null | null | filenames removing invalid chars
| codeqa | def sanitize file name 2 name substitute ' ' if isbytestring name return sanitize file name name substitute substitute return sanitize file name unicode name substitute substitute
| null | null | null | null | Question:
What does the code sanitize ?
Code:
def sanitize_file_name2(name, substitute='_'):
if isbytestring(name):
return sanitize_file_name(name, substitute=substitute)
return sanitize_file_name_unicode(name, substitute=substitute)
|
null | null | null | What is containing the specified information ?
| def make_instance(klass, spec, base64encode=False):
return klass().loadd(spec, base64encode)
| null | null | null | a class instance
| codeqa | def make instance klass spec base 64 encode False return klass loadd spec base 64 encode
| null | null | null | null | Question:
What is containing the specified information ?
Code:
def make_instance(klass, spec, base64encode=False):
return klass().loadd(spec, base64encode)
|
null | null | null | What do a class instance contain ?
| def make_instance(klass, spec, base64encode=False):
return klass().loadd(spec, base64encode)
| null | null | null | the specified information
| codeqa | def make instance klass spec base 64 encode False return klass loadd spec base 64 encode
| null | null | null | null | Question:
What do a class instance contain ?
Code:
def make_instance(klass, spec, base64encode=False):
return klass().loadd(spec, base64encode)
|
null | null | null | What does the code calculate ?
| def moment(a, moment=1, axis=0, nan_policy='propagate'):
(a, axis) = _chk_asarray(a, axis)
(contains_nan, nan_policy) = _contains_nan(a, nan_policy)
if (contains_nan and (nan_policy == 'omit')):
a = ma.masked_invalid(a)
return mstats_basic.moment(a, moment, axis)
if (a.size == 0):
if np.isscalar(moment):
return np.nan
else:
return (np.ones(np.asarray(moment).shape, dtype=np.float64) * np.nan)
if (not np.isscalar(moment)):
mmnt = [_moment(a, i, axis) for i in moment]
return np.array(mmnt)
else:
return _moment(a, moment, axis)
| null | null | null | the nth moment about the mean for a sample
| codeqa | def moment a moment 1 axis 0 nan policy 'propagate' a axis chk asarray a axis contains nan nan policy contains nan a nan policy if contains nan and nan policy 'omit' a ma masked invalid a return mstats basic moment a moment axis if a size 0 if np isscalar moment return np nanelse return np ones np asarray moment shape dtype np float 64 * np nan if not np isscalar moment mmnt [ moment a i axis for i in moment]return np array mmnt else return moment a moment axis
| null | null | null | null | Question:
What does the code calculate ?
Code:
def moment(a, moment=1, axis=0, nan_policy='propagate'):
(a, axis) = _chk_asarray(a, axis)
(contains_nan, nan_policy) = _contains_nan(a, nan_policy)
if (contains_nan and (nan_policy == 'omit')):
a = ma.masked_invalid(a)
return mstats_basic.moment(a, moment, axis)
if (a.size == 0):
if np.isscalar(moment):
return np.nan
else:
return (np.ones(np.asarray(moment).shape, dtype=np.float64) * np.nan)
if (not np.isscalar(moment)):
mmnt = [_moment(a, i, axis) for i in moment]
return np.array(mmnt)
else:
return _moment(a, moment, axis)
|
null | null | null | What does the code improve ?
| def _correct_auto_elements(surf, mat):
pi2 = (2.0 * np.pi)
tris_flat = surf['tris'].ravel()
misses = (pi2 - mat.sum(axis=1))
for (j, miss) in enumerate(misses):
n_memb = len(surf['neighbor_tri'][j])
mat[(j, j)] = (miss / 2.0)
miss /= (4.0 * n_memb)
members = np.where((j == tris_flat))[0]
mods = (members % 3)
offsets = np.array([[1, 2], [(-1), 1], [(-1), (-2)]])
tri_1 = (members + offsets[(mods, 0)])
tri_2 = (members + offsets[(mods, 1)])
for (t1, t2) in zip(tri_1, tri_2):
mat[(j, tris_flat[t1])] += miss
mat[(j, tris_flat[t2])] += miss
return
| null | null | null | auto - element approximation
| codeqa | def correct auto elements surf mat pi 2 2 0 * np pi tris flat surf['tris'] ravel misses pi 2 - mat sum axis 1 for j miss in enumerate misses n memb len surf['neighbor tri'][j] mat[ j j ] miss / 2 0 miss / 4 0 * n memb members np where j tris flat [0 ]mods members % 3 offsets np array [[ 1 2] [ -1 1] [ -1 -2 ]] tri 1 members + offsets[ mods 0 ] tri 2 members + offsets[ mods 1 ] for t1 t2 in zip tri 1 tri 2 mat[ j tris flat[t 1 ] ] + missmat[ j tris flat[t 2 ] ] + missreturn
| null | null | null | null | Question:
What does the code improve ?
Code:
def _correct_auto_elements(surf, mat):
pi2 = (2.0 * np.pi)
tris_flat = surf['tris'].ravel()
misses = (pi2 - mat.sum(axis=1))
for (j, miss) in enumerate(misses):
n_memb = len(surf['neighbor_tri'][j])
mat[(j, j)] = (miss / 2.0)
miss /= (4.0 * n_memb)
members = np.where((j == tris_flat))[0]
mods = (members % 3)
offsets = np.array([[1, 2], [(-1), 1], [(-1), (-2)]])
tri_1 = (members + offsets[(mods, 0)])
tri_2 = (members + offsets[(mods, 1)])
for (t1, t2) in zip(tri_1, tri_2):
mat[(j, tris_flat[t1])] += miss
mat[(j, tris_flat[t2])] += miss
return
|
null | null | null | What does the code configure ?
| def configure_celery_app(app, celery):
app.config.update({'BROKER_URL': app.config['CELERY_BROKER_URL']})
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase, ):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
| null | null | null | the celery app
| codeqa | def configure celery app app celery app config update {'BROKER URL' app config['CELERY BROKER URL']} celery conf update app config Task Base celery Taskclass Context Task Task Base abstract Truedef call self *args **kwargs with app app context return Task Base call self *args **kwargs celery Task Context Task
| null | null | null | null | Question:
What does the code configure ?
Code:
def configure_celery_app(app, celery):
app.config.update({'BROKER_URL': app.config['CELERY_BROKER_URL']})
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase, ):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
|
null | null | null | What does the code delete from a dataset ?
| def resource_delete(context, data_dict):
model = context['model']
id = _get_or_bust(data_dict, 'id')
entity = model.Resource.get(id)
if (entity is None):
raise NotFound
_check_access('resource_delete', context, data_dict)
package_id = entity.get_package_id()
pkg_dict = _get_action('package_show')(context, {'id': package_id})
for plugin in plugins.PluginImplementations(plugins.IResourceController):
plugin.before_delete(context, data_dict, pkg_dict.get('resources', []))
if pkg_dict.get('resources'):
pkg_dict['resources'] = [r for r in pkg_dict['resources'] if (not (r['id'] == id))]
try:
pkg_dict = _get_action('package_update')(context, pkg_dict)
except ValidationError as e:
errors = e.error_dict['resources'][(-1)]
raise ValidationError(errors)
for plugin in plugins.PluginImplementations(plugins.IResourceController):
plugin.after_delete(context, pkg_dict.get('resources', []))
model.repo.commit()
| null | null | null | a resource
| codeqa | def resource delete context data dict model context['model']id get or bust data dict 'id' entity model Resource get id if entity is None raise Not Found check access 'resource delete' context data dict package id entity get package id pkg dict get action 'package show' context {'id' package id} for plugin in plugins Plugin Implementations plugins I Resource Controller plugin before delete context data dict pkg dict get 'resources' [] if pkg dict get 'resources' pkg dict['resources'] [r for r in pkg dict['resources'] if not r['id'] id ]try pkg dict get action 'package update' context pkg dict except Validation Error as e errors e error dict['resources'][ -1 ]raise Validation Error errors for plugin in plugins Plugin Implementations plugins I Resource Controller plugin after delete context pkg dict get 'resources' [] model repo commit
| null | null | null | null | Question:
What does the code delete from a dataset ?
Code:
def resource_delete(context, data_dict):
model = context['model']
id = _get_or_bust(data_dict, 'id')
entity = model.Resource.get(id)
if (entity is None):
raise NotFound
_check_access('resource_delete', context, data_dict)
package_id = entity.get_package_id()
pkg_dict = _get_action('package_show')(context, {'id': package_id})
for plugin in plugins.PluginImplementations(plugins.IResourceController):
plugin.before_delete(context, data_dict, pkg_dict.get('resources', []))
if pkg_dict.get('resources'):
pkg_dict['resources'] = [r for r in pkg_dict['resources'] if (not (r['id'] == id))]
try:
pkg_dict = _get_action('package_update')(context, pkg_dict)
except ValidationError as e:
errors = e.error_dict['resources'][(-1)]
raise ValidationError(errors)
for plugin in plugins.PluginImplementations(plugins.IResourceController):
plugin.after_delete(context, pkg_dict.get('resources', []))
model.repo.commit()
|
null | null | null | What does the code delete ?
| @utils.arg('id', metavar='<id>', help='Unique ID of the monitor type to delete')
@utils.service_type('monitor')
def do_type_delete(cs, args):
cs.monitor_types.delete(args.id)
| null | null | null | a specific monitor type
| codeqa | @utils arg 'id' metavar '<id>' help ' Unique I Dofthemonitortypetodelete' @utils service type 'monitor' def do type delete cs args cs monitor types delete args id
| null | null | null | null | Question:
What does the code delete ?
Code:
@utils.arg('id', metavar='<id>', help='Unique ID of the monitor type to delete')
@utils.service_type('monitor')
def do_type_delete(cs, args):
cs.monitor_types.delete(args.id)
|
null | null | null | When do first position return ?
| def _skip_whitespace(data, pos, must_be_nontrivial=False):
if must_be_nontrivial:
if ((pos == len(data)) or (not data[pos].isspace())):
raise ParsingError(u'Expecting whitespace at {0}!'.format(_format_position(data, pos)))
while (pos < len(data)):
if (not data[pos].isspace()):
break
pos += 1
return pos
| null | null | null | after whitespace
| codeqa | def skip whitespace data pos must be nontrivial False if must be nontrivial if pos len data or not data[pos] isspace raise Parsing Error u' Expectingwhitespaceat{ 0 } ' format format position data pos while pos < len data if not data[pos] isspace breakpos + 1return pos
| null | null | null | null | Question:
When do first position return ?
Code:
def _skip_whitespace(data, pos, must_be_nontrivial=False):
if must_be_nontrivial:
if ((pos == len(data)) or (not data[pos].isspace())):
raise ParsingError(u'Expecting whitespace at {0}!'.format(_format_position(data, pos)))
while (pos < len(data)):
if (not data[pos].isspace()):
break
pos += 1
return pos
|
null | null | null | How does the code execute a minion function ?
| def cross_test(func, args=None):
if (args is None):
args = []
return __salt__[func](*args)
| null | null | null | via the _ _ salt _ _ object in the test module
| codeqa | def cross test func args None if args is None args []return salt [func] *args
| null | null | null | null | Question:
How does the code execute a minion function ?
Code:
def cross_test(func, args=None):
if (args is None):
args = []
return __salt__[func](*args)
|
null | null | null | What does the code execute via the _ _ salt _ _ object in the test module ?
| def cross_test(func, args=None):
if (args is None):
args = []
return __salt__[func](*args)
| null | null | null | a minion function
| codeqa | def cross test func args None if args is None args []return salt [func] *args
| null | null | null | null | Question:
What does the code execute via the _ _ salt _ _ object in the test module ?
Code:
def cross_test(func, args=None):
if (args is None):
args = []
return __salt__[func](*args)
|
null | null | null | What instructs to verify the validity of a resource record that appears to be out of date ?
| def DNSServiceReconfirmRecord(flags=0, interfaceIndex=kDNSServiceInterfaceIndexAny, fullname=_NO_DEFAULT, rrtype=_NO_DEFAULT, rrclass=kDNSServiceClass_IN, rdata=_NO_DEFAULT):
_NO_DEFAULT.check(fullname)
_NO_DEFAULT.check(rrtype)
_NO_DEFAULT.check(rdata)
(rdlen, rdata) = _string_to_length_and_void_p(rdata)
_global_lock.acquire()
try:
_DNSServiceReconfirmRecord(flags, interfaceIndex, fullname, rrtype, rrclass, rdlen, rdata)
finally:
_global_lock.release()
| null | null | null | the daemon
| codeqa | def DNS Service Reconfirm Record flags 0 interface Index kDNS Service Interface Index Any fullname NO DEFAULT rrtype NO DEFAULT rrclass kDNS Service Class IN rdata NO DEFAULT NO DEFAULT check fullname NO DEFAULT check rrtype NO DEFAULT check rdata rdlen rdata string to length and void p rdata global lock acquire try DNS Service Reconfirm Record flags interface Index fullname rrtype rrclass rdlen rdata finally global lock release
| null | null | null | null | Question:
What instructs to verify the validity of a resource record that appears to be out of date ?
Code:
def DNSServiceReconfirmRecord(flags=0, interfaceIndex=kDNSServiceInterfaceIndexAny, fullname=_NO_DEFAULT, rrtype=_NO_DEFAULT, rrclass=kDNSServiceClass_IN, rdata=_NO_DEFAULT):
_NO_DEFAULT.check(fullname)
_NO_DEFAULT.check(rrtype)
_NO_DEFAULT.check(rdata)
(rdlen, rdata) = _string_to_length_and_void_p(rdata)
_global_lock.acquire()
try:
_DNSServiceReconfirmRecord(flags, interfaceIndex, fullname, rrtype, rrclass, rdlen, rdata)
finally:
_global_lock.release()
|
null | null | null | What is comprising foreground and background examples ?
| def _sample_rois(roidb, fg_rois_per_image, rois_per_image, num_classes):
labels = roidb['max_classes']
overlaps = roidb['max_overlaps']
rois = roidb['boxes']
fg_inds = np.where((overlaps >= cfg.TRAIN.FG_THRESH))[0]
fg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_inds.size)
if (fg_inds.size > 0):
fg_inds = npr.choice(fg_inds, size=fg_rois_per_this_image, replace=False)
bg_inds = np.where(((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO)))[0]
bg_rois_per_this_image = (rois_per_image - fg_rois_per_this_image)
bg_rois_per_this_image = np.minimum(bg_rois_per_this_image, bg_inds.size)
if (bg_inds.size > 0):
bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False)
keep_inds = np.append(fg_inds, bg_inds)
labels = labels[keep_inds]
labels[fg_rois_per_this_image:] = 0
overlaps = overlaps[keep_inds]
rois = rois[keep_inds]
(bbox_targets, bbox_inside_weights) = _get_bbox_regression_labels(roidb['bbox_targets'][keep_inds, :], num_classes)
return (labels, overlaps, rois, bbox_targets, bbox_inside_weights)
| null | null | null | rois
| codeqa | def sample rois roidb fg rois per image rois per image num classes labels roidb['max classes']overlaps roidb['max overlaps']rois roidb['boxes']fg inds np where overlaps > cfg TRAIN FG THRESH [0 ]fg rois per this image np minimum fg rois per image fg inds size if fg inds size > 0 fg inds npr choice fg inds size fg rois per this image replace False bg inds np where overlaps < cfg TRAIN BG THRESH HI & overlaps > cfg TRAIN BG THRESH LO [0 ]bg rois per this image rois per image - fg rois per this image bg rois per this image np minimum bg rois per this image bg inds size if bg inds size > 0 bg inds npr choice bg inds size bg rois per this image replace False keep inds np append fg inds bg inds labels labels[keep inds]labels[fg rois per this image ] 0overlaps overlaps[keep inds]rois rois[keep inds] bbox targets bbox inside weights get bbox regression labels roidb['bbox targets'][keep inds ] num classes return labels overlaps rois bbox targets bbox inside weights
| null | null | null | null | Question:
What is comprising foreground and background examples ?
Code:
def _sample_rois(roidb, fg_rois_per_image, rois_per_image, num_classes):
labels = roidb['max_classes']
overlaps = roidb['max_overlaps']
rois = roidb['boxes']
fg_inds = np.where((overlaps >= cfg.TRAIN.FG_THRESH))[0]
fg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_inds.size)
if (fg_inds.size > 0):
fg_inds = npr.choice(fg_inds, size=fg_rois_per_this_image, replace=False)
bg_inds = np.where(((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO)))[0]
bg_rois_per_this_image = (rois_per_image - fg_rois_per_this_image)
bg_rois_per_this_image = np.minimum(bg_rois_per_this_image, bg_inds.size)
if (bg_inds.size > 0):
bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False)
keep_inds = np.append(fg_inds, bg_inds)
labels = labels[keep_inds]
labels[fg_rois_per_this_image:] = 0
overlaps = overlaps[keep_inds]
rois = rois[keep_inds]
(bbox_targets, bbox_inside_weights) = _get_bbox_regression_labels(roidb['bbox_targets'][keep_inds, :], num_classes)
return (labels, overlaps, rois, bbox_targets, bbox_inside_weights)
|
null | null | null | What does the code compute ?
| def inverse_cosine_transform(F, k, x, **hints):
return InverseCosineTransform(F, k, x).doit(**hints)
| null | null | null | the unitary
| codeqa | def inverse cosine transform F k x **hints return Inverse Cosine Transform F k x doit **hints
| null | null | null | null | Question:
What does the code compute ?
Code:
def inverse_cosine_transform(F, k, x, **hints):
return InverseCosineTransform(F, k, x).doit(**hints)
|
null | null | null | What does the code create ?
| def quota_class_create(context, class_name, resource, limit):
return IMPL.quota_class_create(context, class_name, resource, limit)
| null | null | null | a quota class for the given name and resource
| codeqa | def quota class create context class name resource limit return IMPL quota class create context class name resource limit
| null | null | null | null | Question:
What does the code create ?
Code:
def quota_class_create(context, class_name, resource, limit):
return IMPL.quota_class_create(context, class_name, resource, limit)
|
null | null | null | What could we assure ?
| def open(*args):
if (len(args) == 2):
args = (args + (50000,))
if (sys.version_info >= (3,)):
return fopen(*args, **{'encoding': 'utf-8', 'errors': 'ignore'})
else:
return fopen(*args)
| null | null | null | sufficiently large buffer explicit
| codeqa | def open *args if len args 2 args args + 50000 if sys version info > 3 return fopen *args **{'encoding' 'utf- 8 ' 'errors' 'ignore'} else return fopen *args
| null | null | null | null | Question:
What could we assure ?
Code:
def open(*args):
if (len(args) == 2):
args = (args + (50000,))
if (sys.version_info >= (3,)):
return fopen(*args, **{'encoding': 'utf-8', 'errors': 'ignore'})
else:
return fopen(*args)
|
null | null | null | For what purpose did overload build in open ?
| def open(*args):
if (len(args) == 2):
args = (args + (50000,))
if (sys.version_info >= (3,)):
return fopen(*args, **{'encoding': 'utf-8', 'errors': 'ignore'})
else:
return fopen(*args)
| null | null | null | so we could assure sufficiently large buffer explicit
| codeqa | def open *args if len args 2 args args + 50000 if sys version info > 3 return fopen *args **{'encoding' 'utf- 8 ' 'errors' 'ignore'} else return fopen *args
| null | null | null | null | Question:
For what purpose did overload build in open ?
Code:
def open(*args):
if (len(args) == 2):
args = (args + (50000,))
if (sys.version_info >= (3,)):
return fopen(*args, **{'encoding': 'utf-8', 'errors': 'ignore'})
else:
return fopen(*args)
|
null | null | null | In which direction do the vehicle fly ?
| def goto_position_target_local_ned(north, east, down):
msg = vehicle.message_factory.set_position_target_local_ned_encode(0, 0, 0, mavutil.mavlink.MAV_FRAME_LOCAL_NED, 4088, north, east, down, 0, 0, 0, 0, 0, 0, 0, 0)
vehicle.send_mavlink(msg)
| null | null | null | to a specified location in the north
| codeqa | def goto position target local ned north east down msg vehicle message factory set position target local ned encode 0 0 0 mavutil mavlink MAV FRAME LOCAL NED 4088 north east down 0 0 0 0 0 0 0 0 vehicle send mavlink msg
| null | null | null | null | Question:
In which direction do the vehicle fly ?
Code:
def goto_position_target_local_ned(north, east, down):
msg = vehicle.message_factory.set_position_target_local_ned_encode(0, 0, 0, mavutil.mavlink.MAV_FRAME_LOCAL_NED, 4088, north, east, down, 0, 0, 0, 0, 0, 0, 0, 0)
vehicle.send_mavlink(msg)
|
null | null | null | What does the code remove from a block of text ?
| def dedent(content):
content = force_text(content)
whitespace_counts = [(len(line) - len(line.lstrip(u' '))) for line in content.splitlines()[1:] if line.lstrip()]
tab_counts = [(len(line) - len(line.lstrip(u' DCTB '))) for line in content.splitlines()[1:] if line.lstrip()]
if whitespace_counts:
whitespace_pattern = (u'^' + (u' ' * min(whitespace_counts)))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), u'', content)
elif tab_counts:
whitespace_pattern = (u'^' + (u' DCTB ' * min(whitespace_counts)))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), u'', content)
return content.strip()
| null | null | null | leading indent
| codeqa | def dedent content content force text content whitespace counts [ len line - len line lstrip u'' for line in content splitlines [1 ] if line lstrip ]tab counts [ len line - len line lstrip u' DCTB ' for line in content splitlines [1 ] if line lstrip ]if whitespace counts whitespace pattern u'^' + u'' * min whitespace counts content re sub re compile whitespace pattern re MULTILINE u'' content elif tab counts whitespace pattern u'^' + u' DCTB ' * min whitespace counts content re sub re compile whitespace pattern re MULTILINE u'' content return content strip
| null | null | null | null | Question:
What does the code remove from a block of text ?
Code:
def dedent(content):
content = force_text(content)
whitespace_counts = [(len(line) - len(line.lstrip(u' '))) for line in content.splitlines()[1:] if line.lstrip()]
tab_counts = [(len(line) - len(line.lstrip(u' DCTB '))) for line in content.splitlines()[1:] if line.lstrip()]
if whitespace_counts:
whitespace_pattern = (u'^' + (u' ' * min(whitespace_counts)))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), u'', content)
elif tab_counts:
whitespace_pattern = (u'^' + (u' DCTB ' * min(whitespace_counts)))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), u'', content)
return content.strip()
|
null | null | null | What does the code get ?
| def getArcDistance(relativeLocation, splitLine):
halfPlaneLineDistance = (0.5 * abs(relativeLocation.dropAxis(2)))
radius = getDoubleFromCharacterSplitLine('R', splitLine)
if (radius == None):
iFloat = getDoubleFromCharacterSplitLine('I', splitLine)
jFloat = getDoubleFromCharacterSplitLine('J', splitLine)
radius = abs(complex(iFloat, jFloat))
angle = 0.0
if (radius > 0.0):
halfPlaneLineDistanceOverRadius = (halfPlaneLineDistance / radius)
if (halfPlaneLineDistance < radius):
angle = (2.0 * math.asin(halfPlaneLineDistanceOverRadius))
else:
angle = (math.pi * halfPlaneLineDistanceOverRadius)
return abs(complex((angle * radius), relativeLocation.z))
| null | null | null | arc distance
| codeqa | def get Arc Distance relative Location split Line half Plane Line Distance 0 5 * abs relative Location drop Axis 2 radius get Double From Character Split Line 'R' split Line if radius None i Float get Double From Character Split Line 'I' split Line j Float get Double From Character Split Line 'J' split Line radius abs complex i Float j Float angle 0 0if radius > 0 0 half Plane Line Distance Over Radius half Plane Line Distance / radius if half Plane Line Distance < radius angle 2 0 * math asin half Plane Line Distance Over Radius else angle math pi * half Plane Line Distance Over Radius return abs complex angle * radius relative Location z
| null | null | null | null | Question:
What does the code get ?
Code:
def getArcDistance(relativeLocation, splitLine):
halfPlaneLineDistance = (0.5 * abs(relativeLocation.dropAxis(2)))
radius = getDoubleFromCharacterSplitLine('R', splitLine)
if (radius == None):
iFloat = getDoubleFromCharacterSplitLine('I', splitLine)
jFloat = getDoubleFromCharacterSplitLine('J', splitLine)
radius = abs(complex(iFloat, jFloat))
angle = 0.0
if (radius > 0.0):
halfPlaneLineDistanceOverRadius = (halfPlaneLineDistance / radius)
if (halfPlaneLineDistance < radius):
angle = (2.0 * math.asin(halfPlaneLineDistanceOverRadius))
else:
angle = (math.pi * halfPlaneLineDistanceOverRadius)
return abs(complex((angle * radius), relativeLocation.z))
|
null | null | null | For what purpose do certs revoke ?
| def revoke_certs_by_user_and_project(user_id, project_id):
admin = context.get_admin_context()
for cert in db.certificate_get_all_by_user_and_project(admin, user_id, project_id):
revoke_cert(cert['project_id'], cert['file_name'])
| null | null | null | for user in project
| codeqa | def revoke certs by user and project user id project id admin context get admin context for cert in db certificate get all by user and project admin user id project id revoke cert cert['project id'] cert['file name']
| null | null | null | null | Question:
For what purpose do certs revoke ?
Code:
def revoke_certs_by_user_and_project(user_id, project_id):
admin = context.get_admin_context()
for cert in db.certificate_get_all_by_user_and_project(admin, user_id, project_id):
revoke_cert(cert['project_id'], cert['file_name'])
|
null | null | null | What does the code return ?
| def status(name, sig=None, runas=None):
if sig:
return __salt__['status.pid'](sig)
output = list_(runas=runas)
pids = ''
for line in output.splitlines():
if ('PID' in line):
continue
if re.search(name, line):
if line.split()[0].isdigit():
if pids:
pids += '\n'
pids += line.split()[0]
return pids
| null | null | null | the status for a service
| codeqa | def status name sig None runas None if sig return salt ['status pid'] sig output list runas runas pids ''for line in output splitlines if 'PID' in line continueif re search name line if line split [0 ] isdigit if pids pids + '\n'pids + line split [0 ]return pids
| null | null | null | null | Question:
What does the code return ?
Code:
def status(name, sig=None, runas=None):
if sig:
return __salt__['status.pid'](sig)
output = list_(runas=runas)
pids = ''
for line in output.splitlines():
if ('PID' in line):
continue
if re.search(name, line):
if line.split()[0].isdigit():
if pids:
pids += '\n'
pids += line.split()[0]
return pids
|
null | null | null | What defined in this file ?
| def validate_password_strength(value):
password_validators = [validate_password_length, validate_password_complexity, validate_password_dictionary]
for validator in password_validators:
validator(value)
| null | null | null | each validator
| codeqa | def validate password strength value password validators [validate password length validate password complexity validate password dictionary]for validator in password validators validator value
| null | null | null | null | Question:
What defined in this file ?
Code:
def validate_password_strength(value):
password_validators = [validate_password_length, validate_password_complexity, validate_password_dictionary]
for validator in password_validators:
validator(value)
|
null | null | null | Where did each validator define ?
| def validate_password_strength(value):
password_validators = [validate_password_length, validate_password_complexity, validate_password_dictionary]
for validator in password_validators:
validator(value)
| null | null | null | in this file
| codeqa | def validate password strength value password validators [validate password length validate password complexity validate password dictionary]for validator in password validators validator value
| null | null | null | null | Question:
Where did each validator define ?
Code:
def validate_password_strength(value):
password_validators = [validate_password_length, validate_password_complexity, validate_password_dictionary]
for validator in password_validators:
validator(value)
|
null | null | null | What does the code create ?
| def _get_user_profile_dict(request, usernames):
request.GET = request.GET.copy()
request.GET['username'] = usernames
user_profile_details = AccountViewSet.as_view({'get': 'list'})(request).data
return {user['username']: user for user in user_profile_details}
| null | null | null | a dictionary with profile details against username
| codeqa | def get user profile dict request usernames request GET request GET copy request GET['username'] usernamesuser profile details Account View Set as view {'get' 'list'} request datareturn {user['username'] user for user in user profile details}
| null | null | null | null | Question:
What does the code create ?
Code:
def _get_user_profile_dict(request, usernames):
request.GET = request.GET.copy()
request.GET['username'] = usernames
user_profile_details = AccountViewSet.as_view({'get': 'list'})(request).data
return {user['username']: user for user in user_profile_details}
|
null | null | null | What does the code get for a list of usernames ?
| def _get_user_profile_dict(request, usernames):
request.GET = request.GET.copy()
request.GET['username'] = usernames
user_profile_details = AccountViewSet.as_view({'get': 'list'})(request).data
return {user['username']: user for user in user_profile_details}
| null | null | null | user profile details
| codeqa | def get user profile dict request usernames request GET request GET copy request GET['username'] usernamesuser profile details Account View Set as view {'get' 'list'} request datareturn {user['username'] user for user in user profile details}
| null | null | null | null | Question:
What does the code get for a list of usernames ?
Code:
def _get_user_profile_dict(request, usernames):
request.GET = request.GET.copy()
request.GET['username'] = usernames
user_profile_details = AccountViewSet.as_view({'get': 'list'})(request).data
return {user['username']: user for user in user_profile_details}
|
null | null | null | What does the code update ?
| def col_update(fid, uid, body):
url = build_url(RESOURCE, id=fid, route='col')
params = make_params(uid=uid)
return request('put', url, json=body, params=params)
| null | null | null | a column from a grid
| codeqa | def col update fid uid body url build url RESOURCE id fid route 'col' params make params uid uid return request 'put' url json body params params
| null | null | null | null | Question:
What does the code update ?
Code:
def col_update(fid, uid, body):
url = build_url(RESOURCE, id=fid, route='col')
params = make_params(uid=uid)
return request('put', url, json=body, params=params)
|
null | null | null | What does the code get ?
| def get_mem_info():
if (not sys.platform.startswith('linux')):
raise RuntimeError('Memory information implemented only for 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 if not sys platform startswith 'linux' raise Runtime Error ' Memoryinformationimplementedonlyfor 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():
if (not sys.platform.startswith('linux')):
raise RuntimeError('Memory information implemented only for 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 did the code set to the lamp ?
| def call_effect(*args, **kwargs):
res = dict()
devices = _get_lights()
for dev_id in ((('id' not in kwargs) and sorted(devices.keys())) or _get_devices(kwargs)):
res[dev_id] = _set(dev_id, {'effect': kwargs.get('type', 'none')})
return res
| null | null | null | an effect
| codeqa | def call effect *args **kwargs res dict devices get lights for dev id in 'id' not in kwargs and sorted devices keys or get devices kwargs res[dev id] set dev id {'effect' kwargs get 'type' 'none' } return res
| null | null | null | null | Question:
What did the code set to the lamp ?
Code:
def call_effect(*args, **kwargs):
res = dict()
devices = _get_lights()
for dev_id in ((('id' not in kwargs) and sorted(devices.keys())) or _get_devices(kwargs)):
res[dev_id] = _set(dev_id, {'effect': kwargs.get('type', 'none')})
return res
|
null | null | null | What does the code retrieve if it does not exist ?
| def reservation_get(context, uuid):
return IMPL.reservation_get(context, uuid)
| null | null | null | a reservation
| codeqa | def reservation get context uuid return IMPL reservation get context uuid
| null | null | null | null | Question:
What does the code retrieve if it does not exist ?
Code:
def reservation_get(context, uuid):
return IMPL.reservation_get(context, uuid)
|
null | null | null | For what purpose does which parameters ignore ?
| def get_resource_ignore_params(params):
ignore_params = []
for param in params:
result = jmespath.compile(param.target)
current = result.parsed
while current['children']:
current = current['children'][0]
if (current['type'] == 'field'):
ignore_params.append(current['value'])
return ignore_params
| null | null | null | for actions
| codeqa | def get resource ignore params params ignore params []for param in params result jmespath compile param target current result parsedwhile current['children'] current current['children'][ 0 ]if current['type'] 'field' ignore params append current['value'] return ignore params
| null | null | null | null | Question:
For what purpose does which parameters ignore ?
Code:
def get_resource_ignore_params(params):
ignore_params = []
for param in params:
result = jmespath.compile(param.target)
current = result.parsed
while current['children']:
current = current['children'][0]
if (current['type'] == 'field'):
ignore_params.append(current['value'])
return ignore_params
|
null | null | null | What does the code get in bytes ?
| def get_disk_usage(d):
if (platform.system() == 'Linux'):
try:
return int(subprocess.Popen(['du', '-sb', d], stdout=subprocess.PIPE).communicate()[0].split()[0])
except:
raise CleanupException('rosclean is not supported on this platform')
elif (platform.system() == 'FreeBSD'):
try:
return (int(subprocess.Popen(['du', '-sA', d], stdout=subprocess.PIPE).communicate()[0].split()[0]) * 1024)
except:
raise CleanupException('rosclean is not supported on this platform')
else:
raise CleanupException('rosclean is not supported on this platform')
| null | null | null | disk usage
| codeqa | def get disk usage d if platform system ' Linux' try return int subprocess Popen ['du' '-sb' d] stdout subprocess PIPE communicate [0 ] split [0 ] except raise Cleanup Exception 'roscleanisnotsupportedonthisplatform' elif platform system ' Free BSD' try return int subprocess Popen ['du' '-s A' d] stdout subprocess PIPE communicate [0 ] split [0 ] * 1024 except raise Cleanup Exception 'roscleanisnotsupportedonthisplatform' else raise Cleanup Exception 'roscleanisnotsupportedonthisplatform'
| null | null | null | null | Question:
What does the code get in bytes ?
Code:
def get_disk_usage(d):
if (platform.system() == 'Linux'):
try:
return int(subprocess.Popen(['du', '-sb', d], stdout=subprocess.PIPE).communicate()[0].split()[0])
except:
raise CleanupException('rosclean is not supported on this platform')
elif (platform.system() == 'FreeBSD'):
try:
return (int(subprocess.Popen(['du', '-sA', d], stdout=subprocess.PIPE).communicate()[0].split()[0]) * 1024)
except:
raise CleanupException('rosclean is not supported on this platform')
else:
raise CleanupException('rosclean is not supported on this platform')
|
null | null | null | Where does the code get disk usage ?
| def get_disk_usage(d):
if (platform.system() == 'Linux'):
try:
return int(subprocess.Popen(['du', '-sb', d], stdout=subprocess.PIPE).communicate()[0].split()[0])
except:
raise CleanupException('rosclean is not supported on this platform')
elif (platform.system() == 'FreeBSD'):
try:
return (int(subprocess.Popen(['du', '-sA', d], stdout=subprocess.PIPE).communicate()[0].split()[0]) * 1024)
except:
raise CleanupException('rosclean is not supported on this platform')
else:
raise CleanupException('rosclean is not supported on this platform')
| null | null | null | in bytes
| codeqa | def get disk usage d if platform system ' Linux' try return int subprocess Popen ['du' '-sb' d] stdout subprocess PIPE communicate [0 ] split [0 ] except raise Cleanup Exception 'roscleanisnotsupportedonthisplatform' elif platform system ' Free BSD' try return int subprocess Popen ['du' '-s A' d] stdout subprocess PIPE communicate [0 ] split [0 ] * 1024 except raise Cleanup Exception 'roscleanisnotsupportedonthisplatform' else raise Cleanup Exception 'roscleanisnotsupportedonthisplatform'
| null | null | null | null | Question:
Where does the code get disk usage ?
Code:
def get_disk_usage(d):
if (platform.system() == 'Linux'):
try:
return int(subprocess.Popen(['du', '-sb', d], stdout=subprocess.PIPE).communicate()[0].split()[0])
except:
raise CleanupException('rosclean is not supported on this platform')
elif (platform.system() == 'FreeBSD'):
try:
return (int(subprocess.Popen(['du', '-sA', d], stdout=subprocess.PIPE).communicate()[0].split()[0]) * 1024)
except:
raise CleanupException('rosclean is not supported on this platform')
else:
raise CleanupException('rosclean is not supported on this platform')
|
null | null | null | What does the code get ?
| def sm_volume_get_all(context):
return IMPL.sm_volume_get_all(context)
| null | null | null | all child zones
| codeqa | def sm volume get all context return IMPL sm volume get all context
| null | null | null | null | Question:
What does the code get ?
Code:
def sm_volume_get_all(context):
return IMPL.sm_volume_get_all(context)
|
null | null | null | What does the code get ?
| def get_pickleable_etype(cls, loads=pickle.loads, dumps=pickle.dumps):
try:
loads(dumps(cls))
except Exception:
return Exception
else:
return cls
| null | null | null | pickleable exception type
| codeqa | def get pickleable etype cls loads pickle loads dumps pickle dumps try loads dumps cls except Exception return Exceptionelse return cls
| null | null | null | null | Question:
What does the code get ?
Code:
def get_pickleable_etype(cls, loads=pickle.loads, dumps=pickle.dumps):
try:
loads(dumps(cls))
except Exception:
return Exception
else:
return cls
|
null | null | null | When does your files not corrupt ?
| def secure_dump(object_, path, dump_function=dump, **kwargs):
try:
logger.debug('Dumping object to a temporary file')
with tempfile.NamedTemporaryFile(delete=False, dir=config.temp_dir) as temp:
dump_function(object_, temp, **kwargs)
logger.debug('Moving the temporary file')
shutil.move(temp.name, path)
logger.debug('Dump finished')
except:
if ('temp' in locals()):
os.remove(temp.name)
raise
| null | null | null | when failed
| codeqa | def secure dump object path dump function dump **kwargs try logger debug ' Dumpingobjecttoatemporaryfile' with tempfile Named Temporary File delete False dir config temp dir as temp dump function object temp **kwargs logger debug ' Movingthetemporaryfile' shutil move temp name path logger debug ' Dumpfinished' except if 'temp' in locals os remove temp name raise
| null | null | null | null | Question:
When does your files not corrupt ?
Code:
def secure_dump(object_, path, dump_function=dump, **kwargs):
try:
logger.debug('Dumping object to a temporary file')
with tempfile.NamedTemporaryFile(delete=False, dir=config.temp_dir) as temp:
dump_function(object_, temp, **kwargs)
logger.debug('Moving the temporary file')
shutil.move(temp.name, path)
logger.debug('Dump finished')
except:
if ('temp' in locals()):
os.remove(temp.name)
raise
|
null | null | null | What does the code create ?
| def new_figure_manager_given_figure(num, figure):
canvas = FigureCanvasPdf(figure)
manager = FigureManagerPdf(canvas, num)
return manager
| null | null | null | a new figure manager instance for the given figure
| codeqa | def new figure manager given figure num figure canvas Figure Canvas Pdf figure manager Figure Manager Pdf canvas num return manager
| null | null | null | null | Question:
What does the code create ?
Code:
def new_figure_manager_given_figure(num, figure):
canvas = FigureCanvasPdf(figure)
manager = FigureManagerPdf(canvas, num)
return manager
|
null | null | null | For what purpose is a survey required ?
| def is_survey_required_for_course(course_descriptor):
return (course_descriptor.course_survey_required and SurveyForm.get(course_descriptor.course_survey_name, throw_if_not_found=False))
| null | null | null | for this course
| codeqa | def is survey required for course course descriptor return course descriptor course survey required and Survey Form get course descriptor course survey name throw if not found False
| null | null | null | null | Question:
For what purpose is a survey required ?
Code:
def is_survey_required_for_course(course_descriptor):
return (course_descriptor.course_survey_required and SurveyForm.get(course_descriptor.course_survey_name, throw_if_not_found=False))
|
null | null | null | When can they be loaded ?
| def save_processed_files(path, processed_files):
try:
path_dir = os.path.dirname(path)
if (not os.path.exists(path_dir)):
os.makedirs(path_dir)
except OSError as exc:
raise IOError(exc)
with open(path, 'w') as output_file:
for (path, timestamp) in list(processed_files.items()):
if (not os.path.isabs(path)):
raise TypeError(('Only absolute paths are acceptable: %s' % path))
output_file.write(('%s %i\n' % (path, timestamp)))
| null | null | null | later
| codeqa | def save processed files path processed files try path dir os path dirname path if not os path exists path dir os makedirs path dir except OS Error as exc raise IO Error exc with open path 'w' as output file for path timestamp in list processed files items if not os path isabs path raise Type Error ' Onlyabsolutepathsareacceptable %s' % path output file write '%s%i\n' % path timestamp
| null | null | null | null | Question:
When can they be loaded ?
Code:
def save_processed_files(path, processed_files):
try:
path_dir = os.path.dirname(path)
if (not os.path.exists(path_dir)):
os.makedirs(path_dir)
except OSError as exc:
raise IOError(exc)
with open(path, 'w') as output_file:
for (path, timestamp) in list(processed_files.items()):
if (not os.path.isabs(path)):
raise TypeError(('Only absolute paths are acceptable: %s' % path))
output_file.write(('%s %i\n' % (path, timestamp)))
|
null | null | null | When did timestamp mappings modify ?
| def save_processed_files(path, processed_files):
try:
path_dir = os.path.dirname(path)
if (not os.path.exists(path_dir)):
os.makedirs(path_dir)
except OSError as exc:
raise IOError(exc)
with open(path, 'w') as output_file:
for (path, timestamp) in list(processed_files.items()):
if (not os.path.isabs(path)):
raise TypeError(('Only absolute paths are acceptable: %s' % path))
output_file.write(('%s %i\n' % (path, timestamp)))
| null | null | null | last
| codeqa | def save processed files path processed files try path dir os path dirname path if not os path exists path dir os makedirs path dir except OS Error as exc raise IO Error exc with open path 'w' as output file for path timestamp in list processed files items if not os path isabs path raise Type Error ' Onlyabsolutepathsareacceptable %s' % path output file write '%s%i\n' % path timestamp
| null | null | null | null | Question:
When did timestamp mappings modify ?
Code:
def save_processed_files(path, processed_files):
try:
path_dir = os.path.dirname(path)
if (not os.path.exists(path_dir)):
os.makedirs(path_dir)
except OSError as exc:
raise IOError(exc)
with open(path, 'w') as output_file:
for (path, timestamp) in list(processed_files.items()):
if (not os.path.isabs(path)):
raise TypeError(('Only absolute paths are acceptable: %s' % path))
output_file.write(('%s %i\n' % (path, timestamp)))
|
null | null | null | For what purpose does the code persist the code ?
| def save_processed_files(path, processed_files):
try:
path_dir = os.path.dirname(path)
if (not os.path.exists(path_dir)):
os.makedirs(path_dir)
except OSError as exc:
raise IOError(exc)
with open(path, 'w') as output_file:
for (path, timestamp) in list(processed_files.items()):
if (not os.path.isabs(path)):
raise TypeError(('Only absolute paths are acceptable: %s' % path))
output_file.write(('%s %i\n' % (path, timestamp)))
| null | null | null | so that they can be loaded later and applied to another : class :~ stem
| codeqa | def save processed files path processed files try path dir os path dirname path if not os path exists path dir os makedirs path dir except OS Error as exc raise IO Error exc with open path 'w' as output file for path timestamp in list processed files items if not os path isabs path raise Type Error ' Onlyabsolutepathsareacceptable %s' % path output file write '%s%i\n' % path timestamp
| null | null | null | null | Question:
For what purpose does the code persist the code ?
Code:
def save_processed_files(path, processed_files):
try:
path_dir = os.path.dirname(path)
if (not os.path.exists(path_dir)):
os.makedirs(path_dir)
except OSError as exc:
raise IOError(exc)
with open(path, 'w') as output_file:
for (path, timestamp) in list(processed_files.items()):
if (not os.path.isabs(path)):
raise TypeError(('Only absolute paths are acceptable: %s' % path))
output_file.write(('%s %i\n' % (path, timestamp)))
|
null | null | null | What keeps internal caches for environments and lexers ?
| def clear_caches():
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
| null | null | null | jinja2
| codeqa | def clear caches from jinja 2 environment import spontaneous environmentsfrom jinja 2 lexer import lexer cache spontaneous environments clear lexer cache clear
| null | null | null | null | Question:
What keeps internal caches for environments and lexers ?
Code:
def clear_caches():
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
|
null | null | null | What does jinja2 keep ?
| def clear_caches():
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
| null | null | null | internal caches for environments and lexers
| codeqa | def clear caches from jinja 2 environment import spontaneous environmentsfrom jinja 2 lexer import lexer cache spontaneous environments clear lexer cache clear
| null | null | null | null | Question:
What does jinja2 keep ?
Code:
def clear_caches():
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
|
null | null | null | Where was the text detected ?
| def extract_descriptions(input_filename, index, texts):
if texts:
document = extract_description(texts)
index.add(input_filename, document)
sys.stdout.write('.')
sys.stdout.flush()
elif (texts == []):
print ('%s had no discernible text.' % input_filename)
index.set_contains_no_text(input_filename)
| null | null | null | in the image
| codeqa | def extract descriptions input filename index texts if texts document extract description texts index add input filename document sys stdout write ' ' sys stdout flush elif texts [] print '%shadnodiscernibletext ' % input filename index set contains no text input filename
| null | null | null | null | Question:
Where was the text detected ?
Code:
def extract_descriptions(input_filename, index, texts):
if texts:
document = extract_description(texts)
index.add(input_filename, document)
sys.stdout.write('.')
sys.stdout.flush()
elif (texts == []):
print ('%s had no discernible text.' % input_filename)
index.set_contains_no_text(input_filename)
|
null | null | null | What does the code get ?
| def extract_descriptions(input_filename, index, texts):
if texts:
document = extract_description(texts)
index.add(input_filename, document)
sys.stdout.write('.')
sys.stdout.flush()
elif (texts == []):
print ('%s had no discernible text.' % input_filename)
index.set_contains_no_text(input_filename)
| null | null | null | the text that was detected in the image
| codeqa | def extract descriptions input filename index texts if texts document extract description texts index add input filename document sys stdout write ' ' sys stdout flush elif texts [] print '%shadnodiscernibletext ' % input filename index set contains no text input filename
| null | null | null | null | Question:
What does the code get ?
Code:
def extract_descriptions(input_filename, index, texts):
if texts:
document = extract_description(texts)
index.add(input_filename, document)
sys.stdout.write('.')
sys.stdout.flush()
elif (texts == []):
print ('%s had no discernible text.' % input_filename)
index.set_contains_no_text(input_filename)
|
null | null | null | What was detected in the image ?
| def extract_descriptions(input_filename, index, texts):
if texts:
document = extract_description(texts)
index.add(input_filename, document)
sys.stdout.write('.')
sys.stdout.flush()
elif (texts == []):
print ('%s had no discernible text.' % input_filename)
index.set_contains_no_text(input_filename)
| null | null | null | the text
| codeqa | def extract descriptions input filename index texts if texts document extract description texts index add input filename document sys stdout write ' ' sys stdout flush elif texts [] print '%shadnodiscernibletext ' % input filename index set contains no text input filename
| null | null | null | null | Question:
What was detected in the image ?
Code:
def extract_descriptions(input_filename, index, texts):
if texts:
document = extract_description(texts)
index.add(input_filename, document)
sys.stdout.write('.')
sys.stdout.flush()
elif (texts == []):
print ('%s had no discernible text.' % input_filename)
index.set_contains_no_text(input_filename)
|
null | null | null | How can we set a locale ?
| def _can_set_locale(lc):
try:
with set_locale(lc):
pass
except locale.Error:
return False
else:
return True
| null | null | null | without throwing an exception
| codeqa | def can set locale lc try with set locale lc passexcept locale Error return Falseelse return True
| null | null | null | null | Question:
How can we set a locale ?
Code:
def _can_set_locale(lc):
try:
with set_locale(lc):
pass
except locale.Error:
return False
else:
return True
|
null | null | null | What can we set without throwing an exception ?
| def _can_set_locale(lc):
try:
with set_locale(lc):
pass
except locale.Error:
return False
else:
return True
| null | null | null | a locale
| codeqa | def can set locale lc try with set locale lc passexcept locale Error return Falseelse return True
| null | null | null | null | Question:
What can we set without throwing an exception ?
Code:
def _can_set_locale(lc):
try:
with set_locale(lc):
pass
except locale.Error:
return False
else:
return True
|
null | null | null | What do we throw ?
| def _can_set_locale(lc):
try:
with set_locale(lc):
pass
except locale.Error:
return False
else:
return True
| null | null | null | an exception
| codeqa | def can set locale lc try with set locale lc passexcept locale Error return Falseelse return True
| null | null | null | null | Question:
What do we throw ?
Code:
def _can_set_locale(lc):
try:
with set_locale(lc):
pass
except locale.Error:
return False
else:
return True
|
null | null | null | How do a vm reconfigure ?
| def reconfigure_vm(session, vm_ref, config_spec):
reconfig_task = session._call_method(session.vim, 'ReconfigVM_Task', vm_ref, spec=config_spec)
session._wait_for_task(reconfig_task)
| null | null | null | according to the config spec
| codeqa | def reconfigure vm session vm ref config spec reconfig task session call method session vim ' Reconfig VM Task' vm ref spec config spec session wait for task reconfig task
| null | null | null | null | Question:
How do a vm reconfigure ?
Code:
def reconfigure_vm(session, vm_ref, config_spec):
reconfig_task = session._call_method(session.vim, 'ReconfigVM_Task', vm_ref, spec=config_spec)
session._wait_for_task(reconfig_task)
|
null | null | null | What does the code get ?
| def get_version():
return get_versions()['version']
| null | null | null | the short version string for this project
| codeqa | def get version return get versions ['version']
| null | null | null | null | Question:
What does the code get ?
Code:
def get_version():
return get_versions()['version']
|
null | null | null | What does the code start ?
| def start(name, call=None):
if (call != 'action'):
raise SaltCloudSystemExit('The start action must be called with -a or --action.')
log.info('Starting node {0}'.format(name))
instance_id = _get_node(name)['instanceId']
params = {'Action': 'StartInstances', 'InstanceId.1': instance_id}
result = aws.query(params, location=get_location(), provider=get_provider(), opts=__opts__, sigver='4')
return result
| null | null | null | a node
| codeqa | def start name call None if call 'action' raise Salt Cloud System Exit ' Thestartactionmustbecalledwith-aor--action ' log info ' Startingnode{ 0 }' format name instance id get node name ['instance Id']params {' Action' ' Start Instances' ' Instance Id 1' instance id}result aws query params location get location provider get provider opts opts sigver '4 ' return result
| null | null | null | null | Question:
What does the code start ?
Code:
def start(name, call=None):
if (call != 'action'):
raise SaltCloudSystemExit('The start action must be called with -a or --action.')
log.info('Starting node {0}'.format(name))
instance_id = _get_node(name)['instanceId']
params = {'Action': 'StartInstances', 'InstanceId.1': instance_id}
result = aws.query(params, location=get_location(), provider=get_provider(), opts=__opts__, sigver='4')
return result
|
null | null | null | What does the code get ?
| def top_contributors_questions(start=None, end=None, locale=None, product=None, count=10, page=1):
query = AnswerMetricsMappingType.search().facet('creator_id', filtered=True, size=BIG_NUMBER)
query = query.filter(by_asker=False)
query = _apply_filters(query, start, end, locale, product)
return _get_creator_counts(query, count, page)
| null | null | null | the top support forum contributors
| codeqa | def top contributors questions start None end None locale None product None count 10 page 1 query Answer Metrics Mapping Type search facet 'creator id' filtered True size BIG NUMBER query query filter by asker False query apply filters query start end locale product return get creator counts query count page
| null | null | null | null | Question:
What does the code get ?
Code:
def top_contributors_questions(start=None, end=None, locale=None, product=None, count=10, page=1):
query = AnswerMetricsMappingType.search().facet('creator_id', filtered=True, size=BIG_NUMBER)
query = query.filter(by_asker=False)
query = _apply_filters(query, start, end, locale, product)
return _get_creator_counts(query, count, page)
|
null | null | null | What does the code get ?
| def _base_args(config):
args = ['--debug', '--json-logging', '--no-err-windows']
if config.webengine:
args += ['--backend', 'webengine']
else:
args += ['--backend', 'webkit']
args.append('about:blank')
return args
| null | null | null | the arguments to pass with every invocation
| codeqa | def base args config args ['--debug' '--json-logging' '--no-err-windows']if config webengine args + ['--backend' 'webengine']else args + ['--backend' 'webkit']args append 'about blank' return args
| null | null | null | null | Question:
What does the code get ?
Code:
def _base_args(config):
args = ['--debug', '--json-logging', '--no-err-windows']
if config.webengine:
args += ['--backend', 'webengine']
else:
args += ['--backend', 'webkit']
args.append('about:blank')
return args
|
null | null | null | What does the code take ?
| def drop_tables(names, session):
metadata = MetaData()
metadata.reflect(bind=session.bind)
for table in metadata.sorted_tables:
if (table.name in names):
table.drop()
| null | null | null | a list of table names
| codeqa | def drop tables names session metadata Meta Data metadata reflect bind session bind for table in metadata sorted tables if table name in names table drop
| null | null | null | null | Question:
What does the code take ?
Code:
def drop_tables(names, session):
metadata = MetaData()
metadata.reflect(bind=session.bind)
for table in metadata.sorted_tables:
if (table.name in names):
table.drop()
|
null | null | null | What is excluding the given author ?
| def _get_all_recipient_ids(exploration_id, thread_id, author_id):
exploration_rights = rights_manager.get_exploration_rights(exploration_id)
owner_ids = set(exploration_rights.owner_ids)
participant_ids = get_all_thread_participants(exploration_id, thread_id)
sender_id = set([author_id])
batch_recipient_ids = (owner_ids - sender_id)
other_recipient_ids = ((participant_ids - batch_recipient_ids) - sender_id)
return (batch_recipient_ids, other_recipient_ids)
| null | null | null | all authors of the exploration
| codeqa | def get all recipient ids exploration id thread id author id exploration rights rights manager get exploration rights exploration id owner ids set exploration rights owner ids participant ids get all thread participants exploration id thread id sender id set [author id] batch recipient ids owner ids - sender id other recipient ids participant ids - batch recipient ids - sender id return batch recipient ids other recipient ids
| null | null | null | null | Question:
What is excluding the given author ?
Code:
def _get_all_recipient_ids(exploration_id, thread_id, author_id):
exploration_rights = rights_manager.get_exploration_rights(exploration_id)
owner_ids = set(exploration_rights.owner_ids)
participant_ids = get_all_thread_participants(exploration_id, thread_id)
sender_id = set([author_id])
batch_recipient_ids = (owner_ids - sender_id)
other_recipient_ids = ((participant_ids - batch_recipient_ids) - sender_id)
return (batch_recipient_ids, other_recipient_ids)
|
null | null | null | What do all authors of the exploration exclude ?
| def _get_all_recipient_ids(exploration_id, thread_id, author_id):
exploration_rights = rights_manager.get_exploration_rights(exploration_id)
owner_ids = set(exploration_rights.owner_ids)
participant_ids = get_all_thread_participants(exploration_id, thread_id)
sender_id = set([author_id])
batch_recipient_ids = (owner_ids - sender_id)
other_recipient_ids = ((participant_ids - batch_recipient_ids) - sender_id)
return (batch_recipient_ids, other_recipient_ids)
| null | null | null | the given author
| codeqa | def get all recipient ids exploration id thread id author id exploration rights rights manager get exploration rights exploration id owner ids set exploration rights owner ids participant ids get all thread participants exploration id thread id sender id set [author id] batch recipient ids owner ids - sender id other recipient ids participant ids - batch recipient ids - sender id return batch recipient ids other recipient ids
| null | null | null | null | Question:
What do all authors of the exploration exclude ?
Code:
def _get_all_recipient_ids(exploration_id, thread_id, author_id):
exploration_rights = rights_manager.get_exploration_rights(exploration_id)
owner_ids = set(exploration_rights.owner_ids)
participant_ids = get_all_thread_participants(exploration_id, thread_id)
sender_id = set([author_id])
batch_recipient_ids = (owner_ids - sender_id)
other_recipient_ids = ((participant_ids - batch_recipient_ids) - sender_id)
return (batch_recipient_ids, other_recipient_ids)
|
null | null | null | What does the code get ?
| def _get_epochs():
raw = read_raw_fif(raw_fname)
raw.add_proj([], remove_existing=True)
events = _get_events()
picks = _get_picks(raw)
epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks)
return epochs
| null | null | null | epochs
| codeqa | def get epochs raw read raw fif raw fname raw add proj [] remove existing True events get events picks get picks raw epochs Epochs raw events[ 10 ] event id tmin tmax picks picks return epochs
| null | null | null | null | Question:
What does the code get ?
Code:
def _get_epochs():
raw = read_raw_fif(raw_fname)
raw.add_proj([], remove_existing=True)
events = _get_events()
picks = _get_picks(raw)
epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks)
return epochs
|
null | null | null | What does the code convert to a list of dictionaries ?
| def _dict_to_list_ids(objects):
list_with_ids = []
for (key, value) in six.iteritems(objects):
element = {'id': key}
element.update(value)
list_with_ids.append(element)
return list_with_ids
| null | null | null | a dictionary
| codeqa | def dict to list ids objects list with ids []for key value in six iteritems objects element {'id' key}element update value list with ids append element return list with ids
| null | null | null | null | Question:
What does the code convert to a list of dictionaries ?
Code:
def _dict_to_list_ids(objects):
list_with_ids = []
for (key, value) in six.iteritems(objects):
element = {'id': key}
element.update(value)
list_with_ids.append(element)
return list_with_ids
|
null | null | null | When does the code return ?
| def get_last_seen_notifications_msec(user_id):
subscriptions_model = user_models.UserSubscriptionsModel.get(user_id, strict=False)
return (utils.get_time_in_millisecs(subscriptions_model.last_checked) if (subscriptions_model and subscriptions_model.last_checked) else None)
| null | null | null | the last time
| codeqa | def get last seen notifications msec user id subscriptions model user models User Subscriptions Model get user id strict False return utils get time in millisecs subscriptions model last checked if subscriptions model and subscriptions model last checked else None
| null | null | null | null | Question:
When does the code return ?
Code:
def get_last_seen_notifications_msec(user_id):
subscriptions_model = user_models.UserSubscriptionsModel.get(user_id, strict=False)
return (utils.get_time_in_millisecs(subscriptions_model.last_checked) if (subscriptions_model and subscriptions_model.last_checked) else None)
|
null | null | null | What does the code display ?
| def main():
if (len(sys.argv) > 1):
writeOutput(' '.join(sys.argv[1:]))
else:
settings.startMainLoopFromConstructor(getNewRepository())
| null | null | null | the coil dialog
| codeqa | def main if len sys argv > 1 write Output '' join sys argv[ 1 ] else settings start Main Loop From Constructor get New Repository
| null | null | null | null | Question:
What does the code display ?
Code:
def main():
if (len(sys.argv) > 1):
writeOutput(' '.join(sys.argv[1:]))
else:
settings.startMainLoopFromConstructor(getNewRepository())
|
null | null | null | What does the code get ?
| def get_container_info(env, app, swift_source=None):
cache = cache_from_env(env)
if (not cache):
return None
(version, account, container, _) = split_path(env['PATH_INFO'], 3, 4, True)
cache_key = get_container_memcache_key(account, container)
env_key = ('swift.%s' % cache_key)
if (env_key not in env):
container_info = cache.get(cache_key)
if (not container_info):
resp = make_pre_authed_request(env, 'HEAD', ('/%s/%s/%s' % (version, account, container)), swift_source=swift_source).get_response(app)
container_info = headers_to_container_info(resp.headers, resp.status_int)
env[env_key] = container_info
return env[env_key]
| null | null | null | the info structure for a container
| codeqa | def get container info env app swift source None cache cache from env env if not cache return None version account container split path env['PATH INFO'] 3 4 True cache key get container memcache key account container env key 'swift %s' % cache key if env key not in env container info cache get cache key if not container info resp make pre authed request env 'HEAD' '/%s/%s/%s' % version account container swift source swift source get response app container info headers to container info resp headers resp status int env[env key] container inforeturn env[env key]
| null | null | null | null | Question:
What does the code get ?
Code:
def get_container_info(env, app, swift_source=None):
cache = cache_from_env(env)
if (not cache):
return None
(version, account, container, _) = split_path(env['PATH_INFO'], 3, 4, True)
cache_key = get_container_memcache_key(account, container)
env_key = ('swift.%s' % cache_key)
if (env_key not in env):
container_info = cache.get(cache_key)
if (not container_info):
resp = make_pre_authed_request(env, 'HEAD', ('/%s/%s/%s' % (version, account, container)), swift_source=swift_source).get_response(app)
container_info = headers_to_container_info(resp.headers, resp.status_int)
env[env_key] = container_info
return env[env_key]
|
null | null | null | What does a generator yield ?
| def parse(handle, format=None, **kwargs):
iterator = get_processor(format, _ITERATOR_MAP)
handle_kwargs = {}
if ((format == 'blast-xml') and (sys.version_info[0] > 2)):
handle_kwargs['encoding'] = 'utf-8'
with as_handle(handle, 'rU', **handle_kwargs) as source_file:
generator = iterator(source_file, **kwargs)
for qresult in generator:
(yield qresult)
| null | null | null | queryresult objects
| codeqa | def parse handle format None **kwargs iterator get processor format ITERATOR MAP handle kwargs {}if format 'blast-xml' and sys version info[ 0 ] > 2 handle kwargs['encoding'] 'utf- 8 'with as handle handle 'r U' **handle kwargs as source file generator iterator source file **kwargs for qresult in generator yield qresult
| null | null | null | null | Question:
What does a generator yield ?
Code:
def parse(handle, format=None, **kwargs):
iterator = get_processor(format, _ITERATOR_MAP)
handle_kwargs = {}
if ((format == 'blast-xml') and (sys.version_info[0] > 2)):
handle_kwargs['encoding'] = 'utf-8'
with as_handle(handle, 'rU', **handle_kwargs) as source_file:
generator = iterator(source_file, **kwargs)
for qresult in generator:
(yield qresult)
|
null | null | null | How did the code return them ?
| def retrieve_flags(flag_dict, flag_filter):
return [(f[0], f[1]) for f in list(flag_dict.items()) if (isinstance(f[0], (str, bytes)) and f[0].startswith(flag_filter))]
| null | null | null | in a usable form
| codeqa | def retrieve flags flag dict flag filter return [ f[ 0 ] f[ 1 ] for f in list flag dict items if isinstance f[ 0 ] str bytes and f[ 0 ] startswith flag filter ]
| null | null | null | null | Question:
How did the code return them ?
Code:
def retrieve_flags(flag_dict, flag_filter):
return [(f[0], f[1]) for f in list(flag_dict.items()) if (isinstance(f[0], (str, bytes)) and f[0].startswith(flag_filter))]
|
null | null | null | What did the code read ?
| def retrieve_flags(flag_dict, flag_filter):
return [(f[0], f[1]) for f in list(flag_dict.items()) if (isinstance(f[0], (str, bytes)) and f[0].startswith(flag_filter))]
| null | null | null | the flags from a dictionary
| codeqa | def retrieve flags flag dict flag filter return [ f[ 0 ] f[ 1 ] for f in list flag dict items if isinstance f[ 0 ] str bytes and f[ 0 ] startswith flag filter ]
| null | null | null | null | Question:
What did the code read ?
Code:
def retrieve_flags(flag_dict, flag_filter):
return [(f[0], f[1]) for f in list(flag_dict.items()) if (isinstance(f[0], (str, bytes)) and f[0].startswith(flag_filter))]
|
null | null | null | What does the code show ?
| def show_image(kwargs, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The show_image action must be called with -f or --function.')
name = kwargs['image']
log.info('Showing image %s', name)
machine = vb_get_machine(name)
ret = {machine['name']: treat_machine_dict(machine)}
del machine['name']
return ret
| null | null | null | the details of an image
| codeqa | def show image kwargs call None if call 'function' raise Salt Cloud System Exit ' Theshow imageactionmustbecalledwith-for--function ' name kwargs['image']log info ' Showingimage%s' name machine vb get machine name ret {machine['name'] treat machine dict machine }del machine['name']return ret
| null | null | null | null | Question:
What does the code show ?
Code:
def show_image(kwargs, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The show_image action must be called with -f or --function.')
name = kwargs['image']
log.info('Showing image %s', name)
machine = vb_get_machine(name)
ret = {machine['name']: treat_machine_dict(machine)}
del machine['name']
return ret
|
null | null | null | What does the code decrease by some percent ?
| def desaturate(color, prop):
if (not (0 <= prop <= 1)):
raise ValueError('prop must be between 0 and 1')
rgb = mplcol.colorConverter.to_rgb(color)
(h, l, s) = colorsys.rgb_to_hls(*rgb)
s *= prop
new_color = colorsys.hls_to_rgb(h, l, s)
return new_color
| null | null | null | the saturation channel of a color
| codeqa | def desaturate color prop if not 0 < prop < 1 raise Value Error 'propmustbebetween 0 and 1 ' rgb mplcol color Converter to rgb color h l s colorsys rgb to hls *rgb s * propnew color colorsys hls to rgb h l s return new color
| null | null | null | null | Question:
What does the code decrease by some percent ?
Code:
def desaturate(color, prop):
if (not (0 <= prop <= 1)):
raise ValueError('prop must be between 0 and 1')
rgb = mplcol.colorConverter.to_rgb(color)
(h, l, s) = colorsys.rgb_to_hls(*rgb)
s *= prop
new_color = colorsys.hls_to_rgb(h, l, s)
return new_color
|
null | null | null | For what purpose does a method wrap ?
| def setupmethod(f):
def wrapper_func(self, *args, **kwargs):
if (self.debug and self._got_first_request):
raise AssertionError('A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.\nTo fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.')
return f(self, *args, **kwargs)
return update_wrapper(wrapper_func, f)
| null | null | null | so that it performs a check in debug mode if the first request was already handled
| codeqa | def setupmethod f def wrapper func self *args **kwargs if self debug and self got first request raise Assertion Error ' Asetupfunctionwascalledafterthefirstrequestwashandled Thisusuallyindicatesabugintheapplicationwhereamodulewasnotimportedanddecoratorsorotherfunctionalitywascalledtoolate \n Tofixthismakesuretoimportallyourviewmodules databasemodelsandeverythingrelatedatacentralplacebeforetheapplicationstartsservingrequests ' return f self *args **kwargs return update wrapper wrapper func f
| null | null | null | null | Question:
For what purpose does a method wrap ?
Code:
def setupmethod(f):
def wrapper_func(self, *args, **kwargs):
if (self.debug and self._got_first_request):
raise AssertionError('A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.\nTo fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.')
return f(self, *args, **kwargs)
return update_wrapper(wrapper_func, f)
|
null | null | null | What does it perform if the first request was already handled ?
| def setupmethod(f):
def wrapper_func(self, *args, **kwargs):
if (self.debug and self._got_first_request):
raise AssertionError('A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.\nTo fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.')
return f(self, *args, **kwargs)
return update_wrapper(wrapper_func, f)
| null | null | null | a check in debug mode
| codeqa | def setupmethod f def wrapper func self *args **kwargs if self debug and self got first request raise Assertion Error ' Asetupfunctionwascalledafterthefirstrequestwashandled Thisusuallyindicatesabugintheapplicationwhereamodulewasnotimportedanddecoratorsorotherfunctionalitywascalledtoolate \n Tofixthismakesuretoimportallyourviewmodules databasemodelsandeverythingrelatedatacentralplacebeforetheapplicationstartsservingrequests ' return f self *args **kwargs return update wrapper wrapper func f
| null | null | null | null | Question:
What does it perform if the first request was already handled ?
Code:
def setupmethod(f):
def wrapper_func(self, *args, **kwargs):
if (self.debug and self._got_first_request):
raise AssertionError('A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.\nTo fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.')
return f(self, *args, **kwargs)
return update_wrapper(wrapper_func, f)
|
null | null | null | When was the first request handled ?
| def setupmethod(f):
def wrapper_func(self, *args, **kwargs):
if (self.debug and self._got_first_request):
raise AssertionError('A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.\nTo fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.')
return f(self, *args, **kwargs)
return update_wrapper(wrapper_func, f)
| null | null | null | already
| codeqa | def setupmethod f def wrapper func self *args **kwargs if self debug and self got first request raise Assertion Error ' Asetupfunctionwascalledafterthefirstrequestwashandled Thisusuallyindicatesabugintheapplicationwhereamodulewasnotimportedanddecoratorsorotherfunctionalitywascalledtoolate \n Tofixthismakesuretoimportallyourviewmodules databasemodelsandeverythingrelatedatacentralplacebeforetheapplicationstartsservingrequests ' return f self *args **kwargs return update wrapper wrapper func f
| null | null | null | null | Question:
When was the first request handled ?
Code:
def setupmethod(f):
def wrapper_func(self, *args, **kwargs):
if (self.debug and self._got_first_request):
raise AssertionError('A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.\nTo fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.')
return f(self, *args, **kwargs)
return update_wrapper(wrapper_func, f)
|
null | null | null | What does the code populate ?
| def parse_scheme(scheme, stream, error_handler=None, allow_pickle_data=False):
warnings.warn("Use 'scheme_load' instead", DeprecationWarning, stacklevel=2)
doc = parse(stream)
scheme_el = doc.getroot()
version = scheme_el.attrib.get('version', None)
if (version is None):
if (scheme_el.find('widgets') is not None):
version = '1.0'
else:
version = '2.0'
if (error_handler is None):
def error_handler(exc):
raise exc
if (version == '1.0'):
parse_scheme_v_1_0(doc, scheme, error_handler=error_handler, allow_pickle_data=allow_pickle_data)
return scheme
else:
parse_scheme_v_2_0(doc, scheme, error_handler=error_handler, allow_pickle_data=allow_pickle_data)
return scheme
| null | null | null | a scheme instance
| codeqa | def parse scheme scheme stream error handler None allow pickle data False warnings warn " Use'scheme load'instead" Deprecation Warning stacklevel 2 doc parse stream scheme el doc getroot version scheme el attrib get 'version' None if version is None if scheme el find 'widgets' is not None version '1 0'else version '2 0'if error handler is None def error handler exc raise excif version '1 0' parse scheme v 1 0 doc scheme error handler error handler allow pickle data allow pickle data return schemeelse parse scheme v 2 0 doc scheme error handler error handler allow pickle data allow pickle data return scheme
| null | null | null | null | Question:
What does the code populate ?
Code:
def parse_scheme(scheme, stream, error_handler=None, allow_pickle_data=False):
warnings.warn("Use 'scheme_load' instead", DeprecationWarning, stacklevel=2)
doc = parse(stream)
scheme_el = doc.getroot()
version = scheme_el.attrib.get('version', None)
if (version is None):
if (scheme_el.find('widgets') is not None):
version = '1.0'
else:
version = '2.0'
if (error_handler is None):
def error_handler(exc):
raise exc
if (version == '1.0'):
parse_scheme_v_1_0(doc, scheme, error_handler=error_handler, allow_pickle_data=allow_pickle_data)
return scheme
else:
parse_scheme_v_2_0(doc, scheme, error_handler=error_handler, allow_pickle_data=allow_pickle_data)
return scheme
|
null | null | null | What creates a temporary directory ?
| @contextlib.contextmanager
def temp_cwd(name='tempcwd', quiet=False):
if (have_unicode and isinstance(name, unicode) and (not os.path.supports_unicode_filenames)):
try:
name = name.encode((sys.getfilesystemencoding() or 'ascii'))
except UnicodeEncodeError:
if (not quiet):
raise unittest.SkipTest('unable to encode the cwd name with the filesystem encoding.')
saved_dir = os.getcwd()
is_temporary = False
try:
os.mkdir(name)
os.chdir(name)
is_temporary = True
except OSError:
if (not quiet):
raise
warnings.warn(('tests may fail, unable to change the CWD to ' + name), RuntimeWarning, stacklevel=3)
try:
(yield os.getcwd())
finally:
os.chdir(saved_dir)
if is_temporary:
rmtree(name)
| null | null | null | context manager
| codeqa | @contextlib contextmanagerdef temp cwd name 'tempcwd' quiet False if have unicode and isinstance name unicode and not os path supports unicode filenames try name name encode sys getfilesystemencoding or 'ascii' except Unicode Encode Error if not quiet raise unittest Skip Test 'unabletoencodethecwdnamewiththefilesystemencoding ' saved dir os getcwd is temporary Falsetry os mkdir name os chdir name is temporary Trueexcept OS Error if not quiet raisewarnings warn 'testsmayfail unabletochangethe CW Dto' + name Runtime Warning stacklevel 3 try yield os getcwd finally os chdir saved dir if is temporary rmtree name
| null | null | null | null | Question:
What creates a temporary directory ?
Code:
@contextlib.contextmanager
def temp_cwd(name='tempcwd', quiet=False):
if (have_unicode and isinstance(name, unicode) and (not os.path.supports_unicode_filenames)):
try:
name = name.encode((sys.getfilesystemencoding() or 'ascii'))
except UnicodeEncodeError:
if (not quiet):
raise unittest.SkipTest('unable to encode the cwd name with the filesystem encoding.')
saved_dir = os.getcwd()
is_temporary = False
try:
os.mkdir(name)
os.chdir(name)
is_temporary = True
except OSError:
if (not quiet):
raise
warnings.warn(('tests may fail, unable to change the CWD to ' + name), RuntimeWarning, stacklevel=3)
try:
(yield os.getcwd())
finally:
os.chdir(saved_dir)
if is_temporary:
rmtree(name)
|
null | null | null | What does context manager create ?
| @contextlib.contextmanager
def temp_cwd(name='tempcwd', quiet=False):
if (have_unicode and isinstance(name, unicode) and (not os.path.supports_unicode_filenames)):
try:
name = name.encode((sys.getfilesystemencoding() or 'ascii'))
except UnicodeEncodeError:
if (not quiet):
raise unittest.SkipTest('unable to encode the cwd name with the filesystem encoding.')
saved_dir = os.getcwd()
is_temporary = False
try:
os.mkdir(name)
os.chdir(name)
is_temporary = True
except OSError:
if (not quiet):
raise
warnings.warn(('tests may fail, unable to change the CWD to ' + name), RuntimeWarning, stacklevel=3)
try:
(yield os.getcwd())
finally:
os.chdir(saved_dir)
if is_temporary:
rmtree(name)
| null | null | null | a temporary directory
| codeqa | @contextlib contextmanagerdef temp cwd name 'tempcwd' quiet False if have unicode and isinstance name unicode and not os path supports unicode filenames try name name encode sys getfilesystemencoding or 'ascii' except Unicode Encode Error if not quiet raise unittest Skip Test 'unabletoencodethecwdnamewiththefilesystemencoding ' saved dir os getcwd is temporary Falsetry os mkdir name os chdir name is temporary Trueexcept OS Error if not quiet raisewarnings warn 'testsmayfail unabletochangethe CW Dto' + name Runtime Warning stacklevel 3 try yield os getcwd finally os chdir saved dir if is temporary rmtree name
| null | null | null | null | Question:
What does context manager create ?
Code:
@contextlib.contextmanager
def temp_cwd(name='tempcwd', quiet=False):
if (have_unicode and isinstance(name, unicode) and (not os.path.supports_unicode_filenames)):
try:
name = name.encode((sys.getfilesystemencoding() or 'ascii'))
except UnicodeEncodeError:
if (not quiet):
raise unittest.SkipTest('unable to encode the cwd name with the filesystem encoding.')
saved_dir = os.getcwd()
is_temporary = False
try:
os.mkdir(name)
os.chdir(name)
is_temporary = True
except OSError:
if (not quiet):
raise
warnings.warn(('tests may fail, unable to change the CWD to ' + name), RuntimeWarning, stacklevel=3)
try:
(yield os.getcwd())
finally:
os.chdir(saved_dir)
if is_temporary:
rmtree(name)
|
null | null | null | What does the code get ?
| def index_in_children_list(module, xml=None):
if hasattr(module, 'xml_attributes'):
val = module.xml_attributes.get('index_in_children_list')
if (val is not None):
return int(val)
return None
if (xml is not None):
create_xml_attributes(module, xml)
return index_in_children_list(module)
return None
| null | null | null | the index_in_children_list
| codeqa | def index in children list module xml None if hasattr module 'xml attributes' val module xml attributes get 'index in children list' if val is not None return int val return Noneif xml is not None create xml attributes module xml return index in children list module return None
| null | null | null | null | Question:
What does the code get ?
Code:
def index_in_children_list(module, xml=None):
if hasattr(module, 'xml_attributes'):
val = module.xml_attributes.get('index_in_children_list')
if (val is not None):
return int(val)
return None
if (xml is not None):
create_xml_attributes(module, xml)
return index_in_children_list(module)
return None
|
null | null | null | When have all mappers been constructed ?
| def configure_mappers():
if (not Mapper._new_mappers):
return
_CONFIGURE_MUTEX.acquire()
try:
global _already_compiling
if _already_compiling:
return
_already_compiling = True
try:
if (not Mapper._new_mappers):
return
Mapper.dispatch._for_class(Mapper).before_configured()
for mapper in list(_mapper_registry):
if getattr(mapper, '_configure_failed', False):
e = sa_exc.InvalidRequestError(("One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: '%s'. Original exception was: %s" % (mapper, mapper._configure_failed)))
e._configure_failed = mapper._configure_failed
raise e
if (not mapper.configured):
try:
mapper._post_configure_properties()
mapper._expire_memoizations()
mapper.dispatch.mapper_configured(mapper, mapper.class_)
except Exception:
exc = sys.exc_info()[1]
if (not hasattr(exc, '_configure_failed')):
mapper._configure_failed = exc
raise
Mapper._new_mappers = False
finally:
_already_compiling = False
finally:
_CONFIGURE_MUTEX.release()
Mapper.dispatch._for_class(Mapper).after_configured()
| null | null | null | thus far
| codeqa | def configure mappers if not Mapper new mappers return CONFIGURE MUTEX acquire try global already compilingif already compiling return already compiling Truetry if not Mapper new mappers return Mapper dispatch for class Mapper before configured for mapper in list mapper registry if getattr mapper ' configure failed' False e sa exc Invalid Request Error " Oneormoremappersfailedtoinitialize-can'tproceedwithinitializationofothermappers Triggeringmapper '%s' Originalexceptionwas %s" % mapper mapper configure failed e configure failed mapper configure failedraise eif not mapper configured try mapper post configure properties mapper expire memoizations mapper dispatch mapper configured mapper mapper class except Exception exc sys exc info [1 ]if not hasattr exc ' configure failed' mapper configure failed excraise Mapper new mappers Falsefinally already compiling Falsefinally CONFIGURE MUTEX release Mapper dispatch for class Mapper after configured
| null | null | null | null | Question:
When have all mappers been constructed ?
Code:
def configure_mappers():
if (not Mapper._new_mappers):
return
_CONFIGURE_MUTEX.acquire()
try:
global _already_compiling
if _already_compiling:
return
_already_compiling = True
try:
if (not Mapper._new_mappers):
return
Mapper.dispatch._for_class(Mapper).before_configured()
for mapper in list(_mapper_registry):
if getattr(mapper, '_configure_failed', False):
e = sa_exc.InvalidRequestError(("One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: '%s'. Original exception was: %s" % (mapper, mapper._configure_failed)))
e._configure_failed = mapper._configure_failed
raise e
if (not mapper.configured):
try:
mapper._post_configure_properties()
mapper._expire_memoizations()
mapper.dispatch.mapper_configured(mapper, mapper.class_)
except Exception:
exc = sys.exc_info()[1]
if (not hasattr(exc, '_configure_failed')):
mapper._configure_failed = exc
raise
Mapper._new_mappers = False
finally:
_already_compiling = False
finally:
_CONFIGURE_MUTEX.release()
Mapper.dispatch._for_class(Mapper).after_configured()
|
null | null | null | What does the code initialize ?
| def configure_mappers():
if (not Mapper._new_mappers):
return
_CONFIGURE_MUTEX.acquire()
try:
global _already_compiling
if _already_compiling:
return
_already_compiling = True
try:
if (not Mapper._new_mappers):
return
Mapper.dispatch._for_class(Mapper).before_configured()
for mapper in list(_mapper_registry):
if getattr(mapper, '_configure_failed', False):
e = sa_exc.InvalidRequestError(("One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: '%s'. Original exception was: %s" % (mapper, mapper._configure_failed)))
e._configure_failed = mapper._configure_failed
raise e
if (not mapper.configured):
try:
mapper._post_configure_properties()
mapper._expire_memoizations()
mapper.dispatch.mapper_configured(mapper, mapper.class_)
except Exception:
exc = sys.exc_info()[1]
if (not hasattr(exc, '_configure_failed')):
mapper._configure_failed = exc
raise
Mapper._new_mappers = False
finally:
_already_compiling = False
finally:
_CONFIGURE_MUTEX.release()
Mapper.dispatch._for_class(Mapper).after_configured()
| null | null | null | the inter - mapper relationships of all mappers that have been constructed thus far
| codeqa | def configure mappers if not Mapper new mappers return CONFIGURE MUTEX acquire try global already compilingif already compiling return already compiling Truetry if not Mapper new mappers return Mapper dispatch for class Mapper before configured for mapper in list mapper registry if getattr mapper ' configure failed' False e sa exc Invalid Request Error " Oneormoremappersfailedtoinitialize-can'tproceedwithinitializationofothermappers Triggeringmapper '%s' Originalexceptionwas %s" % mapper mapper configure failed e configure failed mapper configure failedraise eif not mapper configured try mapper post configure properties mapper expire memoizations mapper dispatch mapper configured mapper mapper class except Exception exc sys exc info [1 ]if not hasattr exc ' configure failed' mapper configure failed excraise Mapper new mappers Falsefinally already compiling Falsefinally CONFIGURE MUTEX release Mapper dispatch for class Mapper after configured
| null | null | null | null | Question:
What does the code initialize ?
Code:
def configure_mappers():
if (not Mapper._new_mappers):
return
_CONFIGURE_MUTEX.acquire()
try:
global _already_compiling
if _already_compiling:
return
_already_compiling = True
try:
if (not Mapper._new_mappers):
return
Mapper.dispatch._for_class(Mapper).before_configured()
for mapper in list(_mapper_registry):
if getattr(mapper, '_configure_failed', False):
e = sa_exc.InvalidRequestError(("One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: '%s'. Original exception was: %s" % (mapper, mapper._configure_failed)))
e._configure_failed = mapper._configure_failed
raise e
if (not mapper.configured):
try:
mapper._post_configure_properties()
mapper._expire_memoizations()
mapper.dispatch.mapper_configured(mapper, mapper.class_)
except Exception:
exc = sys.exc_info()[1]
if (not hasattr(exc, '_configure_failed')):
mapper._configure_failed = exc
raise
Mapper._new_mappers = False
finally:
_already_compiling = False
finally:
_CONFIGURE_MUTEX.release()
Mapper.dispatch._for_class(Mapper).after_configured()
|
null | null | null | When is no music playing ?
| def jog_music():
if (music_enabled and (not music.get_busy())):
start_next_music()
| null | null | null | currently
| codeqa | def jog music if music enabled and not music get busy start next music
| null | null | null | null | Question:
When is no music playing ?
Code:
def jog_music():
if (music_enabled and (not music.get_busy())):
start_next_music()
|
null | null | null | How does a content return ?
| def prefix(handlers, default=None, error='The requested prefix does not match any of those allowed'):
def output_type(data, request, response):
path = request.path
handler = default
for (prefix_test, prefix_handler) in handlers.items():
if path.startswith(prefix_test):
handler = prefix_handler
break
if (not handler):
raise falcon.HTTPNotAcceptable(error)
response.content_type = handler.content_type
return handler(data, request=request, response=response)
output_type.__doc__ = 'Supports any of the following formats: {0}'.format(', '.join((function.__doc__ for function in handlers.values())))
output_type.content_type = ', '.join(handlers.keys())
return output_type
| null | null | null | in a different format
| codeqa | def prefix handlers default None error ' Therequestedprefixdoesnotmatchanyofthoseallowed' def output type data request response path request pathhandler defaultfor prefix test prefix handler in handlers items if path startswith prefix test handler prefix handlerbreakif not handler raise falcon HTTP Not Acceptable error response content type handler content typereturn handler data request request response response output type doc ' Supportsanyofthefollowingformats {0 }' format ' ' join function doc for function in handlers values output type content type ' ' join handlers keys return output type
| null | null | null | null | Question:
How does a content return ?
Code:
def prefix(handlers, default=None, error='The requested prefix does not match any of those allowed'):
def output_type(data, request, response):
path = request.path
handler = default
for (prefix_test, prefix_handler) in handlers.items():
if path.startswith(prefix_test):
handler = prefix_handler
break
if (not handler):
raise falcon.HTTPNotAcceptable(error)
response.content_type = handler.content_type
return handler(data, request=request, response=response)
output_type.__doc__ = 'Supports any of the following formats: {0}'.format(', '.join((function.__doc__ for function in handlers.values())))
output_type.content_type = ', '.join(handlers.keys())
return output_type
|
null | null | null | What does this function set ?
| def enable_console_debug_logging():
logger = logging.getLogger('github')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
| null | null | null | a very simple logging configuration that is useful for troubleshooting
| codeqa | def enable console debug logging logger logging get Logger 'github' logger set Level logging DEBUG logger add Handler logging Stream Handler
| null | null | null | null | Question:
What does this function set ?
Code:
def enable_console_debug_logging():
logger = logging.getLogger('github')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.