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 receives buffers constantly ?
def _buffer_recv_worker(ft_client): try: for raw_buffer in ft_client.iter_raw_buffers(): ft_client._push_raw_buffer(raw_buffer) except RuntimeError as err: ft_client._recv_thread = None print ('Buffer receive thread stopped: %s' % err)
null
null
null
worker thread
codeqa
def buffer recv worker ft client try for raw buffer in ft client iter raw buffers ft client push raw buffer raw buffer except Runtime Error as err ft client recv thread Noneprint ' Bufferreceivethreadstopped %s' % err
null
null
null
null
Question: What receives buffers constantly ? Code: def _buffer_recv_worker(ft_client): try: for raw_buffer in ft_client.iter_raw_buffers(): ft_client._push_raw_buffer(raw_buffer) except RuntimeError as err: ft_client._recv_thread = None print ('Buffer receive thread stopped: %s' % err)
null
null
null
What does worker thread receive constantly ?
def _buffer_recv_worker(ft_client): try: for raw_buffer in ft_client.iter_raw_buffers(): ft_client._push_raw_buffer(raw_buffer) except RuntimeError as err: ft_client._recv_thread = None print ('Buffer receive thread stopped: %s' % err)
null
null
null
buffers
codeqa
def buffer recv worker ft client try for raw buffer in ft client iter raw buffers ft client push raw buffer raw buffer except Runtime Error as err ft client recv thread Noneprint ' Bufferreceivethreadstopped %s' % err
null
null
null
null
Question: What does worker thread receive constantly ? Code: def _buffer_recv_worker(ft_client): try: for raw_buffer in ft_client.iter_raw_buffers(): ft_client._push_raw_buffer(raw_buffer) except RuntimeError as err: ft_client._recv_thread = None print ('Buffer receive thread stopped: %s' % err)
null
null
null
When does worker thread receive buffers ?
def _buffer_recv_worker(ft_client): try: for raw_buffer in ft_client.iter_raw_buffers(): ft_client._push_raw_buffer(raw_buffer) except RuntimeError as err: ft_client._recv_thread = None print ('Buffer receive thread stopped: %s' % err)
null
null
null
constantly
codeqa
def buffer recv worker ft client try for raw buffer in ft client iter raw buffers ft client push raw buffer raw buffer except Runtime Error as err ft client recv thread Noneprint ' Bufferreceivethreadstopped %s' % err
null
null
null
null
Question: When does worker thread receive buffers ? Code: def _buffer_recv_worker(ft_client): try: for raw_buffer in ft_client.iter_raw_buffers(): ft_client._push_raw_buffer(raw_buffer) except RuntimeError as err: ft_client._recv_thread = None print ('Buffer receive thread stopped: %s' % err)
null
null
null
What does the code find within an interval ?
def bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, full_output=False, disp=True): if (not isinstance(args, tuple)): args = (args,) if (xtol <= 0): raise ValueError(('xtol too small (%g <= 0)' % xtol)) if (rtol < _rtol): raise ValueError(('rtol too small (%g < %g)' % (rtol, _rtol))) r = _zeros._bisect(f, a, b, xtol, rtol, maxiter, args, full_output, disp) return results_c(full_output, r)
null
null
null
root of a function
codeqa
def bisect f a b args xtol xtol rtol rtol maxiter iter full output False disp True if not isinstance args tuple args args if xtol < 0 raise Value Error 'xtoltoosmall %g< 0 ' % xtol if rtol < rtol raise Value Error 'rtoltoosmall %g<%g ' % rtol rtol r zeros bisect f a b xtol rtol maxiter args full output disp return results c full output r
null
null
null
null
Question: What does the code find within an interval ? Code: def bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, full_output=False, disp=True): if (not isinstance(args, tuple)): args = (args,) if (xtol <= 0): raise ValueError(('xtol too small (%g <= 0)' % xtol)) if (rtol < _rtol): raise ValueError(('rtol too small (%g < %g)' % (rtol, _rtol))) r = _zeros._bisect(f, a, b, xtol, rtol, maxiter, args, full_output, disp) return results_c(full_output, r)
null
null
null
What does the code compare with a hashed token ?
def compare_token(compare, token): (algorithm, srounds, salt, _) = compare.split(':') hashed = hash_token(token, salt=salt, rounds=int(srounds), algorithm=algorithm).encode('utf8') compare = compare.encode('utf8') if compare_digest(compare, hashed): return True return False
null
null
null
a token
codeqa
def compare token compare token algorithm srounds salt compare split ' ' hashed hash token token salt salt rounds int srounds algorithm algorithm encode 'utf 8 ' compare compare encode 'utf 8 ' if compare digest compare hashed return Truereturn False
null
null
null
null
Question: What does the code compare with a hashed token ? Code: def compare_token(compare, token): (algorithm, srounds, salt, _) = compare.split(':') hashed = hash_token(token, salt=salt, rounds=int(srounds), algorithm=algorithm).encode('utf8') compare = compare.encode('utf8') if compare_digest(compare, hashed): return True return False
null
null
null
What does the code use for comparison ?
def compare_token(compare, token): (algorithm, srounds, salt, _) = compare.split(':') hashed = hash_token(token, salt=salt, rounds=int(srounds), algorithm=algorithm).encode('utf8') compare = compare.encode('utf8') if compare_digest(compare, hashed): return True return False
null
null
null
the same algorithm and salt of the hashed token
codeqa
def compare token compare token algorithm srounds salt compare split ' ' hashed hash token token salt salt rounds int srounds algorithm algorithm encode 'utf 8 ' compare compare encode 'utf 8 ' if compare digest compare hashed return Truereturn False
null
null
null
null
Question: What does the code use for comparison ? Code: def compare_token(compare, token): (algorithm, srounds, salt, _) = compare.split(':') hashed = hash_token(token, salt=salt, rounds=int(srounds), algorithm=algorithm).encode('utf8') compare = compare.encode('utf8') if compare_digest(compare, hashed): return True return False
null
null
null
What can user vote ?
@cache_permission def can_vote_suggestion(user, translation): if (not translation.subproject.suggestion_voting): return False if translation.subproject.locked: return False project = translation.subproject.project if check_owner(user, project, 'trans.vote_suggestion'): return True if (not has_group_perm(user, 'trans.vote_suggestion', translation)): return False if (translation.is_template() and (not has_group_perm(user, 'trans.save_template', translation))): return False return True
null
null
null
suggestions on given translation
codeqa
@cache permissiondef can vote suggestion user translation if not translation subproject suggestion voting return Falseif translation subproject locked return Falseproject translation subproject projectif check owner user project 'trans vote suggestion' return Trueif not has group perm user 'trans vote suggestion' translation return Falseif translation is template and not has group perm user 'trans save template' translation return Falsereturn True
null
null
null
null
Question: What can user vote ? Code: @cache_permission def can_vote_suggestion(user, translation): if (not translation.subproject.suggestion_voting): return False if translation.subproject.locked: return False project = translation.subproject.project if check_owner(user, project, 'trans.vote_suggestion'): return True if (not has_group_perm(user, 'trans.vote_suggestion', translation)): return False if (translation.is_template() and (not has_group_perm(user, 'trans.save_template', translation))): return False return True
null
null
null
How does quotas apply ?
def create_usage_plan(name, description=None, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): try: _validate_throttle(throttle) _validate_quota(quota) values = dict(name=name) if description: values['description'] = description if throttle: values['throttle'] = throttle if quota: values['quota'] = quota conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.create_usage_plan(**values) return {'created': True, 'result': res} except ClientError as e: return {'error': salt.utils.boto3.get_error(e)} except (TypeError, ValueError) as e: return {'error': '{0}'.format(e)}
null
null
null
optionally
codeqa
def create usage plan name description None throttle None quota None region None key None keyid None profile None try validate throttle throttle validate quota quota values dict name name if description values['description'] descriptionif throttle values['throttle'] throttleif quota values['quota'] quotaconn get conn region region key key keyid keyid profile profile res conn create usage plan **values return {'created' True 'result' res}except Client Error as e return {'error' salt utils boto 3 get error e }except Type Error Value Error as e return {'error' '{ 0 }' format e }
null
null
null
null
Question: How does quotas apply ? Code: def create_usage_plan(name, description=None, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): try: _validate_throttle(throttle) _validate_quota(quota) values = dict(name=name) if description: values['description'] = description if throttle: values['throttle'] = throttle if quota: values['quota'] = quota conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.create_usage_plan(**values) return {'created': True, 'result': res} except ClientError as e: return {'error': salt.utils.boto3.get_error(e)} except (TypeError, ValueError) as e: return {'error': '{0}'.format(e)}
null
null
null
What does the code create ?
def create_usage_plan(name, description=None, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): try: _validate_throttle(throttle) _validate_quota(quota) values = dict(name=name) if description: values['description'] = description if throttle: values['throttle'] = throttle if quota: values['quota'] = quota conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.create_usage_plan(**values) return {'created': True, 'result': res} except ClientError as e: return {'error': salt.utils.boto3.get_error(e)} except (TypeError, ValueError) as e: return {'error': '{0}'.format(e)}
null
null
null
a new usage plan with throttling and quotas optionally applied
codeqa
def create usage plan name description None throttle None quota None region None key None keyid None profile None try validate throttle throttle validate quota quota values dict name name if description values['description'] descriptionif throttle values['throttle'] throttleif quota values['quota'] quotaconn get conn region region key key keyid keyid profile profile res conn create usage plan **values return {'created' True 'result' res}except Client Error as e return {'error' salt utils boto 3 get error e }except Type Error Value Error as e return {'error' '{ 0 }' format e }
null
null
null
null
Question: What does the code create ? Code: def create_usage_plan(name, description=None, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): try: _validate_throttle(throttle) _validate_quota(quota) values = dict(name=name) if description: values['description'] = description if throttle: values['throttle'] = throttle if quota: values['quota'] = quota conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = conn.create_usage_plan(**values) return {'created': True, 'result': res} except ClientError as e: return {'error': salt.utils.boto3.get_error(e)} except (TypeError, ValueError) as e: return {'error': '{0}'.format(e)}
null
null
null
How do nodes inferred by the given statement generate ?
def unpack_infer(stmt, context=None): if isinstance(stmt, (List, Tuple)): for elt in stmt.elts: for infered_elt in unpack_infer(elt, context): (yield infered_elt) return infered = next(stmt.infer(context)) if (infered is stmt): (yield infered) return for infered in stmt.infer(context): if (infered is YES): (yield infered) else: for inf_inf in unpack_infer(infered, context): (yield inf_inf)
null
null
null
recursively
codeqa
def unpack infer stmt context None if isinstance stmt List Tuple for elt in stmt elts for infered elt in unpack infer elt context yield infered elt returninfered next stmt infer context if infered is stmt yield infered returnfor infered in stmt infer context if infered is YES yield infered else for inf inf in unpack infer infered context yield inf inf
null
null
null
null
Question: How do nodes inferred by the given statement generate ? Code: def unpack_infer(stmt, context=None): if isinstance(stmt, (List, Tuple)): for elt in stmt.elts: for infered_elt in unpack_infer(elt, context): (yield infered_elt) return infered = next(stmt.infer(context)) if (infered is stmt): (yield infered) return for infered in stmt.infer(context): if (infered is YES): (yield infered) else: for inf_inf in unpack_infer(infered, context): (yield inf_inf)
null
null
null
What installed on the system ?
def net_io_counters(): with open_text(('%s/net/dev' % get_procfs_path())) as f: lines = f.readlines() retdict = {} for line in lines[2:]: colon = line.rfind(':') assert (colon > 0), repr(line) name = line[:colon].strip() fields = line[(colon + 1):].strip().split() (bytes_recv, packets_recv, errin, dropin, fifoin, framein, compressedin, multicastin, bytes_sent, packets_sent, errout, dropout, fifoout, collisionsout, carrierout, compressedout) = map(int, fields) retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv, errin, errout, dropin, dropout) return retdict
null
null
null
every network interface
codeqa
def net io counters with open text '%s/net/dev' % get procfs path as f lines f readlines retdict {}for line in lines[ 2 ] colon line rfind ' ' assert colon > 0 repr line name line[ colon] strip fields line[ colon + 1 ] strip split bytes recv packets recv errin dropin fifoin framein compressedin multicastin bytes sent packets sent errout dropout fifoout collisionsout carrierout compressedout map int fields retdict[name] bytes sent bytes recv packets sent packets recv errin errout dropin dropout return retdict
null
null
null
null
Question: What installed on the system ? Code: def net_io_counters(): with open_text(('%s/net/dev' % get_procfs_path())) as f: lines = f.readlines() retdict = {} for line in lines[2:]: colon = line.rfind(':') assert (colon > 0), repr(line) name = line[:colon].strip() fields = line[(colon + 1):].strip().split() (bytes_recv, packets_recv, errin, dropin, fifoin, framein, compressedin, multicastin, bytes_sent, packets_sent, errout, dropout, fifoout, collisionsout, carrierout, compressedout) = map(int, fields) retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv, errin, errout, dropin, dropout) return retdict
null
null
null
What did the code rename ?
def rename_doc(doctype, old, new, debug=0, force=False, merge=False, ignore_permissions=False): from frappe.model.rename_doc import rename_doc return rename_doc(doctype, old, new, force=force, merge=merge, ignore_permissions=ignore_permissions)
null
null
null
a document
codeqa
def rename doc doctype old new debug 0 force False merge False ignore permissions False from frappe model rename doc import rename docreturn rename doc doctype old new force force merge merge ignore permissions ignore permissions
null
null
null
null
Question: What did the code rename ? Code: def rename_doc(doctype, old, new, debug=0, force=False, merge=False, ignore_permissions=False): from frappe.model.rename_doc import rename_doc return rename_doc(doctype, old, new, force=force, merge=merge, ignore_permissions=ignore_permissions)
null
null
null
What does the code get ?
def getRoundedToPlaces(decimalPlaces, number): decimalPlacesRounded = max(1, int(round(decimalPlaces))) return round(number, decimalPlacesRounded)
null
null
null
number rounded to a number of decimal places
codeqa
def get Rounded To Places decimal Places number decimal Places Rounded max 1 int round decimal Places return round number decimal Places Rounded
null
null
null
null
Question: What does the code get ? Code: def getRoundedToPlaces(decimalPlaces, number): decimalPlacesRounded = max(1, int(round(decimalPlaces))) return round(number, decimalPlacesRounded)
null
null
null
What does the code get from a db ?
def get(uri): return salt.utils.sdb.sdb_get(uri, __opts__)
null
null
null
a value
codeqa
def get uri return salt utils sdb sdb get uri opts
null
null
null
null
Question: What does the code get from a db ? Code: def get(uri): return salt.utils.sdb.sdb_get(uri, __opts__)
null
null
null
What does the code calculate ?
@statfunc def mc_error(x, batches=5): if (x.ndim > 1): dims = np.shape(x) trace = np.transpose([t.ravel() for t in x]) return np.reshape([mc_error(t, batches) for t in trace], dims[1:]) else: if (batches == 1): return (np.std(x) / np.sqrt(len(x))) try: batched_traces = np.resize(x, (batches, int((len(x) / batches)))) except ValueError: resid = (len(x) % batches) new_shape = (batches, ((len(x) - resid) / batches)) batched_traces = np.resize(x[:(- resid)], new_shape) means = np.mean(batched_traces, 1) return (np.std(means) / np.sqrt(batches))
null
null
null
the simulation standard error
codeqa
@statfuncdef mc error x batches 5 if x ndim > 1 dims np shape x trace np transpose [t ravel for t in x] return np reshape [mc error t batches for t in trace] dims[ 1 ] else if batches 1 return np std x / np sqrt len x try batched traces np resize x batches int len x / batches except Value Error resid len x % batches new shape batches len x - resid / batches batched traces np resize x[ - resid ] new shape means np mean batched traces 1 return np std means / np sqrt batches
null
null
null
null
Question: What does the code calculate ? Code: @statfunc def mc_error(x, batches=5): if (x.ndim > 1): dims = np.shape(x) trace = np.transpose([t.ravel() for t in x]) return np.reshape([mc_error(t, batches) for t in trace], dims[1:]) else: if (batches == 1): return (np.std(x) / np.sqrt(len(x))) try: batched_traces = np.resize(x, (batches, int((len(x) / batches)))) except ValueError: resid = (len(x) % batches) new_shape = (batches, ((len(x) - resid) / batches)) batched_traces = np.resize(x[:(- resid)], new_shape) means = np.mean(batched_traces, 1) return (np.std(means) / np.sqrt(batches))
null
null
null
How does the code reverse the songs ?
@command('reverse\\s*(\\d{1,4})\\s*-\\s*(\\d{1,4})\\s*') def reverse_songs_range(lower, upper): (lower, upper) = (int(lower), int(upper)) if (lower > upper): (lower, upper) = (upper, lower) g.model.songs[(lower - 1):upper] = reversed(g.model.songs[(lower - 1):upper]) g.message = (((((c.y + 'Reversed range: ') + str(lower)) + '-') + str(upper)) + c.w) g.content = content.generate_songlist_display()
null
null
null
within a specified range
codeqa
@command 'reverse\\s* \\d{ 1 4} \\s*-\\s* \\d{ 1 4} \\s*' def reverse songs range lower upper lower upper int lower int upper if lower > upper lower upper upper lower g model songs[ lower - 1 upper] reversed g model songs[ lower - 1 upper] g message c y + ' Reversedrange ' + str lower + '-' + str upper + c w g content content generate songlist display
null
null
null
null
Question: How does the code reverse the songs ? Code: @command('reverse\\s*(\\d{1,4})\\s*-\\s*(\\d{1,4})\\s*') def reverse_songs_range(lower, upper): (lower, upper) = (int(lower), int(upper)) if (lower > upper): (lower, upper) = (upper, lower) g.model.songs[(lower - 1):upper] = reversed(g.model.songs[(lower - 1):upper]) g.message = (((((c.y + 'Reversed range: ') + str(lower)) + '-') + str(upper)) + c.w) g.content = content.generate_songlist_display()
null
null
null
What does the code reverse within a specified range ?
@command('reverse\\s*(\\d{1,4})\\s*-\\s*(\\d{1,4})\\s*') def reverse_songs_range(lower, upper): (lower, upper) = (int(lower), int(upper)) if (lower > upper): (lower, upper) = (upper, lower) g.model.songs[(lower - 1):upper] = reversed(g.model.songs[(lower - 1):upper]) g.message = (((((c.y + 'Reversed range: ') + str(lower)) + '-') + str(upper)) + c.w) g.content = content.generate_songlist_display()
null
null
null
the songs
codeqa
@command 'reverse\\s* \\d{ 1 4} \\s*-\\s* \\d{ 1 4} \\s*' def reverse songs range lower upper lower upper int lower int upper if lower > upper lower upper upper lower g model songs[ lower - 1 upper] reversed g model songs[ lower - 1 upper] g message c y + ' Reversedrange ' + str lower + '-' + str upper + c w g content content generate songlist display
null
null
null
null
Question: What does the code reverse within a specified range ? Code: @command('reverse\\s*(\\d{1,4})\\s*-\\s*(\\d{1,4})\\s*') def reverse_songs_range(lower, upper): (lower, upper) = (int(lower), int(upper)) if (lower > upper): (lower, upper) = (upper, lower) g.model.songs[(lower - 1):upper] = reversed(g.model.songs[(lower - 1):upper]) g.message = (((((c.y + 'Reversed range: ') + str(lower)) + '-') + str(upper)) + c.w) g.content = content.generate_songlist_display()
null
null
null
What did the code set ?
def log_to_stream(name=None, stream=None, format=None, level=None, debug=False): if (level is None): level = (logging.DEBUG if debug else logging.INFO) if (format is None): format = '%(message)s' if (stream is None): stream = sys.stderr handler = logging.StreamHandler(stream) handler.setLevel(level) handler.setFormatter(logging.Formatter(format)) logger = logging.getLogger(name) logger.setLevel(level) logger.addHandler(handler)
null
null
null
logging
codeqa
def log to stream name None stream None format None level None debug False if level is None level logging DEBUG if debug else logging INFO if format is None format '% message s'if stream is None stream sys stderrhandler logging Stream Handler stream handler set Level level handler set Formatter logging Formatter format logger logging get Logger name logger set Level level logger add Handler handler
null
null
null
null
Question: What did the code set ? Code: def log_to_stream(name=None, stream=None, format=None, level=None, debug=False): if (level is None): level = (logging.DEBUG if debug else logging.INFO) if (format is None): format = '%(message)s' if (stream is None): stream = sys.stderr handler = logging.StreamHandler(stream) handler.setLevel(level) handler.setFormatter(logging.Formatter(format)) logger = logging.getLogger(name) logger.setLevel(level) logger.addHandler(handler)
null
null
null
For what purpose does the unmet dependencies return from the perspective of the scheduler ?
def task_failed_deps(args): dag = get_dag(args) task = dag.get_task(task_id=args.task_id) ti = TaskInstance(task, args.execution_date) dep_context = DepContext(deps=SCHEDULER_DEPS) failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context)) if failed_deps: print('Task instance dependencies not met:') for dep in failed_deps: print('{}: {}'.format(dep.dep_name, dep.reason)) else: print('Task instance dependencies are all met.')
null
null
null
for a task instance
codeqa
def task failed deps args dag get dag args task dag get task task id args task id ti Task Instance task args execution date dep context Dep Context deps SCHEDULER DEPS failed deps list ti get failed dep statuses dep context dep context if failed deps print ' Taskinstancedependenciesnotmet ' for dep in failed deps print '{} {}' format dep dep name dep reason else print ' Taskinstancedependenciesareallmet '
null
null
null
null
Question: For what purpose does the unmet dependencies return from the perspective of the scheduler ? Code: def task_failed_deps(args): dag = get_dag(args) task = dag.get_task(task_id=args.task_id) ti = TaskInstance(task, args.execution_date) dep_context = DepContext(deps=SCHEDULER_DEPS) failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context)) if failed_deps: print('Task instance dependencies not met:') for dep in failed_deps: print('{}: {}'.format(dep.dep_name, dep.reason)) else: print('Task instance dependencies are all met.')
null
null
null
In which direction does the unmet dependencies return for a task instance ?
def task_failed_deps(args): dag = get_dag(args) task = dag.get_task(task_id=args.task_id) ti = TaskInstance(task, args.execution_date) dep_context = DepContext(deps=SCHEDULER_DEPS) failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context)) if failed_deps: print('Task instance dependencies not met:') for dep in failed_deps: print('{}: {}'.format(dep.dep_name, dep.reason)) else: print('Task instance dependencies are all met.')
null
null
null
from the perspective of the scheduler
codeqa
def task failed deps args dag get dag args task dag get task task id args task id ti Task Instance task args execution date dep context Dep Context deps SCHEDULER DEPS failed deps list ti get failed dep statuses dep context dep context if failed deps print ' Taskinstancedependenciesnotmet ' for dep in failed deps print '{} {}' format dep dep name dep reason else print ' Taskinstancedependenciesareallmet '
null
null
null
null
Question: In which direction does the unmet dependencies return for a task instance ? Code: def task_failed_deps(args): dag = get_dag(args) task = dag.get_task(task_id=args.task_id) ti = TaskInstance(task, args.execution_date) dep_context = DepContext(deps=SCHEDULER_DEPS) failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context)) if failed_deps: print('Task instance dependencies not met:') for dep in failed_deps: print('{}: {}'.format(dep.dep_name, dep.reason)) else: print('Task instance dependencies are all met.')
null
null
null
What does the code create on a specified network ?
def subnet_create(request, network_id, cidr, ip_version, **kwargs): LOG.debug(('subnet_create(): netid=%s, cidr=%s, ipver=%d, kwargs=%s' % (network_id, cidr, ip_version, kwargs))) body = {'subnet': {'network_id': network_id, 'ip_version': ip_version, 'cidr': cidr}} body['subnet'].update(kwargs) subnet = quantumclient(request).create_subnet(body=body).get('subnet') return Subnet(subnet)
null
null
null
a subnet
codeqa
def subnet create request network id cidr ip version **kwargs LOG debug 'subnet create netid %s cidr %s ipver %d kwargs %s' % network id cidr ip version kwargs body {'subnet' {'network id' network id 'ip version' ip version 'cidr' cidr}}body['subnet'] update kwargs subnet quantumclient request create subnet body body get 'subnet' return Subnet subnet
null
null
null
null
Question: What does the code create on a specified network ? Code: def subnet_create(request, network_id, cidr, ip_version, **kwargs): LOG.debug(('subnet_create(): netid=%s, cidr=%s, ipver=%d, kwargs=%s' % (network_id, cidr, ip_version, kwargs))) body = {'subnet': {'network_id': network_id, 'ip_version': ip_version, 'cidr': cidr}} body['subnet'].update(kwargs) subnet = quantumclient(request).create_subnet(body=body).get('subnet') return Subnet(subnet)
null
null
null
Where does the code create a subnet ?
def subnet_create(request, network_id, cidr, ip_version, **kwargs): LOG.debug(('subnet_create(): netid=%s, cidr=%s, ipver=%d, kwargs=%s' % (network_id, cidr, ip_version, kwargs))) body = {'subnet': {'network_id': network_id, 'ip_version': ip_version, 'cidr': cidr}} body['subnet'].update(kwargs) subnet = quantumclient(request).create_subnet(body=body).get('subnet') return Subnet(subnet)
null
null
null
on a specified network
codeqa
def subnet create request network id cidr ip version **kwargs LOG debug 'subnet create netid %s cidr %s ipver %d kwargs %s' % network id cidr ip version kwargs body {'subnet' {'network id' network id 'ip version' ip version 'cidr' cidr}}body['subnet'] update kwargs subnet quantumclient request create subnet body body get 'subnet' return Subnet subnet
null
null
null
null
Question: Where does the code create a subnet ? Code: def subnet_create(request, network_id, cidr, ip_version, **kwargs): LOG.debug(('subnet_create(): netid=%s, cidr=%s, ipver=%d, kwargs=%s' % (network_id, cidr, ip_version, kwargs))) body = {'subnet': {'network_id': network_id, 'ip_version': ip_version, 'cidr': cidr}} body['subnet'].update(kwargs) subnet = quantumclient(request).create_subnet(body=body).get('subnet') return Subnet(subnet)
null
null
null
What does the code create ?
def migration_create(context, values): return IMPL.migration_create(context, values)
null
null
null
a migration record
codeqa
def migration create context values return IMPL migration create context values
null
null
null
null
Question: What does the code create ? Code: def migration_create(context, values): return IMPL.migration_create(context, values)
null
null
null
What does the code create ?
def GetFunctionName(f): try: name = f.__name__ if hasattr(f, 'im_class'): name = ((f.im_class.__name__ + '.') + name) return name except: return ''
null
null
null
a formatted function string for display
codeqa
def Get Function Name f try name f name if hasattr f 'im class' name f im class name + ' ' + name return nameexcept return ''
null
null
null
null
Question: What does the code create ? Code: def GetFunctionName(f): try: name = f.__name__ if hasattr(f, 'im_class'): name = ((f.im_class.__name__ + '.') + name) return name except: return ''
null
null
null
What reads an encoded stream ?
def utf8_recoder(stream, encoding): for line in codecs.getreader(encoding)(stream): (yield line.encode('utf-8'))
null
null
null
generator
codeqa
def utf 8 recoder stream encoding for line in codecs getreader encoding stream yield line encode 'utf- 8 '
null
null
null
null
Question: What reads an encoded stream ? Code: def utf8_recoder(stream, encoding): for line in codecs.getreader(encoding)(stream): (yield line.encode('utf-8'))
null
null
null
What does generator read ?
def utf8_recoder(stream, encoding): for line in codecs.getreader(encoding)(stream): (yield line.encode('utf-8'))
null
null
null
an encoded stream
codeqa
def utf 8 recoder stream encoding for line in codecs getreader encoding stream yield line encode 'utf- 8 '
null
null
null
null
Question: What does generator read ? Code: def utf8_recoder(stream, encoding): for line in codecs.getreader(encoding)(stream): (yield line.encode('utf-8'))
null
null
null
What do a string show ?
def connection_info(): from matplotlib._pylab_helpers import Gcf result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.canvas.figure result.append('{0} - {0}'.format((fig.get_label() or 'Figure {0}'.format(manager.num)), manager.web_sockets)) if (not is_interactive()): result.append('Figures pending show: {0}'.format(len(Gcf._activeQue))) return '\n'.join(result)
null
null
null
the figure and connection status for the backend
codeqa
def connection info from matplotlib pylab helpers import Gcfresult []for manager in Gcf get all fig managers fig manager canvas figureresult append '{ 0 }-{ 0 }' format fig get label or ' Figure{ 0 }' format manager num manager web sockets if not is interactive result append ' Figurespendingshow {0 }' format len Gcf active Que return '\n' join result
null
null
null
null
Question: What do a string show ? Code: def connection_info(): from matplotlib._pylab_helpers import Gcf result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.canvas.figure result.append('{0} - {0}'.format((fig.get_label() or 'Figure {0}'.format(manager.num)), manager.web_sockets)) if (not is_interactive()): result.append('Figures pending show: {0}'.format(len(Gcf._activeQue))) return '\n'.join(result)
null
null
null
What is showing the figure and connection status for the backend ?
def connection_info(): from matplotlib._pylab_helpers import Gcf result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.canvas.figure result.append('{0} - {0}'.format((fig.get_label() or 'Figure {0}'.format(manager.num)), manager.web_sockets)) if (not is_interactive()): result.append('Figures pending show: {0}'.format(len(Gcf._activeQue))) return '\n'.join(result)
null
null
null
a string
codeqa
def connection info from matplotlib pylab helpers import Gcfresult []for manager in Gcf get all fig managers fig manager canvas figureresult append '{ 0 }-{ 0 }' format fig get label or ' Figure{ 0 }' format manager num manager web sockets if not is interactive result append ' Figurespendingshow {0 }' format len Gcf active Que return '\n' join result
null
null
null
null
Question: What is showing the figure and connection status for the backend ? Code: def connection_info(): from matplotlib._pylab_helpers import Gcf result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.canvas.figure result.append('{0} - {0}'.format((fig.get_label() or 'Figure {0}'.format(manager.num)), manager.web_sockets)) if (not is_interactive()): result.append('Figures pending show: {0}'.format(len(Gcf._activeQue))) return '\n'.join(result)
null
null
null
What purges all effects running on the caller ?
def purge_processor(caller): try: del caller.ndb.batch_stack del caller.ndb.batch_stackptr del caller.ndb.batch_pythonpath del caller.ndb.batch_batchmode except: pass if caller.ndb.batch_cmdset_backup: caller.cmdset.cmdset_stack = caller.ndb.batch_cmdset_backup caller.cmdset.update() del caller.ndb.batch_cmdset_backup else: caller.cmdset.clear() caller.scripts.validate()
null
null
null
this
codeqa
def purge processor caller try del caller ndb batch stackdel caller ndb batch stackptrdel caller ndb batch pythonpathdel caller ndb batch batchmodeexcept passif caller ndb batch cmdset backup caller cmdset cmdset stack caller ndb batch cmdset backupcaller cmdset update del caller ndb batch cmdset backupelse caller cmdset clear caller scripts validate
null
null
null
null
Question: What purges all effects running on the caller ? Code: def purge_processor(caller): try: del caller.ndb.batch_stack del caller.ndb.batch_stackptr del caller.ndb.batch_pythonpath del caller.ndb.batch_batchmode except: pass if caller.ndb.batch_cmdset_backup: caller.cmdset.cmdset_stack = caller.ndb.batch_cmdset_backup caller.cmdset.update() del caller.ndb.batch_cmdset_backup else: caller.cmdset.clear() caller.scripts.validate()
null
null
null
What does this purge ?
def purge_processor(caller): try: del caller.ndb.batch_stack del caller.ndb.batch_stackptr del caller.ndb.batch_pythonpath del caller.ndb.batch_batchmode except: pass if caller.ndb.batch_cmdset_backup: caller.cmdset.cmdset_stack = caller.ndb.batch_cmdset_backup caller.cmdset.update() del caller.ndb.batch_cmdset_backup else: caller.cmdset.clear() caller.scripts.validate()
null
null
null
all effects running on the caller
codeqa
def purge processor caller try del caller ndb batch stackdel caller ndb batch stackptrdel caller ndb batch pythonpathdel caller ndb batch batchmodeexcept passif caller ndb batch cmdset backup caller cmdset cmdset stack caller ndb batch cmdset backupcaller cmdset update del caller ndb batch cmdset backupelse caller cmdset clear caller scripts validate
null
null
null
null
Question: What does this purge ? Code: def purge_processor(caller): try: del caller.ndb.batch_stack del caller.ndb.batch_stackptr del caller.ndb.batch_pythonpath del caller.ndb.batch_batchmode except: pass if caller.ndb.batch_cmdset_backup: caller.cmdset.cmdset_stack = caller.ndb.batch_cmdset_backup caller.cmdset.update() del caller.ndb.batch_cmdset_backup else: caller.cmdset.clear() caller.scripts.validate()
null
null
null
What does the code try ?
def unmonitor(name): ret = {'result': None, 'name': name, 'comment': '', 'changes': {}} result = __salt__['monit.summary'](name) try: for (key, value) in result.items(): if ('Not monitored' in value[name]): ret['comment'] = '{0} is not being monitored.'.format(name) ret['result'] = True else: if __opts__['test']: ret['comment'] = 'Service {0} is set to be unmonitored.'.format(name) ret['result'] = None return ret __salt__['monit.unmonitor'](name) ret['comment'] = '{0} stopped being monitored.'.format(name) ret['changes'][name] = 'Not monitored' ret['result'] = True break except KeyError: ret['comment'] = '{0} not found in configuration.'.format(name) ret['result'] = False return ret
null
null
null
to see if service is being monitored
codeqa
def unmonitor name ret {'result' None 'name' name 'comment' '' 'changes' {}}result salt ['monit summary'] name try for key value in result items if ' Notmonitored' in value[name] ret['comment'] '{ 0 }isnotbeingmonitored ' format name ret['result'] Trueelse if opts ['test'] ret['comment'] ' Service{ 0 }issettobeunmonitored ' format name ret['result'] Nonereturn ret salt ['monit unmonitor'] name ret['comment'] '{ 0 }stoppedbeingmonitored ' format name ret['changes'][name] ' Notmonitored'ret['result'] Truebreakexcept Key Error ret['comment'] '{ 0 }notfoundinconfiguration ' format name ret['result'] Falsereturn ret
null
null
null
null
Question: What does the code try ? Code: def unmonitor(name): ret = {'result': None, 'name': name, 'comment': '', 'changes': {}} result = __salt__['monit.summary'](name) try: for (key, value) in result.items(): if ('Not monitored' in value[name]): ret['comment'] = '{0} is not being monitored.'.format(name) ret['result'] = True else: if __opts__['test']: ret['comment'] = 'Service {0} is set to be unmonitored.'.format(name) ret['result'] = None return ret __salt__['monit.unmonitor'](name) ret['comment'] = '{0} stopped being monitored.'.format(name) ret['changes'][name] = 'Not monitored' ret['result'] = True break except KeyError: ret['comment'] = '{0} not found in configuration.'.format(name) ret['result'] = False return ret
null
null
null
What does the code create ?
def makeZip(fileList, archive): try: a = zipfile.ZipFile(archive, u'w', zipfile.ZIP_DEFLATED, allowZip64=True) for f in fileList: a.write(f) a.close() return True except Exception as e: sickrage.srCore.srLogger.error((u'Zip creation error: %r ' % repr(e))) return False
null
null
null
a zip of files
codeqa
def make Zip file List archive try a zipfile Zip File archive u'w' zipfile ZIP DEFLATED allow Zip 64 True for f in file List a write f a close return Trueexcept Exception as e sickrage sr Core sr Logger error u' Zipcreationerror %r' % repr e return False
null
null
null
null
Question: What does the code create ? Code: def makeZip(fileList, archive): try: a = zipfile.ZipFile(archive, u'w', zipfile.ZIP_DEFLATED, allowZip64=True) for f in fileList: a.write(f) a.close() return True except Exception as e: sickrage.srCore.srLogger.error((u'Zip creation error: %r ' % repr(e))) return False
null
null
null
What has the permissions to modify a workflow or coordinator ?
def check_job_edition_permission(authorize_get=False, exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if ((job is not None) and (not (authorize_get and (request.method == 'GET')))): Job.objects.can_edit_or_exception(request, job, exception_class=exception_class) return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
the user
codeqa
def check job edition permission authorize get False exception class Popup Exception def inner view func def decorate request *args **kwargs if 'workflow' in kwargs job type 'workflow'elif 'coordinator' in kwargs job type 'coordinator'else job type 'bundle'job kwargs get job type if job is not None and not authorize get and request method 'GET' Job objects can edit or exception request job exception class exception class return view func request *args **kwargs return wraps view func decorate return inner
null
null
null
null
Question: What has the permissions to modify a workflow or coordinator ? Code: def check_job_edition_permission(authorize_get=False, exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if ((job is not None) and (not (authorize_get and (request.method == 'GET')))): Job.objects.can_edit_or_exception(request, job, exception_class=exception_class) return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
How do the user modify a workflow or coordinator ?
def check_job_edition_permission(authorize_get=False, exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if ((job is not None) and (not (authorize_get and (request.method == 'GET')))): Job.objects.can_edit_or_exception(request, job, exception_class=exception_class) return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
the permissions
codeqa
def check job edition permission authorize get False exception class Popup Exception def inner view func def decorate request *args **kwargs if 'workflow' in kwargs job type 'workflow'elif 'coordinator' in kwargs job type 'coordinator'else job type 'bundle'job kwargs get job type if job is not None and not authorize get and request method 'GET' Job objects can edit or exception request job exception class exception class return view func request *args **kwargs return wraps view func decorate return inner
null
null
null
null
Question: How do the user modify a workflow or coordinator ? Code: def check_job_edition_permission(authorize_get=False, exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if ((job is not None) and (not (authorize_get and (request.method == 'GET')))): Job.objects.can_edit_or_exception(request, job, exception_class=exception_class) return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
What has decorator ensuring ?
def check_job_edition_permission(authorize_get=False, exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if ((job is not None) and (not (authorize_get and (request.method == 'GET')))): Job.objects.can_edit_or_exception(request, job, exception_class=exception_class) return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
that the user has the permissions to modify a workflow or coordinator
codeqa
def check job edition permission authorize get False exception class Popup Exception def inner view func def decorate request *args **kwargs if 'workflow' in kwargs job type 'workflow'elif 'coordinator' in kwargs job type 'coordinator'else job type 'bundle'job kwargs get job type if job is not None and not authorize get and request method 'GET' Job objects can edit or exception request job exception class exception class return view func request *args **kwargs return wraps view func decorate return inner
null
null
null
null
Question: What has decorator ensuring ? Code: def check_job_edition_permission(authorize_get=False, exception_class=PopupException): def inner(view_func): def decorate(request, *args, **kwargs): if ('workflow' in kwargs): job_type = 'workflow' elif ('coordinator' in kwargs): job_type = 'coordinator' else: job_type = 'bundle' job = kwargs.get(job_type) if ((job is not None) and (not (authorize_get and (request.method == 'GET')))): Job.objects.can_edit_or_exception(request, job, exception_class=exception_class) return view_func(request, *args, **kwargs) return wraps(view_func)(decorate) return inner
null
null
null
What does the code detach ?
def detach(zone): ret = {'status': True} res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(zone=('-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone)))) ret['status'] = (res['retcode'] == 0) ret['message'] = (res['stdout'] if ret['status'] else res['stderr']) ret['message'] = ret['message'].replace('zoneadm: ', '') if (ret['message'] == ''): del ret['message'] return ret
null
null
null
the specified zone
codeqa
def detach zone ret {'status' True}res salt ['cmd run all'] 'zoneadm{zone}detach' format zone '-u{ 0 }' format zone if is uuid zone else '-z{ 0 }' format zone ret['status'] res['retcode'] 0 ret['message'] res['stdout'] if ret['status'] else res['stderr'] ret['message'] ret['message'] replace 'zoneadm ' '' if ret['message'] '' del ret['message']return ret
null
null
null
null
Question: What does the code detach ? Code: def detach(zone): ret = {'status': True} res = __salt__['cmd.run_all']('zoneadm {zone} detach'.format(zone=('-u {0}'.format(zone) if _is_uuid(zone) else '-z {0}'.format(zone)))) ret['status'] = (res['retcode'] == 0) ret['message'] = (res['stdout'] if ret['status'] else res['stderr']) ret['message'] = ret['message'].replace('zoneadm: ', '') if (ret['message'] == ''): del ret['message'] return ret
null
null
null
What does the code get ?
def get_token_status(token, serializer, max_age=None, return_data=False): serializer = getattr(_security, (serializer + '_serializer')) max_age = get_max_age(max_age) (user, data) = (None, None) (expired, invalid) = (False, False) try: data = serializer.loads(token, max_age=max_age) except SignatureExpired: (d, data) = serializer.loads_unsafe(token) expired = True except (BadSignature, TypeError, ValueError): invalid = True if data: user = _datastore.find_user(id=data[0]) expired = (expired and (user is not None)) if return_data: return (expired, invalid, user, data) else: return (expired, invalid, user)
null
null
null
the status of a token
codeqa
def get token status token serializer max age None return data False serializer getattr security serializer + ' serializer' max age get max age max age user data None None expired invalid False False try data serializer loads token max age max age except Signature Expired d data serializer loads unsafe token expired Trueexcept Bad Signature Type Error Value Error invalid Trueif data user datastore find user id data[ 0 ] expired expired and user is not None if return data return expired invalid user data else return expired invalid user
null
null
null
null
Question: What does the code get ? Code: def get_token_status(token, serializer, max_age=None, return_data=False): serializer = getattr(_security, (serializer + '_serializer')) max_age = get_max_age(max_age) (user, data) = (None, None) (expired, invalid) = (False, False) try: data = serializer.loads(token, max_age=max_age) except SignatureExpired: (d, data) = serializer.loads_unsafe(token) expired = True except (BadSignature, TypeError, ValueError): invalid = True if data: user = _datastore.find_user(id=data[0]) expired = (expired and (user is not None)) if return_data: return (expired, invalid, user, data) else: return (expired, invalid, user)
null
null
null
What does the code execute ?
def warn_exception(func, *args, **kwargs): try: return func(*args, **kwargs) except Exception: warn(("%s('%s') ignored" % sys.exc_info()[0:2]))
null
null
null
the given function
codeqa
def warn exception func *args **kwargs try return func *args **kwargs except Exception warn "%s '%s' ignored" % sys exc info [0 2]
null
null
null
null
Question: What does the code execute ? Code: def warn_exception(func, *args, **kwargs): try: return func(*args, **kwargs) except Exception: warn(("%s('%s') ignored" % sys.exc_info()[0:2]))
null
null
null
What did a decorator use ?
def deprecated(message=''): def decorator(fn): if ((not fn.__doc__) or (not re.search('\\bdeprecated\\b', fn.__doc__, re.IGNORECASE))): raise Exception(('Function %s() in module %s has been deprecated but this is not mentioned in the docstring. Please update the docstring for the function. It must include the word `deprecated`.' % (fn.__name__, fn.__module__))) def wrapped(*args, **kw): log.warning(('Function %s() in module %s has been deprecated and will be removed in a later release of ckan. %s' % (fn.__name__, fn.__module__, message))) return fn(*args, **kw) return wrapped return decorator
null
null
null
to mark functions as deprecated
codeqa
def deprecated message '' def decorator fn if not fn doc or not re search '\\bdeprecated\\b' fn doc re IGNORECASE raise Exception ' Function%s inmodule%shasbeendeprecatedbutthisisnotmentionedinthedocstring Pleaseupdatethedocstringforthefunction Itmustincludetheword`deprecated` ' % fn name fn module def wrapped *args **kw log warning ' Function%s inmodule%shasbeendeprecatedandwillberemovedinalaterreleaseofckan %s' % fn name fn module message return fn *args **kw return wrappedreturn decorator
null
null
null
null
Question: What did a decorator use ? Code: def deprecated(message=''): def decorator(fn): if ((not fn.__doc__) or (not re.search('\\bdeprecated\\b', fn.__doc__, re.IGNORECASE))): raise Exception(('Function %s() in module %s has been deprecated but this is not mentioned in the docstring. Please update the docstring for the function. It must include the word `deprecated`.' % (fn.__name__, fn.__module__))) def wrapped(*args, **kw): log.warning(('Function %s() in module %s has been deprecated and will be removed in a later release of ckan. %s' % (fn.__name__, fn.__module__, message))) return fn(*args, **kw) return wrapped return decorator
null
null
null
What used to mark functions as deprecated ?
def deprecated(message=''): def decorator(fn): if ((not fn.__doc__) or (not re.search('\\bdeprecated\\b', fn.__doc__, re.IGNORECASE))): raise Exception(('Function %s() in module %s has been deprecated but this is not mentioned in the docstring. Please update the docstring for the function. It must include the word `deprecated`.' % (fn.__name__, fn.__module__))) def wrapped(*args, **kw): log.warning(('Function %s() in module %s has been deprecated and will be removed in a later release of ckan. %s' % (fn.__name__, fn.__module__, message))) return fn(*args, **kw) return wrapped return decorator
null
null
null
a decorator
codeqa
def deprecated message '' def decorator fn if not fn doc or not re search '\\bdeprecated\\b' fn doc re IGNORECASE raise Exception ' Function%s inmodule%shasbeendeprecatedbutthisisnotmentionedinthedocstring Pleaseupdatethedocstringforthefunction Itmustincludetheword`deprecated` ' % fn name fn module def wrapped *args **kw log warning ' Function%s inmodule%shasbeendeprecatedandwillberemovedinalaterreleaseofckan %s' % fn name fn module message return fn *args **kw return wrappedreturn decorator
null
null
null
null
Question: What used to mark functions as deprecated ? Code: def deprecated(message=''): def decorator(fn): if ((not fn.__doc__) or (not re.search('\\bdeprecated\\b', fn.__doc__, re.IGNORECASE))): raise Exception(('Function %s() in module %s has been deprecated but this is not mentioned in the docstring. Please update the docstring for the function. It must include the word `deprecated`.' % (fn.__name__, fn.__module__))) def wrapped(*args, **kw): log.warning(('Function %s() in module %s has been deprecated and will be removed in a later release of ckan. %s' % (fn.__name__, fn.__module__, message))) return fn(*args, **kw) return wrapped return decorator
null
null
null
When does it not be there ?
def createPythonExtensionBuilder(env): try: pyext = env['BUILDERS']['PythonExtension'] except KeyError: import SCons.Action import SCons.Defaults action = SCons.Action.Action('$PYEXTLINKCOM', '$PYEXTLINKCOMSTR') action_list = [SCons.Defaults.SharedCheck, action] pyext = SCons.Builder.Builder(action=action_list, emitter='$SHLIBEMITTER', prefix='$PYEXTPREFIX', suffix='$PYEXTSUFFIX', target_scanner=ProgramScanner, src_suffix='$PYEXTOBJSUFFIX', src_builder='PythonObject') env['BUILDERS']['PythonExtension'] = pyext return pyext
null
null
null
already
codeqa
def create Python Extension Builder env try pyext env['BUILDERS'][' Python Extension']except Key Error import S Cons Actionimport S Cons Defaultsaction S Cons Action Action '$PYEXTLINKCOM' '$PYEXTLINKCOMSTR' action list [S Cons Defaults Shared Check action]pyext S Cons Builder Builder action action list emitter '$SHLIBEMITTER' prefix '$PYEXTPREFIX' suffix '$PYEXTSUFFIX' target scanner Program Scanner src suffix '$PYEXTOBJSUFFIX' src builder ' Python Object' env['BUILDERS'][' Python Extension'] pyextreturn pyext
null
null
null
null
Question: When does it not be there ? Code: def createPythonExtensionBuilder(env): try: pyext = env['BUILDERS']['PythonExtension'] except KeyError: import SCons.Action import SCons.Defaults action = SCons.Action.Action('$PYEXTLINKCOM', '$PYEXTLINKCOMSTR') action_list = [SCons.Defaults.SharedCheck, action] pyext = SCons.Builder.Builder(action=action_list, emitter='$SHLIBEMITTER', prefix='$PYEXTPREFIX', suffix='$PYEXTSUFFIX', target_scanner=ProgramScanner, src_suffix='$PYEXTOBJSUFFIX', src_builder='PythonObject') env['BUILDERS']['PythonExtension'] = pyext return pyext
null
null
null
What did the code set ?
def setLevel(level): level = level.lower().strip() imdbpyLogger.setLevel(LEVELS.get(level, logging.NOTSET)) imdbpyLogger.log(imdbpyLogger.level, 'set logging threshold to "%s"', logging.getLevelName(imdbpyLogger.level))
null
null
null
logging level
codeqa
def set Level level level level lower strip imdbpy Logger set Level LEVELS get level logging NOTSET imdbpy Logger log imdbpy Logger level 'setloggingthresholdto"%s"' logging get Level Name imdbpy Logger level
null
null
null
null
Question: What did the code set ? Code: def setLevel(level): level = level.lower().strip() imdbpyLogger.setLevel(LEVELS.get(level, logging.NOTSET)) imdbpyLogger.log(imdbpyLogger.level, 'set logging threshold to "%s"', logging.getLevelName(imdbpyLogger.level))
null
null
null
How do commands operate ?
def _do_query(lib, query, album, also_items=True): if album: albums = list(lib.albums(query)) items = [] if also_items: for al in albums: items += al.items() else: albums = [] items = list(lib.items(query)) if (album and (not albums)): raise ui.UserError('No matching albums found.') elif ((not album) and (not items)): raise ui.UserError('No matching items found.') return (items, albums)
null
null
null
on matched items
codeqa
def do query lib query album also items True if album albums list lib albums query items []if also items for al in albums items + al items else albums []items list lib items query if album and not albums raise ui User Error ' Nomatchingalbumsfound ' elif not album and not items raise ui User Error ' Nomatchingitemsfound ' return items albums
null
null
null
null
Question: How do commands operate ? Code: def _do_query(lib, query, album, also_items=True): if album: albums = list(lib.albums(query)) items = [] if also_items: for al in albums: items += al.items() else: albums = [] items = list(lib.items(query)) if (album and (not albums)): raise ui.UserError('No matching albums found.') elif ((not album) and (not items)): raise ui.UserError('No matching items found.') return (items, albums)
null
null
null
How does the code create a more useful type string ?
def typeStr(obj): typ = type(obj) if (typ == getattr(types, 'InstanceType', None)): return ('<instance of %s>' % obj.__class__.__name__) else: return str(typ)
null
null
null
by making < instance > types report their class
codeqa
def type Str obj typ type obj if typ getattr types ' Instance Type' None return '<instanceof%s>' % obj class name else return str typ
null
null
null
null
Question: How does the code create a more useful type string ? Code: def typeStr(obj): typ = type(obj) if (typ == getattr(types, 'InstanceType', None)): return ('<instance of %s>' % obj.__class__.__name__) else: return str(typ)
null
null
null
How does a random k - out graph return ?
def random_k_out_graph(n, k, alpha, self_loops=True, seed=None): if (alpha < 0): raise ValueError('alpha must be positive') random.seed(seed) G = nx.empty_graph(n, create_using=nx.MultiDiGraph()) weights = Counter({v: alpha for v in G}) for i in range((k * n)): u = random.choice([v for (v, d) in G.out_degree() if (d < k)]) if (not self_loops): adjustment = Counter({u: weights[u]}) else: adjustment = Counter() v = weighted_choice((weights - adjustment)) G.add_edge(u, v) weights[v] += 1 G.name = 'random_k_out_graph({0}, {1}, {2})'.format(n, k, alpha) return G
null
null
null
with preferential attachment
codeqa
def random k out graph n k alpha self loops True seed None if alpha < 0 raise Value Error 'alphamustbepositive' random seed seed G nx empty graph n create using nx Multi Di Graph weights Counter {v alpha for v in G} for i in range k * n u random choice [v for v d in G out degree if d < k ] if not self loops adjustment Counter {u weights[u]} else adjustment Counter v weighted choice weights - adjustment G add edge u v weights[v] + 1G name 'random k out graph {0 } {1 } {2 } ' format n k alpha return G
null
null
null
null
Question: How does a random k - out graph return ? Code: def random_k_out_graph(n, k, alpha, self_loops=True, seed=None): if (alpha < 0): raise ValueError('alpha must be positive') random.seed(seed) G = nx.empty_graph(n, create_using=nx.MultiDiGraph()) weights = Counter({v: alpha for v in G}) for i in range((k * n)): u = random.choice([v for (v, d) in G.out_degree() if (d < k)]) if (not self_loops): adjustment = Counter({u: weights[u]}) else: adjustment = Counter() v = weighted_choice((weights - adjustment)) G.add_edge(u, v) weights[v] += 1 G.name = 'random_k_out_graph({0}, {1}, {2})'.format(n, k, alpha) return G
null
null
null
What does the code return ?
def _PasswordName(user): return '{0}_pwd'.format(user)
null
null
null
the name of the password file for the specified user
codeqa
def Password Name user return '{ 0 } pwd' format user
null
null
null
null
Question: What does the code return ? Code: def _PasswordName(user): return '{0}_pwd'.format(user)
null
null
null
What does the code write ?
def _write_file_routes(iface, data, folder, pattern): filename = os.path.join(folder, pattern.format(iface)) if (not os.path.exists(folder)): msg = '{0} cannot be written. {1} does not exist' msg = msg.format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.flopen(filename, 'w') as fout: fout.write(data) __salt__['file.set_mode'](filename, '0755') return filename
null
null
null
a file to disk
codeqa
def write file routes iface data folder pattern filename os path join folder pattern format iface if not os path exists folder msg '{ 0 }cannotbewritten {1 }doesnotexist'msg msg format filename folder log error msg raise Attribute Error msg with salt utils flopen filename 'w' as fout fout write data salt ['file set mode'] filename '0755 ' return filename
null
null
null
null
Question: What does the code write ? Code: def _write_file_routes(iface, data, folder, pattern): filename = os.path.join(folder, pattern.format(iface)) if (not os.path.exists(folder)): msg = '{0} cannot be written. {1} does not exist' msg = msg.format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.flopen(filename, 'w') as fout: fout.write(data) __salt__['file.set_mode'](filename, '0755') return filename
null
null
null
What does the code remove ?
def removePrefixFromDictionary(dictionary, prefix): for key in dictionary.keys(): if key.startswith(prefix): del dictionary[key]
null
null
null
the attributes starting with the prefix from the dictionary
codeqa
def remove Prefix From Dictionary dictionary prefix for key in dictionary keys if key startswith prefix del dictionary[key]
null
null
null
null
Question: What does the code remove ? Code: def removePrefixFromDictionary(dictionary, prefix): for key in dictionary.keys(): if key.startswith(prefix): del dictionary[key]
null
null
null
What does the code add in database ?
def db_update_group(**kwargs): group_id = kwargs.pop('id') asset_id_list = kwargs.pop('asset_select') group = get_object(AssetGroup, id=group_id) for asset_id in asset_id_list: group_add_asset(group, asset_id) AssetGroup.objects.filter(id=group_id).update(**kwargs)
null
null
null
a asset group
codeqa
def db update group **kwargs group id kwargs pop 'id' asset id list kwargs pop 'asset select' group get object Asset Group id group id for asset id in asset id list group add asset group asset id Asset Group objects filter id group id update **kwargs
null
null
null
null
Question: What does the code add in database ? Code: def db_update_group(**kwargs): group_id = kwargs.pop('id') asset_id_list = kwargs.pop('asset_select') group = get_object(AssetGroup, id=group_id) for asset_id in asset_id_list: group_add_asset(group, asset_id) AssetGroup.objects.filter(id=group_id).update(**kwargs)
null
null
null
Are methods / functions implemented in the production environment ?
def NotImplementedFake(*args, **kwargs): raise NotImplementedError('This class/method is not available.')
null
null
null
No
codeqa
def Not Implemented Fake *args **kwargs raise Not Implemented Error ' Thisclass/methodisnotavailable '
null
null
null
null
Question: Are methods / functions implemented in the production environment ? Code: def NotImplementedFake(*args, **kwargs): raise NotImplementedError('This class/method is not available.')
null
null
null
Where are methods / functions not implemented ?
def NotImplementedFake(*args, **kwargs): raise NotImplementedError('This class/method is not available.')
null
null
null
in the production environment
codeqa
def Not Implemented Fake *args **kwargs raise Not Implemented Error ' Thisclass/methodisnotavailable '
null
null
null
null
Question: Where are methods / functions not implemented ? Code: def NotImplementedFake(*args, **kwargs): raise NotImplementedError('This class/method is not available.')
null
null
null
What are not implemented in the production environment ?
def NotImplementedFake(*args, **kwargs): raise NotImplementedError('This class/method is not available.')
null
null
null
methods / functions
codeqa
def Not Implemented Fake *args **kwargs raise Not Implemented Error ' Thisclass/methodisnotavailable '
null
null
null
null
Question: What are not implemented in the production environment ? Code: def NotImplementedFake(*args, **kwargs): raise NotImplementedError('This class/method is not available.')
null
null
null
What does the code call ?
def upgrade(migrate_engine): meta = sqlalchemy.MetaData() meta.bind = migrate_engine t_images = _get_table('images', meta) t_image_members = _get_table('image_members', meta) t_image_properties = _get_table('image_properties', meta) dialect = migrate_engine.url.get_dialect().name if (dialect == 'sqlite'): _upgrade_sqlite(meta, t_images, t_image_members, t_image_properties) _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties) elif (dialect == 'ibm_db_sa'): _upgrade_db2(meta, t_images, t_image_members, t_image_properties) _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties) _add_db2_constraints(meta) else: _upgrade_other(t_images, t_image_members, t_image_properties, dialect)
null
null
null
the correct dialect - specific upgrade
codeqa
def upgrade migrate engine meta sqlalchemy Meta Data meta bind migrate enginet images get table 'images' meta t image members get table 'image members' meta t image properties get table 'image properties' meta dialect migrate engine url get dialect nameif dialect 'sqlite' upgrade sqlite meta t images t image members t image properties update all ids to uuids t images t image members t image properties elif dialect 'ibm db sa' upgrade db 2 meta t images t image members t image properties update all ids to uuids t images t image members t image properties add db 2 constraints meta else upgrade other t images t image members t image properties dialect
null
null
null
null
Question: What does the code call ? Code: def upgrade(migrate_engine): meta = sqlalchemy.MetaData() meta.bind = migrate_engine t_images = _get_table('images', meta) t_image_members = _get_table('image_members', meta) t_image_properties = _get_table('image_properties', meta) dialect = migrate_engine.url.get_dialect().name if (dialect == 'sqlite'): _upgrade_sqlite(meta, t_images, t_image_members, t_image_properties) _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties) elif (dialect == 'ibm_db_sa'): _upgrade_db2(meta, t_images, t_image_members, t_image_properties) _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties) _add_db2_constraints(meta) else: _upgrade_other(t_images, t_image_members, t_image_properties, dialect)
null
null
null
What does the code remove from the handlers for event name ?
def remove_event_handler(name, func): for e in list(_events.get(name, [])): if (e.func is func): _events[name].remove(e)
null
null
null
func
codeqa
def remove event handler name func for e in list events get name [] if e func is func events[name] remove e
null
null
null
null
Question: What does the code remove from the handlers for event name ? Code: def remove_event_handler(name, func): for e in list(_events.get(name, [])): if (e.func is func): _events[name].remove(e)
null
null
null
What does the code convert into a slightly more human - friendly string with spaces and capitalized letters ?
def nameToLabel(mname): labelList = [] word = '' lastWasUpper = False for letter in mname: if (letter.isupper() == lastWasUpper): word += letter elif lastWasUpper: if (len(word) == 1): word += letter else: lastWord = word[:(-1)] firstLetter = word[(-1)] labelList.append(lastWord) word = (firstLetter + letter) else: labelList.append(word) word = letter lastWasUpper = letter.isupper() if labelList: labelList[0] = labelList[0].capitalize() else: return mname.capitalize() labelList.append(word) return ' '.join(labelList)
null
null
null
a string like a variable name
codeqa
def name To Label mname label List []word ''last Was Upper Falsefor letter in mname if letter isupper last Was Upper word + letterelif last Was Upper if len word 1 word + letterelse last Word word[ -1 ]first Letter word[ -1 ]label List append last Word word first Letter + letter else label List append word word letterlast Was Upper letter isupper if label List label List[ 0 ] label List[ 0 ] capitalize else return mname capitalize label List append word return '' join label List
null
null
null
null
Question: What does the code convert into a slightly more human - friendly string with spaces and capitalized letters ? Code: def nameToLabel(mname): labelList = [] word = '' lastWasUpper = False for letter in mname: if (letter.isupper() == lastWasUpper): word += letter elif lastWasUpper: if (len(word) == 1): word += letter else: lastWord = word[:(-1)] firstLetter = word[(-1)] labelList.append(lastWord) word = (firstLetter + letter) else: labelList.append(word) word = letter lastWasUpper = letter.isupper() if labelList: labelList[0] = labelList[0].capitalize() else: return mname.capitalize() labelList.append(word) return ' '.join(labelList)
null
null
null
What returns the path to the tarball ?
def build_sdist(py): with cd(repo_root): cmd = [py, 'setup.py', 'sdist', '--formats=gztar'] run(cmd) return glob.glob(pjoin(repo_root, 'dist', '*.tar.gz'))[0]
null
null
null
sdists
codeqa
def build sdist py with cd repo root cmd [py 'setup py' 'sdist' '--formats gztar']run cmd return glob glob pjoin repo root 'dist' '* tar gz' [0 ]
null
null
null
null
Question: What returns the path to the tarball ? Code: def build_sdist(py): with cd(repo_root): cmd = [py, 'setup.py', 'sdist', '--formats=gztar'] run(cmd) return glob.glob(pjoin(repo_root, 'dist', '*.tar.gz'))[0]
null
null
null
What does the code follow ?
def webtest_maybe_follow(response, **kw): remaining_redirects = 100 while ((300 <= response.status_int < 400) and remaining_redirects): response = response.follow(**kw) remaining_redirects -= 1 assert (remaining_redirects > 0), 'redirects chain looks infinite' return response
null
null
null
all redirects
codeqa
def webtest maybe follow response **kw remaining redirects 100 while 300 < response status int < 400 and remaining redirects response response follow **kw remaining redirects - 1assert remaining redirects > 0 'redirectschainlooksinfinite'return response
null
null
null
null
Question: What does the code follow ? Code: def webtest_maybe_follow(response, **kw): remaining_redirects = 100 while ((300 <= response.status_int < 400) and remaining_redirects): response = response.follow(**kw) remaining_redirects -= 1 assert (remaining_redirects > 0), 'redirects chain looks infinite' return response
null
null
null
What does the code calculate ?
def batch_size(batch): size = 0 for mutation in batch: size += len(mutation['key']) if ('values' in mutation): for value in mutation['values'].values(): size += len(value) return size
null
null
null
the size of a batch
codeqa
def batch size batch size 0for mutation in batch size + len mutation['key'] if 'values' in mutation for value in mutation['values'] values size + len value return size
null
null
null
null
Question: What does the code calculate ? Code: def batch_size(batch): size = 0 for mutation in batch: size += len(mutation['key']) if ('values' in mutation): for value in mutation['values'].values(): size += len(value) return size
null
null
null
What do action merge ?
def _AddActionStep(actions_dict, inputs, outputs, description, command): assert inputs action = {'inputs': inputs, 'outputs': outputs, 'description': description, 'command': command} chosen_input = inputs[0] if (chosen_input not in actions_dict): actions_dict[chosen_input] = [] actions_dict[chosen_input].append(action)
null
null
null
into an existing list of actions
codeqa
def Add Action Step actions dict inputs outputs description command assert inputsaction {'inputs' inputs 'outputs' outputs 'description' description 'command' command}chosen input inputs[ 0 ]if chosen input not in actions dict actions dict[chosen input] []actions dict[chosen input] append action
null
null
null
null
Question: What do action merge ? Code: def _AddActionStep(actions_dict, inputs, outputs, description, command): assert inputs action = {'inputs': inputs, 'outputs': outputs, 'description': description, 'command': command} chosen_input = inputs[0] if (chosen_input not in actions_dict): actions_dict[chosen_input] = [] actions_dict[chosen_input].append(action)
null
null
null
What merges into an existing list of actions ?
def _AddActionStep(actions_dict, inputs, outputs, description, command): assert inputs action = {'inputs': inputs, 'outputs': outputs, 'description': description, 'command': command} chosen_input = inputs[0] if (chosen_input not in actions_dict): actions_dict[chosen_input] = [] actions_dict[chosen_input].append(action)
null
null
null
action
codeqa
def Add Action Step actions dict inputs outputs description command assert inputsaction {'inputs' inputs 'outputs' outputs 'description' description 'command' command}chosen input inputs[ 0 ]if chosen input not in actions dict actions dict[chosen input] []actions dict[chosen input] append action
null
null
null
null
Question: What merges into an existing list of actions ? Code: def _AddActionStep(actions_dict, inputs, outputs, description, command): assert inputs action = {'inputs': inputs, 'outputs': outputs, 'description': description, 'command': command} chosen_input = inputs[0] if (chosen_input not in actions_dict): actions_dict[chosen_input] = [] actions_dict[chosen_input].append(action)
null
null
null
How do two pairs convert into a cell range string ?
def rowcol_pair_to_cellrange(row1, col1, row2, col2, row1_abs=False, col1_abs=False, row2_abs=False, col2_abs=False): assert (row1 <= row2) assert (col1 <= col2) return ((rowcol_to_cell(row1, col1, row1_abs, col1_abs) + ':') + rowcol_to_cell(row2, col2, row2_abs, col2_abs))
null
null
null
in a1:b2 notation
codeqa
def rowcol pair to cellrange row 1 col 1 row 2 col 2 row 1 abs False col 1 abs False row 2 abs False col 2 abs False assert row 1 < row 2 assert col 1 < col 2 return rowcol to cell row 1 col 1 row 1 abs col 1 abs + ' ' + rowcol to cell row 2 col 2 row 2 abs col 2 abs
null
null
null
null
Question: How do two pairs convert into a cell range string ? Code: def rowcol_pair_to_cellrange(row1, col1, row2, col2, row1_abs=False, col1_abs=False, row2_abs=False, col2_abs=False): assert (row1 <= row2) assert (col1 <= col2) return ((rowcol_to_cell(row1, col1, row1_abs, col1_abs) + ':') + rowcol_to_cell(row2, col2, row2_abs, col2_abs))
null
null
null
What do the user grant to their twitch account ?
def authenticate_twitch_oauth(): client_id = 'ewvlchtxgqq88ru9gmfp1gmyt6h2b93' redirect_uri = 'http://livestreamer.tanuki.se/en/develop/twitch_oauth.html' url = 'https://api.twitch.tv/kraken/oauth2/authorize/?response_type=token&client_id={0}&redirect_uri={1}&scope=user_read+user_subscriptions'.format(client_id, redirect_uri) console.msg('Attempting to open a browser to let you authenticate Livestreamer with Twitch') try: if (not webbrowser.open_new_tab(url)): raise webbrowser.Error except webbrowser.Error: console.exit('Unable to open a web browser, try accessing this URL manually instead:\n{0}'.format(url))
null
null
null
livestreamer access
codeqa
def authenticate twitch oauth client id 'ewvlchtxgqq 88 ru 9 gmfp 1 gmyt 6 h 2 b 93 'redirect uri 'http //livestreamer tanuki se/en/develop/twitch oauth html'url 'https //api twitch tv/kraken/oauth 2 /authorize/?response type token&client id {0 }&redirect uri {1 }&scope user read+user subscriptions' format client id redirect uri console msg ' Attemptingtoopenabrowsertoletyouauthenticate Livestreamerwith Twitch' try if not webbrowser open new tab url raise webbrowser Errorexcept webbrowser Error console exit ' Unabletoopenawebbrowser tryaccessingthis UR Lmanuallyinstead \n{ 0 }' format url
null
null
null
null
Question: What do the user grant to their twitch account ? Code: def authenticate_twitch_oauth(): client_id = 'ewvlchtxgqq88ru9gmfp1gmyt6h2b93' redirect_uri = 'http://livestreamer.tanuki.se/en/develop/twitch_oauth.html' url = 'https://api.twitch.tv/kraken/oauth2/authorize/?response_type=token&client_id={0}&redirect_uri={1}&scope=user_read+user_subscriptions'.format(client_id, redirect_uri) console.msg('Attempting to open a browser to let you authenticate Livestreamer with Twitch') try: if (not webbrowser.open_new_tab(url)): raise webbrowser.Error except webbrowser.Error: console.exit('Unable to open a web browser, try accessing this URL manually instead:\n{0}'.format(url))
null
null
null
What haves a safe representation ?
def has_safe_repr(value): if ((value is None) or (value is NotImplemented) or (value is Ellipsis)): return True if isinstance(value, ((bool, int, float, complex, range_type, Markup) + string_types)): return True if isinstance(value, (tuple, list, set, frozenset)): for item in value: if (not has_safe_repr(item)): return False return True elif isinstance(value, dict): for (key, value) in iteritems(value): if (not has_safe_repr(key)): return False if (not has_safe_repr(value)): return False return True return False
null
null
null
the node
codeqa
def has safe repr value if value is None or value is Not Implemented or value is Ellipsis return Trueif isinstance value bool int float complex range type Markup + string types return Trueif isinstance value tuple list set frozenset for item in value if not has safe repr item return Falsereturn Trueelif isinstance value dict for key value in iteritems value if not has safe repr key return Falseif not has safe repr value return Falsereturn Truereturn False
null
null
null
null
Question: What haves a safe representation ? Code: def has_safe_repr(value): if ((value is None) or (value is NotImplemented) or (value is Ellipsis)): return True if isinstance(value, ((bool, int, float, complex, range_type, Markup) + string_types)): return True if isinstance(value, (tuple, list, set, frozenset)): for item in value: if (not has_safe_repr(item)): return False return True elif isinstance(value, dict): for (key, value) in iteritems(value): if (not has_safe_repr(key)): return False if (not has_safe_repr(value)): return False return True return False
null
null
null
What does the node have ?
def has_safe_repr(value): if ((value is None) or (value is NotImplemented) or (value is Ellipsis)): return True if isinstance(value, ((bool, int, float, complex, range_type, Markup) + string_types)): return True if isinstance(value, (tuple, list, set, frozenset)): for item in value: if (not has_safe_repr(item)): return False return True elif isinstance(value, dict): for (key, value) in iteritems(value): if (not has_safe_repr(key)): return False if (not has_safe_repr(value)): return False return True return False
null
null
null
a safe representation
codeqa
def has safe repr value if value is None or value is Not Implemented or value is Ellipsis return Trueif isinstance value bool int float complex range type Markup + string types return Trueif isinstance value tuple list set frozenset for item in value if not has safe repr item return Falsereturn Trueelif isinstance value dict for key value in iteritems value if not has safe repr key return Falseif not has safe repr value return Falsereturn Truereturn False
null
null
null
null
Question: What does the node have ? Code: def has_safe_repr(value): if ((value is None) or (value is NotImplemented) or (value is Ellipsis)): return True if isinstance(value, ((bool, int, float, complex, range_type, Markup) + string_types)): return True if isinstance(value, (tuple, list, set, frozenset)): for item in value: if (not has_safe_repr(item)): return False return True elif isinstance(value, dict): for (key, value) in iteritems(value): if (not has_safe_repr(key)): return False if (not has_safe_repr(value)): return False return True return False
null
null
null
When is the job instance being executed ?
def get_current_job(connection=None): job_id = _job_stack.top if (job_id is None): return None return Job.fetch(job_id, connection=connection)
null
null
null
currently
codeqa
def get current job connection None job id job stack topif job id is None return Nonereturn Job fetch job id connection connection
null
null
null
null
Question: When is the job instance being executed ? Code: def get_current_job(connection=None): job_id = _job_stack.top if (job_id is None): return None return Job.fetch(job_id, connection=connection)
null
null
null
What do command line options override ?
def test_command_line_options_override_env_vars(script, virtualenv): script.environ['PIP_INDEX_URL'] = 'https://b.pypi.python.org/simple/' result = script.pip('install', '-vvv', 'INITools', expect_error=True) assert ('Getting page https://b.pypi.python.org/simple/initools' in result.stdout) virtualenv.clear() result = script.pip('install', '-vvv', '--index-url', 'https://download.zope.org/ppix', 'INITools', expect_error=True) assert ('b.pypi.python.org' not in result.stdout) assert ('Getting page https://download.zope.org/ppix' in result.stdout)
null
null
null
environmental variables
codeqa
def test command line options override env vars script virtualenv script environ['PIP INDEX URL'] 'https //b pypi python org/simple/'result script pip 'install' '-vvv' 'INI Tools' expect error True assert ' Gettingpagehttps //b pypi python org/simple/initools' in result stdout virtualenv clear result script pip 'install' '-vvv' '--index-url' 'https //download zope org/ppix' 'INI Tools' expect error True assert 'b pypi python org' not in result stdout assert ' Gettingpagehttps //download zope org/ppix' in result stdout
null
null
null
null
Question: What do command line options override ? Code: def test_command_line_options_override_env_vars(script, virtualenv): script.environ['PIP_INDEX_URL'] = 'https://b.pypi.python.org/simple/' result = script.pip('install', '-vvv', 'INITools', expect_error=True) assert ('Getting page https://b.pypi.python.org/simple/initools' in result.stdout) virtualenv.clear() result = script.pip('install', '-vvv', '--index-url', 'https://download.zope.org/ppix', 'INITools', expect_error=True) assert ('b.pypi.python.org' not in result.stdout) assert ('Getting page https://download.zope.org/ppix' in result.stdout)
null
null
null
What override environmental variables ?
def test_command_line_options_override_env_vars(script, virtualenv): script.environ['PIP_INDEX_URL'] = 'https://b.pypi.python.org/simple/' result = script.pip('install', '-vvv', 'INITools', expect_error=True) assert ('Getting page https://b.pypi.python.org/simple/initools' in result.stdout) virtualenv.clear() result = script.pip('install', '-vvv', '--index-url', 'https://download.zope.org/ppix', 'INITools', expect_error=True) assert ('b.pypi.python.org' not in result.stdout) assert ('Getting page https://download.zope.org/ppix' in result.stdout)
null
null
null
command line options
codeqa
def test command line options override env vars script virtualenv script environ['PIP INDEX URL'] 'https //b pypi python org/simple/'result script pip 'install' '-vvv' 'INI Tools' expect error True assert ' Gettingpagehttps //b pypi python org/simple/initools' in result stdout virtualenv clear result script pip 'install' '-vvv' '--index-url' 'https //download zope org/ppix' 'INI Tools' expect error True assert 'b pypi python org' not in result stdout assert ' Gettingpagehttps //download zope org/ppix' in result stdout
null
null
null
null
Question: What override environmental variables ? Code: def test_command_line_options_override_env_vars(script, virtualenv): script.environ['PIP_INDEX_URL'] = 'https://b.pypi.python.org/simple/' result = script.pip('install', '-vvv', 'INITools', expect_error=True) assert ('Getting page https://b.pypi.python.org/simple/initools' in result.stdout) virtualenv.clear() result = script.pip('install', '-vvv', '--index-url', 'https://download.zope.org/ppix', 'INITools', expect_error=True) assert ('b.pypi.python.org' not in result.stdout) assert ('Getting page https://download.zope.org/ppix' in result.stdout)
null
null
null
What does the code validate ?
def __validate__(config): if (not isinstance(config, dict)): return (False, 'Configuration for sh beacon must be a dictionary.') return (True, 'Valid beacon configuration')
null
null
null
the beacon configuration
codeqa
def validate config if not isinstance config dict return False ' Configurationforshbeaconmustbeadictionary ' return True ' Validbeaconconfiguration'
null
null
null
null
Question: What does the code validate ? Code: def __validate__(config): if (not isinstance(config, dict)): return (False, 'Configuration for sh beacon must be a dictionary.') return (True, 'Valid beacon configuration')
null
null
null
What does the code create ?
def WriteComponent(name='grr-rekall', version='0.4', build_system=None, modules=None, token=None, raw_data=''): components_base = 'grr.client.components.rekall_support.' if (modules is None): modules = [(components_base + 'grr_rekall')] result = rdf_client.ClientComponent(raw_data=raw_data) if build_system: result.build_system = build_system else: with utils.Stubber(platform, 'libc_ver', (lambda : ('glibc', '2.3'))): result.build_system = result.build_system.FromCurrentSystem() result.summary.modules = modules result.summary.name = name result.summary.version = version result.summary.cipher = rdf_crypto.SymmetricCipher.Generate('AES128CBC') with utils.TempDirectory() as tmp_dir: with open(os.path.join(tmp_dir, 'component'), 'wb') as fd: fd.write(result.SerializeToString()) return maintenance_utils.SignComponent(fd.name, token=token)
null
null
null
a fake component
codeqa
def Write Component name 'grr-rekall' version '0 4' build system None modules None token None raw data '' components base 'grr client components rekall support 'if modules is None modules [ components base + 'grr rekall' ]result rdf client Client Component raw data raw data if build system result build system build systemelse with utils Stubber platform 'libc ver' lambda 'glibc' '2 3' result build system result build system From Current System result summary modules modulesresult summary name nameresult summary version versionresult summary cipher rdf crypto Symmetric Cipher Generate 'AES 128 CBC' with utils Temp Directory as tmp dir with open os path join tmp dir 'component' 'wb' as fd fd write result Serialize To String return maintenance utils Sign Component fd name token token
null
null
null
null
Question: What does the code create ? Code: def WriteComponent(name='grr-rekall', version='0.4', build_system=None, modules=None, token=None, raw_data=''): components_base = 'grr.client.components.rekall_support.' if (modules is None): modules = [(components_base + 'grr_rekall')] result = rdf_client.ClientComponent(raw_data=raw_data) if build_system: result.build_system = build_system else: with utils.Stubber(platform, 'libc_ver', (lambda : ('glibc', '2.3'))): result.build_system = result.build_system.FromCurrentSystem() result.summary.modules = modules result.summary.name = name result.summary.version = version result.summary.cipher = rdf_crypto.SymmetricCipher.Generate('AES128CBC') with utils.TempDirectory() as tmp_dir: with open(os.path.join(tmp_dir, 'component'), 'wb') as fd: fd.write(result.SerializeToString()) return maintenance_utils.SignComponent(fd.name, token=token)
null
null
null
What does the code take ?
def convert_pep0(): check_paths() pep0_path = os.path.join(settings.PEP_REPO_PATH, 'pep-0000.html') pep0_content = open(pep0_path).read() soup = BeautifulSoup(pep0_content) body_children = list(soup.body.children) header = body_children[3] pep_content = body_children[7] body_links = pep_content.find_all('a') pep_href_re = re.compile('pep-(\\d+)\\.html') for b in body_links: m = pep_href_re.search(b.attrs['href']) if (not m): continue b.attrs['href'] = '/dev/peps/pep-{}/'.format(m.group(1)) header_rows = header.find_all('th') for t in header_rows: if (('Version:' in t.text) and ('N/A' in t.next_sibling.text)): t.parent.extract() return ''.join([header.prettify(), pep_content.prettify()])
null
null
null
existing generated pep-0000
codeqa
def convert pep 0 check paths pep 0 path os path join settings PEP REPO PATH 'pep- 0000 html' pep 0 content open pep 0 path read soup Beautiful Soup pep 0 content body children list soup body children header body children[ 3 ]pep content body children[ 7 ]body links pep content find all 'a' pep href re re compile 'pep- \\d+ \\ html' for b in body links m pep href re search b attrs['href'] if not m continueb attrs['href'] '/dev/peps/pep-{}/' format m group 1 header rows header find all 'th' for t in header rows if ' Version ' in t text and 'N/A' in t next sibling text t parent extract return '' join [header prettify pep content prettify ]
null
null
null
null
Question: What does the code take ? Code: def convert_pep0(): check_paths() pep0_path = os.path.join(settings.PEP_REPO_PATH, 'pep-0000.html') pep0_content = open(pep0_path).read() soup = BeautifulSoup(pep0_content) body_children = list(soup.body.children) header = body_children[3] pep_content = body_children[7] body_links = pep_content.find_all('a') pep_href_re = re.compile('pep-(\\d+)\\.html') for b in body_links: m = pep_href_re.search(b.attrs['href']) if (not m): continue b.attrs['href'] = '/dev/peps/pep-{}/'.format(m.group(1)) header_rows = header.find_all('th') for t in header_rows: if (('Version:' in t.text) and ('N/A' in t.next_sibling.text)): t.parent.extract() return ''.join([header.prettify(), pep_content.prettify()])
null
null
null
When did the code generate ?
def convert_pep0(): check_paths() pep0_path = os.path.join(settings.PEP_REPO_PATH, 'pep-0000.html') pep0_content = open(pep0_path).read() soup = BeautifulSoup(pep0_content) body_children = list(soup.body.children) header = body_children[3] pep_content = body_children[7] body_links = pep_content.find_all('a') pep_href_re = re.compile('pep-(\\d+)\\.html') for b in body_links: m = pep_href_re.search(b.attrs['href']) if (not m): continue b.attrs['href'] = '/dev/peps/pep-{}/'.format(m.group(1)) header_rows = header.find_all('th') for t in header_rows: if (('Version:' in t.text) and ('N/A' in t.next_sibling.text)): t.parent.extract() return ''.join([header.prettify(), pep_content.prettify()])
null
null
null
pep-0000
codeqa
def convert pep 0 check paths pep 0 path os path join settings PEP REPO PATH 'pep- 0000 html' pep 0 content open pep 0 path read soup Beautiful Soup pep 0 content body children list soup body children header body children[ 3 ]pep content body children[ 7 ]body links pep content find all 'a' pep href re re compile 'pep- \\d+ \\ html' for b in body links m pep href re search b attrs['href'] if not m continueb attrs['href'] '/dev/peps/pep-{}/' format m group 1 header rows header find all 'th' for t in header rows if ' Version ' in t text and 'N/A' in t next sibling text t parent extract return '' join [header prettify pep content prettify ]
null
null
null
null
Question: When did the code generate ? Code: def convert_pep0(): check_paths() pep0_path = os.path.join(settings.PEP_REPO_PATH, 'pep-0000.html') pep0_content = open(pep0_path).read() soup = BeautifulSoup(pep0_content) body_children = list(soup.body.children) header = body_children[3] pep_content = body_children[7] body_links = pep_content.find_all('a') pep_href_re = re.compile('pep-(\\d+)\\.html') for b in body_links: m = pep_href_re.search(b.attrs['href']) if (not m): continue b.attrs['href'] = '/dev/peps/pep-{}/'.format(m.group(1)) header_rows = header.find_all('th') for t in header_rows: if (('Version:' in t.text) and ('N/A' in t.next_sibling.text)): t.parent.extract() return ''.join([header.prettify(), pep_content.prettify()])
null
null
null
What contains the specified log records ?
@then('the file "{filename}" should not contain the log records') def step_file_should_not_contain_log_records(context, filename): assert context.table, 'REQUIRE: context.table' context.table.require_columns(['category', 'level', 'message']) format = getattr(context, 'log_record_format', context.config.logging_format) for row in context.table.rows: output = LogRecordTable.make_output_for_row(row, format) context.text = output step_file_should_not_contain_multiline_text(context, filename)
null
null
null
the command output
codeqa
@then 'thefile"{filename}"shouldnotcontainthelogrecords' def step file should not contain log records context filename assert context table 'REQUIRE context table'context table require columns ['category' 'level' 'message'] format getattr context 'log record format' context config logging format for row in context table rows output Log Record Table make output for row row format context text outputstep file should not contain multiline text context filename
null
null
null
null
Question: What contains the specified log records ? Code: @then('the file "{filename}" should not contain the log records') def step_file_should_not_contain_log_records(context, filename): assert context.table, 'REQUIRE: context.table' context.table.require_columns(['category', 'level', 'message']) format = getattr(context, 'log_record_format', context.config.logging_format) for row in context.table.rows: output = LogRecordTable.make_output_for_row(row, format) context.text = output step_file_should_not_contain_multiline_text(context, filename)
null
null
null
What does the command output contain ?
@then('the file "{filename}" should not contain the log records') def step_file_should_not_contain_log_records(context, filename): assert context.table, 'REQUIRE: context.table' context.table.require_columns(['category', 'level', 'message']) format = getattr(context, 'log_record_format', context.config.logging_format) for row in context.table.rows: output = LogRecordTable.make_output_for_row(row, format) context.text = output step_file_should_not_contain_multiline_text(context, filename)
null
null
null
the specified log records
codeqa
@then 'thefile"{filename}"shouldnotcontainthelogrecords' def step file should not contain log records context filename assert context table 'REQUIRE context table'context table require columns ['category' 'level' 'message'] format getattr context 'log record format' context config logging format for row in context table rows output Log Record Table make output for row row format context text outputstep file should not contain multiline text context filename
null
null
null
null
Question: What does the command output contain ? Code: @then('the file "{filename}" should not contain the log records') def step_file_should_not_contain_log_records(context, filename): assert context.table, 'REQUIRE: context.table' context.table.require_columns(['category', 'level', 'message']) format = getattr(context, 'log_record_format', context.config.logging_format) for row in context.table.rows: output = LogRecordTable.make_output_for_row(row, format) context.text = output step_file_should_not_contain_multiline_text(context, filename)
null
null
null
What does the code add ?
def filter_access_token(interaction, current_cassette): request_uri = interaction.data['request']['uri'] response = interaction.data['response'] if (('api/v1/access_token' not in request_uri) or (response['status']['code'] != 200)): return body = response['body']['string'] try: token = json.loads(body)['access_token'] except (KeyError, TypeError, ValueError): return current_cassette.placeholders.append(betamax.cassette.cassette.Placeholder(placeholder='<ACCESS_TOKEN>', replace=token))
null
null
null
betamax placeholder to filter access token
codeqa
def filter access token interaction current cassette request uri interaction data['request']['uri']response interaction data['response']if 'api/v 1 /access token' not in request uri or response['status']['code'] 200 returnbody response['body']['string']try token json loads body ['access token']except Key Error Type Error Value Error returncurrent cassette placeholders append betamax cassette cassette Placeholder placeholder '<ACCESS TOKEN>' replace token
null
null
null
null
Question: What does the code add ? Code: def filter_access_token(interaction, current_cassette): request_uri = interaction.data['request']['uri'] response = interaction.data['response'] if (('api/v1/access_token' not in request_uri) or (response['status']['code'] != 200)): return body = response['body']['string'] try: token = json.loads(body)['access_token'] except (KeyError, TypeError, ValueError): return current_cassette.placeholders.append(betamax.cassette.cassette.Placeholder(placeholder='<ACCESS_TOKEN>', replace=token))
null
null
null
What does the code get ?
def latestFunction(oldFunc): dictID = id(oldFunc.func_globals) module = _modDictIDMap.get(dictID) if (module is None): return oldFunc return getattr(module, oldFunc.__name__)
null
null
null
the latest version of a function
codeqa
def latest Function old Func dict ID id old Func func globals module mod Dict ID Map get dict ID if module is None return old Funcreturn getattr module old Func name
null
null
null
null
Question: What does the code get ? Code: def latestFunction(oldFunc): dictID = id(oldFunc.func_globals) module = _modDictIDMap.get(dictID) if (module is None): return oldFunc return getattr(module, oldFunc.__name__)
null
null
null
How does the code send the draft ?
def send_draft(account, draft, db_session): update_draft_on_send(account, draft, db_session) response_on_success = APIEncoder().jsonify(draft) try: sendmail_client = get_sendmail_client(account) sendmail_client.send(draft) except SendMailException as exc: kwargs = {} if exc.failures: kwargs['failures'] = exc.failures if exc.server_error: kwargs['server_error'] = exc.server_error return err(exc.http_code, exc.message, **kwargs) return response_on_success
null
null
null
with i d = draft_id
codeqa
def send draft account draft db session update draft on send account draft db session response on success API Encoder jsonify draft try sendmail client get sendmail client account sendmail client send draft except Send Mail Exception as exc kwargs {}if exc failures kwargs['failures'] exc failuresif exc server error kwargs['server error'] exc server errorreturn err exc http code exc message **kwargs return response on success
null
null
null
null
Question: How does the code send the draft ? Code: def send_draft(account, draft, db_session): update_draft_on_send(account, draft, db_session) response_on_success = APIEncoder().jsonify(draft) try: sendmail_client = get_sendmail_client(account) sendmail_client.send(draft) except SendMailException as exc: kwargs = {} if exc.failures: kwargs['failures'] = exc.failures if exc.server_error: kwargs['server_error'] = exc.server_error return err(exc.http_code, exc.message, **kwargs) return response_on_success
null
null
null
What does the code send with i d = draft_id ?
def send_draft(account, draft, db_session): update_draft_on_send(account, draft, db_session) response_on_success = APIEncoder().jsonify(draft) try: sendmail_client = get_sendmail_client(account) sendmail_client.send(draft) except SendMailException as exc: kwargs = {} if exc.failures: kwargs['failures'] = exc.failures if exc.server_error: kwargs['server_error'] = exc.server_error return err(exc.http_code, exc.message, **kwargs) return response_on_success
null
null
null
the draft
codeqa
def send draft account draft db session update draft on send account draft db session response on success API Encoder jsonify draft try sendmail client get sendmail client account sendmail client send draft except Send Mail Exception as exc kwargs {}if exc failures kwargs['failures'] exc failuresif exc server error kwargs['server error'] exc server errorreturn err exc http code exc message **kwargs return response on success
null
null
null
null
Question: What does the code send with i d = draft_id ? Code: def send_draft(account, draft, db_session): update_draft_on_send(account, draft, db_session) response_on_success = APIEncoder().jsonify(draft) try: sendmail_client = get_sendmail_client(account) sendmail_client.send(draft) except SendMailException as exc: kwargs = {} if exc.failures: kwargs['failures'] = exc.failures if exc.server_error: kwargs['server_error'] = exc.server_error return err(exc.http_code, exc.message, **kwargs) return response_on_success
null
null
null
What does the code invert into a dictionary with pairs flipped ?
def invert_unique(d, check=True): if check: assert (len(set(d.values())) == len(d)), 'Values were not unique!' return {v: k for (k, v) in iteritems(d)}
null
null
null
a dictionary with unique values
codeqa
def invert unique d check True if check assert len set d values len d ' Valueswerenotunique 'return {v k for k v in iteritems d }
null
null
null
null
Question: What does the code invert into a dictionary with pairs flipped ? Code: def invert_unique(d, check=True): if check: assert (len(set(d.values())) == len(d)), 'Values were not unique!' return {v: k for (k, v) in iteritems(d)}
null
null
null
How do a table with missing data read ?
@pytest.mark.skipif('not HAS_BEAUTIFUL_SOUP') def test_missing_data(): table_in = ['<table>', '<tr><th>A</th></tr>', '<tr><td></td></tr>', '<tr><td>1</td></tr>', '</table>'] dat = Table.read(table_in, format='ascii.html') assert (dat.masked is True) assert np.all((dat['A'].mask == [True, False])) assert (dat['A'].dtype.kind == 'i') table_in = ['<table>', '<tr><th>A</th></tr>', '<tr><td>...</td></tr>', '<tr><td>1</td></tr>', '</table>'] dat = Table.read(table_in, format='ascii.html', fill_values=[('...', '0')]) assert (dat.masked is True) assert np.all((dat['A'].mask == [True, False])) assert (dat['A'].dtype.kind == 'i')
null
null
null
test
codeqa
@pytest mark skipif 'not HAS BEAUTIFUL SOUP' def test missing data table in ['<table>' '<tr><th>A</th></tr>' '<tr><td></td></tr>' '<tr><td> 1 </td></tr>' '</table>']dat Table read table in format 'ascii html' assert dat masked is True assert np all dat['A'] mask [ True False] assert dat['A'] dtype kind 'i' table in ['<table>' '<tr><th>A</th></tr>' '<tr><td> </td></tr>' '<tr><td> 1 </td></tr>' '</table>']dat Table read table in format 'ascii html' fill values [ ' ' '0 ' ] assert dat masked is True assert np all dat['A'] mask [ True False] assert dat['A'] dtype kind 'i'
null
null
null
null
Question: How do a table with missing data read ? Code: @pytest.mark.skipif('not HAS_BEAUTIFUL_SOUP') def test_missing_data(): table_in = ['<table>', '<tr><th>A</th></tr>', '<tr><td></td></tr>', '<tr><td>1</td></tr>', '</table>'] dat = Table.read(table_in, format='ascii.html') assert (dat.masked is True) assert np.all((dat['A'].mask == [True, False])) assert (dat['A'].dtype.kind == 'i') table_in = ['<table>', '<tr><th>A</th></tr>', '<tr><td>...</td></tr>', '<tr><td>1</td></tr>', '</table>'] dat = Table.read(table_in, format='ascii.html', fill_values=[('...', '0')]) assert (dat.masked is True) assert np.all((dat['A'].mask == [True, False])) assert (dat['A'].dtype.kind == 'i')
null
null
null
What does the code get ?
def get_object_properties(vim, collector, mobj, type, properties): client_factory = vim.client.factory if (mobj is None): return None usecoll = collector if (usecoll is None): usecoll = vim.service_content.propertyCollector property_filter_spec = client_factory.create('ns0:PropertyFilterSpec') property_spec = client_factory.create('ns0:PropertySpec') property_spec.all = ((properties is None) or (len(properties) == 0)) property_spec.pathSet = properties property_spec.type = type object_spec = client_factory.create('ns0:ObjectSpec') object_spec.obj = mobj object_spec.skip = False property_filter_spec.propSet = [property_spec] property_filter_spec.objectSet = [object_spec] options = client_factory.create('ns0:RetrieveOptions') options.maxObjects = CONF.vmware.maximum_objects return vim.RetrievePropertiesEx(usecoll, specSet=[property_filter_spec], options=options)
null
null
null
the properties of the managed object specified
codeqa
def get object properties vim collector mobj type properties client factory vim client factoryif mobj is None return Noneusecoll collectorif usecoll is None usecoll vim service content property Collectorproperty filter spec client factory create 'ns 0 Property Filter Spec' property spec client factory create 'ns 0 Property Spec' property spec all properties is None or len properties 0 property spec path Set propertiesproperty spec type typeobject spec client factory create 'ns 0 Object Spec' object spec obj mobjobject spec skip Falseproperty filter spec prop Set [property spec]property filter spec object Set [object spec]options client factory create 'ns 0 Retrieve Options' options max Objects CONF vmware maximum objectsreturn vim Retrieve Properties Ex usecoll spec Set [property filter spec] options options
null
null
null
null
Question: What does the code get ? Code: def get_object_properties(vim, collector, mobj, type, properties): client_factory = vim.client.factory if (mobj is None): return None usecoll = collector if (usecoll is None): usecoll = vim.service_content.propertyCollector property_filter_spec = client_factory.create('ns0:PropertyFilterSpec') property_spec = client_factory.create('ns0:PropertySpec') property_spec.all = ((properties is None) or (len(properties) == 0)) property_spec.pathSet = properties property_spec.type = type object_spec = client_factory.create('ns0:ObjectSpec') object_spec.obj = mobj object_spec.skip = False property_filter_spec.propSet = [property_spec] property_filter_spec.objectSet = [object_spec] options = client_factory.create('ns0:RetrieveOptions') options.maxObjects = CONF.vmware.maximum_objects return vim.RetrievePropertiesEx(usecoll, specSet=[property_filter_spec], options=options)
null
null
null
What does the code create ?
def meta_kw_extractor(index, msg_mid, msg, msg_size, msg_ts, **kwargs): if (msg_size <= 0): return [] return [('%s:ln2sz' % int(math.log(msg_size, 2)))]
null
null
null
a search term with the floored log2 size of the message
codeqa
def meta kw extractor index msg mid msg msg size msg ts **kwargs if msg size < 0 return []return [ '%s ln 2 sz' % int math log msg size 2 ]
null
null
null
null
Question: What does the code create ? Code: def meta_kw_extractor(index, msg_mid, msg, msg_size, msg_ts, **kwargs): if (msg_size <= 0): return [] return [('%s:ln2sz' % int(math.log(msg_size, 2)))]
null
null
null
What does the code make ?
def patternbroadcast(x, broadcastable): rval = Rebroadcast(*[(i, broadcastable[i]) for i in xrange(len(broadcastable))])(x) return theano.tensor.opt.apply_rebroadcast_opt(rval)
null
null
null
the input adopt a specific broadcasting pattern
codeqa
def patternbroadcast x broadcastable rval Rebroadcast *[ i broadcastable[i] for i in xrange len broadcastable ] x return theano tensor opt apply rebroadcast opt rval
null
null
null
null
Question: What does the code make ? Code: def patternbroadcast(x, broadcastable): rval = Rebroadcast(*[(i, broadcastable[i]) for i in xrange(len(broadcastable))])(x) return theano.tensor.opt.apply_rebroadcast_opt(rval)
null
null
null
What adopts a specific broadcasting pattern ?
def patternbroadcast(x, broadcastable): rval = Rebroadcast(*[(i, broadcastable[i]) for i in xrange(len(broadcastable))])(x) return theano.tensor.opt.apply_rebroadcast_opt(rval)
null
null
null
the input
codeqa
def patternbroadcast x broadcastable rval Rebroadcast *[ i broadcastable[i] for i in xrange len broadcastable ] x return theano tensor opt apply rebroadcast opt rval
null
null
null
null
Question: What adopts a specific broadcasting pattern ? Code: def patternbroadcast(x, broadcastable): rval = Rebroadcast(*[(i, broadcastable[i]) for i in xrange(len(broadcastable))])(x) return theano.tensor.opt.apply_rebroadcast_opt(rval)
null
null
null
Can it find the supplied directory ?
def test_patch_returns_error_on_invalid_dir(): from gooey.gui import image_repository with pytest.raises(IOError) as kaboom: image_repository.patch_images('foo/bar/not/a/path') assert (' user supplied' in str(kaboom.value)) assert ('foo/bar/not/a/path' in str(kaboom.value))
null
null
null
No
codeqa
def test patch returns error on invalid dir from gooey gui import image repositorywith pytest raises IO Error as kaboom image repository patch images 'foo/bar/not/a/path' assert 'usersupplied' in str kaboom value assert 'foo/bar/not/a/path' in str kaboom value
null
null
null
null
Question: Can it find the supplied directory ? Code: def test_patch_returns_error_on_invalid_dir(): from gooey.gui import image_repository with pytest.raises(IOError) as kaboom: image_repository.patch_images('foo/bar/not/a/path') assert (' user supplied' in str(kaboom.value)) assert ('foo/bar/not/a/path' in str(kaboom.value))
null
null
null
What can it not find ?
def test_patch_returns_error_on_invalid_dir(): from gooey.gui import image_repository with pytest.raises(IOError) as kaboom: image_repository.patch_images('foo/bar/not/a/path') assert (' user supplied' in str(kaboom.value)) assert ('foo/bar/not/a/path' in str(kaboom.value))
null
null
null
the supplied directory
codeqa
def test patch returns error on invalid dir from gooey gui import image repositorywith pytest raises IO Error as kaboom image repository patch images 'foo/bar/not/a/path' assert 'usersupplied' in str kaboom value assert 'foo/bar/not/a/path' in str kaboom value
null
null
null
null
Question: What can it not find ? Code: def test_patch_returns_error_on_invalid_dir(): from gooey.gui import image_repository with pytest.raises(IOError) as kaboom: image_repository.patch_images('foo/bar/not/a/path') assert (' user supplied' in str(kaboom.value)) assert ('foo/bar/not/a/path' in str(kaboom.value))
null
null
null
How did ellipse bound ?
def _ellipse_in_shape(shape, center, radii, rotation=0.0): (r_lim, c_lim) = np.ogrid[0:float(shape[0]), 0:float(shape[1])] (r_org, c_org) = center (r_rad, c_rad) = radii rotation %= np.pi (sin_alpha, cos_alpha) = (np.sin(rotation), np.cos(rotation)) (r, c) = ((r_lim - r_org), (c_lim - c_org)) distances = (((((r * cos_alpha) + (c * sin_alpha)) / r_rad) ** 2) + ((((r * sin_alpha) - (c * cos_alpha)) / c_rad) ** 2)) return np.nonzero((distances < 1))
null
null
null
by shape
codeqa
def ellipse in shape shape center radii rotation 0 0 r lim c lim np ogrid[ 0 float shape[ 0 ] 0 float shape[ 1 ] ] r org c org center r rad c rad radiirotation % np pi sin alpha cos alpha np sin rotation np cos rotation r c r lim - r org c lim - c org distances r * cos alpha + c * sin alpha / r rad ** 2 + r * sin alpha - c * cos alpha / c rad ** 2 return np nonzero distances < 1
null
null
null
null
Question: How did ellipse bound ? Code: def _ellipse_in_shape(shape, center, radii, rotation=0.0): (r_lim, c_lim) = np.ogrid[0:float(shape[0]), 0:float(shape[1])] (r_org, c_org) = center (r_rad, c_rad) = radii rotation %= np.pi (sin_alpha, cos_alpha) = (np.sin(rotation), np.cos(rotation)) (r, c) = ((r_lim - r_org), (c_lim - c_org)) distances = (((((r * cos_alpha) + (c * sin_alpha)) / r_rad) ** 2) + ((((r * sin_alpha) - (c * cos_alpha)) / c_rad) ** 2)) return np.nonzero((distances < 1))
null
null
null
How do a signal skip ?
@contextmanager def skip_signal(signal, **kwargs): signal.disconnect(**kwargs) (yield) signal.connect(**kwargs)
null
null
null
by disconnecting it
codeqa
@contextmanagerdef skip signal signal **kwargs signal disconnect **kwargs yield signal connect **kwargs
null
null
null
null
Question: How do a signal skip ? Code: @contextmanager def skip_signal(signal, **kwargs): signal.disconnect(**kwargs) (yield) signal.connect(**kwargs)
null
null
null
What does the code build into a configuration object ?
def buildConfiguration(config_dict, dirpath='.'): (scheme, h, path, p, q, f) = urlparse(dirpath) if (scheme in ('', 'file')): sys.path.insert(0, path) cache_dict = config_dict.get('cache', {}) cache = _parseConfigCache(cache_dict, dirpath) config = Configuration(cache, dirpath) for (name, layer_dict) in config_dict.get('layers', {}).items(): config.layers[name] = _parseConfigLayer(layer_dict, config, dirpath) if ('index' in config_dict): index_href = urljoin(dirpath, config_dict['index']) index_body = urlopen(index_href).read() index_type = guess_type(index_href) config.index = (index_type[0], index_body) if ('logging' in config_dict): level = config_dict['logging'].upper() if hasattr(logging, level): logging.basicConfig(level=getattr(logging, level)) return config
null
null
null
a configuration dictionary
codeqa
def build Configuration config dict dirpath ' ' scheme h path p q f urlparse dirpath if scheme in '' 'file' sys path insert 0 path cache dict config dict get 'cache' {} cache parse Config Cache cache dict dirpath config Configuration cache dirpath for name layer dict in config dict get 'layers' {} items config layers[name] parse Config Layer layer dict config dirpath if 'index' in config dict index href urljoin dirpath config dict['index'] index body urlopen index href read index type guess type index href config index index type[ 0 ] index body if 'logging' in config dict level config dict['logging'] upper if hasattr logging level logging basic Config level getattr logging level return config
null
null
null
null
Question: What does the code build into a configuration object ? Code: def buildConfiguration(config_dict, dirpath='.'): (scheme, h, path, p, q, f) = urlparse(dirpath) if (scheme in ('', 'file')): sys.path.insert(0, path) cache_dict = config_dict.get('cache', {}) cache = _parseConfigCache(cache_dict, dirpath) config = Configuration(cache, dirpath) for (name, layer_dict) in config_dict.get('layers', {}).items(): config.layers[name] = _parseConfigLayer(layer_dict, config, dirpath) if ('index' in config_dict): index_href = urljoin(dirpath, config_dict['index']) index_body = urlopen(index_href).read() index_type = guess_type(index_href) config.index = (index_type[0], index_body) if ('logging' in config_dict): level = config_dict['logging'].upper() if hasattr(logging, level): logging.basicConfig(level=getattr(logging, level)) return config
null
null
null
What does the code load from the path ?
def loadExperiment(path): if (not os.path.isdir(path)): path = os.path.dirname(path) descriptionPyModule = loadExperimentDescriptionScriptFromDir(path) expIface = getExperimentDescriptionInterfaceFromModule(descriptionPyModule) return (expIface.getModelDescription(), expIface.getModelControl())
null
null
null
the experiment description file
codeqa
def load Experiment path if not os path isdir path path os path dirname path description Py Module load Experiment Description Script From Dir path exp Iface get Experiment Description Interface From Module description Py Module return exp Iface get Model Description exp Iface get Model Control
null
null
null
null
Question: What does the code load from the path ? Code: def loadExperiment(path): if (not os.path.isdir(path)): path = os.path.dirname(path) descriptionPyModule = loadExperimentDescriptionScriptFromDir(path) expIface = getExperimentDescriptionInterfaceFromModule(descriptionPyModule) return (expIface.getModelDescription(), expIface.getModelControl())
null
null
null
What does this return ?
def get_nova_objects(): all_classes = base.NovaObjectRegistry.obj_classes() nova_classes = {} for name in all_classes: objclasses = all_classes[name] if (objclasses[0].OBJ_PROJECT_NAMESPACE != base.NovaObject.OBJ_PROJECT_NAMESPACE): continue nova_classes[name] = objclasses return nova_classes
null
null
null
a dict of versioned objects which are in the nova project namespace only
codeqa
def get nova objects all classes base Nova Object Registry obj classes nova classes {}for name in all classes objclasses all classes[name]if objclasses[ 0 ] OBJ PROJECT NAMESPACE base Nova Object OBJ PROJECT NAMESPACE continuenova classes[name] objclassesreturn nova classes
null
null
null
null
Question: What does this return ? Code: def get_nova_objects(): all_classes = base.NovaObjectRegistry.obj_classes() nova_classes = {} for name in all_classes: objclasses = all_classes[name] if (objclasses[0].OBJ_PROJECT_NAMESPACE != base.NovaObject.OBJ_PROJECT_NAMESPACE): continue nova_classes[name] = objclasses return nova_classes
null
null
null
What does the code get ?
def get_nova_objects(): all_classes = base.NovaObjectRegistry.obj_classes() nova_classes = {} for name in all_classes: objclasses = all_classes[name] if (objclasses[0].OBJ_PROJECT_NAMESPACE != base.NovaObject.OBJ_PROJECT_NAMESPACE): continue nova_classes[name] = objclasses return nova_classes
null
null
null
nova versioned objects
codeqa
def get nova objects all classes base Nova Object Registry obj classes nova classes {}for name in all classes objclasses all classes[name]if objclasses[ 0 ] OBJ PROJECT NAMESPACE base Nova Object OBJ PROJECT NAMESPACE continuenova classes[name] objclassesreturn nova classes
null
null
null
null
Question: What does the code get ? Code: def get_nova_objects(): all_classes = base.NovaObjectRegistry.obj_classes() nova_classes = {} for name in all_classes: objclasses = all_classes[name] if (objclasses[0].OBJ_PROJECT_NAMESPACE != base.NovaObject.OBJ_PROJECT_NAMESPACE): continue nova_classes[name] = objclasses return nova_classes
null
null
null
What returns a dict of versioned objects which are in the nova project namespace only ?
def get_nova_objects(): all_classes = base.NovaObjectRegistry.obj_classes() nova_classes = {} for name in all_classes: objclasses = all_classes[name] if (objclasses[0].OBJ_PROJECT_NAMESPACE != base.NovaObject.OBJ_PROJECT_NAMESPACE): continue nova_classes[name] = objclasses return nova_classes
null
null
null
this
codeqa
def get nova objects all classes base Nova Object Registry obj classes nova classes {}for name in all classes objclasses all classes[name]if objclasses[ 0 ] OBJ PROJECT NAMESPACE base Nova Object OBJ PROJECT NAMESPACE continuenova classes[name] objclassesreturn nova classes
null
null
null
null
Question: What returns a dict of versioned objects which are in the nova project namespace only ? Code: def get_nova_objects(): all_classes = base.NovaObjectRegistry.obj_classes() nova_classes = {} for name in all_classes: objclasses = all_classes[name] if (objclasses[0].OBJ_PROJECT_NAMESPACE != base.NovaObject.OBJ_PROJECT_NAMESPACE): continue nova_classes[name] = objclasses return nova_classes
null
null
null
Does the code add the numbers a and b add ?
def add(a, b): return (a + b)
null
null
null
No
codeqa
def add a b return a + b
null
null
null
null
Question: Does the code add the numbers a and b add ? Code: def add(a, b): return (a + b)
null
null
null
For what purpose do a transfer function register ?
def register_transfer(fn): transfer._others.append(fn)
null
null
null
for alternative targets
codeqa
def register transfer fn transfer others append fn
null
null
null
null
Question: For what purpose do a transfer function register ? Code: def register_transfer(fn): transfer._others.append(fn)
null
null
null
What does the code get by flavor i d ?
def instance_type_get_by_flavor_id(context, id): return IMPL.instance_type_get_by_flavor_id(context, id)
null
null
null
instance type
codeqa
def instance type get by flavor id context id return IMPL instance type get by flavor id context id
null
null
null
null
Question: What does the code get by flavor i d ? Code: def instance_type_get_by_flavor_id(context, id): return IMPL.instance_type_get_by_flavor_id(context, id)
null
null
null
What does the code write to the socket ?
def _net_write(sock, data, expiration): current = 0 l = len(data) while (current < l): _wait_for_writable(sock, expiration) current += sock.send(data[current:])
null
null
null
the specified data
codeqa
def net write sock data expiration current 0l len data while current < l wait for writable sock expiration current + sock send data[current ]
null
null
null
null
Question: What does the code write to the socket ? Code: def _net_write(sock, data, expiration): current = 0 l = len(data) while (current < l): _wait_for_writable(sock, expiration) current += sock.send(data[current:])
null
null
null
What do format options return then ?
def _val_or_dict(tk, options, *args): options = _format_optdict(options) res = tk.call(*(args + options)) if (len(options) % 2): return res return _dict_from_tcltuple(tk.splitlist(res))
null
null
null
the appropriate result
codeqa
def val or dict tk options *args options format optdict options res tk call * args + options if len options % 2 return resreturn dict from tcltuple tk splitlist res
null
null
null
null
Question: What do format options return then ? Code: def _val_or_dict(tk, options, *args): options = _format_optdict(options) res = tk.call(*(args + options)) if (len(options) % 2): return res return _dict_from_tcltuple(tk.splitlist(res))
null
null
null
What does the code extract ?
def lopen_loc(x): lineno = (x._lopen_lineno if hasattr(x, '_lopen_lineno') else x.lineno) col = (x._lopen_col if hasattr(x, '_lopen_col') else x.col_offset) return (lineno, col)
null
null
null
the line and column number
codeqa
def lopen loc x lineno x lopen lineno if hasattr x ' lopen lineno' else x lineno col x lopen col if hasattr x ' lopen col' else x col offset return lineno col
null
null
null
null
Question: What does the code extract ? Code: def lopen_loc(x): lineno = (x._lopen_lineno if hasattr(x, '_lopen_lineno') else x.lineno) col = (x._lopen_col if hasattr(x, '_lopen_col') else x.col_offset) return (lineno, col)
null
null
null
What may a node have ?
def lopen_loc(x): lineno = (x._lopen_lineno if hasattr(x, '_lopen_lineno') else x.lineno) col = (x._lopen_col if hasattr(x, '_lopen_col') else x.col_offset) return (lineno, col)
null
null
null
anb opening parenthesis
codeqa
def lopen loc x lineno x lopen lineno if hasattr x ' lopen lineno' else x lineno col x lopen col if hasattr x ' lopen col' else x col offset return lineno col
null
null
null
null
Question: What may a node have ? Code: def lopen_loc(x): lineno = (x._lopen_lineno if hasattr(x, '_lopen_lineno') else x.lineno) col = (x._lopen_col if hasattr(x, '_lopen_col') else x.col_offset) return (lineno, col)
null
null
null
What does the code update ?
def update_dir_prior(prior, N, logphat, rho): dprior = np.copy(prior) gradf = (N * ((psi(np.sum(prior)) - psi(prior)) + logphat)) c = (N * polygamma(1, np.sum(prior))) q = ((- N) * polygamma(1, prior)) b = (np.sum((gradf / q)) / ((1 / c) + np.sum((1 / q)))) dprior = ((- (gradf - b)) / q) if all((((rho * dprior) + prior) > 0)): prior += (rho * dprior) else: logger.warning('updated prior not positive') return prior
null
null
null
a given prior using newtons method
codeqa
def update dir prior prior N logphat rho dprior np copy prior gradf N * psi np sum prior - psi prior + logphat c N * polygamma 1 np sum prior q - N * polygamma 1 prior b np sum gradf / q / 1 / c + np sum 1 / q dprior - gradf - b / q if all rho * dprior + prior > 0 prior + rho * dprior else logger warning 'updatedpriornotpositive' return prior
null
null
null
null
Question: What does the code update ? Code: def update_dir_prior(prior, N, logphat, rho): dprior = np.copy(prior) gradf = (N * ((psi(np.sum(prior)) - psi(prior)) + logphat)) c = (N * polygamma(1, np.sum(prior))) q = ((- N) * polygamma(1, prior)) b = (np.sum((gradf / q)) / ((1 / c) + np.sum((1 / q)))) dprior = ((- (gradf - b)) / q) if all((((rho * dprior) + prior) > 0)): prior += (rho * dprior) else: logger.warning('updated prior not positive') return prior