labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2 values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4 values | answer stringlengths 2 905 | src stringclasses 3 values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does the code provide ?
| def elevation_along_path(client, path, samples):
if (type(path) is str):
path = ('enc:%s' % path)
else:
path = convert.shortest_path(path)
params = {'path': path, 'samples': samples}
return client._get('/maps/api/elevation/json', params)['results']
| null | null | null | elevation data sampled along a path on the surface of the earth
| codeqa | def elevation along path client path samples if type path is str path 'enc %s' % path else path convert shortest path path params {'path' path 'samples' samples}return client get '/maps/api/elevation/json' params ['results']
| null | null | null | null | Question:
What does the code provide ?
Code:
def elevation_along_path(client, path, samples):
if (type(path) is str):
path = ('enc:%s' % path)
else:
path = convert.shortest_path(path)
params = {'path': path, 'samples': samples}
return client._get('/maps/api/elevation/json', params)['results']
|
null | null | null | Where did elevation data sample along a path ?
| def elevation_along_path(client, path, samples):
if (type(path) is str):
path = ('enc:%s' % path)
else:
path = convert.shortest_path(path)
params = {'path': path, 'samples': samples}
return client._get('/maps/api/elevation/json', params)['results']
| null | null | null | on the surface of the earth
| codeqa | def elevation along path client path samples if type path is str path 'enc %s' % path else path convert shortest path path params {'path' path 'samples' samples}return client get '/maps/api/elevation/json' params ['results']
| null | null | null | null | Question:
Where did elevation data sample along a path ?
Code:
def elevation_along_path(client, path, samples):
if (type(path) is str):
path = ('enc:%s' % path)
else:
path = convert.shortest_path(path)
params = {'path': path, 'samples': samples}
return client._get('/maps/api/elevation/json', params)['results']
|
null | null | null | What does the given directory return ?
| def DetermineRunner(bbdir):
tacfile = os.path.join(bbdir, 'buildbot.tac')
if (not os.path.exists(tacfile)):
import buildbot.scripts.runner
return buildbot.scripts.runner.run
with open(tacfile, 'r') as f:
contents = f.read()
try:
if ('import Worker' in contents):
import buildbot_worker.scripts.runner
return buildbot_worker.scripts.runner.run
except ImportError:
pass
try:
if ('import BuildSlave' in contents):
import buildslave.scripts.runner
return buildslave.scripts.runner.run
except ImportError:
pass
import buildbot.scripts.runner
return buildbot.scripts.runner.run
| null | null | null | the appropriate run function
| codeqa | def Determine Runner bbdir tacfile os path join bbdir 'buildbot tac' if not os path exists tacfile import buildbot scripts runnerreturn buildbot scripts runner runwith open tacfile 'r' as f contents f read try if 'import Worker' in contents import buildbot worker scripts runnerreturn buildbot worker scripts runner runexcept Import Error passtry if 'import Build Slave' in contents import buildslave scripts runnerreturn buildslave scripts runner runexcept Import Error passimport buildbot scripts runnerreturn buildbot scripts runner run
| null | null | null | null | Question:
What does the given directory return ?
Code:
def DetermineRunner(bbdir):
tacfile = os.path.join(bbdir, 'buildbot.tac')
if (not os.path.exists(tacfile)):
import buildbot.scripts.runner
return buildbot.scripts.runner.run
with open(tacfile, 'r') as f:
contents = f.read()
try:
if ('import Worker' in contents):
import buildbot_worker.scripts.runner
return buildbot_worker.scripts.runner.run
except ImportError:
pass
try:
if ('import BuildSlave' in contents):
import buildslave.scripts.runner
return buildslave.scripts.runner.run
except ImportError:
pass
import buildbot.scripts.runner
return buildbot.scripts.runner.run
|
null | null | null | What returns the appropriate run function ?
| def DetermineRunner(bbdir):
tacfile = os.path.join(bbdir, 'buildbot.tac')
if (not os.path.exists(tacfile)):
import buildbot.scripts.runner
return buildbot.scripts.runner.run
with open(tacfile, 'r') as f:
contents = f.read()
try:
if ('import Worker' in contents):
import buildbot_worker.scripts.runner
return buildbot_worker.scripts.runner.run
except ImportError:
pass
try:
if ('import BuildSlave' in contents):
import buildslave.scripts.runner
return buildslave.scripts.runner.run
except ImportError:
pass
import buildbot.scripts.runner
return buildbot.scripts.runner.run
| null | null | null | the given directory
| codeqa | def Determine Runner bbdir tacfile os path join bbdir 'buildbot tac' if not os path exists tacfile import buildbot scripts runnerreturn buildbot scripts runner runwith open tacfile 'r' as f contents f read try if 'import Worker' in contents import buildbot worker scripts runnerreturn buildbot worker scripts runner runexcept Import Error passtry if 'import Build Slave' in contents import buildslave scripts runnerreturn buildslave scripts runner runexcept Import Error passimport buildbot scripts runnerreturn buildbot scripts runner run
| null | null | null | null | Question:
What returns the appropriate run function ?
Code:
def DetermineRunner(bbdir):
tacfile = os.path.join(bbdir, 'buildbot.tac')
if (not os.path.exists(tacfile)):
import buildbot.scripts.runner
return buildbot.scripts.runner.run
with open(tacfile, 'r') as f:
contents = f.read()
try:
if ('import Worker' in contents):
import buildbot_worker.scripts.runner
return buildbot_worker.scripts.runner.run
except ImportError:
pass
try:
if ('import BuildSlave' in contents):
import buildslave.scripts.runner
return buildslave.scripts.runner.run
except ImportError:
pass
import buildbot.scripts.runner
return buildbot.scripts.runner.run
|
null | null | null | What does the code take ?
| def sanitizeSceneName(name, ezrss=False):
if (not ezrss):
bad_chars = u",:()'!?\u2019"
else:
bad_chars = u",()'?\u2019"
for x in bad_chars:
name = name.replace(x, '')
name = name.replace('- ', '.').replace(' ', '.').replace('&', 'and').replace('/', '.')
name = re.sub('\\.\\.*', '.', name)
if name.endswith('.'):
name = name[:(-1)]
return name
| null | null | null | a show name
| codeqa | def sanitize Scene Name name ezrss False if not ezrss bad chars u" ' ?\u 2019 "else bad chars u" '?\u 2019 "for x in bad chars name name replace x '' name name replace '-' ' ' replace '' ' ' replace '&' 'and' replace '/' ' ' name re sub '\\ \\ *' ' ' name if name endswith ' ' name name[ -1 ]return name
| null | null | null | null | Question:
What does the code take ?
Code:
def sanitizeSceneName(name, ezrss=False):
if (not ezrss):
bad_chars = u",:()'!?\u2019"
else:
bad_chars = u",()'?\u2019"
for x in bad_chars:
name = name.replace(x, '')
name = name.replace('- ', '.').replace(' ', '.').replace('&', 'and').replace('/', '.')
name = re.sub('\\.\\.*', '.', name)
if name.endswith('.'):
name = name[:(-1)]
return name
|
null | null | null | What is raised in a context ?
| @contextmanager
def assert_raises_regex(exc, pattern, msg=''):
try:
(yield)
except exc as e:
assert re.search(pattern, str(e)), ('%s%r not found in %r' % (_fmt_msg(msg), pattern, str(e)))
else:
raise AssertionError(('%s%s was not raised' % (_fmt_msg(msg), exc)))
| null | null | null | some exception
| codeqa | @contextmanagerdef assert raises regex exc pattern msg '' try yield except exc as e assert re search pattern str e '%s%rnotfoundin%r' % fmt msg msg pattern str e else raise Assertion Error '%s%swasnotraised' % fmt msg msg exc
| null | null | null | null | Question:
What is raised in a context ?
Code:
@contextmanager
def assert_raises_regex(exc, pattern, msg=''):
try:
(yield)
except exc as e:
assert re.search(pattern, str(e)), ('%s%r not found in %r' % (_fmt_msg(msg), pattern, str(e)))
else:
raise AssertionError(('%s%s was not raised' % (_fmt_msg(msg), exc)))
|
null | null | null | What matches some pattern ?
| @contextmanager
def assert_raises_regex(exc, pattern, msg=''):
try:
(yield)
except exc as e:
assert re.search(pattern, str(e)), ('%s%r not found in %r' % (_fmt_msg(msg), pattern, str(e)))
else:
raise AssertionError(('%s%s was not raised' % (_fmt_msg(msg), exc)))
| null | null | null | the message
| codeqa | @contextmanagerdef assert raises regex exc pattern msg '' try yield except exc as e assert re search pattern str e '%s%rnotfoundin%r' % fmt msg msg pattern str e else raise Assertion Error '%s%swasnotraised' % fmt msg msg exc
| null | null | null | null | Question:
What matches some pattern ?
Code:
@contextmanager
def assert_raises_regex(exc, pattern, msg=''):
try:
(yield)
except exc as e:
assert re.search(pattern, str(e)), ('%s%r not found in %r' % (_fmt_msg(msg), pattern, str(e)))
else:
raise AssertionError(('%s%s was not raised' % (_fmt_msg(msg), exc)))
|
null | null | null | Where is some exception raised ?
| @contextmanager
def assert_raises_regex(exc, pattern, msg=''):
try:
(yield)
except exc as e:
assert re.search(pattern, str(e)), ('%s%r not found in %r' % (_fmt_msg(msg), pattern, str(e)))
else:
raise AssertionError(('%s%s was not raised' % (_fmt_msg(msg), exc)))
| null | null | null | in a context
| codeqa | @contextmanagerdef assert raises regex exc pattern msg '' try yield except exc as e assert re search pattern str e '%s%rnotfoundin%r' % fmt msg msg pattern str e else raise Assertion Error '%s%swasnotraised' % fmt msg msg exc
| null | null | null | null | Question:
Where is some exception raised ?
Code:
@contextmanager
def assert_raises_regex(exc, pattern, msg=''):
try:
(yield)
except exc as e:
assert re.search(pattern, str(e)), ('%s%r not found in %r' % (_fmt_msg(msg), pattern, str(e)))
else:
raise AssertionError(('%s%s was not raised' % (_fmt_msg(msg), exc)))
|
null | null | null | What did the message match ?
| @contextmanager
def assert_raises_regex(exc, pattern, msg=''):
try:
(yield)
except exc as e:
assert re.search(pattern, str(e)), ('%s%r not found in %r' % (_fmt_msg(msg), pattern, str(e)))
else:
raise AssertionError(('%s%s was not raised' % (_fmt_msg(msg), exc)))
| null | null | null | some pattern
| codeqa | @contextmanagerdef assert raises regex exc pattern msg '' try yield except exc as e assert re search pattern str e '%s%rnotfoundin%r' % fmt msg msg pattern str e else raise Assertion Error '%s%swasnotraised' % fmt msg msg exc
| null | null | null | null | Question:
What did the message match ?
Code:
@contextmanager
def assert_raises_regex(exc, pattern, msg=''):
try:
(yield)
except exc as e:
assert re.search(pattern, str(e)), ('%s%r not found in %r' % (_fmt_msg(msg), pattern, str(e)))
else:
raise AssertionError(('%s%s was not raised' % (_fmt_msg(msg), exc)))
|
null | null | null | What does the code compute from a list of words ?
| def compute_words_maxsize(words):
max_size = 0
for word in words:
if (len(word) > max_size):
max_size = len(word)
return max_size
| null | null | null | the maximum word size
| codeqa | def compute words maxsize words max size 0for word in words if len word > max size max size len word return max size
| null | null | null | null | Question:
What does the code compute from a list of words ?
Code:
def compute_words_maxsize(words):
max_size = 0
for word in words:
if (len(word) > max_size):
max_size = len(word)
return max_size
|
null | null | null | What does the code calculate ?
| def change(value, reference):
if (not reference):
return None
return (((value or 0) - reference) / float(reference))
| null | null | null | the relative change between a value and a reference point
| codeqa | def change value reference if not reference return Nonereturn value or 0 - reference / float reference
| null | null | null | null | Question:
What does the code calculate ?
Code:
def change(value, reference):
if (not reference):
return None
return (((value or 0) - reference) / float(reference))
|
null | null | null | What will we tell functions ?
| def do_not_report_as_logging_caller(func):
_caller_code_to_skip_in_logging_stack.add(func.func_code)
return func
| null | null | null | logging
| codeqa | def do not report as logging caller func caller code to skip in logging stack add func func code return func
| null | null | null | null | Question:
What will we tell functions ?
Code:
def do_not_report_as_logging_caller(func):
_caller_code_to_skip_in_logging_stack.add(func.func_code)
return func
|
null | null | null | What does the code add ?
| def _add_directives(block, directives, replace):
for directive in directives:
_add_directive(block, directive, replace)
if (block and ('\n' not in block[(-1)])):
block.append(nginxparser.UnspacedList('\n'))
| null | null | null | directives in a config block
| codeqa | def add directives block directives replace for directive in directives add directive block directive replace if block and '\n' not in block[ -1 ] block append nginxparser Unspaced List '\n'
| null | null | null | null | Question:
What does the code add ?
Code:
def _add_directives(block, directives, replace):
for directive in directives:
_add_directive(block, directive, replace)
if (block and ('\n' not in block[(-1)])):
block.append(nginxparser.UnspacedList('\n'))
|
null | null | null | What does the code get ?
| def defined_names(source, path=None, encoding='utf-8'):
warnings.warn('Use call_signatures instead.', DeprecationWarning)
return names(source, path, encoding)
| null | null | null | all definitions
| codeqa | def defined names source path None encoding 'utf- 8 ' warnings warn ' Usecall signaturesinstead ' Deprecation Warning return names source path encoding
| null | null | null | null | Question:
What does the code get ?
Code:
def defined_names(source, path=None, encoding='utf-8'):
warnings.warn('Use call_signatures instead.', DeprecationWarning)
return names(source, path, encoding)
|
null | null | null | What does the code add ?
| def addPillarFromConvexLoopsGridTop(faces, indexedGridTop, indexedLoops):
addFacesByLoopReversed(faces, indexedLoops[0])
addFacesByConvexLoops(faces, indexedLoops)
addFacesByGrid(faces, indexedGridTop)
| null | null | null | pillar
| codeqa | def add Pillar From Convex Loops Grid Top faces indexed Grid Top indexed Loops add Faces By Loop Reversed faces indexed Loops[ 0 ] add Faces By Convex Loops faces indexed Loops add Faces By Grid faces indexed Grid Top
| null | null | null | null | Question:
What does the code add ?
Code:
def addPillarFromConvexLoopsGridTop(faces, indexedGridTop, indexedLoops):
addFacesByLoopReversed(faces, indexedLoops[0])
addFacesByConvexLoops(faces, indexedLoops)
addFacesByGrid(faces, indexedGridTop)
|
null | null | null | What do filename contain by default ?
| def contains(filename, text, exact=False, use_sudo=False, escape=True, shell=False, case_sensitive=True):
func = ((use_sudo and sudo) or run)
if escape:
text = _escape_for_regex(text)
if exact:
text = ('^%s$' % text)
with settings(hide('everything'), warn_only=True):
egrep_cmd = ('egrep "%s" %s' % (text, _expand_path(filename)))
if (not case_sensitive):
egrep_cmd = egrep_cmd.replace('egrep', 'egrep -i', 1)
return func(egrep_cmd, shell=shell).succeeded
| null | null | null | text
| codeqa | def contains filename text exact False use sudo False escape True shell False case sensitive True func use sudo and sudo or run if escape text escape for regex text if exact text '^%s$' % text with settings hide 'everything' warn only True egrep cmd 'egrep"%s"%s' % text expand path filename if not case sensitive egrep cmd egrep cmd replace 'egrep' 'egrep-i' 1 return func egrep cmd shell shell succeeded
| null | null | null | null | Question:
What do filename contain by default ?
Code:
def contains(filename, text, exact=False, use_sudo=False, escape=True, shell=False, case_sensitive=True):
func = ((use_sudo and sudo) or run)
if escape:
text = _escape_for_regex(text)
if exact:
text = ('^%s$' % text)
with settings(hide('everything'), warn_only=True):
egrep_cmd = ('egrep "%s" %s' % (text, _expand_path(filename)))
if (not case_sensitive):
egrep_cmd = egrep_cmd.replace('egrep', 'egrep -i', 1)
return func(egrep_cmd, shell=shell).succeeded
|
null | null | null | What contains text by default ?
| def contains(filename, text, exact=False, use_sudo=False, escape=True, shell=False, case_sensitive=True):
func = ((use_sudo and sudo) or run)
if escape:
text = _escape_for_regex(text)
if exact:
text = ('^%s$' % text)
with settings(hide('everything'), warn_only=True):
egrep_cmd = ('egrep "%s" %s' % (text, _expand_path(filename)))
if (not case_sensitive):
egrep_cmd = egrep_cmd.replace('egrep', 'egrep -i', 1)
return func(egrep_cmd, shell=shell).succeeded
| null | null | null | filename
| codeqa | def contains filename text exact False use sudo False escape True shell False case sensitive True func use sudo and sudo or run if escape text escape for regex text if exact text '^%s$' % text with settings hide 'everything' warn only True egrep cmd 'egrep"%s"%s' % text expand path filename if not case sensitive egrep cmd egrep cmd replace 'egrep' 'egrep-i' 1 return func egrep cmd shell shell succeeded
| null | null | null | null | Question:
What contains text by default ?
Code:
def contains(filename, text, exact=False, use_sudo=False, escape=True, shell=False, case_sensitive=True):
func = ((use_sudo and sudo) or run)
if escape:
text = _escape_for_regex(text)
if exact:
text = ('^%s$' % text)
with settings(hide('everything'), warn_only=True):
egrep_cmd = ('egrep "%s" %s' % (text, _expand_path(filename)))
if (not case_sensitive):
egrep_cmd = egrep_cmd.replace('egrep', 'egrep -i', 1)
return func(egrep_cmd, shell=shell).succeeded
|
null | null | null | How do filename contain text ?
| def contains(filename, text, exact=False, use_sudo=False, escape=True, shell=False, case_sensitive=True):
func = ((use_sudo and sudo) or run)
if escape:
text = _escape_for_regex(text)
if exact:
text = ('^%s$' % text)
with settings(hide('everything'), warn_only=True):
egrep_cmd = ('egrep "%s" %s' % (text, _expand_path(filename)))
if (not case_sensitive):
egrep_cmd = egrep_cmd.replace('egrep', 'egrep -i', 1)
return func(egrep_cmd, shell=shell).succeeded
| null | null | null | by default
| codeqa | def contains filename text exact False use sudo False escape True shell False case sensitive True func use sudo and sudo or run if escape text escape for regex text if exact text '^%s$' % text with settings hide 'everything' warn only True egrep cmd 'egrep"%s"%s' % text expand path filename if not case sensitive egrep cmd egrep cmd replace 'egrep' 'egrep-i' 1 return func egrep cmd shell shell succeeded
| null | null | null | null | Question:
How do filename contain text ?
Code:
def contains(filename, text, exact=False, use_sudo=False, escape=True, shell=False, case_sensitive=True):
func = ((use_sudo and sudo) or run)
if escape:
text = _escape_for_regex(text)
if exact:
text = ('^%s$' % text)
with settings(hide('everything'), warn_only=True):
egrep_cmd = ('egrep "%s" %s' % (text, _expand_path(filename)))
if (not case_sensitive):
egrep_cmd = egrep_cmd.replace('egrep', 'egrep -i', 1)
return func(egrep_cmd, shell=shell).succeeded
|
null | null | null | What does the code run ?
| @click.command(u'request')
@click.argument(u'args')
@pass_context
def request(context, args):
import frappe.handler
import frappe.api
for site in context.sites:
try:
frappe.init(site=site)
frappe.connect()
if (u'?' in args):
frappe.local.form_dict = frappe._dict([a.split(u'=') for a in args.split(u'?')[(-1)].split(u'&')])
else:
frappe.local.form_dict = frappe._dict()
if args.startswith(u'/api/method'):
frappe.local.form_dict.cmd = args.split(u'?')[0].split(u'/')[(-1)]
frappe.handler.execute_cmd(frappe.form_dict.cmd)
print frappe.response
finally:
frappe.destroy()
| null | null | null | a request as an admin
| codeqa | @click command u'request' @click argument u'args' @pass contextdef request context args import frappe handlerimport frappe apifor site in context sites try frappe init site site frappe connect if u'?' in args frappe local form dict frappe dict [a split u' ' for a in args split u'?' [ -1 ] split u'&' ] else frappe local form dict frappe dict if args startswith u'/api/method' frappe local form dict cmd args split u'?' [0 ] split u'/' [ -1 ]frappe handler execute cmd frappe form dict cmd print frappe responsefinally frappe destroy
| null | null | null | null | Question:
What does the code run ?
Code:
@click.command(u'request')
@click.argument(u'args')
@pass_context
def request(context, args):
import frappe.handler
import frappe.api
for site in context.sites:
try:
frappe.init(site=site)
frappe.connect()
if (u'?' in args):
frappe.local.form_dict = frappe._dict([a.split(u'=') for a in args.split(u'?')[(-1)].split(u'&')])
else:
frappe.local.form_dict = frappe._dict()
if args.startswith(u'/api/method'):
frappe.local.form_dict.cmd = args.split(u'?')[0].split(u'/')[(-1)]
frappe.handler.execute_cmd(frappe.form_dict.cmd)
print frappe.response
finally:
frappe.destroy()
|
null | null | null | What does the code delete ?
| def task_delete(context, task_id, session=None):
session = (session or get_session())
task_ref = _task_get(context, task_id, session=session)
task_ref.delete(session=session)
return _task_format(task_ref, task_ref.info)
| null | null | null | a task
| codeqa | def task delete context task id session None session session or get session task ref task get context task id session session task ref delete session session return task format task ref task ref info
| null | null | null | null | Question:
What does the code delete ?
Code:
def task_delete(context, task_id, session=None):
session = (session or get_session())
task_ref = _task_get(context, task_id, session=session)
task_ref.delete(session=session)
return _task_format(task_ref, task_ref.info)
|
null | null | null | What declared in config ?
| def request_namespace(k, v):
if (k[:5] == 'body.'):
setattr(cherrypy.serving.request.body, k[5:], v)
else:
setattr(cherrypy.serving.request, k, v)
| null | null | null | request attributes
| codeqa | def request namespace k v if k[ 5] 'body ' setattr cherrypy serving request body k[ 5 ] v else setattr cherrypy serving request k v
| null | null | null | null | Question:
What declared in config ?
Code:
def request_namespace(k, v):
if (k[:5] == 'body.'):
setattr(cherrypy.serving.request.body, k[5:], v)
else:
setattr(cherrypy.serving.request, k, v)
|
null | null | null | Where did request attributes declare ?
| def request_namespace(k, v):
if (k[:5] == 'body.'):
setattr(cherrypy.serving.request.body, k[5:], v)
else:
setattr(cherrypy.serving.request, k, v)
| null | null | null | in config
| codeqa | def request namespace k v if k[ 5] 'body ' setattr cherrypy serving request body k[ 5 ] v else setattr cherrypy serving request k v
| null | null | null | null | Question:
Where did request attributes declare ?
Code:
def request_namespace(k, v):
if (k[:5] == 'body.'):
setattr(cherrypy.serving.request.body, k[5:], v)
else:
setattr(cherrypy.serving.request, k, v)
|
null | null | null | What returns to remove_tag for question 2 ?
| def _remove_tag_url(question_id):
return reverse('questions.remove_tag', kwargs={'question_id': question_id})
| null | null | null | url
| codeqa | def remove tag url question id return reverse 'questions remove tag' kwargs {'question id' question id}
| null | null | null | null | Question:
What returns to remove_tag for question 2 ?
Code:
def _remove_tag_url(question_id):
return reverse('questions.remove_tag', kwargs={'question_id': question_id})
|
null | null | null | What is provided in the argument ?
| def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
| null | null | null | a space
| codeqa | def view with argument request name if name ' Arthur Dent' return Http Response ' Hi Arthur' else return Http Response ' Howdy %s' % name
| null | null | null | null | Question:
What is provided in the argument ?
Code:
def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
|
null | null | null | What does a view take ?
| def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
| null | null | null | a string argument
| codeqa | def view with argument request name if name ' Arthur Dent' return Http Response ' Hi Arthur' else return Http Response ' Howdy %s' % name
| null | null | null | null | Question:
What does a view take ?
Code:
def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
|
null | null | null | Where is a space provided ?
| def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
| null | null | null | in the argument
| codeqa | def view with argument request name if name ' Arthur Dent' return Http Response ' Hi Arthur' else return Http Response ' Howdy %s' % name
| null | null | null | null | Question:
Where is a space provided ?
Code:
def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
|
null | null | null | What takes a string argument ?
| def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
| null | null | null | a view
| codeqa | def view with argument request name if name ' Arthur Dent' return Http Response ' Hi Arthur' else return Http Response ' Howdy %s' % name
| null | null | null | null | Question:
What takes a string argument ?
Code:
def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
|
null | null | null | What is to check that if a space is provided in the argument ?
| def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
| null | null | null | a view that takes a string argument
| codeqa | def view with argument request name if name ' Arthur Dent' return Http Response ' Hi Arthur' else return Http Response ' Howdy %s' % name
| null | null | null | null | Question:
What is to check that if a space is provided in the argument ?
Code:
def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
|
null | null | null | What does a view that takes a string argument be ?
| def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
| null | null | null | to check that if a space is provided in the argument
| codeqa | def view with argument request name if name ' Arthur Dent' return Http Response ' Hi Arthur' else return Http Response ' Howdy %s' % name
| null | null | null | null | Question:
What does a view that takes a string argument be ?
Code:
def view_with_argument(request, name):
if (name == 'Arthur Dent'):
return HttpResponse('Hi, Arthur')
else:
return HttpResponse(('Howdy, %s' % name))
|
null | null | null | Do you add a duplicate file extension ?
| @pytest.mark.django_db
def test_data_store_checks(tp0):
store = StoreDBFactory(name='foo.po', parent=tp0.directory, translation_project=tp0)
check_data = StoreChecksData.objects.create(store=store)
assert (repr(check_data) == ('<StoreChecksData: %s>' % store.pootle_path))
| null | null | null | No
| codeqa | @pytest mark django dbdef test data store checks tp 0 store Store DB Factory name 'foo po' parent tp 0 directory translation project tp 0 check data Store Checks Data objects create store store assert repr check data '< Store Checks Data %s>' % store pootle path
| null | null | null | null | Question:
Do you add a duplicate file extension ?
Code:
@pytest.mark.django_db
def test_data_store_checks(tp0):
store = StoreDBFactory(name='foo.po', parent=tp0.directory, translation_project=tp0)
check_data = StoreChecksData.objects.create(store=store)
assert (repr(check_data) == ('<StoreChecksData: %s>' % store.pootle_path))
|
null | null | null | What does the code generate ?
| def versionFromCommitNo(commitNo):
return ('0.0.0-dev%d' % commitNo)
| null | null | null | a version string
| codeqa | def version From Commit No commit No return '0 0 0-dev%d' % commit No
| null | null | null | null | Question:
What does the code generate ?
Code:
def versionFromCommitNo(commitNo):
return ('0.0.0-dev%d' % commitNo)
|
null | null | null | What does the code get ?
| def getEvaluatedIntByKeys(defaultValue, elementNode, keys):
for key in keys:
defaultValue = getEvaluatedInt(defaultValue, elementNode, key)
return defaultValue
| null | null | null | the evaluated int by keys
| codeqa | def get Evaluated Int By Keys default Value element Node keys for key in keys default Value get Evaluated Int default Value element Node key return default Value
| null | null | null | null | Question:
What does the code get ?
Code:
def getEvaluatedIntByKeys(defaultValue, elementNode, keys):
for key in keys:
defaultValue = getEvaluatedInt(defaultValue, elementNode, key)
return defaultValue
|
null | null | null | What does the code add ?
| def add_group_type_access(context, group_type_id, project_id):
if (group_type_id is None):
msg = _('group_type_id cannot be None')
raise exception.InvalidGroupType(reason=msg)
elevated = (context if context.is_admin else context.elevated())
if is_public_group_type(elevated, group_type_id):
msg = _('Type access modification is not applicable to public group type.')
raise exception.InvalidGroupType(reason=msg)
return db.group_type_access_add(elevated, group_type_id, project_id)
| null | null | null | access to group type for project_id
| codeqa | def add group type access context group type id project id if group type id is None msg 'group type idcannotbe None' raise exception Invalid Group Type reason msg elevated context if context is admin else context elevated if is public group type elevated group type id msg ' Typeaccessmodificationisnotapplicabletopublicgrouptype ' raise exception Invalid Group Type reason msg return db group type access add elevated group type id project id
| null | null | null | null | Question:
What does the code add ?
Code:
def add_group_type_access(context, group_type_id, project_id):
if (group_type_id is None):
msg = _('group_type_id cannot be None')
raise exception.InvalidGroupType(reason=msg)
elevated = (context if context.is_admin else context.elevated())
if is_public_group_type(elevated, group_type_id):
msg = _('Type access modification is not applicable to public group type.')
raise exception.InvalidGroupType(reason=msg)
return db.group_type_access_add(elevated, group_type_id, project_id)
|
null | null | null | What renders in the currently set locale ?
| def render_email(template, context):
@safe_translation
def _render(locale):
'Render an email in the given locale.\n\n Because of safe_translation decorator, if this fails,\n the function will be run again in English.\n '
req = RequestFactory()
req.META = {}
req.locale = locale
return render_to_string(template, context)
return _render(translation.get_language())
| null | null | null | a template
| codeqa | def render email template context @safe translationdef render locale ' Renderanemailinthegivenlocale \n\n Becauseofsafe translationdecorator ifthisfails \nthefunctionwillberunagainin English \n'req Request Factory req META {}req locale localereturn render to string template context return render translation get language
| null | null | null | null | Question:
What renders in the currently set locale ?
Code:
def render_email(template, context):
@safe_translation
def _render(locale):
'Render an email in the given locale.\n\n Because of safe_translation decorator, if this fails,\n the function will be run again in English.\n '
req = RequestFactory()
req.META = {}
req.locale = locale
return render_to_string(template, context)
return _render(translation.get_language())
|
null | null | null | When did locale set ?
| def render_email(template, context):
@safe_translation
def _render(locale):
'Render an email in the given locale.\n\n Because of safe_translation decorator, if this fails,\n the function will be run again in English.\n '
req = RequestFactory()
req.META = {}
req.locale = locale
return render_to_string(template, context)
return _render(translation.get_language())
| null | null | null | currently
| codeqa | def render email template context @safe translationdef render locale ' Renderanemailinthegivenlocale \n\n Becauseofsafe translationdecorator ifthisfails \nthefunctionwillberunagainin English \n'req Request Factory req META {}req locale localereturn render to string template context return render translation get language
| null | null | null | null | Question:
When did locale set ?
Code:
def render_email(template, context):
@safe_translation
def _render(locale):
'Render an email in the given locale.\n\n Because of safe_translation decorator, if this fails,\n the function will be run again in English.\n '
req = RequestFactory()
req.META = {}
req.locale = locale
return render_to_string(template, context)
return _render(translation.get_language())
|
null | null | null | Where does a template render ?
| def render_email(template, context):
@safe_translation
def _render(locale):
'Render an email in the given locale.\n\n Because of safe_translation decorator, if this fails,\n the function will be run again in English.\n '
req = RequestFactory()
req.META = {}
req.locale = locale
return render_to_string(template, context)
return _render(translation.get_language())
| null | null | null | in the currently set locale
| codeqa | def render email template context @safe translationdef render locale ' Renderanemailinthegivenlocale \n\n Becauseofsafe translationdecorator ifthisfails \nthefunctionwillberunagainin English \n'req Request Factory req META {}req locale localereturn render to string template context return render translation get language
| null | null | null | null | Question:
Where does a template render ?
Code:
def render_email(template, context):
@safe_translation
def _render(locale):
'Render an email in the given locale.\n\n Because of safe_translation decorator, if this fails,\n the function will be run again in English.\n '
req = RequestFactory()
req.META = {}
req.locale = locale
return render_to_string(template, context)
return _render(translation.get_language())
|
null | null | null | What does the code subscribe ?
| @shared_task()
def subscribe_user_to_basket(instance_id, newsletters=[]):
from mozillians.users.models import UserProfile
try:
instance = UserProfile.objects.get(pk=instance_id)
except UserProfile.DoesNotExist:
instance = None
if ((not BASKET_ENABLED) or (not instance) or (not newsletters) or (not waffle.switch_is_active('BASKET_SWITCH_ENABLED'))):
return
lookup_subtask = lookup_user_task.subtask((instance.user.email,))
subscribe_subtask = subscribe_user_task.subtask((instance.user.email, newsletters))
chain((lookup_subtask | subscribe_subtask))()
| null | null | null | a user to basket
| codeqa | @shared task def subscribe user to basket instance id newsletters [] from mozillians users models import User Profiletry instance User Profile objects get pk instance id except User Profile Does Not Exist instance Noneif not BASKET ENABLED or not instance or not newsletters or not waffle switch is active 'BASKET SWITCH ENABLED' returnlookup subtask lookup user task subtask instance user email subscribe subtask subscribe user task subtask instance user email newsletters chain lookup subtask subscribe subtask
| null | null | null | null | Question:
What does the code subscribe ?
Code:
@shared_task()
def subscribe_user_to_basket(instance_id, newsletters=[]):
from mozillians.users.models import UserProfile
try:
instance = UserProfile.objects.get(pk=instance_id)
except UserProfile.DoesNotExist:
instance = None
if ((not BASKET_ENABLED) or (not instance) or (not newsletters) or (not waffle.switch_is_active('BASKET_SWITCH_ENABLED'))):
return
lookup_subtask = lookup_user_task.subtask((instance.user.email,))
subscribe_subtask = subscribe_user_task.subtask((instance.user.email, newsletters))
chain((lookup_subtask | subscribe_subtask))()
|
null | null | null | What does the code create ?
| def new_figure_manager(num, *args, **kwargs):
if DEBUG:
print(u'backend_gtkagg.new_figure_manager')
FigureClass = kwargs.pop(u'FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig)
| null | null | null | a new figure manager instance
| codeqa | def new figure manager num *args **kwargs if DEBUG print u'backend gtkagg new figure manager' Figure Class kwargs pop u' Figure Class' Figure this Fig Figure Class *args **kwargs return new figure manager given figure num this Fig
| null | null | null | null | Question:
What does the code create ?
Code:
def new_figure_manager(num, *args, **kwargs):
if DEBUG:
print(u'backend_gtkagg.new_figure_manager')
FigureClass = kwargs.pop(u'FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig)
|
null | null | null | For what purpose did the code share ?
| def main(suite=None):
parseArgs()
if (suite is None):
suite = unittest.defaultTestLoader.loadTestsFromModule(__import__('__main__'))
if debug:
print >>sys.stderr, ('Debug: Suite=%s' % suite)
testRunner = unittest.TextTestRunner(verbosity=verbosity)
if (type(suite) == type([])):
for s in suite:
testRunner.run(s)
else:
return testRunner.run(suite)
| null | null | null | for any individual test _ * file
| codeqa | def main suite None parse Args if suite is None suite unittest default Test Loader load Tests From Module import ' main ' if debug print >>sys stderr ' Debug Suite %s' % suite test Runner unittest Text Test Runner verbosity verbosity if type suite type [] for s in suite test Runner run s else return test Runner run suite
| null | null | null | null | Question:
For what purpose did the code share ?
Code:
def main(suite=None):
parseArgs()
if (suite is None):
suite = unittest.defaultTestLoader.loadTestsFromModule(__import__('__main__'))
if debug:
print >>sys.stderr, ('Debug: Suite=%s' % suite)
testRunner = unittest.TextTestRunner(verbosity=verbosity)
if (type(suite) == type([])):
for s in suite:
testRunner.run(s)
else:
return testRunner.run(suite)
|
null | null | null | What does the code run ?
| def exec_(name, command, runas=None):
args = [_sdecode(name)]
args.extend(_normalize_args(command))
return prlctl('exec', args, runas=runas)
| null | null | null | a command on a vm
| codeqa | def exec name command runas None args [ sdecode name ]args extend normalize args command return prlctl 'exec' args runas runas
| null | null | null | null | Question:
What does the code run ?
Code:
def exec_(name, command, runas=None):
args = [_sdecode(name)]
args.extend(_normalize_args(command))
return prlctl('exec', args, runas=runas)
|
null | null | null | What does the code parse ?
| def _parse_entry(line, quoted, escaped):
if (line == ''):
raise IndexError('no remaining content to parse')
(next_entry, remainder) = ('', line)
if quoted:
(start_quote, end_quote) = _get_quote_indices(remainder, escaped)
if ((start_quote != 0) or (end_quote == (-1))):
raise ValueError(("the next entry isn't a quoted value: " + line))
(next_entry, remainder) = (remainder[1:end_quote], remainder[(end_quote + 1):])
elif (' ' in remainder):
(next_entry, remainder) = remainder.split(' ', 1)
else:
(next_entry, remainder) = (remainder, '')
if escaped:
next_entry = _unescape(next_entry)
return (next_entry, remainder.lstrip())
| null | null | null | the next entry from the given space separated content
| codeqa | def parse entry line quoted escaped if line '' raise Index Error 'noremainingcontenttoparse' next entry remainder '' line if quoted start quote end quote get quote indices remainder escaped if start quote 0 or end quote -1 raise Value Error "thenextentryisn'taquotedvalue " + line next entry remainder remainder[ 1 end quote] remainder[ end quote + 1 ] elif '' in remainder next entry remainder remainder split '' 1 else next entry remainder remainder '' if escaped next entry unescape next entry return next entry remainder lstrip
| null | null | null | null | Question:
What does the code parse ?
Code:
def _parse_entry(line, quoted, escaped):
if (line == ''):
raise IndexError('no remaining content to parse')
(next_entry, remainder) = ('', line)
if quoted:
(start_quote, end_quote) = _get_quote_indices(remainder, escaped)
if ((start_quote != 0) or (end_quote == (-1))):
raise ValueError(("the next entry isn't a quoted value: " + line))
(next_entry, remainder) = (remainder[1:end_quote], remainder[(end_quote + 1):])
elif (' ' in remainder):
(next_entry, remainder) = remainder.split(' ', 1)
else:
(next_entry, remainder) = (remainder, '')
if escaped:
next_entry = _unescape(next_entry)
return (next_entry, remainder.lstrip())
|
null | null | null | When does the code decorate the given function to be a no - op ?
| def only_once(fn):
once = [fn]
def go(*arg, **kw):
if once:
once_fn = once.pop()
return once_fn(*arg, **kw)
return go
| null | null | null | after it is called exactly once
| codeqa | def only once fn once [fn]def go *arg **kw if once once fn once pop return once fn *arg **kw return go
| null | null | null | null | Question:
When does the code decorate the given function to be a no - op ?
Code:
def only_once(fn):
once = [fn]
def go(*arg, **kw):
if once:
once_fn = once.pop()
return once_fn(*arg, **kw)
return go
|
null | null | null | When is it called ?
| def only_once(fn):
once = [fn]
def go(*arg, **kw):
if once:
once_fn = once.pop()
return once_fn(*arg, **kw)
return go
| null | null | null | exactly once
| codeqa | def only once fn once [fn]def go *arg **kw if once once fn once pop return once fn *arg **kw return go
| null | null | null | null | Question:
When is it called ?
Code:
def only_once(fn):
once = [fn]
def go(*arg, **kw):
if once:
once_fn = once.pop()
return once_fn(*arg, **kw)
return go
|
null | null | null | For what purpose does the code decorate the given function after it is called exactly once ?
| def only_once(fn):
once = [fn]
def go(*arg, **kw):
if once:
once_fn = once.pop()
return once_fn(*arg, **kw)
return go
| null | null | null | to be a no - op
| codeqa | def only once fn once [fn]def go *arg **kw if once once fn once pop return once fn *arg **kw return go
| null | null | null | null | Question:
For what purpose does the code decorate the given function after it is called exactly once ?
Code:
def only_once(fn):
once = [fn]
def go(*arg, **kw):
if once:
once_fn = once.pop()
return once_fn(*arg, **kw)
return go
|
null | null | null | What does the code decorate to be a no - op after it is called exactly once ?
| def only_once(fn):
once = [fn]
def go(*arg, **kw):
if once:
once_fn = once.pop()
return once_fn(*arg, **kw)
return go
| null | null | null | the given function
| codeqa | def only once fn once [fn]def go *arg **kw if once once fn once pop return once fn *arg **kw return go
| null | null | null | null | Question:
What does the code decorate to be a no - op after it is called exactly once ?
Code:
def only_once(fn):
once = [fn]
def go(*arg, **kw):
if once:
once_fn = once.pop()
return once_fn(*arg, **kw)
return go
|
null | null | null | In which direction does a blob copy to another with a new name ?
| def copy_blob(bucket_name, blob_name, new_bucket_name, new_blob_name):
storage_client = storage.Client()
source_bucket = storage_client.get_bucket(bucket_name)
source_blob = source_bucket.blob(blob_name)
destination_bucket = storage_client.get_bucket(new_bucket_name)
new_blob = source_bucket.copy_blob(source_blob, destination_bucket, new_blob_name)
print 'Blob {} in bucket {} copied to blob {} in bucket {}.'.format(source_blob.name, source_bucket.name, new_blob.name, destination_bucket.name)
| null | null | null | from one bucket
| codeqa | def copy blob bucket name blob name new bucket name new blob name storage client storage Client source bucket storage client get bucket bucket name source blob source bucket blob blob name destination bucket storage client get bucket new bucket name new blob source bucket copy blob source blob destination bucket new blob name print ' Blob{}inbucket{}copiedtoblob{}inbucket{} ' format source blob name source bucket name new blob name destination bucket name
| null | null | null | null | Question:
In which direction does a blob copy to another with a new name ?
Code:
def copy_blob(bucket_name, blob_name, new_bucket_name, new_blob_name):
storage_client = storage.Client()
source_bucket = storage_client.get_bucket(bucket_name)
source_blob = source_bucket.blob(blob_name)
destination_bucket = storage_client.get_bucket(new_bucket_name)
new_blob = source_bucket.copy_blob(source_blob, destination_bucket, new_blob_name)
print 'Blob {} in bucket {} copied to blob {} in bucket {}.'.format(source_blob.name, source_bucket.name, new_blob.name, destination_bucket.name)
|
null | null | null | How does a blob copy to another from one bucket ?
| def copy_blob(bucket_name, blob_name, new_bucket_name, new_blob_name):
storage_client = storage.Client()
source_bucket = storage_client.get_bucket(bucket_name)
source_blob = source_bucket.blob(blob_name)
destination_bucket = storage_client.get_bucket(new_bucket_name)
new_blob = source_bucket.copy_blob(source_blob, destination_bucket, new_blob_name)
print 'Blob {} in bucket {} copied to blob {} in bucket {}.'.format(source_blob.name, source_bucket.name, new_blob.name, destination_bucket.name)
| null | null | null | with a new name
| codeqa | def copy blob bucket name blob name new bucket name new blob name storage client storage Client source bucket storage client get bucket bucket name source blob source bucket blob blob name destination bucket storage client get bucket new bucket name new blob source bucket copy blob source blob destination bucket new blob name print ' Blob{}inbucket{}copiedtoblob{}inbucket{} ' format source blob name source bucket name new blob name destination bucket name
| null | null | null | null | Question:
How does a blob copy to another from one bucket ?
Code:
def copy_blob(bucket_name, blob_name, new_bucket_name, new_blob_name):
storage_client = storage.Client()
source_bucket = storage_client.get_bucket(bucket_name)
source_blob = source_bucket.blob(blob_name)
destination_bucket = storage_client.get_bucket(new_bucket_name)
new_blob = source_bucket.copy_blob(source_blob, destination_bucket, new_blob_name)
print 'Blob {} in bucket {} copied to blob {} in bucket {}.'.format(source_blob.name, source_bucket.name, new_blob.name, destination_bucket.name)
|
null | null | null | For what purpose does the code modify the extensions ?
| def build_from_c_and_cpp_files(extensions):
for extension in extensions:
sources = []
for sfile in extension.sources:
(path, ext) = os.path.splitext(sfile)
if (ext in ('.pyx', '.py')):
if (extension.language == 'c++'):
ext = '.cpp'
else:
ext = '.c'
sfile = (path + ext)
sources.append(sfile)
extension.sources = sources
| null | null | null | to build from the
| codeqa | def build from c and cpp files extensions for extension in extensions sources []for sfile in extension sources path ext os path splitext sfile if ext in ' pyx' ' py' if extension language 'c++' ext ' cpp'else ext ' c'sfile path + ext sources append sfile extension sources sources
| null | null | null | null | Question:
For what purpose does the code modify the extensions ?
Code:
def build_from_c_and_cpp_files(extensions):
for extension in extensions:
sources = []
for sfile in extension.sources:
(path, ext) = os.path.splitext(sfile)
if (ext in ('.pyx', '.py')):
if (extension.language == 'c++'):
ext = '.cpp'
else:
ext = '.c'
sfile = (path + ext)
sources.append(sfile)
extension.sources = sources
|
null | null | null | In which direction do the extensions build ?
| def build_from_c_and_cpp_files(extensions):
for extension in extensions:
sources = []
for sfile in extension.sources:
(path, ext) = os.path.splitext(sfile)
if (ext in ('.pyx', '.py')):
if (extension.language == 'c++'):
ext = '.cpp'
else:
ext = '.c'
sfile = (path + ext)
sources.append(sfile)
extension.sources = sources
| null | null | null | from the
| codeqa | def build from c and cpp files extensions for extension in extensions sources []for sfile in extension sources path ext os path splitext sfile if ext in ' pyx' ' py' if extension language 'c++' ext ' cpp'else ext ' c'sfile path + ext sources append sfile extension sources sources
| null | null | null | null | Question:
In which direction do the extensions build ?
Code:
def build_from_c_and_cpp_files(extensions):
for extension in extensions:
sources = []
for sfile in extension.sources:
(path, ext) = os.path.splitext(sfile)
if (ext in ('.pyx', '.py')):
if (extension.language == 'c++'):
ext = '.cpp'
else:
ext = '.c'
sfile = (path + ext)
sources.append(sfile)
extension.sources = sources
|
null | null | null | What does the code modify to build from the ?
| def build_from_c_and_cpp_files(extensions):
for extension in extensions:
sources = []
for sfile in extension.sources:
(path, ext) = os.path.splitext(sfile)
if (ext in ('.pyx', '.py')):
if (extension.language == 'c++'):
ext = '.cpp'
else:
ext = '.c'
sfile = (path + ext)
sources.append(sfile)
extension.sources = sources
| null | null | null | the extensions
| codeqa | def build from c and cpp files extensions for extension in extensions sources []for sfile in extension sources path ext os path splitext sfile if ext in ' pyx' ' py' if extension language 'c++' ext ' cpp'else ext ' c'sfile path + ext sources append sfile extension sources sources
| null | null | null | null | Question:
What does the code modify to build from the ?
Code:
def build_from_c_and_cpp_files(extensions):
for extension in extensions:
sources = []
for sfile in extension.sources:
(path, ext) = os.path.splitext(sfile)
if (ext in ('.pyx', '.py')):
if (extension.language == 'c++'):
ext = '.cpp'
else:
ext = '.c'
sfile = (path + ext)
sources.append(sfile)
extension.sources = sources
|
null | null | null | For what purpose do font size convert to rem ?
| def convert_fontsize(length, unit, base_font_size=16.0, dpi=96.0):
if (unit == u'px'):
return (length / base_font_size)
pt_to_px = (dpi / 72.0)
pt_to_rem = (pt_to_px / base_font_size)
return ((length * length_factors.get(unit, 1)) * pt_to_rem)
| null | null | null | so that font size scaling works
| codeqa | def convert fontsize length unit base font size 16 0 dpi 96 0 if unit u'px' return length / base font size pt to px dpi / 72 0 pt to rem pt to px / base font size return length * length factors get unit 1 * pt to rem
| null | null | null | null | Question:
For what purpose do font size convert to rem ?
Code:
def convert_fontsize(length, unit, base_font_size=16.0, dpi=96.0):
if (unit == u'px'):
return (length / base_font_size)
pt_to_px = (dpi / 72.0)
pt_to_rem = (pt_to_px / base_font_size)
return ((length * length_factors.get(unit, 1)) * pt_to_rem)
|
null | null | null | What is valid on the target in this context ?
| def check(context, action, target, plugin=None, might_not_exist=False, pluralized=None):
if context.is_admin:
return True
if (might_not_exist and (not (_ENFORCER.rules and (action in _ENFORCER.rules)))):
return True
(match_rule, target, credentials) = _prepare_check(context, action, target, pluralized)
result = _ENFORCER.enforce(match_rule, target, credentials, pluralized=pluralized)
if (not result):
log_rule_list(match_rule)
return result
| null | null | null | the action
| codeqa | def check context action target plugin None might not exist False pluralized None if context is admin return Trueif might not exist and not ENFORCER rules and action in ENFORCER rules return True match rule target credentials prepare check context action target pluralized result ENFORCER enforce match rule target credentials pluralized pluralized if not result log rule list match rule return result
| null | null | null | null | Question:
What is valid on the target in this context ?
Code:
def check(context, action, target, plugin=None, might_not_exist=False, pluralized=None):
if context.is_admin:
return True
if (might_not_exist and (not (_ENFORCER.rules and (action in _ENFORCER.rules)))):
return True
(match_rule, target, credentials) = _prepare_check(context, action, target, pluralized)
result = _ENFORCER.enforce(match_rule, target, credentials, pluralized=pluralized)
if (not result):
log_rule_list(match_rule)
return result
|
null | null | null | Where is the action valid on the target ?
| def check(context, action, target, plugin=None, might_not_exist=False, pluralized=None):
if context.is_admin:
return True
if (might_not_exist and (not (_ENFORCER.rules and (action in _ENFORCER.rules)))):
return True
(match_rule, target, credentials) = _prepare_check(context, action, target, pluralized)
result = _ENFORCER.enforce(match_rule, target, credentials, pluralized=pluralized)
if (not result):
log_rule_list(match_rule)
return result
| null | null | null | in this context
| codeqa | def check context action target plugin None might not exist False pluralized None if context is admin return Trueif might not exist and not ENFORCER rules and action in ENFORCER rules return True match rule target credentials prepare check context action target pluralized result ENFORCER enforce match rule target credentials pluralized pluralized if not result log rule list match rule return result
| null | null | null | null | Question:
Where is the action valid on the target ?
Code:
def check(context, action, target, plugin=None, might_not_exist=False, pluralized=None):
if context.is_admin:
return True
if (might_not_exist and (not (_ENFORCER.rules and (action in _ENFORCER.rules)))):
return True
(match_rule, target, credentials) = _prepare_check(context, action, target, pluralized)
result = _ENFORCER.enforce(match_rule, target, credentials, pluralized=pluralized)
if (not result):
log_rule_list(match_rule)
return result
|
null | null | null | What does the code take ?
| def to_names(domain_obj_list):
objs = []
for obj in domain_obj_list:
objs.append((obj.name if obj else None))
return objs
| null | null | null | a list of domain objects
| codeqa | def to names domain obj list objs []for obj in domain obj list objs append obj name if obj else None return objs
| null | null | null | null | Question:
What does the code take ?
Code:
def to_names(domain_obj_list):
objs = []
for obj in domain_obj_list:
objs.append((obj.name if obj else None))
return objs
|
null | null | null | What does the code return ?
| def to_names(domain_obj_list):
objs = []
for obj in domain_obj_list:
objs.append((obj.name if obj else None))
return objs
| null | null | null | a corresponding list of their names
| codeqa | def to names domain obj list objs []for obj in domain obj list objs append obj name if obj else None return objs
| null | null | null | null | Question:
What does the code return ?
Code:
def to_names(domain_obj_list):
objs = []
for obj in domain_obj_list:
objs.append((obj.name if obj else None))
return objs
|
null | null | null | How is scenario#matches_tags called when ?
| def test_scenario_matches_tags_excluding_fuzzywuzzy():
scenario = Scenario.from_string(SCENARIO1, original_string=('@anothertag\n@another-tag\n' + SCENARIO1.strip()))
assert (not scenario.matches_tags(['-~anothertag']))
| null | null | null | with a member starting with -~
| codeqa | def test scenario matches tags excluding fuzzywuzzy scenario Scenario from string SCENARIO 1 original string '@anothertag\n@another-tag\n' + SCENARIO 1 strip assert not scenario matches tags ['-~anothertag']
| null | null | null | null | Question:
How is scenario#matches_tags called when ?
Code:
def test_scenario_matches_tags_excluding_fuzzywuzzy():
scenario = Scenario.from_string(SCENARIO1, original_string=('@anothertag\n@another-tag\n' + SCENARIO1.strip()))
assert (not scenario.matches_tags(['-~anothertag']))
|
null | null | null | What does the code execute in a given global environment ?
| def ExecuteCode(code, global_dict):
exec code in global_dict
| null | null | null | some code
| codeqa | def Execute Code code global dict exec code in global dict
| null | null | null | null | Question:
What does the code execute in a given global environment ?
Code:
def ExecuteCode(code, global_dict):
exec code in global_dict
|
null | null | null | Where does the code execute some code ?
| def ExecuteCode(code, global_dict):
exec code in global_dict
| null | null | null | in a given global environment
| codeqa | def Execute Code code global dict exec code in global dict
| null | null | null | null | Question:
Where does the code execute some code ?
Code:
def ExecuteCode(code, global_dict):
exec code in global_dict
|
null | null | null | When did file modify ?
| def get_last_modified(files):
files = list(files)
if files:
return max((datetime.datetime.fromtimestamp(os.path.getmtime(f)) for f in files))
return datetime.datetime(1970, 1, 1)
| null | null | null | most recently
| codeqa | def get last modified files files list files if files return max datetime datetime fromtimestamp os path getmtime f for f in files return datetime datetime 1970 1 1
| null | null | null | null | Question:
When did file modify ?
Code:
def get_last_modified(files):
files = list(files)
if files:
return max((datetime.datetime.fromtimestamp(os.path.getmtime(f)) for f in files))
return datetime.datetime(1970, 1, 1)
|
null | null | null | How is a view requested ?
| def read_all(request):
return HttpResponse(request.read())
| null | null | null | with accesses request
| codeqa | def read all request return Http Response request read
| null | null | null | null | Question:
How is a view requested ?
Code:
def read_all(request):
return HttpResponse(request.read())
|
null | null | null | For what purpose do the changes display ?
| def GetChangesSample():
client = CreateClient()
changes = client.GetChanges()
for change in changes.entry:
print change.title.text, change.changestamp.value
| null | null | null | for the user
| codeqa | def Get Changes Sample client Create Client changes client Get Changes for change in changes entry print change title text change changestamp value
| null | null | null | null | Question:
For what purpose do the changes display ?
Code:
def GetChangesSample():
client = CreateClient()
changes = client.GetChanges()
for change in changes.entry:
print change.title.text, change.changestamp.value
|
null | null | null | How does the variance return ?
| def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
return a.var(axis=axis, dtype=dtype, out=out, keepdims=keepdims)
| null | null | null | along an axis
| codeqa | def var a axis None dtype None out None ddof 0 keepdims False return a var axis axis dtype dtype out out keepdims keepdims
| null | null | null | null | Question:
How does the variance return ?
Code:
def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
return a.var(axis=axis, dtype=dtype, out=out, keepdims=keepdims)
|
null | null | null | What does the code get ?
| def getDistanceToLineByPaths(begin, end, paths):
distanceToLine = (-987654321.0)
for path in paths:
distanceToLine = max(getDistanceToLineByPath(begin, end, path), distanceToLine)
return distanceToLine
| null | null | null | the maximum distance from paths to an infinite line
| codeqa | def get Distance To Line By Paths begin end paths distance To Line -987654321 0 for path in paths distance To Line max get Distance To Line By Path begin end path distance To Line return distance To Line
| null | null | null | null | Question:
What does the code get ?
Code:
def getDistanceToLineByPaths(begin, end, paths):
distanceToLine = (-987654321.0)
for path in paths:
distanceToLine = max(getDistanceToLineByPath(begin, end, path), distanceToLine)
return distanceToLine
|
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 lash 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 delete ?
| def snapshot_metadata_delete(context, snapshot_id, key):
return IMPL.snapshot_metadata_delete(context, snapshot_id, key)
| null | null | null | the given metadata item
| codeqa | def snapshot metadata delete context snapshot id key return IMPL snapshot metadata delete context snapshot id key
| null | null | null | null | Question:
What does the code delete ?
Code:
def snapshot_metadata_delete(context, snapshot_id, key):
return IMPL.snapshot_metadata_delete(context, snapshot_id, key)
|
null | null | null | How is opus lib loaded ?
| def is_loaded():
global _lib
return (_lib is not None)
| null | null | null | successfully
| codeqa | def is loaded global libreturn lib is not None
| null | null | null | null | Question:
How is opus lib loaded ?
Code:
def is_loaded():
global _lib
return (_lib is not None)
|
null | null | null | What passes the given test ?
| def user_passes_test(test_func, login_url=LOGIN_URL):
def _dec(view_func):
def _checklogin(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))))
_checklogin.__doc__ = view_func.__doc__
_checklogin.__dict__ = view_func.__dict__
return _checklogin
return _dec
| null | null | null | the user
| codeqa | def user passes test test func login url LOGIN URL def dec view func def checklogin request *args **kwargs if test func request user return view func request *args **kwargs return Http Response Redirect '%s?%s %s' % login url REDIRECT FIELD NAME quote request get full path checklogin doc view func doc checklogin dict view func dict return checkloginreturn dec
| null | null | null | null | Question:
What passes the given test ?
Code:
def user_passes_test(test_func, login_url=LOGIN_URL):
def _dec(view_func):
def _checklogin(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))))
_checklogin.__doc__ = view_func.__doc__
_checklogin.__dict__ = view_func.__dict__
return _checklogin
return _dec
|
null | null | null | What does decorator for views check ?
| def user_passes_test(test_func, login_url=LOGIN_URL):
def _dec(view_func):
def _checklogin(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))))
_checklogin.__doc__ = view_func.__doc__
_checklogin.__dict__ = view_func.__dict__
return _checklogin
return _dec
| null | null | null | that the user passes the given test
| codeqa | def user passes test test func login url LOGIN URL def dec view func def checklogin request *args **kwargs if test func request user return view func request *args **kwargs return Http Response Redirect '%s?%s %s' % login url REDIRECT FIELD NAME quote request get full path checklogin doc view func doc checklogin dict view func dict return checkloginreturn dec
| null | null | null | null | Question:
What does decorator for views check ?
Code:
def user_passes_test(test_func, login_url=LOGIN_URL):
def _dec(view_func):
def _checklogin(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))))
_checklogin.__doc__ = view_func.__doc__
_checklogin.__dict__ = view_func.__dict__
return _checklogin
return _dec
|
null | null | null | What does the user pass ?
| def user_passes_test(test_func, login_url=LOGIN_URL):
def _dec(view_func):
def _checklogin(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))))
_checklogin.__doc__ = view_func.__doc__
_checklogin.__dict__ = view_func.__dict__
return _checklogin
return _dec
| null | null | null | the given test
| codeqa | def user passes test test func login url LOGIN URL def dec view func def checklogin request *args **kwargs if test func request user return view func request *args **kwargs return Http Response Redirect '%s?%s %s' % login url REDIRECT FIELD NAME quote request get full path checklogin doc view func doc checklogin dict view func dict return checkloginreturn dec
| null | null | null | null | Question:
What does the user pass ?
Code:
def user_passes_test(test_func, login_url=LOGIN_URL):
def _dec(view_func):
def _checklogin(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))))
_checklogin.__doc__ = view_func.__doc__
_checklogin.__dict__ = view_func.__dict__
return _checklogin
return _dec
|
null | null | null | What checks that the user passes the given test ?
| def user_passes_test(test_func, login_url=LOGIN_URL):
def _dec(view_func):
def _checklogin(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))))
_checklogin.__doc__ = view_func.__doc__
_checklogin.__dict__ = view_func.__dict__
return _checklogin
return _dec
| null | null | null | decorator for views
| codeqa | def user passes test test func login url LOGIN URL def dec view func def checklogin request *args **kwargs if test func request user return view func request *args **kwargs return Http Response Redirect '%s?%s %s' % login url REDIRECT FIELD NAME quote request get full path checklogin doc view func doc checklogin dict view func dict return checkloginreturn dec
| null | null | null | null | Question:
What checks that the user passes the given test ?
Code:
def user_passes_test(test_func, login_url=LOGIN_URL):
def _dec(view_func):
def _checklogin(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(('%s?%s=%s' % (login_url, REDIRECT_FIELD_NAME, quote(request.get_full_path()))))
_checklogin.__doc__ = view_func.__doc__
_checklogin.__dict__ = view_func.__dict__
return _checklogin
return _dec
|
null | null | null | What adds request_id field ?
| def upgrade(engine):
meta = MetaData(bind=engine)
pci_devices = Table('pci_devices', meta, autoload=True)
shadow_pci_devices = Table('shadow_pci_devices', meta, autoload=True)
request_id = Column('request_id', String(36), nullable=True)
if (not hasattr(pci_devices.c, 'request_id')):
pci_devices.create_column(request_id)
if (not hasattr(shadow_pci_devices.c, 'request_id')):
shadow_pci_devices.create_column(request_id.copy())
| null | null | null | function
| codeqa | def upgrade engine meta Meta Data bind engine pci devices Table 'pci devices' meta autoload True shadow pci devices Table 'shadow pci devices' meta autoload True request id Column 'request id' String 36 nullable True if not hasattr pci devices c 'request id' pci devices create column request id if not hasattr shadow pci devices c 'request id' shadow pci devices create column request id copy
| null | null | null | null | Question:
What adds request_id field ?
Code:
def upgrade(engine):
meta = MetaData(bind=engine)
pci_devices = Table('pci_devices', meta, autoload=True)
shadow_pci_devices = Table('shadow_pci_devices', meta, autoload=True)
request_id = Column('request_id', String(36), nullable=True)
if (not hasattr(pci_devices.c, 'request_id')):
pci_devices.create_column(request_id)
if (not hasattr(shadow_pci_devices.c, 'request_id')):
shadow_pci_devices.create_column(request_id.copy())
|
null | null | null | What does function add ?
| def upgrade(engine):
meta = MetaData(bind=engine)
pci_devices = Table('pci_devices', meta, autoload=True)
shadow_pci_devices = Table('shadow_pci_devices', meta, autoload=True)
request_id = Column('request_id', String(36), nullable=True)
if (not hasattr(pci_devices.c, 'request_id')):
pci_devices.create_column(request_id)
if (not hasattr(shadow_pci_devices.c, 'request_id')):
shadow_pci_devices.create_column(request_id.copy())
| null | null | null | request_id field
| codeqa | def upgrade engine meta Meta Data bind engine pci devices Table 'pci devices' meta autoload True shadow pci devices Table 'shadow pci devices' meta autoload True request id Column 'request id' String 36 nullable True if not hasattr pci devices c 'request id' pci devices create column request id if not hasattr shadow pci devices c 'request id' shadow pci devices create column request id copy
| null | null | null | null | Question:
What does function add ?
Code:
def upgrade(engine):
meta = MetaData(bind=engine)
pci_devices = Table('pci_devices', meta, autoload=True)
shadow_pci_devices = Table('shadow_pci_devices', meta, autoload=True)
request_id = Column('request_id', String(36), nullable=True)
if (not hasattr(pci_devices.c, 'request_id')):
pci_devices.create_column(request_id)
if (not hasattr(shadow_pci_devices.c, 'request_id')):
shadow_pci_devices.create_column(request_id.copy())
|
null | null | null | For what purpose do the syslog service reload ?
| @depends(HAS_ESX_CLI)
def syslog_service_reload(host, username, password, protocol=None, port=None, esxi_hosts=None):
cmd = 'system syslog reload'
ret = {}
if esxi_hosts:
if (not isinstance(esxi_hosts, list)):
raise CommandExecutionError("'esxi_hosts' must be a list.")
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port, esxi_host=esxi_host)
ret.update({esxi_host: response})
else:
response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port)
ret.update({host: response})
return ret
| null | null | null | so it will pick up any changes
| codeqa | @depends HAS ESX CLI def syslog service reload host username password protocol None port None esxi hosts None cmd 'systemsyslogreload'ret {}if esxi hosts if not isinstance esxi hosts list raise Command Execution Error "'esxi hosts'mustbealist " for esxi host in esxi hosts response salt utils vmware esxcli host username password cmd protocol protocol port port esxi host esxi host ret update {esxi host response} else response salt utils vmware esxcli host username password cmd protocol protocol port port ret update {host response} return ret
| null | null | null | null | Question:
For what purpose do the syslog service reload ?
Code:
@depends(HAS_ESX_CLI)
def syslog_service_reload(host, username, password, protocol=None, port=None, esxi_hosts=None):
cmd = 'system syslog reload'
ret = {}
if esxi_hosts:
if (not isinstance(esxi_hosts, list)):
raise CommandExecutionError("'esxi_hosts' must be a list.")
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port, esxi_host=esxi_host)
ret.update({esxi_host: response})
else:
response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port)
ret.update({host: response})
return ret
|
null | null | null | What will it pick ?
| @depends(HAS_ESX_CLI)
def syslog_service_reload(host, username, password, protocol=None, port=None, esxi_hosts=None):
cmd = 'system syslog reload'
ret = {}
if esxi_hosts:
if (not isinstance(esxi_hosts, list)):
raise CommandExecutionError("'esxi_hosts' must be a list.")
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port, esxi_host=esxi_host)
ret.update({esxi_host: response})
else:
response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port)
ret.update({host: response})
return ret
| null | null | null | any changes
| codeqa | @depends HAS ESX CLI def syslog service reload host username password protocol None port None esxi hosts None cmd 'systemsyslogreload'ret {}if esxi hosts if not isinstance esxi hosts list raise Command Execution Error "'esxi hosts'mustbealist " for esxi host in esxi hosts response salt utils vmware esxcli host username password cmd protocol protocol port port esxi host esxi host ret update {esxi host response} else response salt utils vmware esxcli host username password cmd protocol protocol port port ret update {host response} return ret
| null | null | null | null | Question:
What will it pick ?
Code:
@depends(HAS_ESX_CLI)
def syslog_service_reload(host, username, password, protocol=None, port=None, esxi_hosts=None):
cmd = 'system syslog reload'
ret = {}
if esxi_hosts:
if (not isinstance(esxi_hosts, list)):
raise CommandExecutionError("'esxi_hosts' must be a list.")
for esxi_host in esxi_hosts:
response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port, esxi_host=esxi_host)
ret.update({esxi_host: response})
else:
response = salt.utils.vmware.esxcli(host, username, password, cmd, protocol=protocol, port=port)
ret.update({host: response})
return ret
|
null | null | null | When have return volumes usage been updated ?
| def vol_get_usage_by_time(context, begin):
return IMPL.vol_get_usage_by_time(context, begin)
| null | null | null | after a specified time
| codeqa | def vol get usage by time context begin return IMPL vol get usage by time context begin
| null | null | null | null | Question:
When have return volumes usage been updated ?
Code:
def vol_get_usage_by_time(context, begin):
return IMPL.vol_get_usage_by_time(context, begin)
|
null | null | null | What does the code validate ?
| def validate_email(email):
message = ''
if (not VALID_EMAIL_RE.match(email)):
message = 'Please enter a real email address.'
elif (len(email) > 255):
message = 'Email address exceeds maximum allowable length.'
return message
| null | null | null | the email format
| codeqa | def validate email email message ''if not VALID EMAIL RE match email message ' Pleaseenterarealemailaddress 'elif len email > 255 message ' Emailaddressexceedsmaximumallowablelength 'return message
| null | null | null | null | Question:
What does the code validate ?
Code:
def validate_email(email):
message = ''
if (not VALID_EMAIL_RE.match(email)):
message = 'Please enter a real email address.'
elif (len(email) > 255):
message = 'Email address exceeds maximum allowable length.'
return message
|
null | null | null | What do the given list of classes arrange ?
| def getclasstree(classes, unique=0):
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if (not (parent in children)):
children[parent] = []
if (c not in children[parent]):
children[parent].append(c)
if (unique and (parent in classes)):
break
elif (c not in roots):
roots.append(c)
for parent in children:
if (parent not in classes):
roots.append(parent)
return walktree(roots, children, None)
| null | null | null | into a hierarchy of nested lists
| codeqa | def getclasstree classes unique 0 children {}roots []for c in classes if c bases for parent in c bases if not parent in children children[parent] []if c not in children[parent] children[parent] append c if unique and parent in classes breakelif c not in roots roots append c for parent in children if parent not in classes roots append parent return walktree roots children None
| null | null | null | null | Question:
What do the given list of classes arrange ?
Code:
def getclasstree(classes, unique=0):
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if (not (parent in children)):
children[parent] = []
if (c not in children[parent]):
children[parent].append(c)
if (unique and (parent in classes)):
break
elif (c not in roots):
roots.append(c)
for parent in children:
if (parent not in classes):
roots.append(parent)
return walktree(roots, children, None)
|
null | null | null | What arranges into a hierarchy of nested lists ?
| def getclasstree(classes, unique=0):
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if (not (parent in children)):
children[parent] = []
if (c not in children[parent]):
children[parent].append(c)
if (unique and (parent in classes)):
break
elif (c not in roots):
roots.append(c)
for parent in children:
if (parent not in classes):
roots.append(parent)
return walktree(roots, children, None)
| null | null | null | the given list of classes
| codeqa | def getclasstree classes unique 0 children {}roots []for c in classes if c bases for parent in c bases if not parent in children children[parent] []if c not in children[parent] children[parent] append c if unique and parent in classes breakelif c not in roots roots append c for parent in children if parent not in classes roots append parent return walktree roots children None
| null | null | null | null | Question:
What arranges into a hierarchy of nested lists ?
Code:
def getclasstree(classes, unique=0):
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if (not (parent in children)):
children[parent] = []
if (c not in children[parent]):
children[parent].append(c)
if (unique and (parent in classes)):
break
elif (c not in roots):
roots.append(c)
for parent in children:
if (parent not in classes):
roots.append(parent)
return walktree(roots, children, None)
|
null | null | null | What does the code get ?
| def get_system_date(utc_offset=None):
offset_time = _get_offset_time(utc_offset)
return datetime.strftime(offset_time, '%a %m/%d/%Y')
| null | null | null | the system date
| codeqa | def get system date utc offset None offset time get offset time utc offset return datetime strftime offset time '%a%m/%d/%Y'
| null | null | null | null | Question:
What does the code get ?
Code:
def get_system_date(utc_offset=None):
offset_time = _get_offset_time(utc_offset)
return datetime.strftime(offset_time, '%a %m/%d/%Y')
|
null | null | null | What does the code retrieve ?
| def get_size_info(api, volume):
backing_file = api._root_path.descendant(['unattached', _backing_file_name(volume)])
backing_file.restat()
actual = (backing_file.statinfo.st_blocks * 512)
reported = backing_file.getsize()
return _SizeInfo(actual=actual, reported=reported)
| null | null | null | information about the size of the backing file for the given volume
| codeqa | def get size info api volume backing file api root path descendant ['unattached' backing file name volume ] backing file restat actual backing file statinfo st blocks * 512 reported backing file getsize return Size Info actual actual reported reported
| null | null | null | null | Question:
What does the code retrieve ?
Code:
def get_size_info(api, volume):
backing_file = api._root_path.descendant(['unattached', _backing_file_name(volume)])
backing_file.restat()
actual = (backing_file.statinfo.st_blocks * 512)
reported = backing_file.getsize()
return _SizeInfo(actual=actual, reported=reported)
|
null | null | null | What does the code return ?
| def latest_release_tag():
git_tags = subprocess.check_output(['git', 'tag', '-l'], stderr=subprocess.STDOUT).split()
release_tags = [tag for tag in git_tags if tag.startswith('ckan-')]
release_tags.sort()
if release_tags:
return release_tags[(-1)]
else:
return 'COULD_NOT_DETECT_VERSION_NUMBER'
| null | null | null | the name of the git tag for the latest stable release
| codeqa | def latest release tag git tags subprocess check output ['git' 'tag' '-l'] stderr subprocess STDOUT split release tags [tag for tag in git tags if tag startswith 'ckan-' ]release tags sort if release tags return release tags[ -1 ]else return 'COULD NOT DETECT VERSION NUMBER'
| null | null | null | null | Question:
What does the code return ?
Code:
def latest_release_tag():
git_tags = subprocess.check_output(['git', 'tag', '-l'], stderr=subprocess.STDOUT).split()
release_tags = [tag for tag in git_tags if tag.startswith('ckan-')]
release_tags.sort()
if release_tags:
return release_tags[(-1)]
else:
return 'COULD_NOT_DETECT_VERSION_NUMBER'
|
null | null | null | For what purpose does the code return the string ?
| def format_navigation_links(additional_languages, default_lang, messages, strip_indexes=False):
f = u' {0}: (\n ("{1}/archive.html", "{2[Archive]}"),\n ("{1}/categories/{3}", "{2[Tags]}"),\n ("{1}/rss.xml", "{2[RSS feed]}"),\n ),'
pairs = []
def get_msg(lang):
u'Generate a smaller messages dict with fallback.'
fmsg = {}
for i in (u'Archive', u'Tags', u'RSS feed'):
if messages[lang][i]:
fmsg[i] = messages[lang][i]
else:
fmsg[i] = i
return fmsg
if strip_indexes:
index_html = u''
else:
index_html = u'index.html'
pairs.append(f.format(u'DEFAULT_LANG', u'', get_msg(default_lang), index_html))
for l in additional_languages:
pairs.append(f.format(json.dumps(l, ensure_ascii=False), (u'/' + l), get_msg(l), index_html))
return u'{{\n{0}\n}}'.format(u'\n\n'.join(pairs))
| null | null | null | to configure navigation_links
| codeqa | def format navigation links additional languages default lang messages strip indexes False f u'{ 0 } \n "{ 1 }/archive html" "{ 2 [ Archive]}" \n "{ 1 }/categories/{ 3 }" "{ 2 [ Tags]}" \n "{ 1 }/rss xml" "{ 2 [RS Sfeed]}" \n 'pairs []def get msg lang u' Generateasmallermessagesdictwithfallback 'fmsg {}for i in u' Archive' u' Tags' u'RS Sfeed' if messages[lang][i] fmsg[i] messages[lang][i]else fmsg[i] ireturn fmsgif strip indexes index html u''else index html u'index html'pairs append f format u'DEFAULT LANG' u'' get msg default lang index html for l in additional languages pairs append f format json dumps l ensure ascii False u'/' + l get msg l index html return u'{{\n{ 0 }\n}}' format u'\n\n' join pairs
| null | null | null | null | Question:
For what purpose does the code return the string ?
Code:
def format_navigation_links(additional_languages, default_lang, messages, strip_indexes=False):
f = u' {0}: (\n ("{1}/archive.html", "{2[Archive]}"),\n ("{1}/categories/{3}", "{2[Tags]}"),\n ("{1}/rss.xml", "{2[RSS feed]}"),\n ),'
pairs = []
def get_msg(lang):
u'Generate a smaller messages dict with fallback.'
fmsg = {}
for i in (u'Archive', u'Tags', u'RSS feed'):
if messages[lang][i]:
fmsg[i] = messages[lang][i]
else:
fmsg[i] = i
return fmsg
if strip_indexes:
index_html = u''
else:
index_html = u'index.html'
pairs.append(f.format(u'DEFAULT_LANG', u'', get_msg(default_lang), index_html))
for l in additional_languages:
pairs.append(f.format(json.dumps(l, ensure_ascii=False), (u'/' + l), get_msg(l), index_html))
return u'{{\n{0}\n}}'.format(u'\n\n'.join(pairs))
|
null | null | null | What does the code return to configure navigation_links ?
| def format_navigation_links(additional_languages, default_lang, messages, strip_indexes=False):
f = u' {0}: (\n ("{1}/archive.html", "{2[Archive]}"),\n ("{1}/categories/{3}", "{2[Tags]}"),\n ("{1}/rss.xml", "{2[RSS feed]}"),\n ),'
pairs = []
def get_msg(lang):
u'Generate a smaller messages dict with fallback.'
fmsg = {}
for i in (u'Archive', u'Tags', u'RSS feed'):
if messages[lang][i]:
fmsg[i] = messages[lang][i]
else:
fmsg[i] = i
return fmsg
if strip_indexes:
index_html = u''
else:
index_html = u'index.html'
pairs.append(f.format(u'DEFAULT_LANG', u'', get_msg(default_lang), index_html))
for l in additional_languages:
pairs.append(f.format(json.dumps(l, ensure_ascii=False), (u'/' + l), get_msg(l), index_html))
return u'{{\n{0}\n}}'.format(u'\n\n'.join(pairs))
| null | null | null | the string
| codeqa | def format navigation links additional languages default lang messages strip indexes False f u'{ 0 } \n "{ 1 }/archive html" "{ 2 [ Archive]}" \n "{ 1 }/categories/{ 3 }" "{ 2 [ Tags]}" \n "{ 1 }/rss xml" "{ 2 [RS Sfeed]}" \n 'pairs []def get msg lang u' Generateasmallermessagesdictwithfallback 'fmsg {}for i in u' Archive' u' Tags' u'RS Sfeed' if messages[lang][i] fmsg[i] messages[lang][i]else fmsg[i] ireturn fmsgif strip indexes index html u''else index html u'index html'pairs append f format u'DEFAULT LANG' u'' get msg default lang index html for l in additional languages pairs append f format json dumps l ensure ascii False u'/' + l get msg l index html return u'{{\n{ 0 }\n}}' format u'\n\n' join pairs
| null | null | null | null | Question:
What does the code return to configure navigation_links ?
Code:
def format_navigation_links(additional_languages, default_lang, messages, strip_indexes=False):
f = u' {0}: (\n ("{1}/archive.html", "{2[Archive]}"),\n ("{1}/categories/{3}", "{2[Tags]}"),\n ("{1}/rss.xml", "{2[RSS feed]}"),\n ),'
pairs = []
def get_msg(lang):
u'Generate a smaller messages dict with fallback.'
fmsg = {}
for i in (u'Archive', u'Tags', u'RSS feed'):
if messages[lang][i]:
fmsg[i] = messages[lang][i]
else:
fmsg[i] = i
return fmsg
if strip_indexes:
index_html = u''
else:
index_html = u'index.html'
pairs.append(f.format(u'DEFAULT_LANG', u'', get_msg(default_lang), index_html))
for l in additional_languages:
pairs.append(f.format(json.dumps(l, ensure_ascii=False), (u'/' + l), get_msg(l), index_html))
return u'{{\n{0}\n}}'.format(u'\n\n'.join(pairs))
|
null | null | null | When do the size of an object return code ?
| def sizeof(s):
if hasattr(s, '_size_'):
return s._size_
elif isinstance(s, bytes):
return len(s)
raise ValueError(s)
| null | null | null | when packed
| codeqa | def sizeof s if hasattr s ' size ' return s size elif isinstance s bytes return len s raise Value Error s
| null | null | null | null | Question:
When do the size of an object return code ?
Code:
def sizeof(s):
if hasattr(s, '_size_'):
return s._size_
elif isinstance(s, bytes):
return len(s)
raise ValueError(s)
|
null | null | null | What does the code get ?
| def get_dir_path(sibling):
py_file = __file__.replace('.pyc', '.py')
dir_paths = [os.path.abspath(os.path.dirname(os.path.realpath(py_file))), os.path.abspath(os.path.dirname(py_file))]
for dir_path in dir_paths:
sibling_path = os.path.join(dir_path, sibling)
if os.path.exists(sibling_path):
return dir_path
raise ValueError(('Could not determine directory that contains both, this file and %s.' % sibling))
| null | null | null | a path to the directory of this script
| codeqa | def get dir path sibling py file file replace ' pyc' ' py' dir paths [os path abspath os path dirname os path realpath py file os path abspath os path dirname py file ]for dir path in dir paths sibling path os path join dir path sibling if os path exists sibling path return dir pathraise Value Error ' Couldnotdeterminedirectorythatcontainsboth thisfileand%s ' % sibling
| null | null | null | null | Question:
What does the code get ?
Code:
def get_dir_path(sibling):
py_file = __file__.replace('.pyc', '.py')
dir_paths = [os.path.abspath(os.path.dirname(os.path.realpath(py_file))), os.path.abspath(os.path.dirname(py_file))]
for dir_path in dir_paths:
sibling_path = os.path.join(dir_path, sibling)
if os.path.exists(sibling_path):
return dir_path
raise ValueError(('Could not determine directory that contains both, this file and %s.' % sibling))
|
null | null | null | When should methods be called ?
| def runonce(exc_class=Exception):
def runonce_meth(meth):
@wraps(meth)
def inner_runonce_meth(self, *args):
if (not getattr(self, '_already_executed', False)):
self._already_executed = True
return meth(self, *args)
raise exc_class()
return inner_runonce_meth
return runonce_meth
| null | null | null | only once
| codeqa | def runonce exc class Exception def runonce meth meth @wraps meth def inner runonce meth self *args if not getattr self ' already executed' False self already executed Truereturn meth self *args raise exc class return inner runonce methreturn runonce meth
| null | null | null | null | Question:
When should methods be called ?
Code:
def runonce(exc_class=Exception):
def runonce_meth(meth):
@wraps(meth)
def inner_runonce_meth(self, *args):
if (not getattr(self, '_already_executed', False)):
self._already_executed = True
return meth(self, *args)
raise exc_class()
return inner_runonce_meth
return runonce_meth
|
null | null | null | What does the code run ?
| def call_command_async(cmd, *args, **kwargs):
is_osx = (sys.platform == 'darwin')
in_proc = kwargs.pop('in_proc', (not is_osx))
if in_proc:
return call_command_threaded(cmd, *args, **kwargs)
else:
if hasattr(sys, 'pyrun'):
if (settings.IS_SOURCE and ('kalite_dir' not in kwargs)):
kwargs['kalite_dir'] = settings.SOURCE_DIR
if ('wait' not in kwargs):
kwargs['wait'] = False
return call_outside_command_with_output(cmd, *args, **kwargs)
return call_command_subprocess(cmd, *args, **kwargs)
| null | null | null | a manage
| codeqa | def call command async cmd *args **kwargs is osx sys platform 'darwin' in proc kwargs pop 'in proc' not is osx if in proc return call command threaded cmd *args **kwargs else if hasattr sys 'pyrun' if settings IS SOURCE and 'kalite dir' not in kwargs kwargs['kalite dir'] settings SOURCE DI Rif 'wait' not in kwargs kwargs['wait'] Falsereturn call outside command with output cmd *args **kwargs return call command subprocess cmd *args **kwargs
| null | null | null | null | Question:
What does the code run ?
Code:
def call_command_async(cmd, *args, **kwargs):
is_osx = (sys.platform == 'darwin')
in_proc = kwargs.pop('in_proc', (not is_osx))
if in_proc:
return call_command_threaded(cmd, *args, **kwargs)
else:
if hasattr(sys, 'pyrun'):
if (settings.IS_SOURCE and ('kalite_dir' not in kwargs)):
kwargs['kalite_dir'] = settings.SOURCE_DIR
if ('wait' not in kwargs):
kwargs['wait'] = False
return call_outside_command_with_output(cmd, *args, **kwargs)
return call_command_subprocess(cmd, *args, **kwargs)
|
null | null | null | What does the code receive just after the object is saved ?
| def post_save(sender, instance, created, **kwargs):
if created:
instance.at_first_save()
| null | null | null | a signal
| codeqa | def post save sender instance created **kwargs if created instance at first save
| null | null | null | null | Question:
What does the code receive just after the object is saved ?
Code:
def post_save(sender, instance, created, **kwargs):
if created:
instance.at_first_save()
|
null | null | null | When does the code receive a signal ?
| def post_save(sender, instance, created, **kwargs):
if created:
instance.at_first_save()
| null | null | null | just after the object is saved
| codeqa | def post save sender instance created **kwargs if created instance at first save
| null | null | null | null | Question:
When does the code receive a signal ?
Code:
def post_save(sender, instance, created, **kwargs):
if created:
instance.at_first_save()
|
null | null | null | What does the code return ?
| def localdate(value=None, timezone=None):
return localtime(value, timezone).date()
| null | null | null | the values date
| codeqa | def localdate value None timezone None return localtime value timezone date
| null | null | null | null | Question:
What does the code return ?
Code:
def localdate(value=None, timezone=None):
return localtime(value, timezone).date()
|
null | null | null | How did count read count ?
| def read_plain_float(file_obj, count):
return struct.unpack('<{0}f'.format(count).encode(u'utf-8'), file_obj.read((4 * count)))
| null | null | null | using the plain encoding
| codeqa | def read plain float file obj count return struct unpack '<{ 0 }f' format count encode u'utf- 8 ' file obj read 4 * count
| null | null | null | null | Question:
How did count read count ?
Code:
def read_plain_float(file_obj, count):
return struct.unpack('<{0}f'.format(count).encode(u'utf-8'), file_obj.read((4 * count)))
|
null | null | null | Who is containing them ?
| def compile_nrt_functions(ctx):
(ir_mod, library) = create_nrt_module(ctx)
library.add_ir_module(ir_mod)
library.finalize()
return library
| null | null | null | a library
| codeqa | def compile nrt functions ctx ir mod library create nrt module ctx library add ir module ir mod library finalize return library
| null | null | null | null | Question:
Who is containing them ?
Code:
def compile_nrt_functions(ctx):
(ir_mod, library) = create_nrt_module(ctx)
library.add_ir_module(ir_mod)
library.finalize()
return library
|
null | null | null | What does the code minimize ?
| def minimize_quadratic_1d(a, b, lb, ub, c=0):
t = [lb, ub]
if (a != 0):
extremum = (((-0.5) * b) / a)
if (lb < extremum < ub):
t.append(extremum)
t = np.asarray(t)
y = (((a * (t ** 2)) + (b * t)) + c)
min_index = np.argmin(y)
return (t[min_index], y[min_index])
| null | null | null | a 1-d quadratic function subject to bounds
| codeqa | def minimize quadratic 1d a b lb ub c 0 t [lb ub]if a 0 extremum -0 5 * b / a if lb < extremum < ub t append extremum t np asarray t y a * t ** 2 + b * t + c min index np argmin y return t[min index] y[min index]
| null | null | null | null | Question:
What does the code minimize ?
Code:
def minimize_quadratic_1d(a, b, lb, ub, c=0):
t = [lb, ub]
if (a != 0):
extremum = (((-0.5) * b) / a)
if (lb < extremum < ub):
t.append(extremum)
t = np.asarray(t)
y = (((a * (t ** 2)) + (b * t)) + c)
min_index = np.argmin(y)
return (t[min_index], y[min_index])
|
null | null | null | Where does the code get a virtual interface from the table filtering ?
| def virtual_interface_get_by_address(context, address):
return IMPL.virtual_interface_get_by_address(context, address)
| null | null | null | on address
| codeqa | def virtual interface get by address context address return IMPL virtual interface get by address context address
| null | null | null | null | Question:
Where does the code get a virtual interface from the table filtering ?
Code:
def virtual_interface_get_by_address(context, address):
return IMPL.virtual_interface_get_by_address(context, address)
|
null | null | null | What does the code get from the table filtering on address ?
| def virtual_interface_get_by_address(context, address):
return IMPL.virtual_interface_get_by_address(context, address)
| null | null | null | a virtual interface
| codeqa | def virtual interface get by address context address return IMPL virtual interface get by address context address
| null | null | null | null | Question:
What does the code get from the table filtering on address ?
Code:
def virtual_interface_get_by_address(context, address):
return IMPL.virtual_interface_get_by_address(context, address)
|
null | null | null | What does the code get a virtual interface on address ?
| def virtual_interface_get_by_address(context, address):
return IMPL.virtual_interface_get_by_address(context, address)
| null | null | null | from the table filtering
| codeqa | def virtual interface get by address context address return IMPL virtual interface get by address context address
| null | null | null | null | Question:
What does the code get a virtual interface on address ?
Code:
def virtual_interface_get_by_address(context, address):
return IMPL.virtual_interface_get_by_address(context, address)
|
null | null | null | What did the code set ?
| def libvlc_video_set_spu_delay(p_mi, i_delay):
f = (_Cfunctions.get('libvlc_video_set_spu_delay', None) or _Cfunction('libvlc_video_set_spu_delay', ((1,), (1,)), None, ctypes.c_int, MediaPlayer, ctypes.c_int64))
return f(p_mi, i_delay)
| null | null | null | the subtitle delay
| codeqa | def libvlc video set spu delay p mi i delay f Cfunctions get 'libvlc video set spu delay' None or Cfunction 'libvlc video set spu delay' 1 1 None ctypes c int Media Player ctypes c int 64 return f p mi i delay
| null | null | null | null | Question:
What did the code set ?
Code:
def libvlc_video_set_spu_delay(p_mi, i_delay):
f = (_Cfunctions.get('libvlc_video_set_spu_delay', None) or _Cfunction('libvlc_video_set_spu_delay', ((1,), (1,)), None, ctypes.c_int, MediaPlayer, ctypes.c_int64))
return f(p_mi, i_delay)
|
null | null | null | How do all the keys list ?
| def list_(match):
skey = get_key(__opts__)
return skey.list_status(match)
| null | null | null | under a named status
| codeqa | def list match skey get key opts return skey list status match
| null | null | null | null | Question:
How do all the keys list ?
Code:
def list_(match):
skey = get_key(__opts__)
return skey.list_status(match)
|
null | null | null | How does the code fit a data ?
| def _fit_dipole_fixed(min_dist_to_inner_skull, B_orig, t, guess_rrs, guess_data, fwd_data, whitener, proj_op, fmin_cobyla, ori):
B = np.dot(whitener, B_orig)
B2 = np.dot(B, B)
if (B2 == 0):
warn(('Zero field found for time %s' % t))
return (np.zeros(3), 0, np.zeros(3), 0)
(Q, gof, residual) = _fit_Q(guess_data, whitener, proj_op, B, B2, B_orig, rd=None, ori=ori)
if (ori is None):
amp = np.sqrt(np.dot(Q, Q))
norm = (1.0 if (amp == 0.0) else amp)
ori = (Q / norm)
else:
amp = np.dot(Q, ori)
return (guess_rrs[0], amp, ori, gof, residual)
| null | null | null | using a fixed position
| codeqa | def fit dipole fixed min dist to inner skull B orig t guess rrs guess data fwd data whitener proj op fmin cobyla ori B np dot whitener B orig B2 np dot B B if B2 0 warn ' Zerofieldfoundfortime%s' % t return np zeros 3 0 np zeros 3 0 Q gof residual fit Q guess data whitener proj op B B2 B orig rd None ori ori if ori is None amp np sqrt np dot Q Q norm 1 0 if amp 0 0 else amp ori Q / norm else amp np dot Q ori return guess rrs[ 0 ] amp ori gof residual
| null | null | null | null | Question:
How does the code fit a data ?
Code:
def _fit_dipole_fixed(min_dist_to_inner_skull, B_orig, t, guess_rrs, guess_data, fwd_data, whitener, proj_op, fmin_cobyla, ori):
B = np.dot(whitener, B_orig)
B2 = np.dot(B, B)
if (B2 == 0):
warn(('Zero field found for time %s' % t))
return (np.zeros(3), 0, np.zeros(3), 0)
(Q, gof, residual) = _fit_Q(guess_data, whitener, proj_op, B, B2, B_orig, rd=None, ori=ori)
if (ori is None):
amp = np.sqrt(np.dot(Q, Q))
norm = (1.0 if (amp == 0.0) else amp)
ori = (Q / norm)
else:
amp = np.dot(Q, ori)
return (guess_rrs[0], amp, ori, gof, residual)
|
null | null | null | What does the code fit using a fixed position ?
| def _fit_dipole_fixed(min_dist_to_inner_skull, B_orig, t, guess_rrs, guess_data, fwd_data, whitener, proj_op, fmin_cobyla, ori):
B = np.dot(whitener, B_orig)
B2 = np.dot(B, B)
if (B2 == 0):
warn(('Zero field found for time %s' % t))
return (np.zeros(3), 0, np.zeros(3), 0)
(Q, gof, residual) = _fit_Q(guess_data, whitener, proj_op, B, B2, B_orig, rd=None, ori=ori)
if (ori is None):
amp = np.sqrt(np.dot(Q, Q))
norm = (1.0 if (amp == 0.0) else amp)
ori = (Q / norm)
else:
amp = np.dot(Q, ori)
return (guess_rrs[0], amp, ori, gof, residual)
| null | null | null | a data
| codeqa | def fit dipole fixed min dist to inner skull B orig t guess rrs guess data fwd data whitener proj op fmin cobyla ori B np dot whitener B orig B2 np dot B B if B2 0 warn ' Zerofieldfoundfortime%s' % t return np zeros 3 0 np zeros 3 0 Q gof residual fit Q guess data whitener proj op B B2 B orig rd None ori ori if ori is None amp np sqrt np dot Q Q norm 1 0 if amp 0 0 else amp ori Q / norm else amp np dot Q ori return guess rrs[ 0 ] amp ori gof residual
| null | null | null | null | Question:
What does the code fit using a fixed position ?
Code:
def _fit_dipole_fixed(min_dist_to_inner_skull, B_orig, t, guess_rrs, guess_data, fwd_data, whitener, proj_op, fmin_cobyla, ori):
B = np.dot(whitener, B_orig)
B2 = np.dot(B, B)
if (B2 == 0):
warn(('Zero field found for time %s' % t))
return (np.zeros(3), 0, np.zeros(3), 0)
(Q, gof, residual) = _fit_Q(guess_data, whitener, proj_op, B, B2, B_orig, rd=None, ori=ori)
if (ori is None):
amp = np.sqrt(np.dot(Q, Q))
norm = (1.0 if (amp == 0.0) else amp)
ori = (Q / norm)
else:
amp = np.dot(Q, ori)
return (guess_rrs[0], amp, ori, gof, residual)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.