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 build ?
| def mkAssocResponse(*keys):
args = dict([(key, association_response_values[key]) for key in keys])
return Message.fromOpenIDArgs(args)
| null | null | null | an association response message that contains the specified subset of keys
| codeqa | def mk Assoc Response *keys args dict [ key association response values[key] for key in keys] return Message from Open ID Args args
| null | null | null | null | Question:
What does the code build ?
Code:
def mkAssocResponse(*keys):
args = dict([(key, association_response_values[key]) for key in keys])
return Message.fromOpenIDArgs(args)
|
null | null | null | What do a dict matching keys in dsk2 return ?
| def sync_keys(dsk1, dsk2):
return _sync_keys(dsk1, dsk2, toposort(dsk2))
| null | null | null | to equivalent keys in dsk1
| codeqa | def sync keys dsk 1 dsk 2 return sync keys dsk 1 dsk 2 toposort dsk 2
| null | null | null | null | Question:
What do a dict matching keys in dsk2 return ?
Code:
def sync_keys(dsk1, dsk2):
return _sync_keys(dsk1, dsk2, toposort(dsk2))
|
null | null | null | What returns to equivalent keys in dsk1 ?
| def sync_keys(dsk1, dsk2):
return _sync_keys(dsk1, dsk2, toposort(dsk2))
| null | null | null | a dict matching keys in dsk2
| codeqa | def sync keys dsk 1 dsk 2 return sync keys dsk 1 dsk 2 toposort dsk 2
| null | null | null | null | Question:
What returns to equivalent keys in dsk1 ?
Code:
def sync_keys(dsk1, dsk2):
return _sync_keys(dsk1, dsk2, toposort(dsk2))
|
null | null | null | What does the code get ?
| def metadef_resource_type_get(context, resource_type_name, session=None):
session = (session or get_session())
return metadef_resource_type_api.get(context, resource_type_name, session)
| null | null | null | a resource_type
| codeqa | def metadef resource type get context resource type name session None session session or get session return metadef resource type api get context resource type name session
| null | null | null | null | Question:
What does the code get ?
Code:
def metadef_resource_type_get(context, resource_type_name, session=None):
session = (session or get_session())
return metadef_resource_type_api.get(context, resource_type_name, session)
|
null | null | null | What does the appropriate helper class handle ?
| def _prepare_argument(ctxt, bld, inp, tyinp, where='input operand'):
if isinstance(tyinp, types.ArrayCompatible):
ary = ctxt.make_array(tyinp)(ctxt, bld, inp)
shape = cgutils.unpack_tuple(bld, ary.shape, tyinp.ndim)
strides = cgutils.unpack_tuple(bld, ary.strides, tyinp.ndim)
return _ArrayHelper(ctxt, bld, shape, strides, ary.data, tyinp.layout, tyinp.dtype, tyinp.ndim, inp)
elif (tyinp in (types.number_domain | set([types.boolean]))):
return _ScalarHelper(ctxt, bld, inp, tyinp)
else:
raise NotImplementedError('unsupported type for {0}: {1}'.format(where, str(tyinp)))
| null | null | null | the argument
| codeqa | def prepare argument ctxt bld inp tyinp where 'inputoperand' if isinstance tyinp types Array Compatible ary ctxt make array tyinp ctxt bld inp shape cgutils unpack tuple bld ary shape tyinp ndim strides cgutils unpack tuple bld ary strides tyinp ndim return Array Helper ctxt bld shape strides ary data tyinp layout tyinp dtype tyinp ndim inp elif tyinp in types number domain set [types boolean] return Scalar Helper ctxt bld inp tyinp else raise Not Implemented Error 'unsupportedtypefor{ 0 } {1 }' format where str tyinp
| null | null | null | null | Question:
What does the appropriate helper class handle ?
Code:
def _prepare_argument(ctxt, bld, inp, tyinp, where='input operand'):
if isinstance(tyinp, types.ArrayCompatible):
ary = ctxt.make_array(tyinp)(ctxt, bld, inp)
shape = cgutils.unpack_tuple(bld, ary.shape, tyinp.ndim)
strides = cgutils.unpack_tuple(bld, ary.strides, tyinp.ndim)
return _ArrayHelper(ctxt, bld, shape, strides, ary.data, tyinp.layout, tyinp.dtype, tyinp.ndim, inp)
elif (tyinp in (types.number_domain | set([types.boolean]))):
return _ScalarHelper(ctxt, bld, inp, tyinp)
else:
raise NotImplementedError('unsupported type for {0}: {1}'.format(where, str(tyinp)))
|
null | null | null | What handles the argument ?
| def _prepare_argument(ctxt, bld, inp, tyinp, where='input operand'):
if isinstance(tyinp, types.ArrayCompatible):
ary = ctxt.make_array(tyinp)(ctxt, bld, inp)
shape = cgutils.unpack_tuple(bld, ary.shape, tyinp.ndim)
strides = cgutils.unpack_tuple(bld, ary.strides, tyinp.ndim)
return _ArrayHelper(ctxt, bld, shape, strides, ary.data, tyinp.layout, tyinp.dtype, tyinp.ndim, inp)
elif (tyinp in (types.number_domain | set([types.boolean]))):
return _ScalarHelper(ctxt, bld, inp, tyinp)
else:
raise NotImplementedError('unsupported type for {0}: {1}'.format(where, str(tyinp)))
| null | null | null | the appropriate helper class
| codeqa | def prepare argument ctxt bld inp tyinp where 'inputoperand' if isinstance tyinp types Array Compatible ary ctxt make array tyinp ctxt bld inp shape cgutils unpack tuple bld ary shape tyinp ndim strides cgutils unpack tuple bld ary strides tyinp ndim return Array Helper ctxt bld shape strides ary data tyinp layout tyinp dtype tyinp ndim inp elif tyinp in types number domain set [types boolean] return Scalar Helper ctxt bld inp tyinp else raise Not Implemented Error 'unsupportedtypefor{ 0 } {1 }' format where str tyinp
| null | null | null | null | Question:
What handles the argument ?
Code:
def _prepare_argument(ctxt, bld, inp, tyinp, where='input operand'):
if isinstance(tyinp, types.ArrayCompatible):
ary = ctxt.make_array(tyinp)(ctxt, bld, inp)
shape = cgutils.unpack_tuple(bld, ary.shape, tyinp.ndim)
strides = cgutils.unpack_tuple(bld, ary.strides, tyinp.ndim)
return _ArrayHelper(ctxt, bld, shape, strides, ary.data, tyinp.layout, tyinp.dtype, tyinp.ndim, inp)
elif (tyinp in (types.number_domain | set([types.boolean]))):
return _ScalarHelper(ctxt, bld, inp, tyinp)
else:
raise NotImplementedError('unsupported type for {0}: {1}'.format(where, str(tyinp)))
|
null | null | null | Does a string contain leading whitespace or return characters ?
| def check_header_validity(header):
(name, value) = header
if isinstance(value, bytes):
pat = _CLEAN_HEADER_REGEX_BYTE
else:
pat = _CLEAN_HEADER_REGEX_STR
try:
if (not pat.match(value)):
raise InvalidHeader(('Invalid return character or leading space in header: %s' % name))
except TypeError:
raise InvalidHeader(('Header value %s must be of type str or bytes, not %s' % (value, type(value))))
| null | null | null | No
| codeqa | def check header validity header name value headerif isinstance value bytes pat CLEAN HEADER REGEX BYT Eelse pat CLEAN HEADER REGEX ST Rtry if not pat match value raise Invalid Header ' Invalidreturncharacterorleadingspaceinheader %s' % name except Type Error raise Invalid Header ' Headervalue%smustbeoftypestrorbytes not%s' % value type value
| null | null | null | null | Question:
Does a string contain leading whitespace or return characters ?
Code:
def check_header_validity(header):
(name, value) = header
if isinstance(value, bytes):
pat = _CLEAN_HEADER_REGEX_BYTE
else:
pat = _CLEAN_HEADER_REGEX_STR
try:
if (not pat.match(value)):
raise InvalidHeader(('Invalid return character or leading space in header: %s' % name))
except TypeError:
raise InvalidHeader(('Header value %s must be of type str or bytes, not %s' % (value, type(value))))
|
null | null | null | What does the code get from salt ?
| def _get_options(ret=None):
attrs = {'database': 'database', 'timeout': 'timeout'}
_options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__)
return _options
| null | null | null | the sqlite3 options
| codeqa | def get options ret None attrs {'database' 'database' 'timeout' 'timeout'} options salt returners get returner options virtualname ret attrs salt salt opts opts return options
| null | null | null | null | Question:
What does the code get from salt ?
Code:
def _get_options(ret=None):
attrs = {'database': 'database', 'timeout': 'timeout'}
_options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__)
return _options
|
null | null | null | What centered at node n within a given radius ?
| def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
if undirected:
if (distance is not None):
(sp, _) = nx.single_source_dijkstra(G.to_undirected(), n, cutoff=radius, weight=distance)
else:
sp = dict(nx.single_source_shortest_path_length(G.to_undirected(), n, cutoff=radius))
elif (distance is not None):
(sp, _) = nx.single_source_dijkstra(G, n, cutoff=radius, weight=distance)
else:
sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))
H = G.subgraph(sp).copy()
if (not center):
H.remove_node(n)
return H
| null | null | null | neighbors
| codeqa | def ego graph G n radius 1 center True undirected False distance None if undirected if distance is not None sp nx single source dijkstra G to undirected n cutoff radius weight distance else sp dict nx single source shortest path length G to undirected n cutoff radius elif distance is not None sp nx single source dijkstra G n cutoff radius weight distance else sp dict nx single source shortest path length G n cutoff radius H G subgraph sp copy if not center H remove node n return H
| null | null | null | null | Question:
What centered at node n within a given radius ?
Code:
def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
if undirected:
if (distance is not None):
(sp, _) = nx.single_source_dijkstra(G.to_undirected(), n, cutoff=radius, weight=distance)
else:
sp = dict(nx.single_source_shortest_path_length(G.to_undirected(), n, cutoff=radius))
elif (distance is not None):
(sp, _) = nx.single_source_dijkstra(G, n, cutoff=radius, weight=distance)
else:
sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))
H = G.subgraph(sp).copy()
if (not center):
H.remove_node(n)
return H
|
null | null | null | What is containing step and history interpretations possibly ?
| def _pick_counters(log_interpretation):
for log_type in ('step', 'history'):
counters = log_interpretation.get(log_type, {}).get('counters')
if counters:
return counters
else:
return {}
| null | null | null | a dictionary
| codeqa | def pick counters log interpretation for log type in 'step' 'history' counters log interpretation get log type {} get 'counters' if counters return counterselse return {}
| null | null | null | null | Question:
What is containing step and history interpretations possibly ?
Code:
def _pick_counters(log_interpretation):
for log_type in ('step', 'history'):
counters = log_interpretation.get(log_type, {}).get('counters')
if counters:
return counters
else:
return {}
|
null | null | null | How do the result match ?
| def assert_regex(result, expected, msg=''):
assert re.search(expected, result), ('%s%r not found in %r' % (_fmt_msg(msg), expected, result))
| null | null | null | expected
| codeqa | def assert regex result expected msg '' assert re search expected result '%s%rnotfoundin%r' % fmt msg msg expected result
| null | null | null | null | Question:
How do the result match ?
Code:
def assert_regex(result, expected, msg=''):
assert re.search(expected, result), ('%s%r not found in %r' % (_fmt_msg(msg), expected, result))
|
null | null | null | How does tabs add if changes to the course require them ?
| def _refresh_course_tabs(request, course_module):
def update_tab(tabs, tab_type, tab_enabled):
'\n Adds or removes a course tab based upon whether it is enabled.\n '
tab_panel = {'type': tab_type.type}
has_tab = (tab_panel in tabs)
if (tab_enabled and (not has_tab)):
tabs.append(CourseTab.from_json(tab_panel))
elif ((not tab_enabled) and has_tab):
tabs.remove(tab_panel)
course_tabs = copy.copy(course_module.tabs)
for tab_type in CourseTabPluginManager.get_tab_types():
if ((not tab_type.is_dynamic) and tab_type.is_default):
tab_enabled = tab_type.is_enabled(course_module, user=request.user)
update_tab(course_tabs, tab_type, tab_enabled)
CourseTabList.validate_tabs(course_tabs)
if (course_tabs != course_module.tabs):
course_module.tabs = course_tabs
| null | null | null | automatically
| codeqa | def refresh course tabs request course module def update tab tabs tab type tab enabled '\n Addsorremovesacoursetabbaseduponwhetheritisenabled \n'tab panel {'type' tab type type}has tab tab panel in tabs if tab enabled and not has tab tabs append Course Tab from json tab panel elif not tab enabled and has tab tabs remove tab panel course tabs copy copy course module tabs for tab type in Course Tab Plugin Manager get tab types if not tab type is dynamic and tab type is default tab enabled tab type is enabled course module user request user update tab course tabs tab type tab enabled Course Tab List validate tabs course tabs if course tabs course module tabs course module tabs course tabs
| null | null | null | null | Question:
How does tabs add if changes to the course require them ?
Code:
def _refresh_course_tabs(request, course_module):
def update_tab(tabs, tab_type, tab_enabled):
'\n Adds or removes a course tab based upon whether it is enabled.\n '
tab_panel = {'type': tab_type.type}
has_tab = (tab_panel in tabs)
if (tab_enabled and (not has_tab)):
tabs.append(CourseTab.from_json(tab_panel))
elif ((not tab_enabled) and has_tab):
tabs.remove(tab_panel)
course_tabs = copy.copy(course_module.tabs)
for tab_type in CourseTabPluginManager.get_tab_types():
if ((not tab_type.is_dynamic) and tab_type.is_default):
tab_enabled = tab_type.is_enabled(course_module, user=request.user)
update_tab(course_tabs, tab_type, tab_enabled)
CourseTabList.validate_tabs(course_tabs)
if (course_tabs != course_module.tabs):
course_module.tabs = course_tabs
|
null | null | null | Who requires them ?
| def _refresh_course_tabs(request, course_module):
def update_tab(tabs, tab_type, tab_enabled):
'\n Adds or removes a course tab based upon whether it is enabled.\n '
tab_panel = {'type': tab_type.type}
has_tab = (tab_panel in tabs)
if (tab_enabled and (not has_tab)):
tabs.append(CourseTab.from_json(tab_panel))
elif ((not tab_enabled) and has_tab):
tabs.remove(tab_panel)
course_tabs = copy.copy(course_module.tabs)
for tab_type in CourseTabPluginManager.get_tab_types():
if ((not tab_type.is_dynamic) and tab_type.is_default):
tab_enabled = tab_type.is_enabled(course_module, user=request.user)
update_tab(course_tabs, tab_type, tab_enabled)
CourseTabList.validate_tabs(course_tabs)
if (course_tabs != course_module.tabs):
course_module.tabs = course_tabs
| null | null | null | changes to the course
| codeqa | def refresh course tabs request course module def update tab tabs tab type tab enabled '\n Addsorremovesacoursetabbaseduponwhetheritisenabled \n'tab panel {'type' tab type type}has tab tab panel in tabs if tab enabled and not has tab tabs append Course Tab from json tab panel elif not tab enabled and has tab tabs remove tab panel course tabs copy copy course module tabs for tab type in Course Tab Plugin Manager get tab types if not tab type is dynamic and tab type is default tab enabled tab type is enabled course module user request user update tab course tabs tab type tab enabled Course Tab List validate tabs course tabs if course tabs course module tabs course module tabs course tabs
| null | null | null | null | Question:
Who requires them ?
Code:
def _refresh_course_tabs(request, course_module):
def update_tab(tabs, tab_type, tab_enabled):
'\n Adds or removes a course tab based upon whether it is enabled.\n '
tab_panel = {'type': tab_type.type}
has_tab = (tab_panel in tabs)
if (tab_enabled and (not has_tab)):
tabs.append(CourseTab.from_json(tab_panel))
elif ((not tab_enabled) and has_tab):
tabs.remove(tab_panel)
course_tabs = copy.copy(course_module.tabs)
for tab_type in CourseTabPluginManager.get_tab_types():
if ((not tab_type.is_dynamic) and tab_type.is_default):
tab_enabled = tab_type.is_enabled(course_module, user=request.user)
update_tab(course_tabs, tab_type, tab_enabled)
CourseTabList.validate_tabs(course_tabs)
if (course_tabs != course_module.tabs):
course_module.tabs = course_tabs
|
null | null | null | When is this endpoint active ?
| @requires_auth('resource')
def schema_item_endpoint(resource):
resource_config = app.config['DOMAIN'].get(resource)
if ((not resource_config) or (resource_config.get('internal_resource') is True)):
return abort(404)
return send_response(None, (resource_config['schema'],))
| null | null | null | when schema_endpoint ! = none
| codeqa | @requires auth 'resource' def schema item endpoint resource resource config app config['DOMAIN'] get resource if not resource config or resource config get 'internal resource' is True return abort 404 return send response None resource config['schema']
| null | null | null | null | Question:
When is this endpoint active ?
Code:
@requires_auth('resource')
def schema_item_endpoint(resource):
resource_config = app.config['DOMAIN'].get(resource)
if ((not resource_config) or (resource_config.get('internal_resource') is True)):
return abort(404)
return send_response(None, (resource_config['schema'],))
|
null | null | null | What does the code perform ?
| def teardown_test_environment():
Template._render = Template.original_render
del Template.original_render
settings.EMAIL_BACKEND = mail.original_email_backend
del mail.original_email_backend
settings.ALLOWED_HOSTS = settings._original_allowed_hosts
del settings._original_allowed_hosts
del mail.outbox
| null | null | null | any global post - test teardown
| codeqa | def teardown test environment Template render Template original renderdel Template original rendersettings EMAIL BACKEND mail original email backenddel mail original email backendsettings ALLOWED HOSTS settings original allowed hostsdel settings original allowed hostsdel mail outbox
| null | null | null | null | Question:
What does the code perform ?
Code:
def teardown_test_environment():
Template._render = Template.original_render
del Template.original_render
settings.EMAIL_BACKEND = mail.original_email_backend
del mail.original_email_backend
settings.ALLOWED_HOSTS = settings._original_allowed_hosts
del settings._original_allowed_hosts
del mail.outbox
|
null | null | null | What do we want ?
| @pytest.fixture(scope='module')
def static_file_path(static_file_directory):
return os.path.join(static_file_directory, 'test.file')
| null | null | null | to serve
| codeqa | @pytest fixture scope 'module' def static file path static file directory return os path join static file directory 'test file'
| null | null | null | null | Question:
What do we want ?
Code:
@pytest.fixture(scope='module')
def static_file_path(static_file_directory):
return os.path.join(static_file_directory, 'test.file')
|
null | null | null | What does the code provide ?
| def port_usage(port):
global PORT_USES
if (PORT_USES is None):
config = conf.Config()
config_path = os.path.join(os.path.dirname(__file__), 'ports.cfg')
try:
config.load(config_path)
port_uses = {}
for (key, value) in config.get('port', {}).items():
if key.isdigit():
port_uses[int(key)] = value
elif ('-' in key):
(min_port, max_port) = key.split('-', 1)
for port_entry in range(int(min_port), (int(max_port) + 1)):
port_uses[port_entry] = value
else:
raise ValueError(("'%s' is an invalid key" % key))
PORT_USES = port_uses
except Exception as exc:
log.warn(("BUG: stem failed to load its internal port descriptions from '%s': %s" % (config_path, exc)))
if (not PORT_USES):
return None
if (isinstance(port, str) and port.isdigit()):
port = int(port)
return PORT_USES.get(port)
| null | null | null | the common use of a given port
| codeqa | def port usage port global PORT USE Sif PORT USES is None config conf Config config path os path join os path dirname file 'ports cfg' try config load config path port uses {}for key value in config get 'port' {} items if key isdigit port uses[int key ] valueelif '-' in key min port max port key split '-' 1 for port entry in range int min port int max port + 1 port uses[port entry] valueelse raise Value Error "'%s'isaninvalidkey" % key PORT USES port usesexcept Exception as exc log warn "BUG stemfailedtoloaditsinternalportdescriptionsfrom'%s' %s" % config path exc if not PORT USES return Noneif isinstance port str and port isdigit port int port return PORT USES get port
| null | null | null | null | Question:
What does the code provide ?
Code:
def port_usage(port):
global PORT_USES
if (PORT_USES is None):
config = conf.Config()
config_path = os.path.join(os.path.dirname(__file__), 'ports.cfg')
try:
config.load(config_path)
port_uses = {}
for (key, value) in config.get('port', {}).items():
if key.isdigit():
port_uses[int(key)] = value
elif ('-' in key):
(min_port, max_port) = key.split('-', 1)
for port_entry in range(int(min_port), (int(max_port) + 1)):
port_uses[port_entry] = value
else:
raise ValueError(("'%s' is an invalid key" % key))
PORT_USES = port_uses
except Exception as exc:
log.warn(("BUG: stem failed to load its internal port descriptions from '%s': %s" % (config_path, exc)))
if (not PORT_USES):
return None
if (isinstance(port, str) and port.isdigit()):
port = int(port)
return PORT_USES.get(port)
|
null | null | null | What is describing specific volume_type ?
| @require_context
def volume_type_get_by_name(context, name, session=None):
result = model_query(context, models.VolumeTypes, session=session).options(joinedload('extra_specs')).filter_by(name=name).first()
if (not result):
raise exception.VolumeTypeNotFoundByName(volume_type_name=name)
else:
return _dict_with_extra_specs(result)
| null | null | null | a dict
| codeqa | @require contextdef volume type get by name context name session None result model query context models Volume Types session session options joinedload 'extra specs' filter by name name first if not result raise exception Volume Type Not Found By Name volume type name name else return dict with extra specs result
| null | null | null | null | Question:
What is describing specific volume_type ?
Code:
@require_context
def volume_type_get_by_name(context, name, session=None):
result = model_query(context, models.VolumeTypes, session=session).options(joinedload('extra_specs')).filter_by(name=name).first()
if (not result):
raise exception.VolumeTypeNotFoundByName(volume_type_name=name)
else:
return _dict_with_extra_specs(result)
|
null | null | null | What represents the given comment prefix ?
| def _CreateCommentsFromPrefix(comment_prefix, comment_lineno, comment_column, standalone=False):
comments = []
lines = comment_prefix.split('\n')
index = 0
while (index < len(lines)):
comment_block = []
while ((index < len(lines)) and lines[index].lstrip().startswith('#')):
comment_block.append(lines[index])
index += 1
if comment_block:
new_lineno = ((comment_lineno + index) - 1)
comment_block[0] = comment_block[0].lstrip()
comment_block[(-1)] = comment_block[(-1)].rstrip('\n')
comment_leaf = pytree.Leaf(type=token.COMMENT, value='\n'.join(comment_block), context=('', (new_lineno, comment_column)))
comment_node = (comment_leaf if (not standalone) else pytree.Node(pygram.python_symbols.simple_stmt, [comment_leaf]))
comments.append(comment_node)
while ((index < len(lines)) and (not lines[index].lstrip())):
index += 1
return comments
| null | null | null | pytree nodes
| codeqa | def Create Comments From Prefix comment prefix comment lineno comment column standalone False comments []lines comment prefix split '\n' index 0while index < len lines comment block []while index < len lines and lines[index] lstrip startswith '#' comment block append lines[index] index + 1if comment block new lineno comment lineno + index - 1 comment block[ 0 ] comment block[ 0 ] lstrip comment block[ -1 ] comment block[ -1 ] rstrip '\n' comment leaf pytree Leaf type token COMMENT value '\n' join comment block context '' new lineno comment column comment node comment leaf if not standalone else pytree Node pygram python symbols simple stmt [comment leaf] comments append comment node while index < len lines and not lines[index] lstrip index + 1return comments
| null | null | null | null | Question:
What represents the given comment prefix ?
Code:
def _CreateCommentsFromPrefix(comment_prefix, comment_lineno, comment_column, standalone=False):
comments = []
lines = comment_prefix.split('\n')
index = 0
while (index < len(lines)):
comment_block = []
while ((index < len(lines)) and lines[index].lstrip().startswith('#')):
comment_block.append(lines[index])
index += 1
if comment_block:
new_lineno = ((comment_lineno + index) - 1)
comment_block[0] = comment_block[0].lstrip()
comment_block[(-1)] = comment_block[(-1)].rstrip('\n')
comment_leaf = pytree.Leaf(type=token.COMMENT, value='\n'.join(comment_block), context=('', (new_lineno, comment_column)))
comment_node = (comment_leaf if (not standalone) else pytree.Node(pygram.python_symbols.simple_stmt, [comment_leaf]))
comments.append(comment_node)
while ((index < len(lines)) and (not lines[index].lstrip())):
index += 1
return comments
|
null | null | null | What does the code copy so that internal objects refer to the new annotated object ?
| def _shallow_annotate(element, annotations):
element = element._annotate(annotations)
element._copy_internals()
return element
| null | null | null | its internals
| codeqa | def shallow annotate element annotations element element annotate annotations element copy internals return element
| null | null | null | null | Question:
What does the code copy so that internal objects refer to the new annotated object ?
Code:
def _shallow_annotate(element, annotations):
element = element._annotate(annotations)
element._copy_internals()
return element
|
null | null | null | For what purpose does the code copy its internals ?
| def _shallow_annotate(element, annotations):
element = element._annotate(annotations)
element._copy_internals()
return element
| null | null | null | so that internal objects refer to the new annotated object
| codeqa | def shallow annotate element annotations element element annotate annotations element copy internals return element
| null | null | null | null | Question:
For what purpose does the code copy its internals ?
Code:
def _shallow_annotate(element, annotations):
element = element._annotate(annotations)
element._copy_internals()
return element
|
null | null | null | Where are python source are returns ?
| def list_downloadable_sources(target_dir):
return [os.path.join(target_dir, fname) for fname in os.listdir(target_dir) if fname.endswith('.py')]
| null | null | null | where
| codeqa | def list downloadable sources target dir return [os path join target dir fname for fname in os listdir target dir if fname endswith ' py' ]
| null | null | null | null | Question:
Where are python source are returns ?
Code:
def list_downloadable_sources(target_dir):
return [os.path.join(target_dir, fname) for fname in os.listdir(target_dir) if fname.endswith('.py')]
|
null | null | null | What are returns where ?
| def list_downloadable_sources(target_dir):
return [os.path.join(target_dir, fname) for fname in os.listdir(target_dir) if fname.endswith('.py')]
| null | null | null | python source
| codeqa | def list downloadable sources target dir return [os path join target dir fname for fname in os listdir target dir if fname endswith ' py' ]
| null | null | null | null | Question:
What are returns where ?
Code:
def list_downloadable_sources(target_dir):
return [os.path.join(target_dir, fname) for fname in os.listdir(target_dir) if fname.endswith('.py')]
|
null | null | null | What does the code get ?
| def getOverhangSpan(elementNode):
return getCascadeFloatWithoutSelf((2.0 * getLayerThickness(elementNode)), elementNode, 'overhangSpan')
| null | null | null | the overhang span
| codeqa | def get Overhang Span element Node return get Cascade Float Without Self 2 0 * get Layer Thickness element Node element Node 'overhang Span'
| null | null | null | null | Question:
What does the code get ?
Code:
def getOverhangSpan(elementNode):
return getCascadeFloatWithoutSelf((2.0 * getLayerThickness(elementNode)), elementNode, 'overhangSpan')
|
null | null | null | When did loops fill ?
| def addAlreadyFilledArounds(alreadyFilledArounds, loop, radius):
radius = abs(radius)
alreadyFilledLoop = []
slightlyGreaterThanRadius = (intercircle.globalIntercircleMultiplier * radius)
muchGreaterThanRadius = (2.5 * radius)
centers = intercircle.getCentersFromLoop(loop, slightlyGreaterThanRadius)
for center in centers:
alreadyFilledInset = intercircle.getSimplifiedInsetFromClockwiseLoop(center, radius)
if intercircle.isLargeSameDirection(alreadyFilledInset, center, radius):
alreadyFilledLoop.append(alreadyFilledInset)
if (len(alreadyFilledLoop) > 0):
alreadyFilledArounds.append(alreadyFilledLoop)
| null | null | null | already
| codeqa | def add Already Filled Arounds already Filled Arounds loop radius radius abs radius already Filled Loop []slightly Greater Than Radius intercircle global Intercircle Multiplier * radius much Greater Than Radius 2 5 * radius centers intercircle get Centers From Loop loop slightly Greater Than Radius for center in centers already Filled Inset intercircle get Simplified Inset From Clockwise Loop center radius if intercircle is Large Same Direction already Filled Inset center radius already Filled Loop append already Filled Inset if len already Filled Loop > 0 already Filled Arounds append already Filled Loop
| null | null | null | null | Question:
When did loops fill ?
Code:
def addAlreadyFilledArounds(alreadyFilledArounds, loop, radius):
radius = abs(radius)
alreadyFilledLoop = []
slightlyGreaterThanRadius = (intercircle.globalIntercircleMultiplier * radius)
muchGreaterThanRadius = (2.5 * radius)
centers = intercircle.getCentersFromLoop(loop, slightlyGreaterThanRadius)
for center in centers:
alreadyFilledInset = intercircle.getSimplifiedInsetFromClockwiseLoop(center, radius)
if intercircle.isLargeSameDirection(alreadyFilledInset, center, radius):
alreadyFilledLoop.append(alreadyFilledInset)
if (len(alreadyFilledLoop) > 0):
alreadyFilledArounds.append(alreadyFilledLoop)
|
null | null | null | What does the code extract from an assignment that looks as follows : ?
| def _paths_from_assignment(evaluator, expr_stmt):
for (assignee, operator) in zip(expr_stmt.children[::2], expr_stmt.children[1::2]):
try:
assert (operator in ['=', '+='])
assert (tree.is_node(assignee, 'power', 'atom_expr') and (len(assignee.children) > 1))
c = assignee.children
assert ((c[0].type == 'name') and (c[0].value == 'sys'))
trailer = c[1]
assert ((trailer.children[0] == '.') and (trailer.children[1].value == 'path'))
"\n execution = c[2]\n assert execution.children[0] == '['\n subscript = execution.children[1]\n assert subscript.type == 'subscript'\n assert ':' in subscript.children\n "
except AssertionError:
continue
from jedi.evaluate.iterable import py__iter__
from jedi.evaluate.precedence import is_string
types = evaluator.eval_element(expr_stmt)
for types in py__iter__(evaluator, types, expr_stmt):
for typ in types:
if is_string(typ):
(yield typ.obj)
| null | null | null | the assigned strings
| codeqa | def paths from assignment evaluator expr stmt for assignee operator in zip expr stmt children[ 2] expr stmt children[ 1 2] try assert operator in [' ' '+ '] assert tree is node assignee 'power' 'atom expr' and len assignee children > 1 c assignee childrenassert c[ 0 ] type 'name' and c[ 0 ] value 'sys' trailer c[ 1 ]assert trailer children[ 0 ] ' ' and trailer children[ 1 ] value 'path' "\nexecution c[ 2 ]\nassertexecution children[ 0 ] '['\nsubscript execution children[ 1 ]\nassertsubscript type 'subscript'\nassert' 'insubscript children\n"except Assertion Error continuefrom jedi evaluate iterable import py iter from jedi evaluate precedence import is stringtypes evaluator eval element expr stmt for types in py iter evaluator types expr stmt for typ in types if is string typ yield typ obj
| null | null | null | null | Question:
What does the code extract from an assignment that looks as follows : ?
Code:
def _paths_from_assignment(evaluator, expr_stmt):
for (assignee, operator) in zip(expr_stmt.children[::2], expr_stmt.children[1::2]):
try:
assert (operator in ['=', '+='])
assert (tree.is_node(assignee, 'power', 'atom_expr') and (len(assignee.children) > 1))
c = assignee.children
assert ((c[0].type == 'name') and (c[0].value == 'sys'))
trailer = c[1]
assert ((trailer.children[0] == '.') and (trailer.children[1].value == 'path'))
"\n execution = c[2]\n assert execution.children[0] == '['\n subscript = execution.children[1]\n assert subscript.type == 'subscript'\n assert ':' in subscript.children\n "
except AssertionError:
continue
from jedi.evaluate.iterable import py__iter__
from jedi.evaluate.precedence import is_string
types = evaluator.eval_element(expr_stmt)
for types in py__iter__(evaluator, types, expr_stmt):
for typ in types:
if is_string(typ):
(yield typ.obj)
|
null | null | null | What takes a header value string ?
| def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '):
h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws)
for (s, charset) in decoded_seq:
if ((charset is not None) and (not isinstance(charset, Charset))):
charset = Charset(charset)
h.append(s, charset)
return h
| null | null | null | decode_header
| codeqa | def make header decoded seq maxlinelen None header name None continuation ws '' h Header maxlinelen maxlinelen header name header name continuation ws continuation ws for s charset in decoded seq if charset is not None and not isinstance charset Charset charset Charset charset h append s charset return h
| null | null | null | null | Question:
What takes a header value string ?
Code:
def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '):
h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws)
for (s, charset) in decoded_seq:
if ((charset is not None) and (not isinstance(charset, Charset))):
charset = Charset(charset)
h.append(s, charset)
return h
|
null | null | null | What does the code create as returned by ?
| def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '):
h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws)
for (s, charset) in decoded_seq:
if ((charset is not None) and (not isinstance(charset, Charset))):
charset = Charset(charset)
h.append(s, charset)
return h
| null | null | null | a header from a sequence of pairs
| codeqa | def make header decoded seq maxlinelen None header name None continuation ws '' h Header maxlinelen maxlinelen header name header name continuation ws continuation ws for s charset in decoded seq if charset is not None and not isinstance charset Charset charset Charset charset h append s charset return h
| null | null | null | null | Question:
What does the code create as returned by ?
Code:
def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '):
h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws)
for (s, charset) in decoded_seq:
if ((charset is not None) and (not isinstance(charset, Charset))):
charset = Charset(charset)
h.append(s, charset)
return h
|
null | null | null | What does decode_header take ?
| def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '):
h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws)
for (s, charset) in decoded_seq:
if ((charset is not None) and (not isinstance(charset, Charset))):
charset = Charset(charset)
h.append(s, charset)
return h
| null | null | null | a header value string
| codeqa | def make header decoded seq maxlinelen None header name None continuation ws '' h Header maxlinelen maxlinelen header name header name continuation ws continuation ws for s charset in decoded seq if charset is not None and not isinstance charset Charset charset Charset charset h append s charset return h
| null | null | null | null | Question:
What does decode_header take ?
Code:
def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '):
h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws)
for (s, charset) in decoded_seq:
if ((charset is not None) and (not isinstance(charset, Charset))):
charset = Charset(charset)
h.append(s, charset)
return h
|
null | null | null | How do an object encode ?
| def _dumps(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '), cls=_ActionEncoder)
| null | null | null | using some visually pleasing formatting
| codeqa | def dumps obj return json dumps obj sort keys True indent 4 separators ' ' ' ' cls Action Encoder
| null | null | null | null | Question:
How do an object encode ?
Code:
def _dumps(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '), cls=_ActionEncoder)
|
null | null | null | In which direction does the code generate a unique file - accessible path ?
| def encoded_path(root, identifiers, extension='.enc', depth=3, digest_filenames=True):
ident = '_'.join(identifiers)
global sha1
if (sha1 is None):
from beaker.crypto import sha1
if digest_filenames:
if py3k:
ident = sha1(ident.encode('utf-8')).hexdigest()
else:
ident = sha1(ident).hexdigest()
ident = os.path.basename(ident)
tokens = []
for d in range(1, depth):
tokens.append(ident[0:d])
dir = os.path.join(root, *tokens)
verify_directory(dir)
return os.path.join(dir, (ident + extension))
| null | null | null | from the given list of identifiers starting at the given root directory
| codeqa | def encoded path root identifiers extension ' enc' depth 3 digest filenames True ident ' ' join identifiers global sha 1 if sha 1 is None from beaker crypto import sha 1 if digest filenames if py 3 k ident sha 1 ident encode 'utf- 8 ' hexdigest else ident sha 1 ident hexdigest ident os path basename ident tokens []for d in range 1 depth tokens append ident[ 0 d] dir os path join root *tokens verify directory dir return os path join dir ident + extension
| null | null | null | null | Question:
In which direction does the code generate a unique file - accessible path ?
Code:
def encoded_path(root, identifiers, extension='.enc', depth=3, digest_filenames=True):
ident = '_'.join(identifiers)
global sha1
if (sha1 is None):
from beaker.crypto import sha1
if digest_filenames:
if py3k:
ident = sha1(ident.encode('utf-8')).hexdigest()
else:
ident = sha1(ident).hexdigest()
ident = os.path.basename(ident)
tokens = []
for d in range(1, depth):
tokens.append(ident[0:d])
dir = os.path.join(root, *tokens)
verify_directory(dir)
return os.path.join(dir, (ident + extension))
|
null | null | null | What does the code generate from the given list of identifiers starting at the given root directory ?
| def encoded_path(root, identifiers, extension='.enc', depth=3, digest_filenames=True):
ident = '_'.join(identifiers)
global sha1
if (sha1 is None):
from beaker.crypto import sha1
if digest_filenames:
if py3k:
ident = sha1(ident.encode('utf-8')).hexdigest()
else:
ident = sha1(ident).hexdigest()
ident = os.path.basename(ident)
tokens = []
for d in range(1, depth):
tokens.append(ident[0:d])
dir = os.path.join(root, *tokens)
verify_directory(dir)
return os.path.join(dir, (ident + extension))
| null | null | null | a unique file - accessible path
| codeqa | def encoded path root identifiers extension ' enc' depth 3 digest filenames True ident ' ' join identifiers global sha 1 if sha 1 is None from beaker crypto import sha 1 if digest filenames if py 3 k ident sha 1 ident encode 'utf- 8 ' hexdigest else ident sha 1 ident hexdigest ident os path basename ident tokens []for d in range 1 depth tokens append ident[ 0 d] dir os path join root *tokens verify directory dir return os path join dir ident + extension
| null | null | null | null | Question:
What does the code generate from the given list of identifiers starting at the given root directory ?
Code:
def encoded_path(root, identifiers, extension='.enc', depth=3, digest_filenames=True):
ident = '_'.join(identifiers)
global sha1
if (sha1 is None):
from beaker.crypto import sha1
if digest_filenames:
if py3k:
ident = sha1(ident.encode('utf-8')).hexdigest()
else:
ident = sha1(ident).hexdigest()
ident = os.path.basename(ident)
tokens = []
for d in range(1, depth):
tokens.append(ident[0:d])
dir = os.path.join(root, *tokens)
verify_directory(dir)
return os.path.join(dir, (ident + extension))
|
null | null | null | What does the code get ?
| def classof(A, B):
try:
if (A._class_priority > B._class_priority):
return A.__class__
else:
return B.__class__
except Exception:
pass
try:
import numpy
if isinstance(A, numpy.ndarray):
return B.__class__
if isinstance(B, numpy.ndarray):
return A.__class__
except Exception:
pass
raise TypeError(('Incompatible classes %s, %s' % (A.__class__, B.__class__)))
| null | null | null | the type of the result when combining matrices of different types
| codeqa | def classof A B try if A class priority > B class priority return A class else return B class except Exception passtry import numpyif isinstance A numpy ndarray return B class if isinstance B numpy ndarray return A class except Exception passraise Type Error ' Incompatibleclasses%s %s' % A class B class
| null | null | null | null | Question:
What does the code get ?
Code:
def classof(A, B):
try:
if (A._class_priority > B._class_priority):
return A.__class__
else:
return B.__class__
except Exception:
pass
try:
import numpy
if isinstance(A, numpy.ndarray):
return B.__class__
if isinstance(B, numpy.ndarray):
return A.__class__
except Exception:
pass
raise TypeError(('Incompatible classes %s, %s' % (A.__class__, B.__class__)))
|
null | null | null | How did a file descriptors read ?
| def cooperative_read(fd):
def readfn(*args):
result = fd.read(*args)
sleep(0)
return result
return readfn
| null | null | null | with a partial function which schedules after each read
| codeqa | def cooperative read fd def readfn *args result fd read *args sleep 0 return resultreturn readfn
| null | null | null | null | Question:
How did a file descriptors read ?
Code:
def cooperative_read(fd):
def readfn(*args):
result = fd.read(*args)
sleep(0)
return result
return readfn
|
null | null | null | When does a file descriptors read schedule ?
| def cooperative_read(fd):
def readfn(*args):
result = fd.read(*args)
sleep(0)
return result
return readfn
| null | null | null | after each read
| codeqa | def cooperative read fd def readfn *args result fd read *args sleep 0 return resultreturn readfn
| null | null | null | null | Question:
When does a file descriptors read schedule ?
Code:
def cooperative_read(fd):
def readfn(*args):
result = fd.read(*args)
sleep(0)
return result
return readfn
|
null | null | null | For what purpose do the certificate file family symlinks use the information in the config file ?
| def update_symlinks(config, unused_plugins):
cert_manager.update_live_symlinks(config)
| null | null | null | to make symlinks point to the correct archive directory
| codeqa | def update symlinks config unused plugins cert manager update live symlinks config
| null | null | null | null | Question:
For what purpose do the certificate file family symlinks use the information in the config file ?
Code:
def update_symlinks(config, unused_plugins):
cert_manager.update_live_symlinks(config)
|
null | null | null | What use the information in the config file to make symlinks point to the correct archive directory ?
| def update_symlinks(config, unused_plugins):
cert_manager.update_live_symlinks(config)
| null | null | null | the certificate file family symlinks
| codeqa | def update symlinks config unused plugins cert manager update live symlinks config
| null | null | null | null | Question:
What use the information in the config file to make symlinks point to the correct archive directory ?
Code:
def update_symlinks(config, unused_plugins):
cert_manager.update_live_symlinks(config)
|
null | null | null | What makes symlinks point to the correct archive directory ?
| def update_symlinks(config, unused_plugins):
cert_manager.update_live_symlinks(config)
| null | null | null | the certificate file family symlinks
| codeqa | def update symlinks config unused plugins cert manager update live symlinks config
| null | null | null | null | Question:
What makes symlinks point to the correct archive directory ?
Code:
def update_symlinks(config, unused_plugins):
cert_manager.update_live_symlinks(config)
|
null | null | null | What does the code create ?
| @click.command()
@click.option('--name', help='Full name', prompt=True)
@click.option('--email', help='A valid email address', prompt=True)
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True)
def cli(name, email, password):
create_user(name, email, password, 'admin')
| null | null | null | a user with administrator permissions
| codeqa | @click command @click option '--name' help ' Fullname' prompt True @click option '--email' help ' Avalidemailaddress' prompt True @click option '--password' prompt True hide input True confirmation prompt True def cli name email password create user name email password 'admin'
| null | null | null | null | Question:
What does the code create ?
Code:
@click.command()
@click.option('--name', help='Full name', prompt=True)
@click.option('--email', help='A valid email address', prompt=True)
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True)
def cli(name, email, password):
create_user(name, email, password, 'admin')
|
null | null | null | When has the current suggestion been accepted ?
| def _is_suggestion_handled(thread_id, exploration_id):
thread = feedback_models.FeedbackThreadModel.get_by_exp_and_thread_id(exploration_id, thread_id)
return (thread.status in [feedback_models.STATUS_CHOICES_FIXED, feedback_models.STATUS_CHOICES_IGNORED])
| null | null | null | already
| codeqa | def is suggestion handled thread id exploration id thread feedback models Feedback Thread Model get by exp and thread id exploration id thread id return thread status in [feedback models STATUS CHOICES FIXED feedback models STATUS CHOICES IGNORED]
| null | null | null | null | Question:
When has the current suggestion been accepted ?
Code:
def _is_suggestion_handled(thread_id, exploration_id):
thread = feedback_models.FeedbackThreadModel.get_by_exp_and_thread_id(exploration_id, thread_id)
return (thread.status in [feedback_models.STATUS_CHOICES_FIXED, feedback_models.STATUS_CHOICES_IGNORED])
|
null | null | null | When did the current suggestion reject ?
| def _is_suggestion_handled(thread_id, exploration_id):
thread = feedback_models.FeedbackThreadModel.get_by_exp_and_thread_id(exploration_id, thread_id)
return (thread.status in [feedback_models.STATUS_CHOICES_FIXED, feedback_models.STATUS_CHOICES_IGNORED])
| null | null | null | already
| codeqa | def is suggestion handled thread id exploration id thread feedback models Feedback Thread Model get by exp and thread id exploration id thread id return thread status in [feedback models STATUS CHOICES FIXED feedback models STATUS CHOICES IGNORED]
| null | null | null | null | Question:
When did the current suggestion reject ?
Code:
def _is_suggestion_handled(thread_id, exploration_id):
thread = feedback_models.FeedbackThreadModel.get_by_exp_and_thread_id(exploration_id, thread_id)
return (thread.status in [feedback_models.STATUS_CHOICES_FIXED, feedback_models.STATUS_CHOICES_IGNORED])
|
null | null | null | What does the code calculate to use for temporary files ?
| def _get_default_tempdir():
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
for dir in dirlist:
if (dir != _os.curdir):
dir = _os.path.abspath(dir)
for seq in range(100):
name = next(namer)
filename = _os.path.join(dir, name)
try:
fd = _os.open(filename, _bin_openflags, 384)
try:
try:
with _io.open(fd, 'wb', closefd=False) as fp:
fp.write('blat')
finally:
_os.close(fd)
finally:
_os.unlink(filename)
return dir
except FileExistsError:
pass
except PermissionError:
if ((_os.name == 'nt') and _os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
continue
break
except OSError:
break
raise FileNotFoundError(_errno.ENOENT, ('No usable temporary directory found in %s' % dirlist))
| null | null | null | the default directory
| codeqa | def get default tempdir namer Random Name Sequence dirlist candidate tempdir list for dir in dirlist if dir os curdir dir os path abspath dir for seq in range 100 name next namer filename os path join dir name try fd os open filename bin openflags 384 try try with io open fd 'wb' closefd False as fp fp write 'blat' finally os close fd finally os unlink filename return direxcept File Exists Error passexcept Permission Error if os name 'nt' and os path isdir dir and os access dir os W OK continuebreakexcept OS Error breakraise File Not Found Error errno ENOENT ' Nousabletemporarydirectoryfoundin%s' % dirlist
| null | null | null | null | Question:
What does the code calculate to use for temporary files ?
Code:
def _get_default_tempdir():
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
for dir in dirlist:
if (dir != _os.curdir):
dir = _os.path.abspath(dir)
for seq in range(100):
name = next(namer)
filename = _os.path.join(dir, name)
try:
fd = _os.open(filename, _bin_openflags, 384)
try:
try:
with _io.open(fd, 'wb', closefd=False) as fp:
fp.write('blat')
finally:
_os.close(fd)
finally:
_os.unlink(filename)
return dir
except FileExistsError:
pass
except PermissionError:
if ((_os.name == 'nt') and _os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
continue
break
except OSError:
break
raise FileNotFoundError(_errno.ENOENT, ('No usable temporary directory found in %s' % dirlist))
|
null | null | null | What does the code calculate the default directory ?
| def _get_default_tempdir():
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
for dir in dirlist:
if (dir != _os.curdir):
dir = _os.path.abspath(dir)
for seq in range(100):
name = next(namer)
filename = _os.path.join(dir, name)
try:
fd = _os.open(filename, _bin_openflags, 384)
try:
try:
with _io.open(fd, 'wb', closefd=False) as fp:
fp.write('blat')
finally:
_os.close(fd)
finally:
_os.unlink(filename)
return dir
except FileExistsError:
pass
except PermissionError:
if ((_os.name == 'nt') and _os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
continue
break
except OSError:
break
raise FileNotFoundError(_errno.ENOENT, ('No usable temporary directory found in %s' % dirlist))
| null | null | null | to use for temporary files
| codeqa | def get default tempdir namer Random Name Sequence dirlist candidate tempdir list for dir in dirlist if dir os curdir dir os path abspath dir for seq in range 100 name next namer filename os path join dir name try fd os open filename bin openflags 384 try try with io open fd 'wb' closefd False as fp fp write 'blat' finally os close fd finally os unlink filename return direxcept File Exists Error passexcept Permission Error if os name 'nt' and os path isdir dir and os access dir os W OK continuebreakexcept OS Error breakraise File Not Found Error errno ENOENT ' Nousabletemporarydirectoryfoundin%s' % dirlist
| null | null | null | null | Question:
What does the code calculate the default directory ?
Code:
def _get_default_tempdir():
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
for dir in dirlist:
if (dir != _os.curdir):
dir = _os.path.abspath(dir)
for seq in range(100):
name = next(namer)
filename = _os.path.join(dir, name)
try:
fd = _os.open(filename, _bin_openflags, 384)
try:
try:
with _io.open(fd, 'wb', closefd=False) as fp:
fp.write('blat')
finally:
_os.close(fd)
finally:
_os.unlink(filename)
return dir
except FileExistsError:
pass
except PermissionError:
if ((_os.name == 'nt') and _os.path.isdir(dir) and _os.access(dir, _os.W_OK)):
continue
break
except OSError:
break
raise FileNotFoundError(_errno.ENOENT, ('No usable temporary directory found in %s' % dirlist))
|
null | null | null | What does the code start for an instance ?
| def action_start(context, values):
return IMPL.action_start(context, values)
| null | null | null | an action
| codeqa | def action start context values return IMPL action start context values
| null | null | null | null | Question:
What does the code start for an instance ?
Code:
def action_start(context, values):
return IMPL.action_start(context, values)
|
null | null | null | For what purpose does the code start an action ?
| def action_start(context, values):
return IMPL.action_start(context, values)
| null | null | null | for an instance
| codeqa | def action start context values return IMPL action start context values
| null | null | null | null | Question:
For what purpose does the code start an action ?
Code:
def action_start(context, values):
return IMPL.action_start(context, values)
|
null | null | null | What does the code get ?
| def getAwayPoints(points, radius):
awayPoints = []
oneOverOverlapDistance = (1000.0 / radius)
pixelDictionary = {}
for point in points:
x = int((point.real * oneOverOverlapDistance))
y = int((point.imag * oneOverOverlapDistance))
if (not getSquareIsOccupied(pixelDictionary, x, y)):
awayPoints.append(point)
pixelDictionary[(x, y)] = None
return awayPoints
| null | null | null | a path with only the points that are far enough away from each other
| codeqa | def get Away Points points radius away Points []one Over Overlap Distance 1000 0 / radius pixel Dictionary {}for point in points x int point real * one Over Overlap Distance y int point imag * one Over Overlap Distance if not get Square Is Occupied pixel Dictionary x y away Points append point pixel Dictionary[ x y ] Nonereturn away Points
| null | null | null | null | Question:
What does the code get ?
Code:
def getAwayPoints(points, radius):
awayPoints = []
oneOverOverlapDistance = (1000.0 / radius)
pixelDictionary = {}
for point in points:
x = int((point.real * oneOverOverlapDistance))
y = int((point.imag * oneOverOverlapDistance))
if (not getSquareIsOccupied(pixelDictionary, x, y)):
awayPoints.append(point)
pixelDictionary[(x, y)] = None
return awayPoints
|
null | null | null | What does the code build ?
| def buildAllTarballs(checkout, destination):
if (not checkout.child('.svn').exists()):
raise NotWorkingDirectory(('%s does not appear to be an SVN working directory.' % (checkout.path,)))
if runCommand(['svn', 'st', checkout.path]).strip():
raise UncleanWorkingDirectory(('There are local modifications to the SVN checkout in %s.' % (checkout.path,)))
workPath = FilePath(mkdtemp())
export = workPath.child('export')
runCommand(['svn', 'export', checkout.path, export.path])
twistedPath = export.child('twisted')
version = Project(twistedPath).getVersion()
versionString = version.base()
apiBaseURL = ('http://twistedmatrix.com/documents/%s/api/%%s.html' % versionString)
if (not destination.exists()):
destination.createDirectory()
db = DistributionBuilder(export, destination, apiBaseURL=apiBaseURL)
db.buildCore(versionString)
for subproject in twisted_subprojects:
if twistedPath.child(subproject).exists():
db.buildSubProject(subproject, versionString)
db.buildTwisted(versionString)
workPath.remove()
| null | null | null | complete tarballs for twisted and all subprojects
| codeqa | def build All Tarballs checkout destination if not checkout child ' svn' exists raise Not Working Directory '%sdoesnotappeartobean SV Nworkingdirectory ' % checkout path if run Command ['svn' 'st' checkout path] strip raise Unclean Working Directory ' Therearelocalmodificationstothe SV Ncheckoutin%s ' % checkout path work Path File Path mkdtemp export work Path child 'export' run Command ['svn' 'export' checkout path export path] twisted Path export child 'twisted' version Project twisted Path get Version version String version base api Base URL 'http //twistedmatrix com/documents/%s/api/%%s html' % version String if not destination exists destination create Directory db Distribution Builder export destination api Base URL api Base URL db build Core version String for subproject in twisted subprojects if twisted Path child subproject exists db build Sub Project subproject version String db build Twisted version String work Path remove
| null | null | null | null | Question:
What does the code build ?
Code:
def buildAllTarballs(checkout, destination):
if (not checkout.child('.svn').exists()):
raise NotWorkingDirectory(('%s does not appear to be an SVN working directory.' % (checkout.path,)))
if runCommand(['svn', 'st', checkout.path]).strip():
raise UncleanWorkingDirectory(('There are local modifications to the SVN checkout in %s.' % (checkout.path,)))
workPath = FilePath(mkdtemp())
export = workPath.child('export')
runCommand(['svn', 'export', checkout.path, export.path])
twistedPath = export.child('twisted')
version = Project(twistedPath).getVersion()
versionString = version.base()
apiBaseURL = ('http://twistedmatrix.com/documents/%s/api/%%s.html' % versionString)
if (not destination.exists()):
destination.createDirectory()
db = DistributionBuilder(export, destination, apiBaseURL=apiBaseURL)
db.buildCore(versionString)
for subproject in twisted_subprojects:
if twistedPath.child(subproject).exists():
db.buildSubProject(subproject, versionString)
db.buildTwisted(versionString)
workPath.remove()
|
null | null | null | What does the code initialize ?
| @_sa_util.deprecated('0.7', message=':func:`.compile_mappers` is renamed to :func:`.configure_mappers`')
def compile_mappers():
configure_mappers()
| null | null | null | the inter - mapper relationships of all mappers that have been defined
| codeqa | @ sa util deprecated '0 7' message ' func ` compile mappers`isrenamedto func ` configure mappers`' def compile mappers configure mappers
| null | null | null | null | Question:
What does the code initialize ?
Code:
@_sa_util.deprecated('0.7', message=':func:`.compile_mappers` is renamed to :func:`.configure_mappers`')
def compile_mappers():
configure_mappers()
|
null | null | null | What did the code read ?
| def get_bootstrap_setting(setting, default=None):
return BOOTSTRAP3.get(setting, default)
| null | null | null | a setting
| codeqa | def get bootstrap setting setting default None return BOOTSTRAP 3 get setting default
| null | null | null | null | Question:
What did the code read ?
Code:
def get_bootstrap_setting(setting, default=None):
return BOOTSTRAP3.get(setting, default)
|
null | null | null | What passes a stack identifier ?
| def identified_stack(handler):
@policy_enforce
@six.wraps(handler)
def handle_stack_method(controller, req, stack_name, stack_id, **kwargs):
stack_identity = identifier.HeatIdentifier(req.context.tenant_id, stack_name, stack_id)
return handler(controller, req, dict(stack_identity), **kwargs)
return handle_stack_method
| null | null | null | decorator
| codeqa | def identified stack handler @policy enforce@six wraps handler def handle stack method controller req stack name stack id **kwargs stack identity identifier Heat Identifier req context tenant id stack name stack id return handler controller req dict stack identity **kwargs return handle stack method
| null | null | null | null | Question:
What passes a stack identifier ?
Code:
def identified_stack(handler):
@policy_enforce
@six.wraps(handler)
def handle_stack_method(controller, req, stack_name, stack_id, **kwargs):
stack_identity = identifier.HeatIdentifier(req.context.tenant_id, stack_name, stack_id)
return handler(controller, req, dict(stack_identity), **kwargs)
return handle_stack_method
|
null | null | null | What does decorator pass ?
| def identified_stack(handler):
@policy_enforce
@six.wraps(handler)
def handle_stack_method(controller, req, stack_name, stack_id, **kwargs):
stack_identity = identifier.HeatIdentifier(req.context.tenant_id, stack_name, stack_id)
return handler(controller, req, dict(stack_identity), **kwargs)
return handle_stack_method
| null | null | null | a stack identifier
| codeqa | def identified stack handler @policy enforce@six wraps handler def handle stack method controller req stack name stack id **kwargs stack identity identifier Heat Identifier req context tenant id stack name stack id return handler controller req dict stack identity **kwargs return handle stack method
| null | null | null | null | Question:
What does decorator pass ?
Code:
def identified_stack(handler):
@policy_enforce
@six.wraps(handler)
def handle_stack_method(controller, req, stack_name, stack_id, **kwargs):
stack_identity = identifier.HeatIdentifier(req.context.tenant_id, stack_name, stack_id)
return handler(controller, req, dict(stack_identity), **kwargs)
return handle_stack_method
|
null | null | null | What does the code evaluate ?
| def evaluate(expression, **kwargs):
global _parser
if (_parser is None):
_parser = _def_parser()
global _vars
_vars = kwargs
try:
result = _parser.parseString(expression, parseAll=True)[0]
except pyparsing.ParseException as e:
raise exception.EvaluatorParseException((_('ParseException: %s') % e))
return result.eval()
| null | null | null | an expression
| codeqa | def evaluate expression **kwargs global parserif parser is None parser def parser global vars vars kwargstry result parser parse String expression parse All True [0 ]except pyparsing Parse Exception as e raise exception Evaluator Parse Exception ' Parse Exception %s' % e return result eval
| null | null | null | null | Question:
What does the code evaluate ?
Code:
def evaluate(expression, **kwargs):
global _parser
if (_parser is None):
_parser = _def_parser()
global _vars
_vars = kwargs
try:
result = _parser.parseString(expression, parseAll=True)[0]
except pyparsing.ParseException as e:
raise exception.EvaluatorParseException((_('ParseException: %s') % e))
return result.eval()
|
null | null | null | What do tables have ?
| def get_tables():
tables = ['address_scopes', 'floatingips', 'meteringlabels', 'networkrbacs', 'networks', 'ports', 'qos_policies', 'qospolicyrbacs', 'quotas', 'reservations', 'routers', 'securitygrouprules', 'securitygroups', 'subnetpools', 'subnets', 'trunks', 'auto_allocated_topologies', 'default_security_group', 'ha_router_networks', 'quotausages']
return tables
| null | null | null | tenant_id column
| codeqa | def get tables tables ['address scopes' 'floatingips' 'meteringlabels' 'networkrbacs' 'networks' 'ports' 'qos policies' 'qospolicyrbacs' 'quotas' 'reservations' 'routers' 'securitygrouprules' 'securitygroups' 'subnetpools' 'subnets' 'trunks' 'auto allocated topologies' 'default security group' 'ha router networks' 'quotausages']return tables
| null | null | null | null | Question:
What do tables have ?
Code:
def get_tables():
tables = ['address_scopes', 'floatingips', 'meteringlabels', 'networkrbacs', 'networks', 'ports', 'qos_policies', 'qospolicyrbacs', 'quotas', 'reservations', 'routers', 'securitygrouprules', 'securitygroups', 'subnetpools', 'subnets', 'trunks', 'auto_allocated_topologies', 'default_security_group', 'ha_router_networks', 'quotausages']
return tables
|
null | null | null | What have tenant_id column ?
| def get_tables():
tables = ['address_scopes', 'floatingips', 'meteringlabels', 'networkrbacs', 'networks', 'ports', 'qos_policies', 'qospolicyrbacs', 'quotas', 'reservations', 'routers', 'securitygrouprules', 'securitygroups', 'subnetpools', 'subnets', 'trunks', 'auto_allocated_topologies', 'default_security_group', 'ha_router_networks', 'quotausages']
return tables
| null | null | null | tables
| codeqa | def get tables tables ['address scopes' 'floatingips' 'meteringlabels' 'networkrbacs' 'networks' 'ports' 'qos policies' 'qospolicyrbacs' 'quotas' 'reservations' 'routers' 'securitygrouprules' 'securitygroups' 'subnetpools' 'subnets' 'trunks' 'auto allocated topologies' 'default security group' 'ha router networks' 'quotausages']return tables
| null | null | null | null | Question:
What have tenant_id column ?
Code:
def get_tables():
tables = ['address_scopes', 'floatingips', 'meteringlabels', 'networkrbacs', 'networks', 'ports', 'qos_policies', 'qospolicyrbacs', 'quotas', 'reservations', 'routers', 'securitygrouprules', 'securitygroups', 'subnetpools', 'subnets', 'trunks', 'auto_allocated_topologies', 'default_security_group', 'ha_router_networks', 'quotausages']
return tables
|
null | null | null | What does test helper context manager mock global ?
| @contextmanager
def set_flask_request(wsgi_environ):
environ = {}
environ.update(wsgi_environ)
wsgiref.util.setup_testing_defaults(environ)
r = werkzeug.wrappers.Request(environ)
with mock.patch.dict(extract_params.__globals__, {'request': r}):
(yield)
| null | null | null | the flask request
| codeqa | @contextmanagerdef set flask request wsgi environ environ {}environ update wsgi environ wsgiref util setup testing defaults environ r werkzeug wrappers Request environ with mock patch dict extract params globals {'request' r} yield
| null | null | null | null | Question:
What does test helper context manager mock global ?
Code:
@contextmanager
def set_flask_request(wsgi_environ):
environ = {}
environ.update(wsgi_environ)
wsgiref.util.setup_testing_defaults(environ)
r = werkzeug.wrappers.Request(environ)
with mock.patch.dict(extract_params.__globals__, {'request': r}):
(yield)
|
null | null | null | Who tests the functions in helpers just ?
| @contextmanager
def set_flask_request(wsgi_environ):
environ = {}
environ.update(wsgi_environ)
wsgiref.util.setup_testing_defaults(environ)
r = werkzeug.wrappers.Request(environ)
with mock.patch.dict(extract_params.__globals__, {'request': r}):
(yield)
| null | null | null | i
| codeqa | @contextmanagerdef set flask request wsgi environ environ {}environ update wsgi environ wsgiref util setup testing defaults environ r werkzeug wrappers Request environ with mock patch dict extract params globals {'request' r} yield
| null | null | null | null | Question:
Who tests the functions in helpers just ?
Code:
@contextmanager
def set_flask_request(wsgi_environ):
environ = {}
environ.update(wsgi_environ)
wsgiref.util.setup_testing_defaults(environ)
r = werkzeug.wrappers.Request(environ)
with mock.patch.dict(extract_params.__globals__, {'request': r}):
(yield)
|
null | null | null | What mocks the flask request global ?
| @contextmanager
def set_flask_request(wsgi_environ):
environ = {}
environ.update(wsgi_environ)
wsgiref.util.setup_testing_defaults(environ)
r = werkzeug.wrappers.Request(environ)
with mock.patch.dict(extract_params.__globals__, {'request': r}):
(yield)
| null | null | null | test helper context manager
| codeqa | @contextmanagerdef set flask request wsgi environ environ {}environ update wsgi environ wsgiref util setup testing defaults environ r werkzeug wrappers Request environ with mock patch dict extract params globals {'request' r} yield
| null | null | null | null | Question:
What mocks the flask request global ?
Code:
@contextmanager
def set_flask_request(wsgi_environ):
environ = {}
environ.update(wsgi_environ)
wsgiref.util.setup_testing_defaults(environ)
r = werkzeug.wrappers.Request(environ)
with mock.patch.dict(extract_params.__globals__, {'request': r}):
(yield)
|
null | null | null | For what purpose is student notes feature enabled ?
| def is_feature_enabled(course):
return EdxNotesTab.is_enabled(course)
| null | null | null | for the course
| codeqa | def is feature enabled course return Edx Notes Tab is enabled course
| null | null | null | null | Question:
For what purpose is student notes feature enabled ?
Code:
def is_feature_enabled(course):
return EdxNotesTab.is_enabled(course)
|
null | null | null | For what purpose does the code convert the given requirement line ?
| def convert_line(line, comments):
for (pattern, repl) in comments['replace'].items():
line = re.sub(pattern, repl, line)
pkgname = line.split('=')[0]
if (pkgname in comments['ignore']):
line = ('# ' + line)
try:
line += (' # ' + comments['comment'][pkgname])
except KeyError:
pass
try:
line += ' # rq.filter: {}'.format(comments['filter'][pkgname])
except KeyError:
pass
return line
| null | null | null | to place into the output
| codeqa | def convert line line comments for pattern repl in comments['replace'] items line re sub pattern repl line pkgname line split ' ' [0 ]if pkgname in comments['ignore'] line '#' + line try line + '#' + comments['comment'][pkgname] except Key Error passtry line + '#rq filter {}' format comments['filter'][pkgname] except Key Error passreturn line
| null | null | null | null | Question:
For what purpose does the code convert the given requirement line ?
Code:
def convert_line(line, comments):
for (pattern, repl) in comments['replace'].items():
line = re.sub(pattern, repl, line)
pkgname = line.split('=')[0]
if (pkgname in comments['ignore']):
line = ('# ' + line)
try:
line += (' # ' + comments['comment'][pkgname])
except KeyError:
pass
try:
line += ' # rq.filter: {}'.format(comments['filter'][pkgname])
except KeyError:
pass
return line
|
null | null | null | What does the code convert to place into the output ?
| def convert_line(line, comments):
for (pattern, repl) in comments['replace'].items():
line = re.sub(pattern, repl, line)
pkgname = line.split('=')[0]
if (pkgname in comments['ignore']):
line = ('# ' + line)
try:
line += (' # ' + comments['comment'][pkgname])
except KeyError:
pass
try:
line += ' # rq.filter: {}'.format(comments['filter'][pkgname])
except KeyError:
pass
return line
| null | null | null | the given requirement line
| codeqa | def convert line line comments for pattern repl in comments['replace'] items line re sub pattern repl line pkgname line split ' ' [0 ]if pkgname in comments['ignore'] line '#' + line try line + '#' + comments['comment'][pkgname] except Key Error passtry line + '#rq filter {}' format comments['filter'][pkgname] except Key Error passreturn line
| null | null | null | null | Question:
What does the code convert to place into the output ?
Code:
def convert_line(line, comments):
for (pattern, repl) in comments['replace'].items():
line = re.sub(pattern, repl, line)
pkgname = line.split('=')[0]
if (pkgname in comments['ignore']):
line = ('# ' + line)
try:
line += (' # ' + comments['comment'][pkgname])
except KeyError:
pass
try:
line += ' # rq.filter: {}'.format(comments['filter'][pkgname])
except KeyError:
pass
return line
|
null | null | null | What does the code find ?
| def database_conf(db_path, prefix='GALAXY'):
database_auto_migrate = False
dburi_var = ('%s_TEST_DBURI' % prefix)
if (dburi_var in os.environ):
database_connection = os.environ[dburi_var]
else:
default_db_filename = ('%s.sqlite' % prefix.lower())
template_var = ('%s_TEST_DB_TEMPLATE' % prefix)
db_path = os.path.join(db_path, default_db_filename)
if (template_var in os.environ):
copy_database_template(os.environ[template_var], db_path)
database_auto_migrate = True
database_connection = ('sqlite:///%s' % db_path)
config = {'database_connection': database_connection, 'database_auto_migrate': database_auto_migrate}
if (not database_connection.startswith('sqlite://')):
config['database_engine_option_max_overflow'] = '20'
config['database_engine_option_pool_size'] = '10'
return config
| null | null | null | galaxy database connection
| codeqa | def database conf db path prefix 'GALAXY' database auto migrate Falsedburi var '%s TEST DBURI' % prefix if dburi var in os environ database connection os environ[dburi var]else default db filename '%s sqlite' % prefix lower template var '%s TEST DB TEMPLATE' % prefix db path os path join db path default db filename if template var in os environ copy database template os environ[template var] db path database auto migrate Truedatabase connection 'sqlite ///%s' % db path config {'database connection' database connection 'database auto migrate' database auto migrate}if not database connection startswith 'sqlite //' config['database engine option max overflow'] '20 'config['database engine option pool size'] '10 'return config
| null | null | null | null | Question:
What does the code find ?
Code:
def database_conf(db_path, prefix='GALAXY'):
database_auto_migrate = False
dburi_var = ('%s_TEST_DBURI' % prefix)
if (dburi_var in os.environ):
database_connection = os.environ[dburi_var]
else:
default_db_filename = ('%s.sqlite' % prefix.lower())
template_var = ('%s_TEST_DB_TEMPLATE' % prefix)
db_path = os.path.join(db_path, default_db_filename)
if (template_var in os.environ):
copy_database_template(os.environ[template_var], db_path)
database_auto_migrate = True
database_connection = ('sqlite:///%s' % db_path)
config = {'database_connection': database_connection, 'database_auto_migrate': database_auto_migrate}
if (not database_connection.startswith('sqlite://')):
config['database_engine_option_max_overflow'] = '20'
config['database_engine_option_pool_size'] = '10'
return config
|
null | null | null | How is no data saved at all ?
| def test_private_browsing(qtbot, tmpdir, fake_save_manager, config_stub):
config_stub.data = {'general': {'private-browsing': True}}
private_hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='history')
with qtbot.assertNotEmitted(private_hist.add_completion_item):
with qtbot.assertNotEmitted(private_hist.item_added):
private_hist.add_url(QUrl('http://www.example.com/'))
assert (not private_hist._temp_history)
with qtbot.assertNotEmitted(private_hist.add_completion_item):
with qtbot.assertNotEmitted(private_hist.item_added):
with qtbot.waitSignals([private_hist.async_read_done], order='strict'):
list(private_hist.async_read())
with qtbot.assertNotEmitted(private_hist.add_completion_item):
with qtbot.assertNotEmitted(private_hist.item_added):
private_hist.add_url(QUrl('http://www.example.com/'))
assert (not private_hist._temp_history)
assert (not private_hist._new_history)
assert (not private_hist.history_dict)
| null | null | null | with private browsing
| codeqa | def test private browsing qtbot tmpdir fake save manager config stub config stub data {'general' {'private-browsing' True}}private hist history Web History hist dir str tmpdir hist name 'history' with qtbot assert Not Emitted private hist add completion item with qtbot assert Not Emitted private hist item added private hist add url Q Url 'http //www example com/' assert not private hist temp history with qtbot assert Not Emitted private hist add completion item with qtbot assert Not Emitted private hist item added with qtbot wait Signals [private hist async read done] order 'strict' list private hist async read with qtbot assert Not Emitted private hist add completion item with qtbot assert Not Emitted private hist item added private hist add url Q Url 'http //www example com/' assert not private hist temp history assert not private hist new history assert not private hist history dict
| null | null | null | null | Question:
How is no data saved at all ?
Code:
def test_private_browsing(qtbot, tmpdir, fake_save_manager, config_stub):
config_stub.data = {'general': {'private-browsing': True}}
private_hist = history.WebHistory(hist_dir=str(tmpdir), hist_name='history')
with qtbot.assertNotEmitted(private_hist.add_completion_item):
with qtbot.assertNotEmitted(private_hist.item_added):
private_hist.add_url(QUrl('http://www.example.com/'))
assert (not private_hist._temp_history)
with qtbot.assertNotEmitted(private_hist.add_completion_item):
with qtbot.assertNotEmitted(private_hist.item_added):
with qtbot.waitSignals([private_hist.async_read_done], order='strict'):
list(private_hist.async_read())
with qtbot.assertNotEmitted(private_hist.add_completion_item):
with qtbot.assertNotEmitted(private_hist.item_added):
private_hist.add_url(QUrl('http://www.example.com/'))
assert (not private_hist._temp_history)
assert (not private_hist._new_history)
assert (not private_hist.history_dict)
|
null | null | null | What did the code use ?
| def agent_service_deregister(consul_url=None, serviceid=None):
ret = {}
data = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not serviceid):
raise SaltInvocationError('Required argument "serviceid" is missing.')
function = 'agent/service/deregister/{0}'.format(serviceid)
res = _query(consul_url=consul_url, function=function, method='PUT', data=data)
if res['res']:
ret['res'] = True
ret['message'] = 'Service {0} removed from agent.'.format(serviceid)
else:
ret['res'] = False
ret['message'] = 'Unable to remove service {0}.'.format(serviceid)
return ret
| null | null | null | to remove a service
| codeqa | def agent service deregister consul url None serviceid None ret {}data {}if not consul url consul url get config if not consul url log error ' No Consul UR Lfound ' ret['message'] ' No Consul UR Lfound 'ret['res'] Falsereturn retif not serviceid raise Salt Invocation Error ' Requiredargument"serviceid"ismissing ' function 'agent/service/deregister/{ 0 }' format serviceid res query consul url consul url function function method 'PUT' data data if res['res'] ret['res'] Trueret['message'] ' Service{ 0 }removedfromagent ' format serviceid else ret['res'] Falseret['message'] ' Unabletoremoveservice{ 0 } ' format serviceid return ret
| null | null | null | null | Question:
What did the code use ?
Code:
def agent_service_deregister(consul_url=None, serviceid=None):
ret = {}
data = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if (not serviceid):
raise SaltInvocationError('Required argument "serviceid" is missing.')
function = 'agent/service/deregister/{0}'.format(serviceid)
res = _query(consul_url=consul_url, function=function, method='PUT', data=data)
if res['res']:
ret['res'] = True
ret['message'] = 'Service {0} removed from agent.'.format(serviceid)
else:
ret['res'] = False
ret['message'] = 'Unable to remove service {0}.'.format(serviceid)
return ret
|
null | null | null | What does the code get ?
| def getOverhangSpan(elementNode):
return getCascadeFloatWithoutSelf((2.0 * getLayerHeight(elementNode)), elementNode, 'overhangSpan')
| null | null | null | the overhang span
| codeqa | def get Overhang Span element Node return get Cascade Float Without Self 2 0 * get Layer Height element Node element Node 'overhang Span'
| null | null | null | null | Question:
What does the code get ?
Code:
def getOverhangSpan(elementNode):
return getCascadeFloatWithoutSelf((2.0 * getLayerHeight(elementNode)), elementNode, 'overhangSpan')
|
null | null | null | Where is an error raised if ?
| def test_duplicate_output():
assert_raises(BundleError, bundle_to_joblist, Bundle(Bundle('s1', output='foo'), Bundle('s2', output='foo')))
| null | null | null | within a single bundle
| codeqa | def test duplicate output assert raises Bundle Error bundle to joblist Bundle Bundle 's 1 ' output 'foo' Bundle 's 2 ' output 'foo'
| null | null | null | null | Question:
Where is an error raised if ?
Code:
def test_duplicate_output():
assert_raises(BundleError, bundle_to_joblist, Bundle(Bundle('s1', output='foo'), Bundle('s2', output='foo')))
|
null | null | null | What is raised within a single bundle ?
| def test_duplicate_output():
assert_raises(BundleError, bundle_to_joblist, Bundle(Bundle('s1', output='foo'), Bundle('s2', output='foo')))
| null | null | null | an error
| codeqa | def test duplicate output assert raises Bundle Error bundle to joblist Bundle Bundle 's 1 ' output 'foo' Bundle 's 2 ' output 'foo'
| null | null | null | null | Question:
What is raised within a single bundle ?
Code:
def test_duplicate_output():
assert_raises(BundleError, bundle_to_joblist, Bundle(Bundle('s1', output='foo'), Bundle('s2', output='foo')))
|
null | null | null | What does the code delete from the index ?
| def col_delete(cols_selected):
if (len(cols_selected) < 1):
flash('No collections selected to delete!', 'error')
else:
for source_id in cols_selected:
delete_collection(source_id)
flash(('%s %s deleted' % (len(cols_selected), ('collection' if (len(cols_selected) == 1) else 'collections'))), 'notification')
return redirect(url_for('index'))
| null | null | null | multiple collections
| codeqa | def col delete cols selected if len cols selected < 1 flash ' Nocollectionsselectedtodelete ' 'error' else for source id in cols selected delete collection source id flash '%s%sdeleted' % len cols selected 'collection' if len cols selected 1 else 'collections' 'notification' return redirect url for 'index'
| null | null | null | null | Question:
What does the code delete from the index ?
Code:
def col_delete(cols_selected):
if (len(cols_selected) < 1):
flash('No collections selected to delete!', 'error')
else:
for source_id in cols_selected:
delete_collection(source_id)
flash(('%s %s deleted' % (len(cols_selected), ('collection' if (len(cols_selected) == 1) else 'collections'))), 'notification')
return redirect(url_for('index'))
|
null | null | null | What does the code get ?
| def _ExtractCLPath(output_of_where):
for line in output_of_where.strip().splitlines():
if line.startswith('LOC:'):
return line[len('LOC:'):].strip()
| null | null | null | the path to cl
| codeqa | def Extract CL Path output of where for line in output of where strip splitlines if line startswith 'LOC ' return line[len 'LOC ' ] strip
| null | null | null | null | Question:
What does the code get ?
Code:
def _ExtractCLPath(output_of_where):
for line in output_of_where.strip().splitlines():
if line.startswith('LOC:'):
return line[len('LOC:'):].strip()
|
null | null | null | How do the bottom 32 bits of w return as a python int ?
| def trunc32(w):
w = int(((w & 2147483647) | (- (w & 2147483648))))
assert (type(w) == int)
return w
| null | null | null | code
| codeqa | def trunc 32 w w int w & 2147483647 - w & 2147483648 assert type w int return w
| null | null | null | null | Question:
How do the bottom 32 bits of w return as a python int ?
Code:
def trunc32(w):
w = int(((w & 2147483647) | (- (w & 2147483648))))
assert (type(w) == int)
return w
|
null | null | null | When be action or script performed ?
| def change_queue_complete_action(action, new=True):
global QUEUECOMPLETE, QUEUECOMPLETEACTION, QUEUECOMPLETEARG
_action = None
_argument = None
if ('script_' in action):
_action = run_script
_argument = action.replace('script_', '')
elif (new or cfg.queue_complete_pers.get()):
if (action == 'shutdown_pc'):
_action = system_shutdown
elif (action == 'hibernate_pc'):
_action = system_hibernate
elif (action == 'standby_pc'):
_action = system_standby
elif (action == 'shutdown_program'):
_action = shutdown_program
else:
action = None
else:
action = None
if new:
cfg.queue_complete.set((action or ''))
config.save_config()
QUEUECOMPLETE = action
QUEUECOMPLETEACTION = _action
QUEUECOMPLETEARG = _argument
| null | null | null | once the queue has been completed
| codeqa | def change queue complete action action new True global QUEUECOMPLETE QUEUECOMPLETEACTION QUEUECOMPLETEARG action None argument Noneif 'script ' in action action run script argument action replace 'script ' '' elif new or cfg queue complete pers get if action 'shutdown pc' action system shutdownelif action 'hibernate pc' action system hibernateelif action 'standby pc' action system standbyelif action 'shutdown program' action shutdown programelse action Noneelse action Noneif new cfg queue complete set action or '' config save config QUEUECOMPLETE action QUEUECOMPLETEACTION action QUEUECOMPLETEARG argument
| null | null | null | null | Question:
When be action or script performed ?
Code:
def change_queue_complete_action(action, new=True):
global QUEUECOMPLETE, QUEUECOMPLETEACTION, QUEUECOMPLETEARG
_action = None
_argument = None
if ('script_' in action):
_action = run_script
_argument = action.replace('script_', '')
elif (new or cfg.queue_complete_pers.get()):
if (action == 'shutdown_pc'):
_action = system_shutdown
elif (action == 'hibernate_pc'):
_action = system_hibernate
elif (action == 'standby_pc'):
_action = system_standby
elif (action == 'shutdown_program'):
_action = shutdown_program
else:
action = None
else:
action = None
if new:
cfg.queue_complete.set((action or ''))
config.save_config()
QUEUECOMPLETE = action
QUEUECOMPLETEACTION = _action
QUEUECOMPLETEARG = _argument
|
null | null | null | When are with script _ prefixed ?
| def change_queue_complete_action(action, new=True):
global QUEUECOMPLETE, QUEUECOMPLETEACTION, QUEUECOMPLETEARG
_action = None
_argument = None
if ('script_' in action):
_action = run_script
_argument = action.replace('script_', '')
elif (new or cfg.queue_complete_pers.get()):
if (action == 'shutdown_pc'):
_action = system_shutdown
elif (action == 'hibernate_pc'):
_action = system_hibernate
elif (action == 'standby_pc'):
_action = system_standby
elif (action == 'shutdown_program'):
_action = shutdown_program
else:
action = None
else:
action = None
if new:
cfg.queue_complete.set((action or ''))
config.save_config()
QUEUECOMPLETE = action
QUEUECOMPLETEACTION = _action
QUEUECOMPLETEARG = _argument
| null | null | null | once the queue has been
| codeqa | def change queue complete action action new True global QUEUECOMPLETE QUEUECOMPLETEACTION QUEUECOMPLETEARG action None argument Noneif 'script ' in action action run script argument action replace 'script ' '' elif new or cfg queue complete pers get if action 'shutdown pc' action system shutdownelif action 'hibernate pc' action system hibernateelif action 'standby pc' action system standbyelif action 'shutdown program' action shutdown programelse action Noneelse action Noneif new cfg queue complete set action or '' config save config QUEUECOMPLETE action QUEUECOMPLETEACTION action QUEUECOMPLETEARG argument
| null | null | null | null | Question:
When are with script _ prefixed ?
Code:
def change_queue_complete_action(action, new=True):
global QUEUECOMPLETE, QUEUECOMPLETEACTION, QUEUECOMPLETEARG
_action = None
_argument = None
if ('script_' in action):
_action = run_script
_argument = action.replace('script_', '')
elif (new or cfg.queue_complete_pers.get()):
if (action == 'shutdown_pc'):
_action = system_shutdown
elif (action == 'hibernate_pc'):
_action = system_hibernate
elif (action == 'standby_pc'):
_action = system_standby
elif (action == 'shutdown_program'):
_action = shutdown_program
else:
action = None
else:
action = None
if new:
cfg.queue_complete.set((action or ''))
config.save_config()
QUEUECOMPLETE = action
QUEUECOMPLETEACTION = _action
QUEUECOMPLETEARG = _argument
|
null | null | null | For what purpose do an implementation factory return ?
| def _unary_int_input_wrapper_impl(wrapped_impl):
def implementer(context, builder, sig, args):
(val,) = args
input_type = sig.args[0]
fpval = context.cast(builder, val, input_type, types.float64)
inner_sig = signature(types.float64, types.float64)
res = wrapped_impl(context, builder, inner_sig, (fpval,))
return context.cast(builder, res, types.float64, sig.return_type)
return implementer
| null | null | null | to convert the single integral input argument to a float64
| codeqa | def unary int input wrapper impl wrapped impl def implementer context builder sig args val argsinput type sig args[ 0 ]fpval context cast builder val input type types float 64 inner sig signature types float 64 types float 64 res wrapped impl context builder inner sig fpval return context cast builder res types float 64 sig return type return implementer
| null | null | null | null | Question:
For what purpose do an implementation factory return ?
Code:
def _unary_int_input_wrapper_impl(wrapped_impl):
def implementer(context, builder, sig, args):
(val,) = args
input_type = sig.args[0]
fpval = context.cast(builder, val, input_type, types.float64)
inner_sig = signature(types.float64, types.float64)
res = wrapped_impl(context, builder, inner_sig, (fpval,))
return context.cast(builder, res, types.float64, sig.return_type)
return implementer
|
null | null | null | What is using to retrieve information from a third party and matching that information to an existing user ?
| @csrf_exempt
@require_POST
@social_utils.strategy('social:complete')
def login_oauth_token(request, backend):
warnings.warn('Please use AccessTokenExchangeView instead.', DeprecationWarning)
backend = request.backend
if (isinstance(backend, social_oauth.BaseOAuth1) or isinstance(backend, social_oauth.BaseOAuth2)):
if ('access_token' in request.POST):
request.session[pipeline.AUTH_ENTRY_KEY] = pipeline.AUTH_ENTRY_LOGIN_API
user = None
try:
user = backend.do_auth(request.POST['access_token'])
except (HTTPError, AuthException):
pass
if (user and isinstance(user, User)):
login(request, user)
return JsonResponse(status=204)
else:
request.social_strategy.clean_partial_pipeline()
return JsonResponse({'error': 'invalid_token'}, status=401)
else:
return JsonResponse({'error': 'invalid_request'}, status=400)
raise Http404
| null | null | null | the token
| codeqa | @csrf exempt@require POST@social utils strategy 'social complete' def login oauth token request backend warnings warn ' Pleaseuse Access Token Exchange Viewinstead ' Deprecation Warning backend request backendif isinstance backend social oauth Base O Auth 1 or isinstance backend social oauth Base O Auth 2 if 'access token' in request POST request session[pipeline AUTH ENTRY KEY] pipeline AUTH ENTRY LOGIN AP Iuser Nonetry user backend do auth request POST['access token'] except HTTP Error Auth Exception passif user and isinstance user User login request user return Json Response status 204 else request social strategy clean partial pipeline return Json Response {'error' 'invalid token'} status 401 else return Json Response {'error' 'invalid request'} status 400 raise Http 404
| null | null | null | null | Question:
What is using to retrieve information from a third party and matching that information to an existing user ?
Code:
@csrf_exempt
@require_POST
@social_utils.strategy('social:complete')
def login_oauth_token(request, backend):
warnings.warn('Please use AccessTokenExchangeView instead.', DeprecationWarning)
backend = request.backend
if (isinstance(backend, social_oauth.BaseOAuth1) or isinstance(backend, social_oauth.BaseOAuth2)):
if ('access_token' in request.POST):
request.session[pipeline.AUTH_ENTRY_KEY] = pipeline.AUTH_ENTRY_LOGIN_API
user = None
try:
user = backend.do_auth(request.POST['access_token'])
except (HTTPError, AuthException):
pass
if (user and isinstance(user, User)):
login(request, user)
return JsonResponse(status=204)
else:
request.social_strategy.clean_partial_pipeline()
return JsonResponse({'error': 'invalid_token'}, status=401)
else:
return JsonResponse({'error': 'invalid_request'}, status=400)
raise Http404
|
null | null | null | What do the token use ?
| @csrf_exempt
@require_POST
@social_utils.strategy('social:complete')
def login_oauth_token(request, backend):
warnings.warn('Please use AccessTokenExchangeView instead.', DeprecationWarning)
backend = request.backend
if (isinstance(backend, social_oauth.BaseOAuth1) or isinstance(backend, social_oauth.BaseOAuth2)):
if ('access_token' in request.POST):
request.session[pipeline.AUTH_ENTRY_KEY] = pipeline.AUTH_ENTRY_LOGIN_API
user = None
try:
user = backend.do_auth(request.POST['access_token'])
except (HTTPError, AuthException):
pass
if (user and isinstance(user, User)):
login(request, user)
return JsonResponse(status=204)
else:
request.social_strategy.clean_partial_pipeline()
return JsonResponse({'error': 'invalid_token'}, status=401)
else:
return JsonResponse({'error': 'invalid_request'}, status=400)
raise Http404
| null | null | null | to retrieve information from a third party and matching that information to an existing user
| codeqa | @csrf exempt@require POST@social utils strategy 'social complete' def login oauth token request backend warnings warn ' Pleaseuse Access Token Exchange Viewinstead ' Deprecation Warning backend request backendif isinstance backend social oauth Base O Auth 1 or isinstance backend social oauth Base O Auth 2 if 'access token' in request POST request session[pipeline AUTH ENTRY KEY] pipeline AUTH ENTRY LOGIN AP Iuser Nonetry user backend do auth request POST['access token'] except HTTP Error Auth Exception passif user and isinstance user User login request user return Json Response status 204 else request social strategy clean partial pipeline return Json Response {'error' 'invalid token'} status 401 else return Json Response {'error' 'invalid request'} status 400 raise Http 404
| null | null | null | null | Question:
What do the token use ?
Code:
@csrf_exempt
@require_POST
@social_utils.strategy('social:complete')
def login_oauth_token(request, backend):
warnings.warn('Please use AccessTokenExchangeView instead.', DeprecationWarning)
backend = request.backend
if (isinstance(backend, social_oauth.BaseOAuth1) or isinstance(backend, social_oauth.BaseOAuth2)):
if ('access_token' in request.POST):
request.session[pipeline.AUTH_ENTRY_KEY] = pipeline.AUTH_ENTRY_LOGIN_API
user = None
try:
user = backend.do_auth(request.POST['access_token'])
except (HTTPError, AuthException):
pass
if (user and isinstance(user, User)):
login(request, user)
return JsonResponse(status=204)
else:
request.social_strategy.clean_partial_pipeline()
return JsonResponse({'error': 'invalid_token'}, status=401)
else:
return JsonResponse({'error': 'invalid_request'}, status=400)
raise Http404
|
null | null | null | For what purpose does this exist ?
| @app.route('/raise-500', methods=['GET'])
@requires_auth
def raise_500():
raise ValueError('Foo!')
| null | null | null | for testing error_500_handler
| codeqa | @app route '/raise- 500 ' methods ['GET'] @requires authdef raise 500 raise Value Error ' Foo '
| null | null | null | null | Question:
For what purpose does this exist ?
Code:
@app.route('/raise-500', methods=['GET'])
@requires_auth
def raise_500():
raise ValueError('Foo!')
|
null | null | null | What tells other modules ?
| def connect_signals(**kwargs):
from reviewboard.notifications import email, webhooks
email.connect_signals()
webhooks.connect_signals()
| null | null | null | to connect their signals
| codeqa | def connect signals **kwargs from reviewboard notifications import email webhooksemail connect signals webhooks connect signals
| null | null | null | null | Question:
What tells other modules ?
Code:
def connect_signals(**kwargs):
from reviewboard.notifications import email, webhooks
email.connect_signals()
webhooks.connect_signals()
|
null | null | null | What connects their signals ?
| def connect_signals(**kwargs):
from reviewboard.notifications import email, webhooks
email.connect_signals()
webhooks.connect_signals()
| null | null | null | other modules
| codeqa | def connect signals **kwargs from reviewboard notifications import email webhooksemail connect signals webhooks connect signals
| null | null | null | null | Question:
What connects their signals ?
Code:
def connect_signals(**kwargs):
from reviewboard.notifications import email, webhooks
email.connect_signals()
webhooks.connect_signals()
|
null | null | null | What does other modules connect ?
| def connect_signals(**kwargs):
from reviewboard.notifications import email, webhooks
email.connect_signals()
webhooks.connect_signals()
| null | null | null | their signals
| codeqa | def connect signals **kwargs from reviewboard notifications import email webhooksemail connect signals webhooks connect signals
| null | null | null | null | Question:
What does other modules connect ?
Code:
def connect_signals(**kwargs):
from reviewboard.notifications import email, webhooks
email.connect_signals()
webhooks.connect_signals()
|
null | null | null | What does the code raise ?
| def verify_vlan_range(vlan_range):
for vlan_tag in vlan_range:
if (not is_valid_vlan_tag(vlan_tag)):
raise_invalid_tag(str(vlan_tag), vlan_range)
if (vlan_range[1] < vlan_range[0]):
raise n_exc.NetworkVlanRangeError(vlan_range=vlan_range, error=_('End of VLAN range is less than start of VLAN range'))
| null | null | null | an exception for invalid tags or malformed range
| codeqa | def verify vlan range vlan range for vlan tag in vlan range if not is valid vlan tag vlan tag raise invalid tag str vlan tag vlan range if vlan range[ 1 ] < vlan range[ 0 ] raise n exc Network Vlan Range Error vlan range vlan range error ' Endof VLA Nrangeislessthanstartof VLA Nrange'
| null | null | null | null | Question:
What does the code raise ?
Code:
def verify_vlan_range(vlan_range):
for vlan_tag in vlan_range:
if (not is_valid_vlan_tag(vlan_tag)):
raise_invalid_tag(str(vlan_tag), vlan_range)
if (vlan_range[1] < vlan_range[0]):
raise n_exc.NetworkVlanRangeError(vlan_range=vlan_range, error=_('End of VLAN range is less than start of VLAN range'))
|
null | null | null | What contain a string ?
| @logic.validate(logic.schema.default_autocomplete_schema)
def user_autocomplete(context, data_dict):
model = context['model']
user = context['user']
_check_access('user_autocomplete', context, data_dict)
q = data_dict['q']
limit = data_dict.get('limit', 20)
query = model.User.search(q)
query = query.filter((model.User.state != model.State.DELETED))
query = query.limit(limit)
user_list = []
for user in query.all():
result_dict = {}
for k in ['id', 'name', 'fullname']:
result_dict[k] = getattr(user, k)
user_list.append(result_dict)
return user_list
| null | null | null | user names
| codeqa | @logic validate logic schema default autocomplete schema def user autocomplete context data dict model context['model']user context['user'] check access 'user autocomplete' context data dict q data dict['q']limit data dict get 'limit' 20 query model User search q query query filter model User state model State DELETED query query limit limit user list []for user in query all result dict {}for k in ['id' 'name' 'fullname'] result dict[k] getattr user k user list append result dict return user list
| null | null | null | null | Question:
What contain a string ?
Code:
@logic.validate(logic.schema.default_autocomplete_schema)
def user_autocomplete(context, data_dict):
model = context['model']
user = context['user']
_check_access('user_autocomplete', context, data_dict)
q = data_dict['q']
limit = data_dict.get('limit', 20)
query = model.User.search(q)
query = query.filter((model.User.state != model.State.DELETED))
query = query.limit(limit)
user_list = []
for user in query.all():
result_dict = {}
for k in ['id', 'name', 'fullname']:
result_dict[k] = getattr(user, k)
user_list.append(result_dict)
return user_list
|
null | null | null | What does the code take of some corner cases in python where the mode string is either oddly formatted or does not truly represent the file mode ?
| def _fileobj_normalize_mode(f):
mode = f.mode
if isinstance(f, gzip.GzipFile):
if (mode == gzip.READ):
return 'rb'
elif (mode == gzip.WRITE):
return 'wb'
else:
return None
if ('+' in mode):
mode = mode.replace('+', '')
mode += '+'
return mode
| null | null | null | care
| codeqa | def fileobj normalize mode f mode f modeif isinstance f gzip Gzip File if mode gzip READ return 'rb'elif mode gzip WRITE return 'wb'else return Noneif '+' in mode mode mode replace '+' '' mode + '+'return mode
| null | null | null | null | Question:
What does the code take of some corner cases in python where the mode string is either oddly formatted or does not truly represent the file mode ?
Code:
def _fileobj_normalize_mode(f):
mode = f.mode
if isinstance(f, gzip.GzipFile):
if (mode == gzip.READ):
return 'rb'
elif (mode == gzip.WRITE):
return 'wb'
else:
return None
if ('+' in mode):
mode = mode.replace('+', '')
mode += '+'
return mode
|
null | null | null | What does the code clean ?
| def metric_cleanup():
logging.debug('metric_cleanup')
pass
| null | null | null | the metric module
| codeqa | def metric cleanup logging debug 'metric cleanup' pass
| null | null | null | null | Question:
What does the code clean ?
Code:
def metric_cleanup():
logging.debug('metric_cleanup')
pass
|
null | null | null | What does the code generate ?
| def rand_text_alphanumeric(length, bad=''):
chars = ((upperAlpha + lowerAlpha) + numerals)
return rand_base(length, bad, set(chars))
| null | null | null | a random string with alpha and numerals chars
| codeqa | def rand text alphanumeric length bad '' chars upper Alpha + lower Alpha + numerals return rand base length bad set chars
| null | null | null | null | Question:
What does the code generate ?
Code:
def rand_text_alphanumeric(length, bad=''):
chars = ((upperAlpha + lowerAlpha) + numerals)
return rand_base(length, bad, set(chars))
|
null | null | null | What does the code disable ?
| def servicegroup_server_disable(sg_name, s_name, s_port, **connection_args):
ret = True
server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args)
if (server is None):
return False
nitro = _connect(**connection_args)
if (nitro is None):
return False
try:
NSServiceGroup.disable_server(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.disable_server() failed: {0}'.format(error))
ret = False
_disconnect(nitro)
return ret
| null | null | null | a server
| codeqa | def servicegroup server disable sg name s name s port **connection args ret Trueserver servicegroup get server sg name s name s port **connection args if server is None return Falsenitro connect **connection args if nitro is None return Falsetry NS Service Group disable server nitro server except NS Nitro Error as error log debug 'netscalermoduleerror-NS Service Group disable server failed {0 }' format error ret False disconnect nitro return ret
| null | null | null | null | Question:
What does the code disable ?
Code:
def servicegroup_server_disable(sg_name, s_name, s_port, **connection_args):
ret = True
server = _servicegroup_get_server(sg_name, s_name, s_port, **connection_args)
if (server is None):
return False
nitro = _connect(**connection_args)
if (nitro is None):
return False
try:
NSServiceGroup.disable_server(nitro, server)
except NSNitroError as error:
log.debug('netscaler module error - NSServiceGroup.disable_server() failed: {0}'.format(error))
ret = False
_disconnect(nitro)
return ret
|
null | null | null | What does this function do ?
| def __qsympify_sequence_helper(seq):
if (not is_sequence(seq)):
if isinstance(seq, Matrix):
return seq
elif isinstance(seq, string_types):
return Symbol(seq)
else:
return sympify(seq)
if isinstance(seq, QExpr):
return seq
result = [__qsympify_sequence_helper(item) for item in seq]
return Tuple(*result)
| null | null | null | the actual work
| codeqa | def qsympify sequence helper seq if not is sequence seq if isinstance seq Matrix return seqelif isinstance seq string types return Symbol seq else return sympify seq if isinstance seq Q Expr return seqresult [ qsympify sequence helper item for item in seq]return Tuple *result
| null | null | null | null | Question:
What does this function do ?
Code:
def __qsympify_sequence_helper(seq):
if (not is_sequence(seq)):
if isinstance(seq, Matrix):
return seq
elif isinstance(seq, string_types):
return Symbol(seq)
else:
return sympify(seq)
if isinstance(seq, QExpr):
return seq
result = [__qsympify_sequence_helper(item) for item in seq]
return Tuple(*result)
|
null | null | null | What does the code write to a descriptor ?
| def _writen(fd, data):
while data:
n = os.write(fd, data)
data = data[n:]
| null | null | null | all the data
| codeqa | def writen fd data while data n os write fd data data data[n ]
| null | null | null | null | Question:
What does the code write to a descriptor ?
Code:
def _writen(fd, data):
while data:
n = os.write(fd, data)
data = data[n:]
|
null | null | null | What is showing the history of a given aggregate ?
| def make_history_query(cls, interval):
time_points = get_time_points(interval)
q = Session.query(cls).filter(cls.date.in_(time_points))
if hasattr(cls, 'interval'):
q = q.filter((cls.interval == interval))
q = q.order_by(desc(cls.date))
return (time_points, q)
| null | null | null | a generic query
| codeqa | def make history query cls interval time points get time points interval q Session query cls filter cls date in time points if hasattr cls 'interval' q q filter cls interval interval q q order by desc cls date return time points q
| null | null | null | null | Question:
What is showing the history of a given aggregate ?
Code:
def make_history_query(cls, interval):
time_points = get_time_points(interval)
q = Session.query(cls).filter(cls.date.in_(time_points))
if hasattr(cls, 'interval'):
q = q.filter((cls.interval == interval))
q = q.order_by(desc(cls.date))
return (time_points, q)
|
null | null | null | What does the code build ?
| def make_history_query(cls, interval):
time_points = get_time_points(interval)
q = Session.query(cls).filter(cls.date.in_(time_points))
if hasattr(cls, 'interval'):
q = q.filter((cls.interval == interval))
q = q.order_by(desc(cls.date))
return (time_points, q)
| null | null | null | a generic query showing the history of a given aggregate
| codeqa | def make history query cls interval time points get time points interval q Session query cls filter cls date in time points if hasattr cls 'interval' q q filter cls interval interval q q order by desc cls date return time points q
| null | null | null | null | Question:
What does the code build ?
Code:
def make_history_query(cls, interval):
time_points = get_time_points(interval)
q = Session.query(cls).filter(cls.date.in_(time_points))
if hasattr(cls, 'interval'):
q = q.filter((cls.interval == interval))
q = q.order_by(desc(cls.date))
return (time_points, q)
|
null | null | null | What do a generic query show ?
| def make_history_query(cls, interval):
time_points = get_time_points(interval)
q = Session.query(cls).filter(cls.date.in_(time_points))
if hasattr(cls, 'interval'):
q = q.filter((cls.interval == interval))
q = q.order_by(desc(cls.date))
return (time_points, q)
| null | null | null | the history of a given aggregate
| codeqa | def make history query cls interval time points get time points interval q Session query cls filter cls date in time points if hasattr cls 'interval' q q filter cls interval interval q q order by desc cls date return time points q
| null | null | null | null | Question:
What do a generic query show ?
Code:
def make_history_query(cls, interval):
time_points = get_time_points(interval)
q = Session.query(cls).filter(cls.date.in_(time_points))
if hasattr(cls, 'interval'):
q = q.filter((cls.interval == interval))
q = q.order_by(desc(cls.date))
return (time_points, q)
|
null | null | null | What does the code get if it does not exist ?
| def worker_get(context, **filters):
return IMPL.worker_get(context, **filters)
| null | null | null | a worker
| codeqa | def worker get context **filters return IMPL worker get context **filters
| null | null | null | null | Question:
What does the code get if it does not exist ?
Code:
def worker_get(context, **filters):
return IMPL.worker_get(context, **filters)
|
null | null | null | What does the code choose ?
| def get_datastore(session, cluster, datastore_regex=None, storage_policy=None, allowed_ds_types=ALL_SUPPORTED_DS_TYPES):
datastore_ret = session._call_method(vutil, 'get_object_property', cluster, 'datastore')
if (not datastore_ret):
raise exception.DatastoreNotFound()
data_store_mors = datastore_ret.ManagedObjectReference
data_stores = session._call_method(vim_util, 'get_properties_for_a_collection_of_objects', 'Datastore', data_store_mors, ['summary.type', 'summary.name', 'summary.capacity', 'summary.freeSpace', 'summary.accessible', 'summary.maintenanceMode'])
best_match = None
while data_stores:
best_match = _select_datastore(session, data_stores, best_match, datastore_regex, storage_policy, allowed_ds_types)
data_stores = session._call_method(vutil, 'continue_retrieval', data_stores)
if best_match:
return best_match
if storage_policy:
raise exception.DatastoreNotFound((_('Storage policy %s did not match any datastores') % storage_policy))
elif datastore_regex:
raise exception.DatastoreNotFound((_('Datastore regex %s did not match any datastores') % datastore_regex.pattern))
else:
raise exception.DatastoreNotFound()
| null | null | null | the most preferable one
| codeqa | def get datastore session cluster datastore regex None storage policy None allowed ds types ALL SUPPORTED DS TYPES datastore ret session call method vutil 'get object property' cluster 'datastore' if not datastore ret raise exception Datastore Not Found data store mors datastore ret Managed Object Referencedata stores session call method vim util 'get properties for a collection of objects' ' Datastore' data store mors ['summary type' 'summary name' 'summary capacity' 'summary free Space' 'summary accessible' 'summary maintenance Mode'] best match Nonewhile data stores best match select datastore session data stores best match datastore regex storage policy allowed ds types data stores session call method vutil 'continue retrieval' data stores if best match return best matchif storage policy raise exception Datastore Not Found ' Storagepolicy%sdidnotmatchanydatastores' % storage policy elif datastore regex raise exception Datastore Not Found ' Datastoreregex%sdidnotmatchanydatastores' % datastore regex pattern else raise exception Datastore Not Found
| null | null | null | null | Question:
What does the code choose ?
Code:
def get_datastore(session, cluster, datastore_regex=None, storage_policy=None, allowed_ds_types=ALL_SUPPORTED_DS_TYPES):
datastore_ret = session._call_method(vutil, 'get_object_property', cluster, 'datastore')
if (not datastore_ret):
raise exception.DatastoreNotFound()
data_store_mors = datastore_ret.ManagedObjectReference
data_stores = session._call_method(vim_util, 'get_properties_for_a_collection_of_objects', 'Datastore', data_store_mors, ['summary.type', 'summary.name', 'summary.capacity', 'summary.freeSpace', 'summary.accessible', 'summary.maintenanceMode'])
best_match = None
while data_stores:
best_match = _select_datastore(session, data_stores, best_match, datastore_regex, storage_policy, allowed_ds_types)
data_stores = session._call_method(vutil, 'continue_retrieval', data_stores)
if best_match:
return best_match
if storage_policy:
raise exception.DatastoreNotFound((_('Storage policy %s did not match any datastores') % storage_policy))
elif datastore_regex:
raise exception.DatastoreNotFound((_('Datastore regex %s did not match any datastores') % datastore_regex.pattern))
else:
raise exception.DatastoreNotFound()
|
null | null | null | What does the code create ?
| def create_error_model(model_name, context):
return error_models[model_name](context.call_conv)
| null | null | null | an error model instance for the given target context
| codeqa | def create error model model name context return error models[model name] context call conv
| null | null | null | null | Question:
What does the code create ?
Code:
def create_error_model(model_name, context):
return error_models[model_name](context.call_conv)
|
null | null | null | What does the code ensure ?
| def test_retry_on_normal_error(b, collect):
key_name = 'test-key-name'
k = key.Key(bucket=b, name=key_name)
collect.inject(Exception('Normal error'))
d = s3_deleter.Deleter()
d.delete(k)
while (len(collect.aborted_keys) < 2):
gevent.sleep(0.1)
assert (not collect.deleted_keys)
collect.inject(None)
d.close()
assert (collect.deleted_keys == [key_name])
| null | null | null | retries are processed for most errors
| codeqa | def test retry on normal error b collect key name 'test-key-name'k key Key bucket b name key name collect inject Exception ' Normalerror' d s3 deleter Deleter d delete k while len collect aborted keys < 2 gevent sleep 0 1 assert not collect deleted keys collect inject None d close assert collect deleted keys [key name]
| null | null | null | null | Question:
What does the code ensure ?
Code:
def test_retry_on_normal_error(b, collect):
key_name = 'test-key-name'
k = key.Key(bucket=b, name=key_name)
collect.inject(Exception('Normal error'))
d = s3_deleter.Deleter()
d.delete(k)
while (len(collect.aborted_keys) < 2):
gevent.sleep(0.1)
assert (not collect.deleted_keys)
collect.inject(None)
d.close()
assert (collect.deleted_keys == [key_name])
|
null | null | null | What do world absorb ?
| def test_world_should_be_able_to_absorb_classs():
assert (not hasattr(world, 'MyClass'))
if (sys.version_info < (2, 6)):
return
class MyClass:
pass
world.absorb(MyClass)
assert hasattr(world, 'MyClass')
assert_equals(world.MyClass, MyClass)
assert isinstance(world.MyClass(), MyClass)
world.spew('MyClass')
assert (not hasattr(world, 'MyClass'))
| null | null | null | class
| codeqa | def test world should be able to absorb classs assert not hasattr world ' My Class' if sys version info < 2 6 returnclass My Class passworld absorb My Class assert hasattr world ' My Class' assert equals world My Class My Class assert isinstance world My Class My Class world spew ' My Class' assert not hasattr world ' My Class'
| null | null | null | null | Question:
What do world absorb ?
Code:
def test_world_should_be_able_to_absorb_classs():
assert (not hasattr(world, 'MyClass'))
if (sys.version_info < (2, 6)):
return
class MyClass:
pass
world.absorb(MyClass)
assert hasattr(world, 'MyClass')
assert_equals(world.MyClass, MyClass)
assert isinstance(world.MyClass(), MyClass)
world.spew('MyClass')
assert (not hasattr(world, 'MyClass'))
|
null | null | null | What absorbs class ?
| def test_world_should_be_able_to_absorb_classs():
assert (not hasattr(world, 'MyClass'))
if (sys.version_info < (2, 6)):
return
class MyClass:
pass
world.absorb(MyClass)
assert hasattr(world, 'MyClass')
assert_equals(world.MyClass, MyClass)
assert isinstance(world.MyClass(), MyClass)
world.spew('MyClass')
assert (not hasattr(world, 'MyClass'))
| null | null | null | world
| codeqa | def test world should be able to absorb classs assert not hasattr world ' My Class' if sys version info < 2 6 returnclass My Class passworld absorb My Class assert hasattr world ' My Class' assert equals world My Class My Class assert isinstance world My Class My Class world spew ' My Class' assert not hasattr world ' My Class'
| null | null | null | null | Question:
What absorbs class ?
Code:
def test_world_should_be_able_to_absorb_classs():
assert (not hasattr(world, 'MyClass'))
if (sys.version_info < (2, 6)):
return
class MyClass:
pass
world.absorb(MyClass)
assert hasattr(world, 'MyClass')
assert_equals(world.MyClass, MyClass)
assert isinstance(world.MyClass(), MyClass)
world.spew('MyClass')
assert (not hasattr(world, 'MyClass'))
|
null | null | null | What does the code make by inserting them into a dictionary ?
| def uniquify(lst):
dct = {}
result = []
for k in lst:
if (not dct.has_key(k)):
result.append(k)
dct[k] = 1
return result
| null | null | null | the elements of a list unique
| codeqa | def uniquify lst dct {}result []for k in lst if not dct has key k result append k dct[k] 1return result
| null | null | null | null | Question:
What does the code make by inserting them into a dictionary ?
Code:
def uniquify(lst):
dct = {}
result = []
for k in lst:
if (not dct.has_key(k)):
result.append(k)
dct[k] = 1
return result
|
null | null | null | How does the code make the elements of a list unique ?
| def uniquify(lst):
dct = {}
result = []
for k in lst:
if (not dct.has_key(k)):
result.append(k)
dct[k] = 1
return result
| null | null | null | by inserting them into a dictionary
| codeqa | def uniquify lst dct {}result []for k in lst if not dct has key k result append k dct[k] 1return result
| null | null | null | null | Question:
How does the code make the elements of a list unique ?
Code:
def uniquify(lst):
dct = {}
result = []
for k in lst:
if (not dct.has_key(k)):
result.append(k)
dct[k] = 1
return result
|
null | null | null | How does operators concatenate ?
| def vstack(operators, size):
return lo.LinOp(lo.VSTACK, size, operators, None)
| null | null | null | vertically
| codeqa | def vstack operators size return lo Lin Op lo VSTACK size operators None
| null | null | null | null | Question:
How does operators concatenate ?
Code:
def vstack(operators, size):
return lo.LinOp(lo.VSTACK, size, operators, None)
|
null | null | null | What does the code create ?
| def connect_to_zookeeper(hostlist, credentials):
client = KazooClient(hostlist, timeout=5, max_retries=3, auth_data=[('digest', ':'.join(credentials))])
client.make_acl = functools.partial(make_digest_acl, *credentials)
client.start()
return client
| null | null | null | a connection to the zookeeper ensemble
| codeqa | def connect to zookeeper hostlist credentials client Kazoo Client hostlist timeout 5 max retries 3 auth data [ 'digest' ' ' join credentials ] client make acl functools partial make digest acl *credentials client start return client
| null | null | null | null | Question:
What does the code create ?
Code:
def connect_to_zookeeper(hostlist, credentials):
client = KazooClient(hostlist, timeout=5, max_retries=3, auth_data=[('digest', ':'.join(credentials))])
client.make_acl = functools.partial(make_digest_acl, *credentials)
client.start()
return client
|
null | null | null | What does the code transform ?
| def drop_first_component(X, y):
pipeline = make_pipeline(PCA(), FunctionTransformer(all_but_first_column))
(X_train, X_test, y_train, y_test) = train_test_split(X, y)
pipeline.fit(X_train, y_train)
return (pipeline.transform(X_test), y_test)
| null | null | null | the dataset
| codeqa | def drop first component X y pipeline make pipeline PCA Function Transformer all but first column X train X test y train y test train test split X y pipeline fit X train y train return pipeline transform X test y test
| null | null | null | null | Question:
What does the code transform ?
Code:
def drop_first_component(X, y):
pipeline = make_pipeline(PCA(), FunctionTransformer(all_but_first_column))
(X_train, X_test, y_train, y_test) = train_test_split(X, y)
pipeline.fit(X_train, y_train)
return (pipeline.transform(X_test), y_test)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.