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 | How d the code find a cloud load balancer ?
| def rax_find_loadbalancer(module, rax_module, loadbalancer):
clb = rax_module.cloud_loadbalancers
try:
found = clb.get(loadbalancer)
except:
found = []
for lb in clb.list():
if (loadbalancer == lb.name):
found.append(lb)
if (not found):
module.fail_json(msg='No loadbalancer was matched')
if (len(found) > 1):
module.fail_json(msg='Multiple loadbalancers matched')
found = found[0]
return found
| null | null | null | by i d or name
| codeqa | def rax find loadbalancer module rax module loadbalancer clb rax module cloud loadbalancerstry found clb get loadbalancer except found []for lb in clb list if loadbalancer lb name found append lb if not found module fail json msg ' Noloadbalancerwasmatched' if len found > 1 module fail json msg ' Multipleloadbalancersmatched' found found[ 0 ]return found
| null | null | null | null | Question:
How d the code find a cloud load balancer ?
Code:
def rax_find_loadbalancer(module, rax_module, loadbalancer):
clb = rax_module.cloud_loadbalancers
try:
found = clb.get(loadbalancer)
except:
found = []
for lb in clb.list():
if (loadbalancer == lb.name):
found.append(lb)
if (not found):
module.fail_json(msg='No loadbalancer was matched')
if (len(found) > 1):
module.fail_json(msg='Multiple loadbalancers matched')
found = found[0]
return found
|
null | null | null | What d the code find by i d or name ?
| def rax_find_loadbalancer(module, rax_module, loadbalancer):
clb = rax_module.cloud_loadbalancers
try:
found = clb.get(loadbalancer)
except:
found = []
for lb in clb.list():
if (loadbalancer == lb.name):
found.append(lb)
if (not found):
module.fail_json(msg='No loadbalancer was matched')
if (len(found) > 1):
module.fail_json(msg='Multiple loadbalancers matched')
found = found[0]
return found
| null | null | null | a cloud load balancer
| codeqa | def rax find loadbalancer module rax module loadbalancer clb rax module cloud loadbalancerstry found clb get loadbalancer except found []for lb in clb list if loadbalancer lb name found append lb if not found module fail json msg ' Noloadbalancerwasmatched' if len found > 1 module fail json msg ' Multipleloadbalancersmatched' found found[ 0 ]return found
| null | null | null | null | Question:
What d the code find by i d or name ?
Code:
def rax_find_loadbalancer(module, rax_module, loadbalancer):
clb = rax_module.cloud_loadbalancers
try:
found = clb.get(loadbalancer)
except:
found = []
for lb in clb.list():
if (loadbalancer == lb.name):
found.append(lb)
if (not found):
module.fail_json(msg='No loadbalancer was matched')
if (len(found) > 1):
module.fail_json(msg='Multiple loadbalancers matched')
found = found[0]
return found
|
null | null | null | How do commands run for minion startup ?
| def _run_all_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, output_loglevel=None):
return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, output_loglevel='quiet', log_callback=None, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override)
| null | null | null | quietly
| codeqa | def run all quiet cmd cwd None stdin None runas None shell DEFAULT SHELL python shell False env None template None umask None timeout None reset system locale True saltenv 'base' pillarenv None pillar override None output loglevel None return run cmd runas runas cwd cwd stdin stdin shell shell python shell python shell env env output loglevel 'quiet' log callback None template template umask umask timeout timeout reset system locale reset system locale saltenv saltenv pillarenv pillarenv pillar override pillar override
| null | null | null | null | Question:
How do commands run for minion startup ?
Code:
def _run_all_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, output_loglevel=None):
return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, output_loglevel='quiet', log_callback=None, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override)
|
null | null | null | For what purpose do commands run quietly ?
| def _run_all_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, output_loglevel=None):
return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, output_loglevel='quiet', log_callback=None, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override)
| null | null | null | for minion startup
| codeqa | def run all quiet cmd cwd None stdin None runas None shell DEFAULT SHELL python shell False env None template None umask None timeout None reset system locale True saltenv 'base' pillarenv None pillar override None output loglevel None return run cmd runas runas cwd cwd stdin stdin shell shell python shell python shell env env output loglevel 'quiet' log callback None template template umask umask timeout timeout reset system locale reset system locale saltenv saltenv pillarenv pillarenv pillar override pillar override
| null | null | null | null | Question:
For what purpose do commands run quietly ?
Code:
def _run_all_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, output_loglevel=None):
return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, output_loglevel='quiet', log_callback=None, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override)
|
null | null | null | How does the code get credentials from the current environment ?
| def get_credentials():
(credentials, _) = google.auth.default()
return credentials
| null | null | null | implicitly
| codeqa | def get credentials credentials google auth default return credentials
| null | null | null | null | Question:
How does the code get credentials from the current environment ?
Code:
def get_credentials():
(credentials, _) = google.auth.default()
return credentials
|
null | null | null | What does the code get from the current environment implicitly ?
| def get_credentials():
(credentials, _) = google.auth.default()
return credentials
| null | null | null | credentials
| codeqa | def get credentials credentials google auth default return credentials
| null | null | null | null | Question:
What does the code get from the current environment implicitly ?
Code:
def get_credentials():
(credentials, _) = google.auth.default()
return credentials
|
null | null | null | What does it compute ?
| def normalized_mean_absolute_error(y_real, y_pred, max_rating, min_rating):
(y_real, y_pred) = check_arrays(y_real, y_pred)
mae = mean_absolute_error(y_real, y_pred)
return (mae / (max_rating - min_rating))
| null | null | null | the normalized average absolute difference between predicted and actual ratings for users
| codeqa | def normalized mean absolute error y real y pred max rating min rating y real y pred check arrays y real y pred mae mean absolute error y real y pred return mae / max rating - min rating
| null | null | null | null | Question:
What does it compute ?
Code:
def normalized_mean_absolute_error(y_real, y_pred, max_rating, min_rating):
(y_real, y_pred) = check_arrays(y_real, y_pred)
mae = mean_absolute_error(y_real, y_pred)
return (mae / (max_rating - min_rating))
|
null | null | null | What does the code retrieve ?
| def _service_disco_configs(agentConfig):
if (agentConfig.get('service_discovery') and (agentConfig.get('service_discovery_backend') in SD_BACKENDS)):
try:
log.info('Fetching service discovery check configurations.')
sd_backend = get_sd_backend(agentConfig=agentConfig)
service_disco_configs = sd_backend.get_configs()
except Exception:
log.exception('Loading service discovery configurations failed.')
return {}
else:
service_disco_configs = {}
return service_disco_configs
| null | null | null | all the service disco configs
| codeqa | def service disco configs agent Config if agent Config get 'service discovery' and agent Config get 'service discovery backend' in SD BACKENDS try log info ' Fetchingservicediscoverycheckconfigurations ' sd backend get sd backend agent Config agent Config service disco configs sd backend get configs except Exception log exception ' Loadingservicediscoveryconfigurationsfailed ' return {}else service disco configs {}return service disco configs
| null | null | null | null | Question:
What does the code retrieve ?
Code:
def _service_disco_configs(agentConfig):
if (agentConfig.get('service_discovery') and (agentConfig.get('service_discovery_backend') in SD_BACKENDS)):
try:
log.info('Fetching service discovery check configurations.')
sd_backend = get_sd_backend(agentConfig=agentConfig)
service_disco_configs = sd_backend.get_configs()
except Exception:
log.exception('Loading service discovery configurations failed.')
return {}
else:
service_disco_configs = {}
return service_disco_configs
|
null | null | null | How do a new periodic job schedule ?
| def every(interval=1):
return default_scheduler.every(interval)
| null | null | null | with the default module scheduler
| codeqa | def every interval 1 return default scheduler every interval
| null | null | null | null | Question:
How do a new periodic job schedule ?
Code:
def every(interval=1):
return default_scheduler.every(interval)
|
null | null | null | In which direction do signal send to all connected receivers ?
| def send(signal=Any, sender=Anonymous, *arguments, **named):
responses = []
for receiver in getAllReceivers(sender, signal):
response = robustapply.robustApply(receiver, signal=signal, sender=sender, *arguments, **named)
responses.append((receiver, response))
return responses
| null | null | null | from sender
| codeqa | def send signal Any sender Anonymous *arguments **named responses []for receiver in get All Receivers sender signal response robustapply robust Apply receiver signal signal sender sender *arguments **named responses append receiver response return responses
| null | null | null | null | Question:
In which direction do signal send to all connected receivers ?
Code:
def send(signal=Any, sender=Anonymous, *arguments, **named):
responses = []
for receiver in getAllReceivers(sender, signal):
response = robustapply.robustApply(receiver, signal=signal, sender=sender, *arguments, **named)
responses.append((receiver, response))
return responses
|
null | null | null | What converts to file path with optional extension ?
| def path_from_name(name, ext=None, sep=u'|'):
if ext:
return fsencode((name.replace(os.sep, sep) + ext))
else:
return fsencode(name.replace(os.sep, sep))
| null | null | null | name
| codeqa | def path from name name ext None sep u' ' if ext return fsencode name replace os sep sep + ext else return fsencode name replace os sep sep
| null | null | null | null | Question:
What converts to file path with optional extension ?
Code:
def path_from_name(name, ext=None, sep=u'|'):
if ext:
return fsencode((name.replace(os.sep, sep) + ext))
else:
return fsencode(name.replace(os.sep, sep))
|
null | null | null | How do name convert to file path ?
| def path_from_name(name, ext=None, sep=u'|'):
if ext:
return fsencode((name.replace(os.sep, sep) + ext))
else:
return fsencode(name.replace(os.sep, sep))
| null | null | null | with optional extension
| codeqa | def path from name name ext None sep u' ' if ext return fsencode name replace os sep sep + ext else return fsencode name replace os sep sep
| null | null | null | null | Question:
How do name convert to file path ?
Code:
def path_from_name(name, ext=None, sep=u'|'):
if ext:
return fsencode((name.replace(os.sep, sep) + ext))
else:
return fsencode(name.replace(os.sep, sep))
|
null | null | null | What do name convert with optional extension ?
| def path_from_name(name, ext=None, sep=u'|'):
if ext:
return fsencode((name.replace(os.sep, sep) + ext))
else:
return fsencode(name.replace(os.sep, sep))
| null | null | null | to file path
| codeqa | def path from name name ext None sep u' ' if ext return fsencode name replace os sep sep + ext else return fsencode name replace os sep sep
| null | null | null | null | Question:
What do name convert with optional extension ?
Code:
def path_from_name(name, ext=None, sep=u'|'):
if ext:
return fsencode((name.replace(os.sep, sep) + ext))
else:
return fsencode(name.replace(os.sep, sep))
|
null | null | null | What do all top level units have ?
| def get_units_with_due_date(course):
units = []
def visit(node):
'\n Visit a node. Checks to see if node has a due date and appends to\n `units` if it does. Otherwise recurses into children to search for\n nodes with due dates.\n '
if getattr(node, 'due', None):
units.append(node)
else:
for child in node.get_children():
visit(child)
visit(course)
return units
| null | null | null | due dates
| codeqa | def get units with due date course units []def visit node '\n Visitanode Checkstoseeifnodehasaduedateandappendsto\n`units`ifitdoes Otherwiserecursesintochildrentosearchfor\nnodeswithduedates \n'if getattr node 'due' None units append node else for child in node get children visit child visit course return units
| null | null | null | null | Question:
What do all top level units have ?
Code:
def get_units_with_due_date(course):
units = []
def visit(node):
'\n Visit a node. Checks to see if node has a due date and appends to\n `units` if it does. Otherwise recurses into children to search for\n nodes with due dates.\n '
if getattr(node, 'due', None):
units.append(node)
else:
for child in node.get_children():
visit(child)
visit(course)
return units
|
null | null | null | What have due dates ?
| def get_units_with_due_date(course):
units = []
def visit(node):
'\n Visit a node. Checks to see if node has a due date and appends to\n `units` if it does. Otherwise recurses into children to search for\n nodes with due dates.\n '
if getattr(node, 'due', None):
units.append(node)
else:
for child in node.get_children():
visit(child)
visit(course)
return units
| null | null | null | all top level units
| codeqa | def get units with due date course units []def visit node '\n Visitanode Checkstoseeifnodehasaduedateandappendsto\n`units`ifitdoes Otherwiserecursesintochildrentosearchfor\nnodeswithduedates \n'if getattr node 'due' None units append node else for child in node get children visit child visit course return units
| null | null | null | null | Question:
What have due dates ?
Code:
def get_units_with_due_date(course):
units = []
def visit(node):
'\n Visit a node. Checks to see if node has a due date and appends to\n `units` if it does. Otherwise recurses into children to search for\n nodes with due dates.\n '
if getattr(node, 'due', None):
units.append(node)
else:
for child in node.get_children():
visit(child)
visit(course)
return units
|
null | null | null | Where did the value find ?
| def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[(~ state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
| null | null | null | in step 4
| codeqa | def step 6 state if np any state row uncovered and np any state col uncovered minval np min state C[state row uncovered] axis 0 minval np min minval[state col uncovered] state C[ ~ state row uncovered ] + minvalstate C[ state col uncovered] - minvalreturn step 4
| null | null | null | null | Question:
Where did the value find ?
Code:
def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[(~ state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
|
null | null | null | What found in step 4 ?
| def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[(~ state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
| null | null | null | the value
| codeqa | def step 6 state if np any state row uncovered and np any state col uncovered minval np min state C[state row uncovered] axis 0 minval np min minval[state col uncovered] state C[ ~ state row uncovered ] + minvalstate C[ state col uncovered] - minvalreturn step 4
| null | null | null | null | Question:
What found in step 4 ?
Code:
def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[(~ state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
|
null | null | null | What does the code add to every element of each covered row ?
| def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[(~ state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
| null | null | null | the value found in step 4
| codeqa | def step 6 state if np any state row uncovered and np any state col uncovered minval np min state C[state row uncovered] axis 0 minval np min minval[state col uncovered] state C[ ~ state row uncovered ] + minvalstate C[ state col uncovered] - minvalreturn step 4
| null | null | null | null | Question:
What does the code add to every element of each covered row ?
Code:
def _step6(state):
if (np.any(state.row_uncovered) and np.any(state.col_uncovered)):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[(~ state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
|
null | null | null | What does the code not send back to scheduler ?
| def not_send_status(func):
@functools.wraps(func)
def wrapper(self, response, task):
self._extinfo['not_send_status'] = True
function = func.__get__(self, self.__class__)
return self._run_func(function, response, task)
return wrapper
| null | null | null | process status package
| codeqa | def not send status func @functools wraps func def wrapper self response task self extinfo['not send status'] Truefunction func get self self class return self run func function response task return wrapper
| null | null | null | null | Question:
What does the code not send back to scheduler ?
Code:
def not_send_status(func):
@functools.wraps(func)
def wrapper(self, response, task):
self._extinfo['not_send_status'] = True
function = func.__get__(self, self.__class__)
return self._run_func(function, response, task)
return wrapper
|
null | null | null | What does this method get ?
| def get_command_from_state(state):
command = None
if (state == 'present'):
command = 'vrouter-loopback-interface-add'
if (state == 'absent'):
command = 'vrouter-loopback-interface-remove'
return command
| null | null | null | appropriate command name for the state specified
| codeqa | def get command from state state command Noneif state 'present' command 'vrouter-loopback-interface-add'if state 'absent' command 'vrouter-loopback-interface-remove'return command
| null | null | null | null | Question:
What does this method get ?
Code:
def get_command_from_state(state):
command = None
if (state == 'present'):
command = 'vrouter-loopback-interface-add'
if (state == 'absent'):
command = 'vrouter-loopback-interface-remove'
return command
|
null | null | null | What will store the language information dictionary for the given language code in a context variable ?
| def do_get_language_info(parser, token):
args = token.contents.split()
if ((len(args) != 5) or (args[1] != 'for') or (args[3] != 'as')):
raise TemplateSyntaxError(("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])))
return GetLanguageInfoNode(args[2], args[4])
| null | null | null | this
| codeqa | def do get language info parser token args token contents split if len args 5 or args[ 1 ] 'for' or args[ 3 ] 'as' raise Template Syntax Error "'%s'requires'forstringasvariable' got%r " % args[ 0 ] args[ 1 ] return Get Language Info Node args[ 2 ] args[ 4 ]
| null | null | null | null | Question:
What will store the language information dictionary for the given language code in a context variable ?
Code:
def do_get_language_info(parser, token):
args = token.contents.split()
if ((len(args) != 5) or (args[1] != 'for') or (args[3] != 'as')):
raise TemplateSyntaxError(("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])))
return GetLanguageInfoNode(args[2], args[4])
|
null | null | null | What will this store in a context variable ?
| def do_get_language_info(parser, token):
args = token.contents.split()
if ((len(args) != 5) or (args[1] != 'for') or (args[3] != 'as')):
raise TemplateSyntaxError(("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])))
return GetLanguageInfoNode(args[2], args[4])
| null | null | null | the language information dictionary for the given language code
| codeqa | def do get language info parser token args token contents split if len args 5 or args[ 1 ] 'for' or args[ 3 ] 'as' raise Template Syntax Error "'%s'requires'forstringasvariable' got%r " % args[ 0 ] args[ 1 ] return Get Language Info Node args[ 2 ] args[ 4 ]
| null | null | null | null | Question:
What will this store in a context variable ?
Code:
def do_get_language_info(parser, token):
args = token.contents.split()
if ((len(args) != 5) or (args[1] != 'for') or (args[3] != 'as')):
raise TemplateSyntaxError(("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])))
return GetLanguageInfoNode(args[2], args[4])
|
null | null | null | How will this store the language information dictionary for the given language code ?
| def do_get_language_info(parser, token):
args = token.contents.split()
if ((len(args) != 5) or (args[1] != 'for') or (args[3] != 'as')):
raise TemplateSyntaxError(("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])))
return GetLanguageInfoNode(args[2], args[4])
| null | null | null | in a context variable
| codeqa | def do get language info parser token args token contents split if len args 5 or args[ 1 ] 'for' or args[ 3 ] 'as' raise Template Syntax Error "'%s'requires'forstringasvariable' got%r " % args[ 0 ] args[ 1 ] return Get Language Info Node args[ 2 ] args[ 4 ]
| null | null | null | null | Question:
How will this store the language information dictionary for the given language code ?
Code:
def do_get_language_info(parser, token):
args = token.contents.split()
if ((len(args) != 5) or (args[1] != 'for') or (args[3] != 'as')):
raise TemplateSyntaxError(("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])))
return GetLanguageInfoNode(args[2], args[4])
|
null | null | null | What does the code execute ?
| def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
| null | null | null | a blend crossover that modify in - place the input individuals
| codeqa | def cx Blend ind 1 ind 2 alpha for i x1 x2 in enumerate zip ind 1 ind 2 gamma 1 0 + 2 0 * alpha * random random - alpha ind 1 [i] 1 0 - gamma * x1 + gamma * x2 ind 2 [i] gamma * x1 + 1 0 - gamma * x2 return ind 1 ind 2
| null | null | null | null | Question:
What does the code execute ?
Code:
def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
|
null | null | null | How do a blend crossover modify the input individuals ?
| def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
| null | null | null | in - place
| codeqa | def cx Blend ind 1 ind 2 alpha for i x1 x2 in enumerate zip ind 1 ind 2 gamma 1 0 + 2 0 * alpha * random random - alpha ind 1 [i] 1 0 - gamma * x1 + gamma * x2 ind 2 [i] gamma * x1 + 1 0 - gamma * x2 return ind 1 ind 2
| null | null | null | null | Question:
How do a blend crossover modify the input individuals ?
Code:
def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
|
null | null | null | What modify the input individuals in - place ?
| def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
| null | null | null | a blend crossover
| codeqa | def cx Blend ind 1 ind 2 alpha for i x1 x2 in enumerate zip ind 1 ind 2 gamma 1 0 + 2 0 * alpha * random random - alpha ind 1 [i] 1 0 - gamma * x1 + gamma * x2 ind 2 [i] gamma * x1 + 1 0 - gamma * x2 return ind 1 ind 2
| null | null | null | null | Question:
What modify the input individuals in - place ?
Code:
def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
|
null | null | null | What do a blend crossover modify in - place ?
| def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
| null | null | null | the input individuals
| codeqa | def cx Blend ind 1 ind 2 alpha for i x1 x2 in enumerate zip ind 1 ind 2 gamma 1 0 + 2 0 * alpha * random random - alpha ind 1 [i] 1 0 - gamma * x1 + gamma * x2 ind 2 [i] gamma * x1 + 1 0 - gamma * x2 return ind 1 ind 2
| null | null | null | null | Question:
What do a blend crossover modify in - place ?
Code:
def cxBlend(ind1, ind2, alpha):
for (i, (x1, x2)) in enumerate(zip(ind1, ind2)):
gamma = (((1.0 + (2.0 * alpha)) * random.random()) - alpha)
ind1[i] = (((1.0 - gamma) * x1) + (gamma * x2))
ind2[i] = ((gamma * x1) + ((1.0 - gamma) * x2))
return (ind1, ind2)
|
null | null | null | What does the code create ?
| def new_figure_manager(num, *args, **kwargs):
FigureClass = kwargs.pop(u'FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig)
| null | null | null | a new figure manager instance
| codeqa | def new figure manager num *args **kwargs Figure Class kwargs pop u' Figure Class' Figure this Fig Figure Class *args **kwargs return new figure manager given figure num this Fig
| null | null | null | null | Question:
What does the code create ?
Code:
def new_figure_manager(num, *args, **kwargs):
FigureClass = kwargs.pop(u'FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, thisFig)
|
null | null | null | How did temporary directory provide ?
| @pytest.fixture()
def chdir(tmpdir):
tmpdir.chdir()
| null | null | null | pytest
| codeqa | @pytest fixture def chdir tmpdir tmpdir chdir
| null | null | null | null | Question:
How did temporary directory provide ?
Code:
@pytest.fixture()
def chdir(tmpdir):
tmpdir.chdir()
|
null | null | null | In which direction do image data read ?
| def imread(filename, format=None):
(imageio, PIL) = _check_img_lib()
if (imageio is not None):
return imageio.imread(filename, format)
elif (PIL is not None):
im = PIL.Image.open(filename)
if (im.mode == 'P'):
im = im.convert()
a = np.asarray(im)
if (len(a.shape) == 0):
raise MemoryError('Too little memory to convert PIL image to array')
return a
else:
raise RuntimeError('imread requires the imageio or PIL package.')
| null | null | null | from disk
| codeqa | def imread filename format None imageio PIL check img lib if imageio is not None return imageio imread filename format elif PIL is not None im PIL Image open filename if im mode 'P' im im convert a np asarray im if len a shape 0 raise Memory Error ' Toolittlememorytoconvert PI Limagetoarray' return aelse raise Runtime Error 'imreadrequirestheimageioor PI Lpackage '
| null | null | null | null | Question:
In which direction do image data read ?
Code:
def imread(filename, format=None):
(imageio, PIL) = _check_img_lib()
if (imageio is not None):
return imageio.imread(filename, format)
elif (PIL is not None):
im = PIL.Image.open(filename)
if (im.mode == 'P'):
im = im.convert()
a = np.asarray(im)
if (len(a.shape) == 0):
raise MemoryError('Too little memory to convert PIL image to array')
return a
else:
raise RuntimeError('imread requires the imageio or PIL package.')
|
null | null | null | What does the code initialize ?
| def setUpModule():
global hass
hass = get_test_home_assistant()
bootstrap.setup_component(hass, http.DOMAIN, {http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD, http.CONF_SERVER_PORT: SERVER_PORT}})
bootstrap.setup_component(hass, 'api')
hass.http.app[KEY_TRUSTED_NETWORKS] = [ip_network(trusted_network) for trusted_network in TRUSTED_NETWORKS]
hass.start()
| null | null | null | a home assistant server
| codeqa | def set Up Module global hasshass get test home assistant bootstrap setup component hass http DOMAIN {http DOMAIN {http CONF API PASSWORD API PASSWORD http CONF SERVER PORT SERVER PORT}} bootstrap setup component hass 'api' hass http app[KEY TRUSTED NETWORKS] [ip network trusted network for trusted network in TRUSTED NETWORKS]hass start
| null | null | null | null | Question:
What does the code initialize ?
Code:
def setUpModule():
global hass
hass = get_test_home_assistant()
bootstrap.setup_component(hass, http.DOMAIN, {http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD, http.CONF_SERVER_PORT: SERVER_PORT}})
bootstrap.setup_component(hass, 'api')
hass.http.app[KEY_TRUSTED_NETWORKS] = [ip_network(trusted_network) for trusted_network in TRUSTED_NETWORKS]
hass.start()
|
null | null | null | What does the code send ?
| def try_send_telemetry(request=None, max_age_hours=24, raise_on_error=False):
force_send = bool(((not get_last_submission_time()) or (not settings.DEBUG)))
try:
return _send_telemetry(request=request, max_age_hours=max_age_hours, force_send=force_send)
except TelemetryNotSent:
if raise_on_error:
raise
return False
| null | null | null | telemetry information
| codeqa | def try send telemetry request None max age hours 24 raise on error False force send bool not get last submission time or not settings DEBUG try return send telemetry request request max age hours max age hours force send force send except Telemetry Not Sent if raise on error raisereturn False
| null | null | null | null | Question:
What does the code send ?
Code:
def try_send_telemetry(request=None, max_age_hours=24, raise_on_error=False):
force_send = bool(((not get_last_submission_time()) or (not settings.DEBUG)))
try:
return _send_telemetry(request=request, max_age_hours=max_age_hours, force_send=force_send)
except TelemetryNotSent:
if raise_on_error:
raise
return False
|
null | null | null | Where does the code find a maximal matching ?
| def maximal_matching(G):
matching = set()
nodes = set()
for (u, v) in G.edges():
if ((u not in nodes) and (v not in nodes) and (u != v)):
matching.add((u, v))
nodes.add(u)
nodes.add(v)
return matching
| null | null | null | in the graph
| codeqa | def maximal matching G matching set nodes set for u v in G edges if u not in nodes and v not in nodes and u v matching add u v nodes add u nodes add v return matching
| null | null | null | null | Question:
Where does the code find a maximal matching ?
Code:
def maximal_matching(G):
matching = set()
nodes = set()
for (u, v) in G.edges():
if ((u not in nodes) and (v not in nodes) and (u != v)):
matching.add((u, v))
nodes.add(u)
nodes.add(v)
return matching
|
null | null | null | What does the code find in the graph ?
| def maximal_matching(G):
matching = set()
nodes = set()
for (u, v) in G.edges():
if ((u not in nodes) and (v not in nodes) and (u != v)):
matching.add((u, v))
nodes.add(u)
nodes.add(v)
return matching
| null | null | null | a maximal matching
| codeqa | def maximal matching G matching set nodes set for u v in G edges if u not in nodes and v not in nodes and u v matching add u v nodes add u nodes add v return matching
| null | null | null | null | Question:
What does the code find in the graph ?
Code:
def maximal_matching(G):
matching = set()
nodes = set()
for (u, v) in G.edges():
if ((u not in nodes) and (v not in nodes) and (u != v)):
matching.add((u, v))
nodes.add(u)
nodes.add(v)
return matching
|
null | null | null | What tries to infer the $ geometry shape for a given value ?
| def _infer_geometry(value):
if isinstance(value, dict):
if ('$geometry' in value):
return value
elif (('coordinates' in value) and ('type' in value)):
return {'$geometry': value}
raise InvalidQueryError('Invalid $geometry dictionary should have type and coordinates keys')
elif isinstance(value, (list, set)):
try:
value[0][0][0]
return {'$geometry': {'type': 'Polygon', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0][0]
return {'$geometry': {'type': 'LineString', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0]
return {'$geometry': {'type': 'Point', 'coordinates': value}}
except (TypeError, IndexError):
pass
raise InvalidQueryError('Invalid $geometry data. Can be either a dictionary or (nested) lists of coordinate(s)')
| null | null | null | helper method
| codeqa | def infer geometry value if isinstance value dict if '$geometry' in value return valueelif 'coordinates' in value and 'type' in value return {'$geometry' value}raise Invalid Query Error ' Invalid$geometrydictionaryshouldhavetypeandcoordinateskeys' elif isinstance value list set try value[ 0 ][ 0 ][ 0 ]return {'$geometry' {'type' ' Polygon' 'coordinates' value}}except Type Error Index Error passtry value[ 0 ][ 0 ]return {'$geometry' {'type' ' Line String' 'coordinates' value}}except Type Error Index Error passtry value[ 0 ]return {'$geometry' {'type' ' Point' 'coordinates' value}}except Type Error Index Error passraise Invalid Query Error ' Invalid$geometrydata Canbeeitheradictionaryor nested listsofcoordinate s '
| null | null | null | null | Question:
What tries to infer the $ geometry shape for a given value ?
Code:
def _infer_geometry(value):
if isinstance(value, dict):
if ('$geometry' in value):
return value
elif (('coordinates' in value) and ('type' in value)):
return {'$geometry': value}
raise InvalidQueryError('Invalid $geometry dictionary should have type and coordinates keys')
elif isinstance(value, (list, set)):
try:
value[0][0][0]
return {'$geometry': {'type': 'Polygon', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0][0]
return {'$geometry': {'type': 'LineString', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0]
return {'$geometry': {'type': 'Point', 'coordinates': value}}
except (TypeError, IndexError):
pass
raise InvalidQueryError('Invalid $geometry data. Can be either a dictionary or (nested) lists of coordinate(s)')
|
null | null | null | What does helper method try ?
| def _infer_geometry(value):
if isinstance(value, dict):
if ('$geometry' in value):
return value
elif (('coordinates' in value) and ('type' in value)):
return {'$geometry': value}
raise InvalidQueryError('Invalid $geometry dictionary should have type and coordinates keys')
elif isinstance(value, (list, set)):
try:
value[0][0][0]
return {'$geometry': {'type': 'Polygon', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0][0]
return {'$geometry': {'type': 'LineString', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0]
return {'$geometry': {'type': 'Point', 'coordinates': value}}
except (TypeError, IndexError):
pass
raise InvalidQueryError('Invalid $geometry data. Can be either a dictionary or (nested) lists of coordinate(s)')
| null | null | null | to infer the $ geometry shape for a given value
| codeqa | def infer geometry value if isinstance value dict if '$geometry' in value return valueelif 'coordinates' in value and 'type' in value return {'$geometry' value}raise Invalid Query Error ' Invalid$geometrydictionaryshouldhavetypeandcoordinateskeys' elif isinstance value list set try value[ 0 ][ 0 ][ 0 ]return {'$geometry' {'type' ' Polygon' 'coordinates' value}}except Type Error Index Error passtry value[ 0 ][ 0 ]return {'$geometry' {'type' ' Line String' 'coordinates' value}}except Type Error Index Error passtry value[ 0 ]return {'$geometry' {'type' ' Point' 'coordinates' value}}except Type Error Index Error passraise Invalid Query Error ' Invalid$geometrydata Canbeeitheradictionaryor nested listsofcoordinate s '
| null | null | null | null | Question:
What does helper method try ?
Code:
def _infer_geometry(value):
if isinstance(value, dict):
if ('$geometry' in value):
return value
elif (('coordinates' in value) and ('type' in value)):
return {'$geometry': value}
raise InvalidQueryError('Invalid $geometry dictionary should have type and coordinates keys')
elif isinstance(value, (list, set)):
try:
value[0][0][0]
return {'$geometry': {'type': 'Polygon', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0][0]
return {'$geometry': {'type': 'LineString', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0]
return {'$geometry': {'type': 'Point', 'coordinates': value}}
except (TypeError, IndexError):
pass
raise InvalidQueryError('Invalid $geometry data. Can be either a dictionary or (nested) lists of coordinate(s)')
|
null | null | null | What does the code retrieve ?
| def get_thread(request, thread_id, requested_fields=None):
(cc_thread, context) = _get_thread_and_context(request, thread_id, retrieve_kwargs={'with_responses': True, 'user_id': unicode(request.user.id)})
return _serialize_discussion_entities(request, context, [cc_thread], requested_fields, DiscussionEntity.thread)[0]
| null | null | null | a thread
| codeqa | def get thread request thread id requested fields None cc thread context get thread and context request thread id retrieve kwargs {'with responses' True 'user id' unicode request user id } return serialize discussion entities request context [cc thread] requested fields Discussion Entity thread [0 ]
| null | null | null | null | Question:
What does the code retrieve ?
Code:
def get_thread(request, thread_id, requested_fields=None):
(cc_thread, context) = _get_thread_and_context(request, thread_id, retrieve_kwargs={'with_responses': True, 'user_id': unicode(request.user.id)})
return _serialize_discussion_entities(request, context, [cc_thread], requested_fields, DiscussionEntity.thread)[0]
|
null | null | null | What did the code require ?
| def register(linter):
linter.register_checker(StringFormatChecker(linter))
linter.register_checker(StringMethodsChecker(linter))
linter.register_checker(StringConstantChecker(linter))
| null | null | null | method to auto register this checker
| codeqa | def register linter linter register checker String Format Checker linter linter register checker String Methods Checker linter linter register checker String Constant Checker linter
| null | null | null | null | Question:
What did the code require ?
Code:
def register(linter):
linter.register_checker(StringFormatChecker(linter))
linter.register_checker(StringMethodsChecker(linter))
linter.register_checker(StringConstantChecker(linter))
|
null | null | null | Where does the code get sections ?
| @newrelic.agent.function_trace()
def get_content_sections(src=''):
sections = []
if src:
attr = '[id]'
selector = ((attr + ',').join(SECTION_TAGS) + attr)
try:
document = pq(src)
except etree.ParserError:
pass
else:
for element in document.find(selector):
sections.append({'title': element.text, 'id': element.attrib.get('id')})
return sections
| null | null | null | in a document
| codeqa | @newrelic agent function trace def get content sections src '' sections []if src attr '[id]'selector attr + ' ' join SECTION TAGS + attr try document pq src except etree Parser Error passelse for element in document find selector sections append {'title' element text 'id' element attrib get 'id' } return sections
| null | null | null | null | Question:
Where does the code get sections ?
Code:
@newrelic.agent.function_trace()
def get_content_sections(src=''):
sections = []
if src:
attr = '[id]'
selector = ((attr + ',').join(SECTION_TAGS) + attr)
try:
document = pq(src)
except etree.ParserError:
pass
else:
for element in document.find(selector):
sections.append({'title': element.text, 'id': element.attrib.get('id')})
return sections
|
null | null | null | What does the code get in a document ?
| @newrelic.agent.function_trace()
def get_content_sections(src=''):
sections = []
if src:
attr = '[id]'
selector = ((attr + ',').join(SECTION_TAGS) + attr)
try:
document = pq(src)
except etree.ParserError:
pass
else:
for element in document.find(selector):
sections.append({'title': element.text, 'id': element.attrib.get('id')})
return sections
| null | null | null | sections
| codeqa | @newrelic agent function trace def get content sections src '' sections []if src attr '[id]'selector attr + ' ' join SECTION TAGS + attr try document pq src except etree Parser Error passelse for element in document find selector sections append {'title' element text 'id' element attrib get 'id' } return sections
| null | null | null | null | Question:
What does the code get in a document ?
Code:
@newrelic.agent.function_trace()
def get_content_sections(src=''):
sections = []
if src:
attr = '[id]'
selector = ((attr + ',').join(SECTION_TAGS) + attr)
try:
document = pq(src)
except etree.ParserError:
pass
else:
for element in document.find(selector):
sections.append({'title': element.text, 'id': element.attrib.get('id')})
return sections
|
null | null | null | When does the code expand the database schema ?
| def expand_schema():
_sync_common_repo(version=None)
_sync_repo(repo_name=EXPAND_REPO)
| null | null | null | ahead of data migration
| codeqa | def expand schema sync common repo version None sync repo repo name EXPAND REPO
| null | null | null | null | Question:
When does the code expand the database schema ?
Code:
def expand_schema():
_sync_common_repo(version=None)
_sync_repo(repo_name=EXPAND_REPO)
|
null | null | null | What does the code expand ahead of data migration ?
| def expand_schema():
_sync_common_repo(version=None)
_sync_repo(repo_name=EXPAND_REPO)
| null | null | null | the database schema
| codeqa | def expand schema sync common repo version None sync repo repo name EXPAND REPO
| null | null | null | null | Question:
What does the code expand ahead of data migration ?
Code:
def expand_schema():
_sync_common_repo(version=None)
_sync_repo(repo_name=EXPAND_REPO)
|
null | null | null | What does the code delete ?
| def AddAclSample():
client = CreateClient()
doc = gdata.docs.data.Resource(type='document', title='My Sample Doc')
doc = client.CreateResource(doc)
acl_entry = gdata.docs.data.AclEntry(scope=gdata.acl.data.AclScope(value='user@example.com', type='user'), role=gdata.acl.data.AclRole(value='reader'))
client.AddAclEntry(doc, acl_entry, send_notification=False)
| null | null | null | a resource
| codeqa | def Add Acl Sample client Create Client doc gdata docs data Resource type 'document' title ' My Sample Doc' doc client Create Resource doc acl entry gdata docs data Acl Entry scope gdata acl data Acl Scope value 'user@example com' type 'user' role gdata acl data Acl Role value 'reader' client Add Acl Entry doc acl entry send notification False
| null | null | null | null | Question:
What does the code delete ?
Code:
def AddAclSample():
client = CreateClient()
doc = gdata.docs.data.Resource(type='document', title='My Sample Doc')
doc = client.CreateResource(doc)
acl_entry = gdata.docs.data.AclEntry(scope=gdata.acl.data.AclScope(value='user@example.com', type='user'), role=gdata.acl.data.AclRole(value='reader'))
client.AddAclEntry(doc, acl_entry, send_notification=False)
|
null | null | null | What changes the effective user i d temporarily ?
| @contextmanager
def attempt_effective_uid(username, suppress_errors=False):
original_euid = os.geteuid()
new_euid = pwd.getpwnam(username).pw_uid
restore_euid = False
if (original_euid != new_euid):
try:
os.seteuid(new_euid)
except OSError as e:
if ((not suppress_errors) or (e.errno != 1)):
raise
else:
restore_euid = True
try:
(yield)
finally:
if restore_euid:
os.seteuid(original_euid)
| null | null | null | a context manager
| codeqa | @contextmanagerdef attempt effective uid username suppress errors False original euid os geteuid new euid pwd getpwnam username pw uidrestore euid Falseif original euid new euid try os seteuid new euid except OS Error as e if not suppress errors or e errno 1 raiseelse restore euid Truetry yield finally if restore euid os seteuid original euid
| null | null | null | null | Question:
What changes the effective user i d temporarily ?
Code:
@contextmanager
def attempt_effective_uid(username, suppress_errors=False):
original_euid = os.geteuid()
new_euid = pwd.getpwnam(username).pw_uid
restore_euid = False
if (original_euid != new_euid):
try:
os.seteuid(new_euid)
except OSError as e:
if ((not suppress_errors) or (e.errno != 1)):
raise
else:
restore_euid = True
try:
(yield)
finally:
if restore_euid:
os.seteuid(original_euid)
|
null | null | null | What do a context manager change temporarily ?
| @contextmanager
def attempt_effective_uid(username, suppress_errors=False):
original_euid = os.geteuid()
new_euid = pwd.getpwnam(username).pw_uid
restore_euid = False
if (original_euid != new_euid):
try:
os.seteuid(new_euid)
except OSError as e:
if ((not suppress_errors) or (e.errno != 1)):
raise
else:
restore_euid = True
try:
(yield)
finally:
if restore_euid:
os.seteuid(original_euid)
| null | null | null | the effective user i d
| codeqa | @contextmanagerdef attempt effective uid username suppress errors False original euid os geteuid new euid pwd getpwnam username pw uidrestore euid Falseif original euid new euid try os seteuid new euid except OS Error as e if not suppress errors or e errno 1 raiseelse restore euid Truetry yield finally if restore euid os seteuid original euid
| null | null | null | null | Question:
What do a context manager change temporarily ?
Code:
@contextmanager
def attempt_effective_uid(username, suppress_errors=False):
original_euid = os.geteuid()
new_euid = pwd.getpwnam(username).pw_uid
restore_euid = False
if (original_euid != new_euid):
try:
os.seteuid(new_euid)
except OSError as e:
if ((not suppress_errors) or (e.errno != 1)):
raise
else:
restore_euid = True
try:
(yield)
finally:
if restore_euid:
os.seteuid(original_euid)
|
null | null | null | When do a context manager change the effective user i d ?
| @contextmanager
def attempt_effective_uid(username, suppress_errors=False):
original_euid = os.geteuid()
new_euid = pwd.getpwnam(username).pw_uid
restore_euid = False
if (original_euid != new_euid):
try:
os.seteuid(new_euid)
except OSError as e:
if ((not suppress_errors) or (e.errno != 1)):
raise
else:
restore_euid = True
try:
(yield)
finally:
if restore_euid:
os.seteuid(original_euid)
| null | null | null | temporarily
| codeqa | @contextmanagerdef attempt effective uid username suppress errors False original euid os geteuid new euid pwd getpwnam username pw uidrestore euid Falseif original euid new euid try os seteuid new euid except OS Error as e if not suppress errors or e errno 1 raiseelse restore euid Truetry yield finally if restore euid os seteuid original euid
| null | null | null | null | Question:
When do a context manager change the effective user i d ?
Code:
@contextmanager
def attempt_effective_uid(username, suppress_errors=False):
original_euid = os.geteuid()
new_euid = pwd.getpwnam(username).pw_uid
restore_euid = False
if (original_euid != new_euid):
try:
os.seteuid(new_euid)
except OSError as e:
if ((not suppress_errors) or (e.errno != 1)):
raise
else:
restore_euid = True
try:
(yield)
finally:
if restore_euid:
os.seteuid(original_euid)
|
null | null | null | For what purpose do argument name tuple return ?
| def varnames(func, startindex=None):
cache = getattr(func, '__dict__', {})
try:
return cache['_varnames']
except KeyError:
pass
if inspect.isclass(func):
try:
func = func.__init__
except AttributeError:
return ()
startindex = 1
else:
if ((not inspect.isfunction(func)) and (not inspect.ismethod(func))):
try:
func = getattr(func, '__call__', func)
except Exception:
return ()
if (startindex is None):
startindex = int(inspect.ismethod(func))
try:
rawcode = func.__code__
except AttributeError:
return ()
try:
x = rawcode.co_varnames[startindex:rawcode.co_argcount]
except AttributeError:
x = ()
else:
defaults = func.__defaults__
if defaults:
x = x[:(- len(defaults))]
try:
cache['_varnames'] = x
except TypeError:
pass
return x
| null | null | null | for a function
| codeqa | def varnames func startindex None cache getattr func ' dict ' {} try return cache[' varnames']except Key Error passif inspect isclass func try func func init except Attribute Error return startindex 1else if not inspect isfunction func and not inspect ismethod func try func getattr func ' call ' func except Exception return if startindex is None startindex int inspect ismethod func try rawcode func code except Attribute Error return try x rawcode co varnames[startindex rawcode co argcount]except Attribute Error x else defaults func defaults if defaults x x[ - len defaults ]try cache[' varnames'] xexcept Type Error passreturn x
| null | null | null | null | Question:
For what purpose do argument name tuple return ?
Code:
def varnames(func, startindex=None):
cache = getattr(func, '__dict__', {})
try:
return cache['_varnames']
except KeyError:
pass
if inspect.isclass(func):
try:
func = func.__init__
except AttributeError:
return ()
startindex = 1
else:
if ((not inspect.isfunction(func)) and (not inspect.ismethod(func))):
try:
func = getattr(func, '__call__', func)
except Exception:
return ()
if (startindex is None):
startindex = int(inspect.ismethod(func))
try:
rawcode = func.__code__
except AttributeError:
return ()
try:
x = rawcode.co_varnames[startindex:rawcode.co_argcount]
except AttributeError:
x = ()
else:
defaults = func.__defaults__
if defaults:
x = x[:(- len(defaults))]
try:
cache['_varnames'] = x
except TypeError:
pass
return x
|
null | null | null | What is containing key ?
| def get_entity_group_version(key):
eg = EntityGroup.key_for_entity_group(key).get()
if eg:
return eg.version
else:
return None
| null | null | null | the entity group
| codeqa | def get entity group version key eg Entity Group key for entity group key get if eg return eg versionelse return None
| null | null | null | null | Question:
What is containing key ?
Code:
def get_entity_group_version(key):
eg = EntityGroup.key_for_entity_group(key).get()
if eg:
return eg.version
else:
return None
|
null | null | null | What haves the same length in the axis dimension ?
| def chisquare_effectsize(probs0, probs1, correction=None, cohen=True, axis=0):
probs0 = np.asarray(probs0, float)
probs1 = np.asarray(probs1, float)
probs0 = (probs0 / probs0.sum(axis))
probs1 = (probs1 / probs1.sum(axis))
d2 = (((probs1 - probs0) ** 2) / probs0).sum(axis)
if (correction is not None):
(nobs, df) = correction
diff = ((probs1 - probs0) / probs0).sum(axis)
d2 = np.maximum(((((d2 * nobs) - diff) - df) / (nobs - 1.0)), 0)
if cohen:
return np.sqrt(d2)
else:
return d2
| null | null | null | probs0 and probs1
| codeqa | def chisquare effectsize probs 0 probs 1 correction None cohen True axis 0 probs 0 np asarray probs 0 float probs 1 np asarray probs 1 float probs 0 probs 0 / probs 0 sum axis probs 1 probs 1 / probs 1 sum axis d2 probs 1 - probs 0 ** 2 / probs 0 sum axis if correction is not None nobs df correctiondiff probs 1 - probs 0 / probs 0 sum axis d2 np maximum d2 * nobs - diff - df / nobs - 1 0 0 if cohen return np sqrt d2 else return d2
| null | null | null | null | Question:
What haves the same length in the axis dimension ?
Code:
def chisquare_effectsize(probs0, probs1, correction=None, cohen=True, axis=0):
probs0 = np.asarray(probs0, float)
probs1 = np.asarray(probs1, float)
probs0 = (probs0 / probs0.sum(axis))
probs1 = (probs1 / probs1.sum(axis))
d2 = (((probs1 - probs0) ** 2) / probs0).sum(axis)
if (correction is not None):
(nobs, df) = correction
diff = ((probs1 - probs0) / probs0).sum(axis)
d2 = np.maximum(((((d2 * nobs) - diff) - df) / (nobs - 1.0)), 0)
if cohen:
return np.sqrt(d2)
else:
return d2
|
null | null | null | What do probs0 and probs1 have ?
| def chisquare_effectsize(probs0, probs1, correction=None, cohen=True, axis=0):
probs0 = np.asarray(probs0, float)
probs1 = np.asarray(probs1, float)
probs0 = (probs0 / probs0.sum(axis))
probs1 = (probs1 / probs1.sum(axis))
d2 = (((probs1 - probs0) ** 2) / probs0).sum(axis)
if (correction is not None):
(nobs, df) = correction
diff = ((probs1 - probs0) / probs0).sum(axis)
d2 = np.maximum(((((d2 * nobs) - diff) - df) / (nobs - 1.0)), 0)
if cohen:
return np.sqrt(d2)
else:
return d2
| null | null | null | the same length in the axis dimension
| codeqa | def chisquare effectsize probs 0 probs 1 correction None cohen True axis 0 probs 0 np asarray probs 0 float probs 1 np asarray probs 1 float probs 0 probs 0 / probs 0 sum axis probs 1 probs 1 / probs 1 sum axis d2 probs 1 - probs 0 ** 2 / probs 0 sum axis if correction is not None nobs df correctiondiff probs 1 - probs 0 / probs 0 sum axis d2 np maximum d2 * nobs - diff - df / nobs - 1 0 0 if cohen return np sqrt d2 else return d2
| null | null | null | null | Question:
What do probs0 and probs1 have ?
Code:
def chisquare_effectsize(probs0, probs1, correction=None, cohen=True, axis=0):
probs0 = np.asarray(probs0, float)
probs1 = np.asarray(probs1, float)
probs0 = (probs0 / probs0.sum(axis))
probs1 = (probs1 / probs1.sum(axis))
d2 = (((probs1 - probs0) ** 2) / probs0).sum(axis)
if (correction is not None):
(nobs, df) = correction
diff = ((probs1 - probs0) / probs0).sum(axis)
d2 = np.maximum(((((d2 * nobs) - diff) - df) / (nobs - 1.0)), 0)
if cohen:
return np.sqrt(d2)
else:
return d2
|
null | null | null | What uses a normal path ?
| def LocalPathToCanonicalPath(path):
return utils.NormalizePath(path)
| null | null | null | linux
| codeqa | def Local Path To Canonical Path path return utils Normalize Path path
| null | null | null | null | Question:
What uses a normal path ?
Code:
def LocalPathToCanonicalPath(path):
return utils.NormalizePath(path)
|
null | null | null | What runs the user ?
| def gemset_delete(ruby, gemset, runas=None):
return _rvm_do(ruby, ['rvm', '--force', 'gemset', 'delete', gemset], runas=runas)
| null | null | null | rvm
| codeqa | def gemset delete ruby gemset runas None return rvm do ruby ['rvm' '--force' 'gemset' 'delete' gemset] runas runas
| null | null | null | null | Question:
What runs the user ?
Code:
def gemset_delete(ruby, gemset, runas=None):
return _rvm_do(ruby, ['rvm', '--force', 'gemset', 'delete', gemset], runas=runas)
|
null | null | null | What do helper create ?
| @contextlib.contextmanager
def example_script(name, output='success'):
tempdir = tempfile.mkdtemp(prefix='tmp-pexpect-test')
try:
script_path = os.path.join(tempdir, name)
with open(script_path, 'w') as f:
f.write(('#!/bin/sh\necho "%s"' % (output,)))
try:
os.chmod(script_path, 493)
(yield tempdir)
finally:
os.remove(script_path)
finally:
os.rmdir(tempdir)
| null | null | null | a temporary shell script that tests can run
| codeqa | @contextlib contextmanagerdef example script name output 'success' tempdir tempfile mkdtemp prefix 'tmp-pexpect-test' try script path os path join tempdir name with open script path 'w' as f f write '# /bin/sh\necho"%s"' % output try os chmod script path 493 yield tempdir finally os remove script path finally os rmdir tempdir
| null | null | null | null | Question:
What do helper create ?
Code:
@contextlib.contextmanager
def example_script(name, output='success'):
tempdir = tempfile.mkdtemp(prefix='tmp-pexpect-test')
try:
script_path = os.path.join(tempdir, name)
with open(script_path, 'w') as f:
f.write(('#!/bin/sh\necho "%s"' % (output,)))
try:
os.chmod(script_path, 493)
(yield tempdir)
finally:
os.remove(script_path)
finally:
os.rmdir(tempdir)
|
null | null | null | What creates a temporary shell script that tests can run ?
| @contextlib.contextmanager
def example_script(name, output='success'):
tempdir = tempfile.mkdtemp(prefix='tmp-pexpect-test')
try:
script_path = os.path.join(tempdir, name)
with open(script_path, 'w') as f:
f.write(('#!/bin/sh\necho "%s"' % (output,)))
try:
os.chmod(script_path, 493)
(yield tempdir)
finally:
os.remove(script_path)
finally:
os.rmdir(tempdir)
| null | null | null | helper
| codeqa | @contextlib contextmanagerdef example script name output 'success' tempdir tempfile mkdtemp prefix 'tmp-pexpect-test' try script path os path join tempdir name with open script path 'w' as f f write '# /bin/sh\necho"%s"' % output try os chmod script path 493 yield tempdir finally os remove script path finally os rmdir tempdir
| null | null | null | null | Question:
What creates a temporary shell script that tests can run ?
Code:
@contextlib.contextmanager
def example_script(name, output='success'):
tempdir = tempfile.mkdtemp(prefix='tmp-pexpect-test')
try:
script_path = os.path.join(tempdir, name)
with open(script_path, 'w') as f:
f.write(('#!/bin/sh\necho "%s"' % (output,)))
try:
os.chmod(script_path, 493)
(yield tempdir)
finally:
os.remove(script_path)
finally:
os.rmdir(tempdir)
|
null | null | null | Where did a higher order function implement ?
| def get_course_blocks(user, starting_block_usage_key, transformers=None, collected_block_structure=None):
if (not transformers):
transformers = BlockStructureTransformers(COURSE_BLOCK_ACCESS_TRANSFORMERS)
transformers.usage_info = CourseUsageInfo(starting_block_usage_key.course_key, user)
return get_block_structure_manager(starting_block_usage_key.course_key).get_transformed(transformers, starting_block_usage_key, collected_block_structure)
| null | null | null | on top of the block_structure
| codeqa | def get course blocks user starting block usage key transformers None collected block structure None if not transformers transformers Block Structure Transformers COURSE BLOCK ACCESS TRANSFORMERS transformers usage info Course Usage Info starting block usage key course key user return get block structure manager starting block usage key course key get transformed transformers starting block usage key collected block structure
| null | null | null | null | Question:
Where did a higher order function implement ?
Code:
def get_course_blocks(user, starting_block_usage_key, transformers=None, collected_block_structure=None):
if (not transformers):
transformers = BlockStructureTransformers(COURSE_BLOCK_ACCESS_TRANSFORMERS)
transformers.usage_info = CourseUsageInfo(starting_block_usage_key.course_key, user)
return get_block_structure_manager(starting_block_usage_key.course_key).get_transformed(transformers, starting_block_usage_key, collected_block_structure)
|
null | null | null | What implemented on top of the block_structure ?
| def get_course_blocks(user, starting_block_usage_key, transformers=None, collected_block_structure=None):
if (not transformers):
transformers = BlockStructureTransformers(COURSE_BLOCK_ACCESS_TRANSFORMERS)
transformers.usage_info = CourseUsageInfo(starting_block_usage_key.course_key, user)
return get_block_structure_manager(starting_block_usage_key.course_key).get_transformed(transformers, starting_block_usage_key, collected_block_structure)
| null | null | null | a higher order function
| codeqa | def get course blocks user starting block usage key transformers None collected block structure None if not transformers transformers Block Structure Transformers COURSE BLOCK ACCESS TRANSFORMERS transformers usage info Course Usage Info starting block usage key course key user return get block structure manager starting block usage key course key get transformed transformers starting block usage key collected block structure
| null | null | null | null | Question:
What implemented on top of the block_structure ?
Code:
def get_course_blocks(user, starting_block_usage_key, transformers=None, collected_block_structure=None):
if (not transformers):
transformers = BlockStructureTransformers(COURSE_BLOCK_ACCESS_TRANSFORMERS)
transformers.usage_info = CourseUsageInfo(starting_block_usage_key.course_key, user)
return get_block_structure_manager(starting_block_usage_key.course_key).get_transformed(transformers, starting_block_usage_key, collected_block_structure)
|
null | null | null | What does the code create from config files ?
| def load_user_configuration(config_path=None):
user_defined_config = dict()
user_config_file = file_find('openstack_user_config.yml', preferred_path=config_path, raise_if_missing=False)
if (user_config_file is not False):
with open(user_config_file, 'rb') as f:
user_defined_config.update((yaml.safe_load(f.read()) or {}))
base_dir = dir_find(config_path, 'conf.d', raise_if_missing=False)
if (base_dir is not False):
_extra_config(user_defined_config, base_dir)
if (not user_defined_config):
raise MissingDataSource((_get_search_paths(config_path) + _get_search_paths(config_path, 'conf.d')))
logger.debug('User configuration loaded from: {}'.format(user_config_file))
return user_defined_config
| null | null | null | a user configuration dictionary
| codeqa | def load user configuration config path None user defined config dict user config file file find 'openstack user config yml' preferred path config path raise if missing False if user config file is not False with open user config file 'rb' as f user defined config update yaml safe load f read or {} base dir dir find config path 'conf d' raise if missing False if base dir is not False extra config user defined config base dir if not user defined config raise Missing Data Source get search paths config path + get search paths config path 'conf d' logger debug ' Userconfigurationloadedfrom {}' format user config file return user defined config
| null | null | null | null | Question:
What does the code create from config files ?
Code:
def load_user_configuration(config_path=None):
user_defined_config = dict()
user_config_file = file_find('openstack_user_config.yml', preferred_path=config_path, raise_if_missing=False)
if (user_config_file is not False):
with open(user_config_file, 'rb') as f:
user_defined_config.update((yaml.safe_load(f.read()) or {}))
base_dir = dir_find(config_path, 'conf.d', raise_if_missing=False)
if (base_dir is not False):
_extra_config(user_defined_config, base_dir)
if (not user_defined_config):
raise MissingDataSource((_get_search_paths(config_path) + _get_search_paths(config_path, 'conf.d')))
logger.debug('User configuration loaded from: {}'.format(user_config_file))
return user_defined_config
|
null | null | null | How do privilege enable ?
| def EnablePrivilege(privilegeStr, hToken=None):
if (hToken == None):
TOKEN_ADJUST_PRIVILEGES = 32
TOKEN_QUERY = 8
hToken = HANDLE(INVALID_HANDLE_VALUE)
hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, windll.kernel32.GetCurrentProcessId())
windll.advapi32.OpenProcessToken(hProcess, (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), byref(hToken))
e = GetLastError()
if (e != 0):
raise WinError(e)
windll.kernel32.CloseHandle(hProcess)
privilege_id = LUID()
windll.advapi32.LookupPrivilegeValueA(None, privilegeStr, byref(privilege_id))
e = GetLastError()
if (e != 0):
raise WinError(e)
SE_PRIVILEGE_ENABLED = 2
laa = LUID_AND_ATTRIBUTES(privilege_id, SE_PRIVILEGE_ENABLED)
tp = TOKEN_PRIVILEGES(1, laa)
windll.advapi32.AdjustTokenPrivileges(hToken, False, byref(tp), sizeof(tp), None, None)
e = GetLastError()
if (e != 0):
raise WinError(e)
| null | null | null | on token
| codeqa | def Enable Privilege privilege Str h Token None if h Token None TOKEN ADJUST PRIVILEGES 32 TOKEN QUERY 8h Token HANDLE INVALID HANDLE VALUE h Process windll kernel 32 Open Process PROCESS QUERY INFORMATION False windll kernel 32 Get Current Process Id windll advapi 32 Open Process Token h Process TOKEN ADJUST PRIVILEGES TOKEN QUERY byref h Token e Get Last Error if e 0 raise Win Error e windll kernel 32 Close Handle h Process privilege id LUID windll advapi 32 Lookup Privilege Value A None privilege Str byref privilege id e Get Last Error if e 0 raise Win Error e SE PRIVILEGE ENABLED 2laa LUID AND ATTRIBUTES privilege id SE PRIVILEGE ENABLED tp TOKEN PRIVILEGES 1 laa windll advapi 32 Adjust Token Privileges h Token False byref tp sizeof tp None None e Get Last Error if e 0 raise Win Error e
| null | null | null | null | Question:
How do privilege enable ?
Code:
def EnablePrivilege(privilegeStr, hToken=None):
if (hToken == None):
TOKEN_ADJUST_PRIVILEGES = 32
TOKEN_QUERY = 8
hToken = HANDLE(INVALID_HANDLE_VALUE)
hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, windll.kernel32.GetCurrentProcessId())
windll.advapi32.OpenProcessToken(hProcess, (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), byref(hToken))
e = GetLastError()
if (e != 0):
raise WinError(e)
windll.kernel32.CloseHandle(hProcess)
privilege_id = LUID()
windll.advapi32.LookupPrivilegeValueA(None, privilegeStr, byref(privilege_id))
e = GetLastError()
if (e != 0):
raise WinError(e)
SE_PRIVILEGE_ENABLED = 2
laa = LUID_AND_ATTRIBUTES(privilege_id, SE_PRIVILEGE_ENABLED)
tp = TOKEN_PRIVILEGES(1, laa)
windll.advapi32.AdjustTokenPrivileges(hToken, False, byref(tp), sizeof(tp), None, None)
e = GetLastError()
if (e != 0):
raise WinError(e)
|
null | null | null | What does the code create only with numbers ?
| def rand_number(length=0, exclude_numbers=()):
_digits = digits[:]
for excluded_number in set(exclude_numbers):
_digits = _digits.replace(str(excluded_number), '')
if (not _digits):
raise ValueError('Failed return random number.')
ru = ''.join((choice(_digits) for _ in xrange((length or randint(10, 30)))))
return ru
| null | null | null | a random string
| codeqa | def rand number length 0 exclude numbers digits digits[ ]for excluded number in set exclude numbers digits digits replace str excluded number '' if not digits raise Value Error ' Failedreturnrandomnumber ' ru '' join choice digits for in xrange length or randint 10 30 return ru
| null | null | null | null | Question:
What does the code create only with numbers ?
Code:
def rand_number(length=0, exclude_numbers=()):
_digits = digits[:]
for excluded_number in set(exclude_numbers):
_digits = _digits.replace(str(excluded_number), '')
if (not _digits):
raise ValueError('Failed return random number.')
ru = ''.join((choice(_digits) for _ in xrange((length or randint(10, 30)))))
return ru
|
null | null | null | How does the code create a random string ?
| def rand_number(length=0, exclude_numbers=()):
_digits = digits[:]
for excluded_number in set(exclude_numbers):
_digits = _digits.replace(str(excluded_number), '')
if (not _digits):
raise ValueError('Failed return random number.')
ru = ''.join((choice(_digits) for _ in xrange((length or randint(10, 30)))))
return ru
| null | null | null | only with numbers
| codeqa | def rand number length 0 exclude numbers digits digits[ ]for excluded number in set exclude numbers digits digits replace str excluded number '' if not digits raise Value Error ' Failedreturnrandomnumber ' ru '' join choice digits for in xrange length or randint 10 30 return ru
| null | null | null | null | Question:
How does the code create a random string ?
Code:
def rand_number(length=0, exclude_numbers=()):
_digits = digits[:]
for excluded_number in set(exclude_numbers):
_digits = _digits.replace(str(excluded_number), '')
if (not _digits):
raise ValueError('Failed return random number.')
ru = ''.join((choice(_digits) for _ in xrange((length or randint(10, 30)))))
return ru
|
null | null | null | What does the code get ?
| def path_separator():
return PATH_SEPARATOR[_os.name]
| null | null | null | the path separator for the current operating system
| codeqa | def path separator return PATH SEPARATOR[ os name]
| null | null | null | null | Question:
What does the code get ?
Code:
def path_separator():
return PATH_SEPARATOR[_os.name]
|
null | null | null | What does the code delete from a db ?
| def delete(uri):
return salt.utils.sdb.sdb_delete(uri, __opts__)
| null | null | null | a value
| codeqa | def delete uri return salt utils sdb sdb delete uri opts
| null | null | null | null | Question:
What does the code delete from a db ?
Code:
def delete(uri):
return salt.utils.sdb.sdb_delete(uri, __opts__)
|
null | null | null | What does the code get ?
| def _get_lights():
return _query(None, None)
| null | null | null | all available lighting devices
| codeqa | def get lights return query None None
| null | null | null | null | Question:
What does the code get ?
Code:
def _get_lights():
return _query(None, None)
|
null | null | null | How does the code create an item ?
| def item_create(item, item_id, item_type, create='create', extra_args=None, cibfile=None):
cmd = ['pcs']
if isinstance(cibfile, six.string_types):
cmd += ['-f', cibfile]
if isinstance(item, six.string_types):
cmd += [item]
elif isinstance(item, (list, tuple)):
cmd += item
if (item in ['constraint']):
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(create, six.string_types):
cmd += [create]
elif isinstance(create, (list, tuple)):
cmd += create
if (item not in ['constraint']):
cmd += [item_id]
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(extra_args, (list, tuple)):
if (item in ['constraint']):
extra_args = (extra_args + ['id={0}'.format(item_id)])
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)
| null | null | null | via pcs command item config
| codeqa | def item create item item id item type create 'create' extra args None cibfile None cmd ['pcs']if isinstance cibfile six string types cmd + ['-f' cibfile]if isinstance item six string types cmd + [item]elif isinstance item list tuple cmd + itemif item in ['constraint'] if isinstance item type six string types cmd + [item type]if isinstance create six string types cmd + [create]elif isinstance create list tuple cmd + createif item not in ['constraint'] cmd + [item id]if isinstance item type six string types cmd + [item type]if isinstance extra args list tuple if item in ['constraint'] extra args extra args + ['id {0 }' format item id ] cmd + extra argsreturn salt ['cmd run all'] cmd output loglevel 'trace' python shell False
| null | null | null | null | Question:
How does the code create an item ?
Code:
def item_create(item, item_id, item_type, create='create', extra_args=None, cibfile=None):
cmd = ['pcs']
if isinstance(cibfile, six.string_types):
cmd += ['-f', cibfile]
if isinstance(item, six.string_types):
cmd += [item]
elif isinstance(item, (list, tuple)):
cmd += item
if (item in ['constraint']):
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(create, six.string_types):
cmd += [create]
elif isinstance(create, (list, tuple)):
cmd += create
if (item not in ['constraint']):
cmd += [item_id]
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(extra_args, (list, tuple)):
if (item in ['constraint']):
extra_args = (extra_args + ['id={0}'.format(item_id)])
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)
|
null | null | null | What does the code create via pcs command item config ?
| def item_create(item, item_id, item_type, create='create', extra_args=None, cibfile=None):
cmd = ['pcs']
if isinstance(cibfile, six.string_types):
cmd += ['-f', cibfile]
if isinstance(item, six.string_types):
cmd += [item]
elif isinstance(item, (list, tuple)):
cmd += item
if (item in ['constraint']):
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(create, six.string_types):
cmd += [create]
elif isinstance(create, (list, tuple)):
cmd += create
if (item not in ['constraint']):
cmd += [item_id]
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(extra_args, (list, tuple)):
if (item in ['constraint']):
extra_args = (extra_args + ['id={0}'.format(item_id)])
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)
| null | null | null | an item
| codeqa | def item create item item id item type create 'create' extra args None cibfile None cmd ['pcs']if isinstance cibfile six string types cmd + ['-f' cibfile]if isinstance item six string types cmd + [item]elif isinstance item list tuple cmd + itemif item in ['constraint'] if isinstance item type six string types cmd + [item type]if isinstance create six string types cmd + [create]elif isinstance create list tuple cmd + createif item not in ['constraint'] cmd + [item id]if isinstance item type six string types cmd + [item type]if isinstance extra args list tuple if item in ['constraint'] extra args extra args + ['id {0 }' format item id ] cmd + extra argsreturn salt ['cmd run all'] cmd output loglevel 'trace' python shell False
| null | null | null | null | Question:
What does the code create via pcs command item config ?
Code:
def item_create(item, item_id, item_type, create='create', extra_args=None, cibfile=None):
cmd = ['pcs']
if isinstance(cibfile, six.string_types):
cmd += ['-f', cibfile]
if isinstance(item, six.string_types):
cmd += [item]
elif isinstance(item, (list, tuple)):
cmd += item
if (item in ['constraint']):
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(create, six.string_types):
cmd += [create]
elif isinstance(create, (list, tuple)):
cmd += create
if (item not in ['constraint']):
cmd += [item_id]
if isinstance(item_type, six.string_types):
cmd += [item_type]
if isinstance(extra_args, (list, tuple)):
if (item in ['constraint']):
extra_args = (extra_args + ['id={0}'.format(item_id)])
cmd += extra_args
return __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)
|
null | null | null | What does the code update ?
| def _connect_user(request, facebook, overwrite=True):
if (not request.user.is_authenticated()):
raise ValueError('Connect user can only be used on authenticated users')
if (not facebook.is_authenticated()):
raise ValueError('Facebook needs to be authenticated for connect flows')
data = facebook.facebook_profile_data()
facebook_id = data['id']
old_connections = _get_old_connections(facebook_id, request.user.id)[:20]
if (old_connections and (not (request.POST.get('confirm_connect') or request.GET.get('confirm_connect')))):
raise facebook_exceptions.AlreadyConnectedError(list(old_connections))
user = _update_user(request.user, facebook, overwrite=overwrite)
return user
| null | null | null | the fields on the user model
| codeqa | def connect user request facebook overwrite True if not request user is authenticated raise Value Error ' Connectusercanonlybeusedonauthenticatedusers' if not facebook is authenticated raise Value Error ' Facebookneedstobeauthenticatedforconnectflows' data facebook facebook profile data facebook id data['id']old connections get old connections facebook id request user id [ 20 ]if old connections and not request POST get 'confirm connect' or request GET get 'confirm connect' raise facebook exceptions Already Connected Error list old connections user update user request user facebook overwrite overwrite return user
| null | null | null | null | Question:
What does the code update ?
Code:
def _connect_user(request, facebook, overwrite=True):
if (not request.user.is_authenticated()):
raise ValueError('Connect user can only be used on authenticated users')
if (not facebook.is_authenticated()):
raise ValueError('Facebook needs to be authenticated for connect flows')
data = facebook.facebook_profile_data()
facebook_id = data['id']
old_connections = _get_old_connections(facebook_id, request.user.id)[:20]
if (old_connections and (not (request.POST.get('confirm_connect') or request.GET.get('confirm_connect')))):
raise facebook_exceptions.AlreadyConnectedError(list(old_connections))
user = _update_user(request.user, facebook, overwrite=overwrite)
return user
|
null | null | null | What does the code get ?
| def get_email_from_username(username):
user_model = user_models.UserSettingsModel.get_by_normalized_username(UserSettings.normalize_username(username))
if (user_model is None):
return None
else:
return user_model.email
| null | null | null | the email for a given username
| codeqa | def get email from username username user model user models User Settings Model get by normalized username User Settings normalize username username if user model is None return Noneelse return user model email
| null | null | null | null | Question:
What does the code get ?
Code:
def get_email_from_username(username):
user_model = user_models.UserSettingsModel.get_by_normalized_username(UserSettings.normalize_username(username))
if (user_model is None):
return None
else:
return user_model.email
|
null | null | null | Till when is this one wrong ?
| def cov_crosssection_0(results, group):
scale = S_crosssection(results.resid[:, None], group)
scale = np.squeeze(scale)
cov = _HCCM1(results, scale)
return cov
| null | null | null | still
| codeqa | def cov crosssection 0 results group scale S crosssection results resid[ None] group scale np squeeze scale cov HCCM 1 results scale return cov
| null | null | null | null | Question:
Till when is this one wrong ?
Code:
def cov_crosssection_0(results, group):
scale = S_crosssection(results.resid[:, None], group)
scale = np.squeeze(scale)
cov = _HCCM1(results, scale)
return cov
|
null | null | null | How do multiple patches perform ?
| def _patch_multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs):
def g_importer():
return _importer(target)
def g_target():
return target
if (type(target) in (unicode, str)):
getter = g_importer
else:
getter = g_target
if (not kwargs):
raise ValueError('Must supply at least one keyword argument with patch.multiple')
items = list(kwargs.items())
(attribute, new) = items[0]
patcher = _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, {})
patcher.attribute_name = attribute
for (attribute, new) in items[1:]:
this_patcher = _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, {})
this_patcher.attribute_name = attribute
patcher.additional_patchers.append(this_patcher)
return patcher
| null | null | null | in a single call
| codeqa | def patch multiple target spec None create False spec set None autospec None new callable None **kwargs def g importer return importer target def g target return targetif type target in unicode str getter g importerelse getter g targetif not kwargs raise Value Error ' Mustsupplyatleastonekeywordargumentwithpatch multiple' items list kwargs items attribute new items[ 0 ]patcher patch getter attribute new spec create spec set autospec new callable {} patcher attribute name attributefor attribute new in items[ 1 ] this patcher patch getter attribute new spec create spec set autospec new callable {} this patcher attribute name attributepatcher additional patchers append this patcher return patcher
| null | null | null | null | Question:
How do multiple patches perform ?
Code:
def _patch_multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs):
def g_importer():
return _importer(target)
def g_target():
return target
if (type(target) in (unicode, str)):
getter = g_importer
else:
getter = g_target
if (not kwargs):
raise ValueError('Must supply at least one keyword argument with patch.multiple')
items = list(kwargs.items())
(attribute, new) = items[0]
patcher = _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, {})
patcher.attribute_name = attribute
for (attribute, new) in items[1:]:
this_patcher = _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, {})
this_patcher.attribute_name = attribute
patcher.additional_patchers.append(this_patcher)
return patcher
|
null | null | null | What does the code write ?
| def read_compressed(path):
with gzip.open(path, 'rb') as f:
return f.read()
| null | null | null | a compressed file
| codeqa | def read compressed path with gzip open path 'rb' as f return f read
| null | null | null | null | Question:
What does the code write ?
Code:
def read_compressed(path):
with gzip.open(path, 'rb') as f:
return f.read()
|
null | null | null | What does the code get by length ?
| def getWiddershinsByLength(begin, end, length):
endMinusBegin = (end - begin)
endMinusBeginLength = abs(endMinusBegin)
if (endMinusBeginLength <= 0.0):
return None
endMinusBegin *= (length / endMinusBeginLength)
return complex((- endMinusBegin.imag), endMinusBegin.real)
| null | null | null | the widdershins
| codeqa | def get Widdershins By Length begin end length end Minus Begin end - begin end Minus Begin Length abs end Minus Begin if end Minus Begin Length < 0 0 return Noneend Minus Begin * length / end Minus Begin Length return complex - end Minus Begin imag end Minus Begin real
| null | null | null | null | Question:
What does the code get by length ?
Code:
def getWiddershinsByLength(begin, end, length):
endMinusBegin = (end - begin)
endMinusBeginLength = abs(endMinusBegin)
if (endMinusBeginLength <= 0.0):
return None
endMinusBegin *= (length / endMinusBeginLength)
return complex((- endMinusBegin.imag), endMinusBegin.real)
|
null | null | null | What did the code give ?
| def _check_for_nonzero_return_code(reason):
m = _BOOTSTRAP_NONZERO_RETURN_CODE_RE.match(reason)
if m:
return _extract_action_num_and_node_id(m)
else:
return None
| null | null | null | a reason for cluster termination
| codeqa | def check for nonzero return code reason m BOOTSTRAP NONZERO RETURN CODE RE match reason if m return extract action num and node id m else return None
| null | null | null | null | Question:
What did the code give ?
Code:
def _check_for_nonzero_return_code(reason):
m = _BOOTSTRAP_NONZERO_RETURN_CODE_RE.match(reason)
if m:
return _extract_action_num_and_node_id(m)
else:
return None
|
null | null | null | What does the code process ?
| def inputhook_wx1():
try:
app = wx.GetApp()
if (app is not None):
assert wx.Thread_IsMain()
evtloop = wx.EventLoop()
ea = wx.EventLoopActivator(evtloop)
while evtloop.Pending():
evtloop.Dispatch()
app.ProcessIdle()
del ea
except KeyboardInterrupt:
pass
return 0
| null | null | null | pending events only
| codeqa | def inputhook wx 1 try app wx Get App if app is not None assert wx Thread Is Main evtloop wx Event Loop ea wx Event Loop Activator evtloop while evtloop Pending evtloop Dispatch app Process Idle del eaexcept Keyboard Interrupt passreturn 0
| null | null | null | null | Question:
What does the code process ?
Code:
def inputhook_wx1():
try:
app = wx.GetApp()
if (app is not None):
assert wx.Thread_IsMain()
evtloop = wx.EventLoop()
ea = wx.EventLoopActivator(evtloop)
while evtloop.Pending():
evtloop.Dispatch()
app.ProcessIdle()
del ea
except KeyboardInterrupt:
pass
return 0
|
null | null | null | In which direction d unique network i d get ?
| def _find_network_id_novanet(cs, net_name):
network_id = None
for net_info in cs.networks.list():
if (net_name == net_info.label):
if (network_id is not None):
msg = (_("Multiple network name matches found for name '%s', use network ID to be more specific.") % net_name)
raise exceptions.NoUniqueMatch(msg)
else:
network_id = net_info.id
if (network_id is None):
msg = (_("No network name match for name '%s'") % net_name)
raise exceptions.ResourceNotFound((msg % {'network': net_name}))
else:
return network_id
| null | null | null | from network name
| codeqa | def find network id novanet cs net name network id Nonefor net info in cs networks list if net name net info label if network id is not None msg " Multiplenetworknamematchesfoundforname'%s' usenetwork I Dtobemorespecific " % net name raise exceptions No Unique Match msg else network id net info idif network id is None msg " Nonetworknamematchforname'%s'" % net name raise exceptions Resource Not Found msg % {'network' net name} else return network id
| null | null | null | null | Question:
In which direction d unique network i d get ?
Code:
def _find_network_id_novanet(cs, net_name):
network_id = None
for net_info in cs.networks.list():
if (net_name == net_info.label):
if (network_id is not None):
msg = (_("Multiple network name matches found for name '%s', use network ID to be more specific.") % net_name)
raise exceptions.NoUniqueMatch(msg)
else:
network_id = net_info.id
if (network_id is None):
msg = (_("No network name match for name '%s'") % net_name)
raise exceptions.ResourceNotFound((msg % {'network': net_name}))
else:
return network_id
|
null | null | null | What does the code find ?
| def nlargest(n, iterable):
if (n < 0):
return []
it = iter(iterable)
result = list(islice(it, n))
if (not result):
return result
heapify(result)
_heappushpop = heappushpop
for elem in it:
_heappushpop(result, elem)
result.sort(reverse=True)
return result
| null | null | null | the n largest elements in a dataset
| codeqa | def nlargest n iterable if n < 0 return []it iter iterable result list islice it n if not result return resultheapify result heappushpop heappushpopfor elem in it heappushpop result elem result sort reverse True return result
| null | null | null | null | Question:
What does the code find ?
Code:
def nlargest(n, iterable):
if (n < 0):
return []
it = iter(iterable)
result = list(islice(it, n))
if (not result):
return result
heapify(result)
_heappushpop = heappushpop
for elem in it:
_heappushpop(result, elem)
result.sort(reverse=True)
return result
|
null | null | null | What does the user change ?
| def unset(bot, update, chat_data):
if ('job' not in chat_data):
update.message.reply_text('You have no active timer')
return
job = chat_data['job']
job.schedule_removal()
del chat_data['job']
update.message.reply_text('Timer successfully unset!')
| null | null | null | their mind
| codeqa | def unset bot update chat data if 'job' not in chat data update message reply text ' Youhavenoactivetimer' returnjob chat data['job']job schedule removal del chat data['job']update message reply text ' Timersuccessfullyunset '
| null | null | null | null | Question:
What does the user change ?
Code:
def unset(bot, update, chat_data):
if ('job' not in chat_data):
update.message.reply_text('You have no active timer')
return
job = chat_data['job']
job.schedule_removal()
del chat_data['job']
update.message.reply_text('Timer successfully unset!')
|
null | null | null | What does the code remove if the user changed their mind ?
| def unset(bot, update, chat_data):
if ('job' not in chat_data):
update.message.reply_text('You have no active timer')
return
job = chat_data['job']
job.schedule_removal()
del chat_data['job']
update.message.reply_text('Timer successfully unset!')
| null | null | null | the job
| codeqa | def unset bot update chat data if 'job' not in chat data update message reply text ' Youhavenoactivetimer' returnjob chat data['job']job schedule removal del chat data['job']update message reply text ' Timersuccessfullyunset '
| null | null | null | null | Question:
What does the code remove if the user changed their mind ?
Code:
def unset(bot, update, chat_data):
if ('job' not in chat_data):
update.message.reply_text('You have no active timer')
return
job = chat_data['job']
job.schedule_removal()
del chat_data['job']
update.message.reply_text('Timer successfully unset!')
|
null | null | null | What changed their mind ?
| def unset(bot, update, chat_data):
if ('job' not in chat_data):
update.message.reply_text('You have no active timer')
return
job = chat_data['job']
job.schedule_removal()
del chat_data['job']
update.message.reply_text('Timer successfully unset!')
| null | null | null | the user
| codeqa | def unset bot update chat data if 'job' not in chat data update message reply text ' Youhavenoactivetimer' returnjob chat data['job']job schedule removal del chat data['job']update message reply text ' Timersuccessfullyunset '
| null | null | null | null | Question:
What changed their mind ?
Code:
def unset(bot, update, chat_data):
if ('job' not in chat_data):
update.message.reply_text('You have no active timer')
return
job = chat_data['job']
job.schedule_removal()
del chat_data['job']
update.message.reply_text('Timer successfully unset!')
|
null | null | null | For what purpose do default price list return ?
| def get_default_price_list(party):
if party.default_price_list:
return party.default_price_list
if (party.doctype == u'Customer'):
price_list = frappe.db.get_value(u'Customer Group', party.customer_group, u'default_price_list')
if price_list:
return price_list
return None
| null | null | null | for party
| codeqa | def get default price list party if party default price list return party default price listif party doctype u' Customer' price list frappe db get value u' Customer Group' party customer group u'default price list' if price list return price listreturn None
| null | null | null | null | Question:
For what purpose do default price list return ?
Code:
def get_default_price_list(party):
if party.default_price_list:
return party.default_price_list
if (party.doctype == u'Customer'):
price_list = frappe.db.get_value(u'Customer Group', party.customer_group, u'default_price_list')
if price_list:
return price_list
return None
|
null | null | null | How did parity bits set ?
| def adjust_key_parity(key_in):
def parity_byte(key_byte):
parity = 1
for i in xrange(1, 8):
parity ^= ((key_byte >> i) & 1)
return ((key_byte & 254) | parity)
if (len(key_in) not in key_size):
raise ValueError('Not a valid TDES key')
key_out = b('').join([bchr(parity_byte(bord(x))) for x in key_in])
if ((key_out[:8] == key_out[8:16]) or (key_out[(-16):(-8)] == key_out[(-8):])):
raise ValueError('Triple DES key degenerates to single DES')
return key_out
| null | null | null | correctly
| codeqa | def adjust key parity key in def parity byte key byte parity 1for i in xrange 1 8 parity ^ key byte >> i & 1 return key byte & 254 parity if len key in not in key size raise Value Error ' Notavalid TDE Skey' key out b '' join [bchr parity byte bord x for x in key in] if key out[ 8] key out[ 8 16 ] or key out[ -16 -8 ] key out[ -8 ] raise Value Error ' Triple DE Skeydegeneratestosingle DES' return key out
| null | null | null | null | Question:
How did parity bits set ?
Code:
def adjust_key_parity(key_in):
def parity_byte(key_byte):
parity = 1
for i in xrange(1, 8):
parity ^= ((key_byte >> i) & 1)
return ((key_byte & 254) | parity)
if (len(key_in) not in key_size):
raise ValueError('Not a valid TDES key')
key_out = b('').join([bchr(parity_byte(bord(x))) for x in key_in])
if ((key_out[:8] == key_out[8:16]) or (key_out[(-16):(-8)] == key_out[(-8):])):
raise ValueError('Triple DES key degenerates to single DES')
return key_out
|
null | null | null | What does the code remove ?
| def delete(fun):
if (__opts__['file_client'] == 'local'):
data = __salt__['data.get']('mine_cache')
if (isinstance(data, dict) and (fun in data)):
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {'cmd': '_mine_delete', 'id': __opts__['id'], 'fun': fun}
return _mine_send(load, __opts__)
| null | null | null | specific function contents of minion
| codeqa | def delete fun if opts ['file client'] 'local' data salt ['data get'] 'mine cache' if isinstance data dict and fun in data del data[fun]return salt ['data update'] 'mine cache' data load {'cmd' ' mine delete' 'id' opts ['id'] 'fun' fun}return mine send load opts
| null | null | null | null | Question:
What does the code remove ?
Code:
def delete(fun):
if (__opts__['file_client'] == 'local'):
data = __salt__['data.get']('mine_cache')
if (isinstance(data, dict) and (fun in data)):
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {'cmd': '_mine_delete', 'id': __opts__['id'], 'fun': fun}
return _mine_send(load, __opts__)
|
null | null | null | What do logging exceptions leave ?
| def logExceptions(logger=None):
logger = (logger if (logger is not None) else logging.getLogger(__name__))
def exceptionLoggingDecorator(func):
@functools.wraps(func)
def exceptionLoggingWrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
logger.exception('Unhandled exception %r from %r. Caller stack:\n%s', sys.exc_info()[1], func, ''.join(traceback.format_stack()))
raise
return exceptionLoggingWrap
return exceptionLoggingDecorator
| null | null | null | the scope of the decorated function
| codeqa | def log Exceptions logger None logger logger if logger is not None else logging get Logger name def exception Logging Decorator func @functools wraps func def exception Logging Wrap *args **kwargs try return func *args **kwargs except logger exception ' Unhandledexception%rfrom%r Callerstack \n%s' sys exc info [1 ] func '' join traceback format stack raisereturn exception Logging Wrapreturn exception Logging Decorator
| null | null | null | null | Question:
What do logging exceptions leave ?
Code:
def logExceptions(logger=None):
logger = (logger if (logger is not None) else logging.getLogger(__name__))
def exceptionLoggingDecorator(func):
@functools.wraps(func)
def exceptionLoggingWrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
logger.exception('Unhandled exception %r from %r. Caller stack:\n%s', sys.exc_info()[1], func, ''.join(traceback.format_stack()))
raise
return exceptionLoggingWrap
return exceptionLoggingDecorator
|
null | null | null | What leave the scope of the decorated function ?
| def logExceptions(logger=None):
logger = (logger if (logger is not None) else logging.getLogger(__name__))
def exceptionLoggingDecorator(func):
@functools.wraps(func)
def exceptionLoggingWrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
logger.exception('Unhandled exception %r from %r. Caller stack:\n%s', sys.exc_info()[1], func, ''.join(traceback.format_stack()))
raise
return exceptionLoggingWrap
return exceptionLoggingDecorator
| null | null | null | logging exceptions
| codeqa | def log Exceptions logger None logger logger if logger is not None else logging get Logger name def exception Logging Decorator func @functools wraps func def exception Logging Wrap *args **kwargs try return func *args **kwargs except logger exception ' Unhandledexception%rfrom%r Callerstack \n%s' sys exc info [1 ] func '' join traceback format stack raisereturn exception Logging Wrapreturn exception Logging Decorator
| null | null | null | null | Question:
What leave the scope of the decorated function ?
Code:
def logExceptions(logger=None):
logger = (logger if (logger is not None) else logging.getLogger(__name__))
def exceptionLoggingDecorator(func):
@functools.wraps(func)
def exceptionLoggingWrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
logger.exception('Unhandled exception %r from %r. Caller stack:\n%s', sys.exc_info()[1], func, ''.join(traceback.format_stack()))
raise
return exceptionLoggingWrap
return exceptionLoggingDecorator
|
null | null | null | What does the code get ?
| def getProfileDescription(profile):
try:
if (not isinstance(profile, ImageCmsProfile)):
profile = ImageCmsProfile(profile)
return (profile.profile.product_description + '\n')
except (AttributeError, IOError, TypeError, ValueError) as v:
raise PyCMSError(v)
| null | null | null | the description for the given profile
| codeqa | def get Profile Description profile try if not isinstance profile Image Cms Profile profile Image Cms Profile profile return profile profile product description + '\n' except Attribute Error IO Error Type Error Value Error as v raise Py CMS Error v
| null | null | null | null | Question:
What does the code get ?
Code:
def getProfileDescription(profile):
try:
if (not isinstance(profile, ImageCmsProfile)):
profile = ImageCmsProfile(profile)
return (profile.profile.product_description + '\n')
except (AttributeError, IOError, TypeError, ValueError) as v:
raise PyCMSError(v)
|
null | null | null | What does the code apply to each element of the matrix mat ?
| def floor(mat, target=None):
if (not target):
target = mat
err_code = _cudamat.apply_floor(mat.p_mat, target.p_mat)
if err_code:
raise generate_exception(err_code)
return target
| null | null | null | the floor function
| codeqa | def floor mat target None if not target target materr code cudamat apply floor mat p mat target p mat if err code raise generate exception err code return target
| null | null | null | null | Question:
What does the code apply to each element of the matrix mat ?
Code:
def floor(mat, target=None):
if (not target):
target = mat
err_code = _cudamat.apply_floor(mat.p_mat, target.p_mat)
if err_code:
raise generate_exception(err_code)
return target
|
null | null | null | What does the code compute ?
| def pinv2(a, cond=None, rcond=None, return_rank=False, check_finite=True):
a = _asarray_validated(a, check_finite=check_finite)
(u, s, vh) = decomp_svd.svd(a, full_matrices=False, check_finite=False)
if (rcond is not None):
cond = rcond
if (cond in [None, (-1)]):
t = u.dtype.char.lower()
factor = {'f': 1000.0, 'd': 1000000.0}
cond = (factor[t] * np.finfo(t).eps)
rank = np.sum((s > (cond * np.max(s))))
u = u[:, :rank]
u /= s[:rank]
B = np.transpose(np.conjugate(np.dot(u, vh[:rank])))
if return_rank:
return (B, rank)
else:
return B
| null | null | null | the pseudo - inverse of a matrix
| codeqa | def pinv 2 a cond None rcond None return rank False check finite True a asarray validated a check finite check finite u s vh decomp svd svd a full matrices False check finite False if rcond is not None cond rcondif cond in [ None -1 ] t u dtype char lower factor {'f' 1000 0 'd' 1000000 0}cond factor[t] * np finfo t eps rank np sum s > cond * np max s u u[ rank]u / s[ rank]B np transpose np conjugate np dot u vh[ rank] if return rank return B rank else return B
| null | null | null | null | Question:
What does the code compute ?
Code:
def pinv2(a, cond=None, rcond=None, return_rank=False, check_finite=True):
a = _asarray_validated(a, check_finite=check_finite)
(u, s, vh) = decomp_svd.svd(a, full_matrices=False, check_finite=False)
if (rcond is not None):
cond = rcond
if (cond in [None, (-1)]):
t = u.dtype.char.lower()
factor = {'f': 1000.0, 'd': 1000000.0}
cond = (factor[t] * np.finfo(t).eps)
rank = np.sum((s > (cond * np.max(s))))
u = u[:, :rank]
u /= s[:rank]
B = np.transpose(np.conjugate(np.dot(u, vh[:rank])))
if return_rank:
return (B, rank)
else:
return B
|
null | null | null | When does the code truncate a string ?
| def truncate_words(content, length=10, suffix='...'):
split = content.split()
if (len(split) <= length):
return ' '.join(split[:length])
else:
return (' '.join(split[:length]) + suffix)
| null | null | null | after a certain number of words
| codeqa | def truncate words content length 10 suffix ' ' split content split if len split < length return '' join split[ length] else return '' join split[ length] + suffix
| null | null | null | null | Question:
When does the code truncate a string ?
Code:
def truncate_words(content, length=10, suffix='...'):
split = content.split()
if (len(split) <= length):
return ' '.join(split[:length])
else:
return (' '.join(split[:length]) + suffix)
|
null | null | null | What does the code truncate after a certain number of words ?
| def truncate_words(content, length=10, suffix='...'):
split = content.split()
if (len(split) <= length):
return ' '.join(split[:length])
else:
return (' '.join(split[:length]) + suffix)
| null | null | null | a string
| codeqa | def truncate words content length 10 suffix ' ' split content split if len split < length return '' join split[ length] else return '' join split[ length] + suffix
| null | null | null | null | Question:
What does the code truncate after a certain number of words ?
Code:
def truncate_words(content, length=10, suffix='...'):
split = content.split()
if (len(split) <= length):
return ' '.join(split[:length])
else:
return (' '.join(split[:length]) + suffix)
|
null | null | null | How does a function return ?
| def return_future(f):
replacer = ArgReplacer(f, 'callback')
@functools.wraps(f)
def wrapper(*args, **kwargs):
future = TracebackFuture()
(callback, args, kwargs) = replacer.replace((lambda value=_NO_RESULT: future.set_result(value)), args, kwargs)
def handle_error(typ, value, tb):
future.set_exc_info((typ, value, tb))
return True
exc_info = None
with ExceptionStackContext(handle_error):
try:
result = f(*args, **kwargs)
if (result is not None):
raise ReturnValueIgnoredError('@return_future should not be used with functions that return values')
except:
exc_info = sys.exc_info()
raise
if (exc_info is not None):
raise_exc_info(exc_info)
if (callback is not None):
def run_callback(future):
result = future.result()
if (result is _NO_RESULT):
callback()
else:
callback(future.result())
future.add_done_callback(wrap(run_callback))
return future
return wrapper
| null | null | null | via callback
| codeqa | def return future f replacer Arg Replacer f 'callback' @functools wraps f def wrapper *args **kwargs future Traceback Future callback args kwargs replacer replace lambda value NO RESULT future set result value args kwargs def handle error typ value tb future set exc info typ value tb return Trueexc info Nonewith Exception Stack Context handle error try result f *args **kwargs if result is not None raise Return Value Ignored Error '@return futureshouldnotbeusedwithfunctionsthatreturnvalues' except exc info sys exc info raiseif exc info is not None raise exc info exc info if callback is not None def run callback future result future result if result is NO RESULT callback else callback future result future add done callback wrap run callback return futurereturn wrapper
| null | null | null | null | Question:
How does a function return ?
Code:
def return_future(f):
replacer = ArgReplacer(f, 'callback')
@functools.wraps(f)
def wrapper(*args, **kwargs):
future = TracebackFuture()
(callback, args, kwargs) = replacer.replace((lambda value=_NO_RESULT: future.set_result(value)), args, kwargs)
def handle_error(typ, value, tb):
future.set_exc_info((typ, value, tb))
return True
exc_info = None
with ExceptionStackContext(handle_error):
try:
result = f(*args, **kwargs)
if (result is not None):
raise ReturnValueIgnoredError('@return_future should not be used with functions that return values')
except:
exc_info = sys.exc_info()
raise
if (exc_info is not None):
raise_exc_info(exc_info)
if (callback is not None):
def run_callback(future):
result = future.result()
if (result is _NO_RESULT):
callback()
else:
callback(future.result())
future.add_done_callback(wrap(run_callback))
return future
return wrapper
|
null | null | null | Where do all tests return ?
| def iter_suite_tests(suite):
for item in suite._tests:
if isinstance(item, unittest.TestCase):
(yield item)
elif isinstance(item, unittest.TestSuite):
for r in iter_suite_tests(item):
(yield r)
else:
raise Exception(('unknown object %r inside test suite %r' % (item, suite)))
| null | null | null | in a suite
| codeqa | def iter suite tests suite for item in suite tests if isinstance item unittest Test Case yield item elif isinstance item unittest Test Suite for r in iter suite tests item yield r else raise Exception 'unknownobject%rinsidetestsuite%r' % item suite
| null | null | null | null | Question:
Where do all tests return ?
Code:
def iter_suite_tests(suite):
for item in suite._tests:
if isinstance(item, unittest.TestCase):
(yield item)
elif isinstance(item, unittest.TestSuite):
for r in iter_suite_tests(item):
(yield r)
else:
raise Exception(('unknown object %r inside test suite %r' % (item, suite)))
|
null | null | null | What returns in a suite ?
| def iter_suite_tests(suite):
for item in suite._tests:
if isinstance(item, unittest.TestCase):
(yield item)
elif isinstance(item, unittest.TestSuite):
for r in iter_suite_tests(item):
(yield r)
else:
raise Exception(('unknown object %r inside test suite %r' % (item, suite)))
| null | null | null | all tests
| codeqa | def iter suite tests suite for item in suite tests if isinstance item unittest Test Case yield item elif isinstance item unittest Test Suite for r in iter suite tests item yield r else raise Exception 'unknownobject%rinsidetestsuite%r' % item suite
| null | null | null | null | Question:
What returns in a suite ?
Code:
def iter_suite_tests(suite):
for item in suite._tests:
if isinstance(item, unittest.TestCase):
(yield item)
elif isinstance(item, unittest.TestSuite):
for r in iter_suite_tests(item):
(yield r)
else:
raise Exception(('unknown object %r inside test suite %r' % (item, suite)))
|
null | null | null | What does the code try ?
| def get_title(url):
if ((not url) or (not url.startswith(('http://', 'https://')))):
return None
try:
req = Request(url)
if g.useragent:
req.add_header('User-Agent', g.useragent)
opener = urlopen(req, timeout=15)
for param in opener.info().getplist():
if param.startswith('charset='):
(param_name, sep, charset) = param.partition('=')
codec = codecs.getreader(charset)
break
else:
codec = codecs.getreader('utf-8')
with codec(opener, 'ignore') as reader:
data = reader.read(1024)
title = extract_title(data)
if (not title):
data += reader.read(10240)
title = extract_title(data)
return title
except:
return None
| null | null | null | to extract the pages title
| codeqa | def get title url if not url or not url startswith 'http //' 'https //' return Nonetry req Request url if g useragent req add header ' User- Agent' g useragent opener urlopen req timeout 15 for param in opener info getplist if param startswith 'charset ' param name sep charset param partition ' ' codec codecs getreader charset breakelse codec codecs getreader 'utf- 8 ' with codec opener 'ignore' as reader data reader read 1024 title extract title data if not title data + reader read 10240 title extract title data return titleexcept return None
| null | null | null | null | Question:
What does the code try ?
Code:
def get_title(url):
if ((not url) or (not url.startswith(('http://', 'https://')))):
return None
try:
req = Request(url)
if g.useragent:
req.add_header('User-Agent', g.useragent)
opener = urlopen(req, timeout=15)
for param in opener.info().getplist():
if param.startswith('charset='):
(param_name, sep, charset) = param.partition('=')
codec = codecs.getreader(charset)
break
else:
codec = codecs.getreader('utf-8')
with codec(opener, 'ignore') as reader:
data = reader.read(1024)
title = extract_title(data)
if (not title):
data += reader.read(10240)
title = extract_title(data)
return title
except:
return None
|
null | null | null | What does the code extract ?
| def get_title(url):
if ((not url) or (not url.startswith(('http://', 'https://')))):
return None
try:
req = Request(url)
if g.useragent:
req.add_header('User-Agent', g.useragent)
opener = urlopen(req, timeout=15)
for param in opener.info().getplist():
if param.startswith('charset='):
(param_name, sep, charset) = param.partition('=')
codec = codecs.getreader(charset)
break
else:
codec = codecs.getreader('utf-8')
with codec(opener, 'ignore') as reader:
data = reader.read(1024)
title = extract_title(data)
if (not title):
data += reader.read(10240)
title = extract_title(data)
return title
except:
return None
| null | null | null | the pages title
| codeqa | def get title url if not url or not url startswith 'http //' 'https //' return Nonetry req Request url if g useragent req add header ' User- Agent' g useragent opener urlopen req timeout 15 for param in opener info getplist if param startswith 'charset ' param name sep charset param partition ' ' codec codecs getreader charset breakelse codec codecs getreader 'utf- 8 ' with codec opener 'ignore' as reader data reader read 1024 title extract title data if not title data + reader read 10240 title extract title data return titleexcept return None
| null | null | null | null | Question:
What does the code extract ?
Code:
def get_title(url):
if ((not url) or (not url.startswith(('http://', 'https://')))):
return None
try:
req = Request(url)
if g.useragent:
req.add_header('User-Agent', g.useragent)
opener = urlopen(req, timeout=15)
for param in opener.info().getplist():
if param.startswith('charset='):
(param_name, sep, charset) = param.partition('=')
codec = codecs.getreader(charset)
break
else:
codec = codecs.getreader('utf-8')
with codec(opener, 'ignore') as reader:
data = reader.read(1024)
title = extract_title(data)
if (not title):
data += reader.read(10240)
title = extract_title(data)
return title
except:
return None
|
null | null | null | What does the code get ?
| def getNewRepository():
return StatisticRepository()
| null | null | null | new repository
| codeqa | def get New Repository return Statistic Repository
| null | null | null | null | Question:
What does the code get ?
Code:
def getNewRepository():
return StatisticRepository()
|
null | null | null | Where does text detect ?
| def detect_text(path):
vision_client = vision.Client()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision_client.image(content=content)
texts = image.detect_text()
print 'Texts:'
for text in texts:
print text.description
| null | null | null | in the file
| codeqa | def detect text path vision client vision Client with io open path 'rb' as image file content image file read image vision client image content content texts image detect text print ' Texts 'for text in texts print text description
| null | null | null | null | Question:
Where does text detect ?
Code:
def detect_text(path):
vision_client = vision.Client()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision_client.image(content=content)
texts = image.detect_text()
print 'Texts:'
for text in texts:
print text.description
|
null | null | null | What detects in the file ?
| def detect_text(path):
vision_client = vision.Client()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision_client.image(content=content)
texts = image.detect_text()
print 'Texts:'
for text in texts:
print text.description
| null | null | null | text
| codeqa | def detect text path vision client vision Client with io open path 'rb' as image file content image file read image vision client image content content texts image detect text print ' Texts 'for text in texts print text description
| null | null | null | null | Question:
What detects in the file ?
Code:
def detect_text(path):
vision_client = vision.Client()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision_client.image(content=content)
texts = image.detect_text()
print 'Texts:'
for text in texts:
print text.description
|
null | null | null | In which direction do that pass it ?
| def call(f):
@wraps(f)
def processor(func, argname, arg):
return f(arg)
return processor
| null | null | null | along
| codeqa | def call f @wraps f def processor func argname arg return f arg return processor
| null | null | null | null | Question:
In which direction do that pass it ?
Code:
def call(f):
@wraps(f)
def processor(func, argname, arg):
return f(arg)
return processor
|
null | null | null | When does a processor call f on the argument ?
| def call(f):
@wraps(f)
def processor(func, argname, arg):
return f(arg)
return processor
| null | null | null | before passing it along
| codeqa | def call f @wraps f def processor func argname arg return f arg return processor
| null | null | null | null | Question:
When does a processor call f on the argument ?
Code:
def call(f):
@wraps(f)
def processor(func, argname, arg):
return f(arg)
return processor
|
null | null | null | What does the code add to vector3rackprofiles ?
| def addRackHoles(derivation, elementNode, vector3RackProfiles):
if (len(derivation.gearHolePaths) > 0):
vector3RackProfiles += derivation.gearHolePaths
return
if (derivation.rackHoleRadius <= 0.0):
return
addRackHole(derivation, elementNode, vector3RackProfiles, 0.0)
rackHoleMargin = (derivation.rackHoleRadius + derivation.rackHoleRadius)
rackHoleSteps = int(math.ceil(((derivation.rackDemilength - rackHoleMargin) / derivation.rackHoleStep)))
for rackHoleIndex in xrange(1, rackHoleSteps):
x = (float(rackHoleIndex) * derivation.rackHoleStep)
addRackHole(derivation, elementNode, vector3RackProfiles, (- x))
addRackHole(derivation, elementNode, vector3RackProfiles, x)
| null | null | null | rack holes
| codeqa | def add Rack Holes derivation element Node vector 3 Rack Profiles if len derivation gear Hole Paths > 0 vector 3 Rack Profiles + derivation gear Hole Pathsreturnif derivation rack Hole Radius < 0 0 returnadd Rack Hole derivation element Node vector 3 Rack Profiles 0 0 rack Hole Margin derivation rack Hole Radius + derivation rack Hole Radius rack Hole Steps int math ceil derivation rack Demilength - rack Hole Margin / derivation rack Hole Step for rack Hole Index in xrange 1 rack Hole Steps x float rack Hole Index * derivation rack Hole Step add Rack Hole derivation element Node vector 3 Rack Profiles - x add Rack Hole derivation element Node vector 3 Rack Profiles x
| null | null | null | null | Question:
What does the code add to vector3rackprofiles ?
Code:
def addRackHoles(derivation, elementNode, vector3RackProfiles):
if (len(derivation.gearHolePaths) > 0):
vector3RackProfiles += derivation.gearHolePaths
return
if (derivation.rackHoleRadius <= 0.0):
return
addRackHole(derivation, elementNode, vector3RackProfiles, 0.0)
rackHoleMargin = (derivation.rackHoleRadius + derivation.rackHoleRadius)
rackHoleSteps = int(math.ceil(((derivation.rackDemilength - rackHoleMargin) / derivation.rackHoleStep)))
for rackHoleIndex in xrange(1, rackHoleSteps):
x = (float(rackHoleIndex) * derivation.rackHoleStep)
addRackHole(derivation, elementNode, vector3RackProfiles, (- x))
addRackHole(derivation, elementNode, vector3RackProfiles, x)
|
null | null | null | What does the code call ?
| def _update_users(users):
return __salt__['users.set_users'](users, commit=False)
| null | null | null | users
| codeqa | def update users users return salt ['users set users'] users commit False
| null | null | null | null | Question:
What does the code call ?
Code:
def _update_users(users):
return __salt__['users.set_users'](users, commit=False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.