id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1 value | is_duplicated bool 2 classes |
|---|---|---|---|---|---|
34,701 | @contextlib.contextmanager
def force_error_model(context, model_name='numpy'):
from . import callconv
old_error_model = context.error_model
context.error_model = callconv.create_error_model(model_name, context)
try:
(yield)
finally:
context.error_model = old_error_model
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"force_error_model",
"(",
"context",
",",
"model_name",
"=",
"'numpy'",
")",
":",
"from",
".",
"import",
"callconv",
"old_error_model",
"=",
"context",
".",
"error_model",
"context",
".",
"error_model",
"=",
"call... | temporarily change the contexts error model . | train | false |
34,704 | def quad_explain(output=sys.stdout):
output.write(quad.__doc__)
| [
"def",
"quad_explain",
"(",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"output",
".",
"write",
"(",
"quad",
".",
"__doc__",
")"
] | print extra information about integrate . | train | false |
34,706 | def index_collections_given_ids(collection_ids):
collection_list = get_multiple_collections_by_id(collection_ids, strict=False).values()
search_services.add_documents_to_index([_collection_to_search_dict(collection) for collection in collection_list if _should_index(collection)], SEARCH_INDEX_COLLECTIONS)
| [
"def",
"index_collections_given_ids",
"(",
"collection_ids",
")",
":",
"collection_list",
"=",
"get_multiple_collections_by_id",
"(",
"collection_ids",
",",
"strict",
"=",
"False",
")",
".",
"values",
"(",
")",
"search_services",
".",
"add_documents_to_index",
"(",
"[... | adds the given collections to the search index . | train | false |
34,707 | def save_join(*args):
return fs_encode(join(*[(x if (type(x) == unicode) else decode(x)) for x in args]))
| [
"def",
"save_join",
"(",
"*",
"args",
")",
":",
"return",
"fs_encode",
"(",
"join",
"(",
"*",
"[",
"(",
"x",
"if",
"(",
"type",
"(",
"x",
")",
"==",
"unicode",
")",
"else",
"decode",
"(",
"x",
")",
")",
"for",
"x",
"in",
"args",
"]",
")",
")"... | joins a path . | train | false |
34,708 | def _pprint_styles(_styles):
(names, attrss, clss) = ([], [], [])
import inspect
_table = [[u'Class', u'Name', u'Attrs']]
for (name, cls) in sorted(_styles.items()):
if six.PY2:
(args, varargs, varkw, defaults) = inspect.getargspec(cls.__init__)
else:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefs, annotations) = inspect.getfullargspec(cls.__init__)
if defaults:
args = [(argname, argdefault) for (argname, argdefault) in zip(args[1:], defaults)]
else:
args = None
if (args is None):
argstr = u'None'
else:
argstr = u','.join([(u'%s=%s' % (an, av)) for (an, av) in args])
_table.append([cls.__name__, (u'``%s``' % name), argstr])
return _pprint_table(_table)
| [
"def",
"_pprint_styles",
"(",
"_styles",
")",
":",
"(",
"names",
",",
"attrss",
",",
"clss",
")",
"=",
"(",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
")",
"import",
"inspect",
"_table",
"=",
"[",
"[",
"u'Class'",
",",
"u'Name'",
",",
"u'Attrs'",
"]... | a helper function for the _style class . | train | false |
34,710 | def run_command(cmd, redirect_output=True, check_exit_code=True):
if redirect_output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=ROOT, stdout=stdout)
output = proc.communicate()[0]
if (check_exit_code and (proc.returncode != 0)):
raise Exception(('Command "%s" failed.\n%s' % (' '.join(cmd), output)))
return output
| [
"def",
"run_command",
"(",
"cmd",
",",
"redirect_output",
"=",
"True",
",",
"check_exit_code",
"=",
"True",
")",
":",
"if",
"redirect_output",
":",
"stdout",
"=",
"subprocess",
".",
"PIPE",
"else",
":",
"stdout",
"=",
"None",
"proc",
"=",
"subprocess",
"."... | call the given command(s) . | train | true |
34,711 | def _ensure_term(where, scope_level):
level = (scope_level + 1)
if isinstance(where, (list, tuple)):
wlist = []
for w in filter((lambda x: (x is not None)), where):
if (not maybe_expression(w)):
wlist.append(w)
else:
wlist.append(Term(w, scope_level=level))
where = wlist
elif maybe_expression(where):
where = Term(where, scope_level=level)
return where
| [
"def",
"_ensure_term",
"(",
"where",
",",
"scope_level",
")",
":",
"level",
"=",
"(",
"scope_level",
"+",
"1",
")",
"if",
"isinstance",
"(",
"where",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"wlist",
"=",
"[",
"]",
"for",
"w",
"in",
"filter",... | ensure that the where is a term or a list of term this makes sure that we are capturing the scope of variables that are passed create the terms here with a frame_level=2 . | train | true |
34,712 | def show_idlehelp(parent):
filename = join(abspath(dirname(__file__)), 'help.html')
if (not isfile(filename)):
return
HelpWindow(parent, filename, ('IDLE Help (%s)' % python_version()))
| [
"def",
"show_idlehelp",
"(",
"parent",
")",
":",
"filename",
"=",
"join",
"(",
"abspath",
"(",
"dirname",
"(",
"__file__",
")",
")",
",",
"'help.html'",
")",
"if",
"(",
"not",
"isfile",
"(",
"filename",
")",
")",
":",
"return",
"HelpWindow",
"(",
"pare... | create helpwindow; called from idle help event handler . | train | false |
34,713 | @intercept_errors(UserAPIInternalError, ignore_errors=[UserAPIRequestError])
def get_user_preferences(requesting_user, username=None):
existing_user = _get_authorized_user(requesting_user, username, allow_staff=True)
context = {'request': get_request_or_stub()}
user_serializer = UserSerializer(existing_user, context=context)
return user_serializer.data['preferences']
| [
"@",
"intercept_errors",
"(",
"UserAPIInternalError",
",",
"ignore_errors",
"=",
"[",
"UserAPIRequestError",
"]",
")",
"def",
"get_user_preferences",
"(",
"requesting_user",
",",
"username",
"=",
"None",
")",
":",
"existing_user",
"=",
"_get_authorized_user",
"(",
"... | returns all user preferences as a json response . | train | false |
34,714 | @cwd_at('.')
def test_completion_docstring():
def docstr(src, result):
c = Script(src).completions()[0]
assert (c.docstring(raw=True, fast=False) == cleandoc(result))
c = Script('import jedi\njed').completions()[0]
assert (c.docstring(fast=False) == cleandoc(jedi_doc))
docstr('import jedi\njedi.Scr', cleandoc(Script.__doc__))
docstr('abcd=3;abcd', '')
docstr('"hello"\nabcd=3\nabcd', 'hello')
docstr('"hello"\nabcd=3;abcd', 'hello')
docstr('"hello",0\nabcd=3\nabcd', '')
| [
"@",
"cwd_at",
"(",
"'.'",
")",
"def",
"test_completion_docstring",
"(",
")",
":",
"def",
"docstr",
"(",
"src",
",",
"result",
")",
":",
"c",
"=",
"Script",
"(",
"src",
")",
".",
"completions",
"(",
")",
"[",
"0",
"]",
"assert",
"(",
"c",
".",
"d... | jedi should follow imports in certain conditions . | train | false |
34,716 | def argmin_list(seq, func):
(best_score, best) = (func(seq[0]), [])
for x in seq:
x_score = func(x)
if (x_score < best_score):
(best, best_score) = ([x], x_score)
elif (x_score == best_score):
best.append(x)
return best
| [
"def",
"argmin_list",
"(",
"seq",
",",
"func",
")",
":",
"(",
"best_score",
",",
"best",
")",
"=",
"(",
"func",
"(",
"seq",
"[",
"0",
"]",
")",
",",
"[",
"]",
")",
"for",
"x",
"in",
"seq",
":",
"x_score",
"=",
"func",
"(",
"x",
")",
"if",
"... | return a list of elements of seq[i] with the lowest func scores . | train | true |
34,717 | def select_filters(filters, level):
return [f for f in filters if ((f.max_debug_level is None) or (cmp_debug_levels(level, f.max_debug_level) <= 0))]
| [
"def",
"select_filters",
"(",
"filters",
",",
"level",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"filters",
"if",
"(",
"(",
"f",
".",
"max_debug_level",
"is",
"None",
")",
"or",
"(",
"cmp_debug_levels",
"(",
"level",
",",
"f",
".",
"max_debug_lev... | return from the list in filters those filters which indicate that they should run for the given debug level . | train | false |
34,718 | def _write_files(output_root, contents, generated_suffix_map=None):
_ensure_dir(output_root)
to_delete = (set((file.basename() for file in output_root.files())) - set(contents.keys()))
if generated_suffix_map:
for output_file in contents.keys():
for (suffix, generated_suffix) in generated_suffix_map.items():
if output_file.endswith(suffix):
to_delete.discard(output_file.replace(suffix, generated_suffix))
for extra_file in to_delete:
(output_root / extra_file).remove_p()
for (filename, file_content) in contents.iteritems():
output_file = (output_root / filename)
not_file = (not output_file.isfile())
write_file = (not_file or (output_file.read_md5() != hashlib.md5(file_content).digest()))
if write_file:
LOG.debug('Writing %s', output_file)
output_file.write_bytes(file_content)
else:
LOG.debug('%s unchanged, skipping', output_file)
| [
"def",
"_write_files",
"(",
"output_root",
",",
"contents",
",",
"generated_suffix_map",
"=",
"None",
")",
":",
"_ensure_dir",
"(",
"output_root",
")",
"to_delete",
"=",
"(",
"set",
"(",
"(",
"file",
".",
"basename",
"(",
")",
"for",
"file",
"in",
"output_... | write file contents to output root . | train | false |
34,720 | @check_job_permission
def set_job_priority(request, job):
priority = request.GET.get('priority')
jid = request.jt.thriftjobid_from_string(job.jobId)
request.jt.set_job_priority(jid, ThriftJobPriority._NAMES_TO_VALUES[priority])
return render_json({})
| [
"@",
"check_job_permission",
"def",
"set_job_priority",
"(",
"request",
",",
"job",
")",
":",
"priority",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'priority'",
")",
"jid",
"=",
"request",
".",
"jt",
".",
"thriftjobid_from_string",
"(",
"job",
".",
"jo... | we get here from /jobs/job/setpriority?priority=priority . | train | false |
34,722 | def xml_readlines(source):
encoding = get_xml_encoding(source)
with data.get_readable_fileobj(source, encoding=encoding) as input:
input.seek(0)
xml_lines = input.readlines()
return xml_lines
| [
"def",
"xml_readlines",
"(",
"source",
")",
":",
"encoding",
"=",
"get_xml_encoding",
"(",
"source",
")",
"with",
"data",
".",
"get_readable_fileobj",
"(",
"source",
",",
"encoding",
"=",
"encoding",
")",
"as",
"input",
":",
"input",
".",
"seek",
"(",
"0",... | get the lines from a given xml file . | train | false |
34,724 | @step(u'(I am viewing|s?he views) the course team settings$')
def view_course_team_settings(_step, whom):
world.click_course_settings()
link_css = 'li.nav-course-settings-team a'
world.css_click(link_css)
| [
"@",
"step",
"(",
"u'(I am viewing|s?he views) the course team settings$'",
")",
"def",
"view_course_team_settings",
"(",
"_step",
",",
"whom",
")",
":",
"world",
".",
"click_course_settings",
"(",
")",
"link_css",
"=",
"'li.nav-course-settings-team a'",
"world",
".",
"... | navigates to course team settings page . | train | false |
34,725 | def disk_copy(session, dc_ref, src_file, dst_file):
LOG.debug('Copying virtual disk from %(src)s to %(dst)s.', {'src': src_file, 'dst': dst_file})
copy_disk_task = session._call_method(session.vim, 'CopyVirtualDisk_Task', session.vim.service_content.virtualDiskManager, sourceName=str(src_file), sourceDatacenter=dc_ref, destName=str(dst_file), destDatacenter=dc_ref, force=False)
session._wait_for_task(copy_disk_task)
LOG.info(_LI('Copied virtual disk from %(src)s to %(dst)s.'), {'src': src_file, 'dst': dst_file})
| [
"def",
"disk_copy",
"(",
"session",
",",
"dc_ref",
",",
"src_file",
",",
"dst_file",
")",
":",
"LOG",
".",
"debug",
"(",
"'Copying virtual disk from %(src)s to %(dst)s.'",
",",
"{",
"'src'",
":",
"src_file",
",",
"'dst'",
":",
"dst_file",
"}",
")",
"copy_disk_... | copies the source virtual disk to the destination . | train | false |
34,726 | def _sum_of_squares(a, axis=0):
(a, axis) = _chk_asarray(a, axis)
return np.sum((a * a), axis)
| [
"def",
"_sum_of_squares",
"(",
"a",
",",
"axis",
"=",
"0",
")",
":",
"(",
"a",
",",
"axis",
")",
"=",
"_chk_asarray",
"(",
"a",
",",
"axis",
")",
"return",
"np",
".",
"sum",
"(",
"(",
"a",
"*",
"a",
")",
",",
"axis",
")"
] | squares each element of the input array . | train | false |
34,729 | def stp_transformation(prev_image, stp_input, num_masks):
from spatial_transformer import transformer
identity_params = tf.convert_to_tensor(np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0], np.float32))
transformed = []
for i in range((num_masks - 1)):
params = (slim.layers.fully_connected(stp_input, 6, scope=('stp_params' + str(i)), activation_fn=None) + identity_params)
transformed.append(transformer(prev_image, params))
return transformed
| [
"def",
"stp_transformation",
"(",
"prev_image",
",",
"stp_input",
",",
"num_masks",
")",
":",
"from",
"spatial_transformer",
"import",
"transformer",
"identity_params",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"np",
".",
"array",
"(",
"[",
"1.0",
",",
"0.0",
... | apply spatial transformer predictor to previous image . | train | false |
34,730 | def generic_bfs_edges(G, source, neighbors=None):
visited = {source}
queue = deque([(source, neighbors(source))])
while queue:
(parent, children) = queue[0]
try:
child = next(children)
if (child not in visited):
(yield (parent, child))
visited.add(child)
queue.append((child, neighbors(child)))
except StopIteration:
queue.popleft()
| [
"def",
"generic_bfs_edges",
"(",
"G",
",",
"source",
",",
"neighbors",
"=",
"None",
")",
":",
"visited",
"=",
"{",
"source",
"}",
"queue",
"=",
"deque",
"(",
"[",
"(",
"source",
",",
"neighbors",
"(",
"source",
")",
")",
"]",
")",
"while",
"queue",
... | iterates over edges in a breadth-first search . | train | false |
34,731 | def _verify_time_range(payload_dict):
now = int(time.time())
issued_at = payload_dict.get('iat')
if (issued_at is None):
raise AppIdentityError('No iat field in token: {0}'.format(payload_dict))
expiration = payload_dict.get('exp')
if (expiration is None):
raise AppIdentityError('No exp field in token: {0}'.format(payload_dict))
if (expiration >= (now + MAX_TOKEN_LIFETIME_SECS)):
raise AppIdentityError('exp field too far in future: {0}'.format(payload_dict))
earliest = (issued_at - CLOCK_SKEW_SECS)
if (now < earliest):
raise AppIdentityError('Token used too early, {0} < {1}: {2}'.format(now, earliest, payload_dict))
latest = (expiration + CLOCK_SKEW_SECS)
if (now > latest):
raise AppIdentityError('Token used too late, {0} > {1}: {2}'.format(now, latest, payload_dict))
| [
"def",
"_verify_time_range",
"(",
"payload_dict",
")",
":",
"now",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"issued_at",
"=",
"payload_dict",
".",
"get",
"(",
"'iat'",
")",
"if",
"(",
"issued_at",
"is",
"None",
")",
":",
"raise",
"AppIdenti... | verifies the issued at and expiration from a jwt payload . | train | true |
34,732 | def diff_mtime_map(map1, map2):
if (sorted(map1) != sorted(map2)):
return True
for (filename, mtime) in six.iteritems(map1):
if (map2[filename] != mtime):
return True
return False
| [
"def",
"diff_mtime_map",
"(",
"map1",
",",
"map2",
")",
":",
"if",
"(",
"sorted",
"(",
"map1",
")",
"!=",
"sorted",
"(",
"map2",
")",
")",
":",
"return",
"True",
"for",
"(",
"filename",
",",
"mtime",
")",
"in",
"six",
".",
"iteritems",
"(",
"map1",... | is there a change to the mtime map? return a boolean . | train | true |
34,733 | def get_redirects(redirects_filename):
redirects = {}
print('Parsing the NT redirect file')
for (l, line) in enumerate(BZ2File(redirects_filename)):
split = line.split()
if (len(split) != 4):
print(('ignoring malformed line: ' + line))
continue
redirects[short_name(split[0])] = short_name(split[2])
if ((l % 1000000) == 0):
print(('[%s] line: %08d' % (datetime.now().isoformat(), l)))
print('Computing the transitive closure of the redirect relation')
for (l, source) in enumerate(redirects.keys()):
transitive_target = None
target = redirects[source]
seen = set([source])
while True:
transitive_target = target
target = redirects.get(target)
if ((target is None) or (target in seen)):
break
seen.add(target)
redirects[source] = transitive_target
if ((l % 1000000) == 0):
print(('[%s] line: %08d' % (datetime.now().isoformat(), l)))
return redirects
| [
"def",
"get_redirects",
"(",
"redirects_filename",
")",
":",
"redirects",
"=",
"{",
"}",
"print",
"(",
"'Parsing the NT redirect file'",
")",
"for",
"(",
"l",
",",
"line",
")",
"in",
"enumerate",
"(",
"BZ2File",
"(",
"redirects_filename",
")",
")",
":",
"spl... | return fathead redirect entries for a fathead title . | train | false |
34,735 | def convert_coord_data_to_dict(data):
coord_header = data['coord'][0]
coords = data['coord'][1]
pct_var = data['coord'][3]
coords_dict = {}
pct_var_dict = {}
coords_dict['pc vector number'] = coord_header
for x in range(len(coords)):
coords_dict[str((x + 1))] = coords[0:, x]
pct_var_dict[str((x + 1))] = pct_var[x]
return (coords_dict, pct_var_dict)
| [
"def",
"convert_coord_data_to_dict",
"(",
"data",
")",
":",
"coord_header",
"=",
"data",
"[",
"'coord'",
"]",
"[",
"0",
"]",
"coords",
"=",
"data",
"[",
"'coord'",
"]",
"[",
"1",
"]",
"pct_var",
"=",
"data",
"[",
"'coord'",
"]",
"[",
"3",
"]",
"coord... | convert the coord data into a dictionary . | train | false |
34,736 | def moving_av(total_loss):
loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')
losses = tf.get_collection('losses')
loss_averages_op = loss_averages.apply((losses + [total_loss]))
return loss_averages_op
| [
"def",
"moving_av",
"(",
"total_loss",
")",
":",
"loss_averages",
"=",
"tf",
".",
"train",
".",
"ExponentialMovingAverage",
"(",
"0.9",
",",
"name",
"=",
"'avg'",
")",
"losses",
"=",
"tf",
".",
"get_collection",
"(",
"'losses'",
")",
"loss_averages_op",
"=",... | generates moving average for all losses args: total_loss: total loss from loss() . | train | false |
34,740 | def XorByteArray(array, key):
for i in xrange(len(array)):
array[i] ^= key
return array
| [
"def",
"XorByteArray",
"(",
"array",
",",
"key",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"array",
")",
")",
":",
"array",
"[",
"i",
"]",
"^=",
"key",
"return",
"array"
] | xors every item in the array with key and returns it . | train | false |
34,741 | @require_context
def volume_types_get_by_name_or_id(context, volume_type_list):
req_volume_types = []
for vol_t in volume_type_list:
if (not uuidutils.is_uuid_like(vol_t)):
vol_type = _volume_type_get_by_name(context, vol_t)
else:
vol_type = _volume_type_get(context, vol_t)
req_volume_types.append(vol_type)
return req_volume_types
| [
"@",
"require_context",
"def",
"volume_types_get_by_name_or_id",
"(",
"context",
",",
"volume_type_list",
")",
":",
"req_volume_types",
"=",
"[",
"]",
"for",
"vol_t",
"in",
"volume_type_list",
":",
"if",
"(",
"not",
"uuidutils",
".",
"is_uuid_like",
"(",
"vol_t",
... | return a dict describing specific volume_type . | train | false |
34,743 | def map_url_out(request, env, application, controller, function, args, other, scheme, host, port, language=None):
map = MapUrlOut(request, env, application, controller, function, args, other, scheme, host, port, language)
return map.acf()
| [
"def",
"map_url_out",
"(",
"request",
",",
"env",
",",
"application",
",",
"controller",
",",
"function",
",",
"args",
",",
"other",
",",
"scheme",
",",
"host",
",",
"port",
",",
"language",
"=",
"None",
")",
":",
"map",
"=",
"MapUrlOut",
"(",
"request... | supply /a/c/f portion of outgoing url the basic rule is that we can only make transformations that map_url_in can reverse . | train | false |
34,744 | @contextfunction
def logo_block_container(context):
response_format = 'html'
return Markup(render_to_string('core/tags/logo_block_container', response_format=response_format))
| [
"@",
"contextfunction",
"def",
"logo_block_container",
"(",
"context",
")",
":",
"response_format",
"=",
"'html'",
"return",
"Markup",
"(",
"render_to_string",
"(",
"'core/tags/logo_block_container'",
",",
"response_format",
"=",
"response_format",
")",
")"
] | returns logo_block_container . | train | false |
34,745 | def cov_nw_panel(results, nlags, groupidx, weights_func=weights_bartlett, use_correction='hac'):
if (nlags == 0):
weights = [1, 0]
else:
weights = weights_func(nlags)
(xu, hessian_inv) = _get_sandwich_arrays(results)
S_hac = S_nw_panel(xu, weights, groupidx)
cov_hac = _HCCM2(hessian_inv, S_hac)
if use_correction:
(nobs, k_params) = xu.shape
if (use_correction == 'hac'):
cov_hac *= (nobs / float((nobs - k_params)))
elif (use_correction in ['c', 'clu', 'cluster']):
n_groups = len(groupidx)
cov_hac *= (n_groups / (n_groups - 1.0))
cov_hac *= ((nobs - 1.0) / float((nobs - k_params)))
return cov_hac
| [
"def",
"cov_nw_panel",
"(",
"results",
",",
"nlags",
",",
"groupidx",
",",
"weights_func",
"=",
"weights_bartlett",
",",
"use_correction",
"=",
"'hac'",
")",
":",
"if",
"(",
"nlags",
"==",
"0",
")",
":",
"weights",
"=",
"[",
"1",
",",
"0",
"]",
"else",... | panel hac robust covariance matrix assumes we have a panel of time series with consecutive . | train | false |
34,746 | def register_loader_type(loader_type, provider_factory):
_provider_factories[loader_type] = provider_factory
| [
"def",
"register_loader_type",
"(",
"loader_type",
",",
"provider_factory",
")",
":",
"_provider_factories",
"[",
"loader_type",
"]",
"=",
"provider_factory"
] | register provider_factory to make providers for loader_type loader_type is the type or class of a pep 302 module . | train | false |
34,747 | def NormjoinPathForceCMakeSource(base_path, rel_path):
if os.path.isabs(rel_path):
return rel_path
if any([rel_path.startswith(var) for var in FULL_PATH_VARS]):
return rel_path
return os.path.join('${CMAKE_CURRENT_LIST_DIR}', os.path.normpath(os.path.join(base_path, rel_path)))
| [
"def",
"NormjoinPathForceCMakeSource",
"(",
"base_path",
",",
"rel_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"rel_path",
")",
":",
"return",
"rel_path",
"if",
"any",
"(",
"[",
"rel_path",
".",
"startswith",
"(",
"var",
")",
"for",
"var... | resolves rel_path against base_path and returns the result . | train | false |
34,749 | def bsgs_direct_product(base1, gens1, base2, gens2, signed=True):
s = (2 if signed else 0)
n1 = (gens1[0].size - s)
base = list(base1)
base += [(x + n1) for x in base2]
gens1 = [h._array_form for h in gens1]
gens2 = [h._array_form for h in gens2]
gens = perm_af_direct_product(gens1, gens2, signed)
size = len(gens[0])
id_af = list(range(size))
gens = [h for h in gens if (h != id_af)]
if (not gens):
gens = [id_af]
return (base, [_af_new(h) for h in gens])
| [
"def",
"bsgs_direct_product",
"(",
"base1",
",",
"gens1",
",",
"base2",
",",
"gens2",
",",
"signed",
"=",
"True",
")",
":",
"s",
"=",
"(",
"2",
"if",
"signed",
"else",
"0",
")",
"n1",
"=",
"(",
"gens1",
"[",
"0",
"]",
".",
"size",
"-",
"s",
")"... | direct product of two bsgs base1 base of the first bsgs . | train | false |
34,750 | @task
@cmdopts([('background', 'b', 'Background mode'), ('theme-dirs=', '-td', 'The themes dir containing all themes (defaults to None)'), ('themes=', '-t', 'The themes to add sass watchers for (defaults to None)')])
@timed
def watch_assets(options):
if tasks.environment.dry_run:
return
themes = get_parsed_option(options, 'themes')
theme_dirs = get_parsed_option(options, 'theme_dirs', [])
if ((not theme_dirs) and themes):
raise ValueError('theme-dirs must be provided for watching theme sass.')
else:
theme_dirs = [path(_dir) for _dir in theme_dirs]
sass_directories = get_watcher_dirs(theme_dirs, themes)
observer = PollingObserver()
CoffeeScriptWatcher().register(observer)
SassWatcher().register(observer, sass_directories)
XModuleSassWatcher().register(observer, ['common/lib/xmodule/'])
XModuleAssetsWatcher().register(observer)
print('Starting asset watcher...')
observer.start()
if (not getattr(options, 'background', False)):
try:
while True:
observer.join(2)
except KeyboardInterrupt:
observer.stop()
print('\nStopped asset watcher.')
| [
"@",
"task",
"@",
"cmdopts",
"(",
"[",
"(",
"'background'",
",",
"'b'",
",",
"'Background mode'",
")",
",",
"(",
"'theme-dirs='",
",",
"'-td'",
",",
"'The themes dir containing all themes (defaults to None)'",
")",
",",
"(",
"'themes='",
",",
"'-t'",
",",
"'The ... | watch for changes to asset files . | train | false |
34,751 | def heappush(heap, item):
heap.append(item)
_siftdown(heap, 0, (len(heap) - 1))
| [
"def",
"heappush",
"(",
"heap",
",",
"item",
")",
":",
"heap",
".",
"append",
"(",
"item",
")",
"_siftdown",
"(",
"heap",
",",
"0",
",",
"(",
"len",
"(",
"heap",
")",
"-",
"1",
")",
")"
] | push item onto heap . | train | true |
34,752 | def rbf_kernel(X, Y=None, gamma=None):
(X, Y) = check_pairwise_arrays(X, Y)
if (gamma is None):
gamma = (1.0 / X.shape[1])
K = euclidean_distances(X, Y, squared=True)
K *= (- gamma)
np.exp(K, K)
return K
| [
"def",
"rbf_kernel",
"(",
"X",
",",
"Y",
"=",
"None",
",",
"gamma",
"=",
"None",
")",
":",
"(",
"X",
",",
"Y",
")",
"=",
"check_pairwise_arrays",
"(",
"X",
",",
"Y",
")",
"if",
"(",
"gamma",
"is",
"None",
")",
":",
"gamma",
"=",
"(",
"1.0",
"... | compute the rbf kernel between x and y:: k = exp for each pair of rows x in x and y in y . | train | true |
34,753 | def index_type(base_type, item):
class InvalidTypeSpecification(Exception, ):
pass
def verify_slice(s):
if (s.start or s.stop or (s.step not in (None, 1))):
raise InvalidTypeSpecification('Only a step of 1 may be provided to indicate C or Fortran contiguity')
if isinstance(item, tuple):
step_idx = None
for (idx, s) in enumerate(item):
verify_slice(s)
if (s.step and (step_idx or (idx not in (0, (len(item) - 1))))):
raise InvalidTypeSpecification('Step may only be provided once, and only in the first or last dimension.')
if (s.step == 1):
step_idx = idx
return _ArrayType(base_type, len(item), is_c_contig=(step_idx == (len(item) - 1)), is_f_contig=(step_idx == 0))
elif isinstance(item, slice):
verify_slice(item)
return _ArrayType(base_type, 1, is_c_contig=bool(item.step))
else:
assert (int(item) == item)
array(base_type, item)
| [
"def",
"index_type",
"(",
"base_type",
",",
"item",
")",
":",
"class",
"InvalidTypeSpecification",
"(",
"Exception",
",",
")",
":",
"pass",
"def",
"verify_slice",
"(",
"s",
")",
":",
"if",
"(",
"s",
".",
"start",
"or",
"s",
".",
"stop",
"or",
"(",
"s... | support array type creation by slicing . | train | false |
34,754 | def fix_mag_coil_types(info):
old_mag_inds = _get_T1T2_mag_inds(info)
for ii in old_mag_inds:
info['chs'][ii]['coil_type'] = FIFF.FIFFV_COIL_VV_MAG_T3
logger.info(('%d of %d T1/T2 magnetometer types replaced with T3.' % (len(old_mag_inds), len(pick_types(info, meg='mag')))))
info._check_consistency()
| [
"def",
"fix_mag_coil_types",
"(",
"info",
")",
":",
"old_mag_inds",
"=",
"_get_T1T2_mag_inds",
"(",
"info",
")",
"for",
"ii",
"in",
"old_mag_inds",
":",
"info",
"[",
"'chs'",
"]",
"[",
"ii",
"]",
"[",
"'coil_type'",
"]",
"=",
"FIFF",
".",
"FIFFV_COIL_VV_MA... | fix magnetometer coil types . | train | false |
34,757 | def split_commutative_parts(e):
(c_part, nc_part) = e.args_cnc()
c_part = list(c_part)
return (c_part, nc_part)
| [
"def",
"split_commutative_parts",
"(",
"e",
")",
":",
"(",
"c_part",
",",
"nc_part",
")",
"=",
"e",
".",
"args_cnc",
"(",
")",
"c_part",
"=",
"list",
"(",
"c_part",
")",
"return",
"(",
"c_part",
",",
"nc_part",
")"
] | split into commutative and non-commutative parts . | train | false |
34,758 | def set_product_summary_serializer_class(product_summary_serializer_class):
global _product_summary_serializer_class
try:
_product_summary_serializer_class
except NameError:
_product_summary_serializer_class = product_summary_serializer_class
else:
msg = u'Class `{}` inheriting from `ProductSummarySerializerBase` already registred.'
raise exceptions.ImproperlyConfigured(msg.format(product_summary_serializer_class.__name__))
| [
"def",
"set_product_summary_serializer_class",
"(",
"product_summary_serializer_class",
")",
":",
"global",
"_product_summary_serializer_class",
"try",
":",
"_product_summary_serializer_class",
"except",
"NameError",
":",
"_product_summary_serializer_class",
"=",
"product_summary_ser... | sets the common productserializer . | train | false |
34,759 | @pytest.mark.usefixtures('mocked_aws_cf_simple')
def test_aws_cf_simple_make_key(capsys, tmpdir):
config = '\n---\nthis_is_a_temporary_config_format_do_not_put_in_production: yes_i_agree\ntype: cloudformation\ntemplate_url: http://us-west-2.amazonaws.com/downloads\nstack_name: foobar\nprovider_info:\n region: us-west-2\n access_key_id: asdf09iasdf3m19238jowsfn\n secret_access_key: asdf0asafawwa3j8ajn\nssh_info:\n user: core\nparameters:\n - ParameterKey: AdminLocation\n ParameterValue: 0.0.0.0/0\n - ParameterKey: PublicSlaveInstanceCount\n ParameterValue: 1\n - ParameterKey: SlaveInstanceCount\n ParameterValue: 5\n'
(info, desc) = check_success(capsys, tmpdir, config)
assert (info['type'] == 'cloudformation')
assert ('stack_name' in info)
assert ('region' in info['provider'])
assert ('access_key_id' in info['provider'])
assert ('secret_access_key' in info['provider'])
assert (info['ssh']['key_name'] == 'foobar')
assert (info['ssh']['delete_with_stack'] is True)
assert (info['ssh']['private_key'] == MOCK_SSH_KEY_DATA)
assert (info['ssh']['user'] == 'core')
assert ('stack_name' in desc)
| [
"@",
"pytest",
".",
"mark",
".",
"usefixtures",
"(",
"'mocked_aws_cf_simple'",
")",
"def",
"test_aws_cf_simple_make_key",
"(",
"capsys",
",",
"tmpdir",
")",
":",
"config",
"=",
"'\\n---\\nthis_is_a_temporary_config_format_do_not_put_in_production: yes_i_agree\\ntype: cloudforma... | same mocked backend as other aws_cf_simple tests . | train | false |
34,760 | def file_upload_content_type_extra(request):
params = {}
for (file_name, uploadedfile) in request.FILES.items():
params[file_name] = {k: force_text(v) for (k, v) in uploadedfile.content_type_extra.items()}
return HttpResponse(json.dumps(params))
| [
"def",
"file_upload_content_type_extra",
"(",
"request",
")",
":",
"params",
"=",
"{",
"}",
"for",
"(",
"file_name",
",",
"uploadedfile",
")",
"in",
"request",
".",
"FILES",
".",
"items",
"(",
")",
":",
"params",
"[",
"file_name",
"]",
"=",
"{",
"k",
"... | simple view to echo back extra content-type parameters . | train | false |
34,761 | def test_ranking_based_on_shortest_match(completer):
text = u'user'
collection = [u'api_user', u'user_group']
matches = completer.find_matches(text, collection)
assert (matches[1].priority > matches[0].priority)
| [
"def",
"test_ranking_based_on_shortest_match",
"(",
"completer",
")",
":",
"text",
"=",
"u'user'",
"collection",
"=",
"[",
"u'api_user'",
",",
"u'user_group'",
"]",
"matches",
"=",
"completer",
".",
"find_matches",
"(",
"text",
",",
"collection",
")",
"assert",
... | fuzzy result rank should be based on shortest match . | train | false |
34,763 | def check_or_raise_uri(value, message=u'WAMP message invalid', strict=False, allow_empty_components=False, allow_last_empty=False, allow_none=False):
if (value is None):
if allow_none:
return
else:
raise ProtocolError(u'{0}: URI cannot be null'.format(message))
if (type(value) != six.text_type):
if (not ((value is None) and allow_none)):
raise ProtocolError(u'{0}: invalid type {1} for URI'.format(message, type(value)))
if strict:
if allow_last_empty:
pat = _URI_PAT_STRICT_LAST_EMPTY
elif allow_empty_components:
pat = _URI_PAT_STRICT_EMPTY
else:
pat = _URI_PAT_STRICT_NON_EMPTY
elif allow_last_empty:
pat = _URI_PAT_LOOSE_LAST_EMPTY
elif allow_empty_components:
pat = _URI_PAT_LOOSE_EMPTY
else:
pat = _URI_PAT_LOOSE_NON_EMPTY
if (not pat.match(value)):
raise ProtocolError(u"{0}: invalid value '{1}' for URI (did not match pattern {2}, strict={3}, allow_empty_components={4}, allow_last_empty={5}, allow_none={6})".format(message, value, pat.pattern, strict, allow_empty_components, allow_last_empty, allow_none))
else:
return value
| [
"def",
"check_or_raise_uri",
"(",
"value",
",",
"message",
"=",
"u'WAMP message invalid'",
",",
"strict",
"=",
"False",
",",
"allow_empty_components",
"=",
"False",
",",
"allow_last_empty",
"=",
"False",
",",
"allow_none",
"=",
"False",
")",
":",
"if",
"(",
"v... | check a value for being a valid wamp uri . | train | false |
34,765 | def checkbox_to_value(option, value_on=1, value_off=0):
if isinstance(option, list):
option = option[(-1)]
if isinstance(option, (str, unicode)):
option = str(option).strip().lower()
if (option in (True, 'on', 'true', '1', value_on)):
return value_on
return value_off
| [
"def",
"checkbox_to_value",
"(",
"option",
",",
"value_on",
"=",
"1",
",",
"value_off",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"option",
",",
"list",
")",
":",
"option",
"=",
"option",
"[",
"(",
"-",
"1",
")",
"]",
"if",
"isinstance",
"(",
"o... | turns checkbox option on or true to value_on (1) any other value returns value_off (0) . | train | false |
34,767 | def deterministicPool():
(worker, doer) = createMemoryWorker()
return (DeterministicThreadPool(Team(LockWorker(Lock(), local()), (lambda : worker), (lambda : None))), doer)
| [
"def",
"deterministicPool",
"(",
")",
":",
"(",
"worker",
",",
"doer",
")",
"=",
"createMemoryWorker",
"(",
")",
"return",
"(",
"DeterministicThreadPool",
"(",
"Team",
"(",
"LockWorker",
"(",
"Lock",
"(",
")",
",",
"local",
"(",
")",
")",
",",
"(",
"la... | create a deterministic threadpool . | train | false |
34,768 | def snippet_text(snippet_file_name):
snippet_file_path = os.path.join(test_file_dir, 'snippets', ('%s.txt' % snippet_file_name))
with open(snippet_file_path, 'rb') as f:
snippet_bytes = f.read()
return snippet_bytes.decode('utf-8')
| [
"def",
"snippet_text",
"(",
"snippet_file_name",
")",
":",
"snippet_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"test_file_dir",
",",
"'snippets'",
",",
"(",
"'%s.txt'",
"%",
"snippet_file_name",
")",
")",
"with",
"open",
"(",
"snippet_file_path",
",... | return the unicode text read from the test snippet file having *snippet_file_name* . | train | false |
34,769 | def GetXcodeArchsDefault():
global XCODE_ARCHS_DEFAULT_CACHE
if XCODE_ARCHS_DEFAULT_CACHE:
return XCODE_ARCHS_DEFAULT_CACHE
(xcode_version, _) = XcodeVersion()
if (xcode_version < '0500'):
XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault('$(ARCHS_STANDARD)', XcodeArchsVariableMapping(['i386']), XcodeArchsVariableMapping(['i386']), XcodeArchsVariableMapping(['armv7']))
elif (xcode_version < '0510'):
XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault('$(ARCHS_STANDARD_INCLUDING_64_BIT)', XcodeArchsVariableMapping(['x86_64'], ['x86_64']), XcodeArchsVariableMapping(['i386'], ['i386', 'x86_64']), XcodeArchsVariableMapping(['armv7', 'armv7s'], ['armv7', 'armv7s', 'arm64']))
else:
XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault('$(ARCHS_STANDARD)', XcodeArchsVariableMapping(['x86_64'], ['x86_64']), XcodeArchsVariableMapping(['i386', 'x86_64'], ['i386', 'x86_64']), XcodeArchsVariableMapping(['armv7', 'armv7s', 'arm64'], ['armv7', 'armv7s', 'arm64']))
return XCODE_ARCHS_DEFAULT_CACHE
| [
"def",
"GetXcodeArchsDefault",
"(",
")",
":",
"global",
"XCODE_ARCHS_DEFAULT_CACHE",
"if",
"XCODE_ARCHS_DEFAULT_CACHE",
":",
"return",
"XCODE_ARCHS_DEFAULT_CACHE",
"(",
"xcode_version",
",",
"_",
")",
"=",
"XcodeVersion",
"(",
")",
"if",
"(",
"xcode_version",
"<",
"... | returns the |xcodearchsdefault| object to use to expand archs for the installed version of xcode . | train | false |
34,770 | def _adjust_shape(dat, k_vars):
dat = np.asarray(dat)
if (dat.ndim > 2):
dat = np.squeeze(dat)
if ((dat.ndim == 1) and (k_vars > 1)):
nobs = 1
elif ((dat.ndim == 1) and (k_vars == 1)):
nobs = len(dat)
else:
if ((np.shape(dat)[0] == k_vars) and (np.shape(dat)[1] != k_vars)):
dat = dat.T
nobs = np.shape(dat)[0]
dat = np.reshape(dat, (nobs, k_vars))
return dat
| [
"def",
"_adjust_shape",
"(",
"dat",
",",
"k_vars",
")",
":",
"dat",
"=",
"np",
".",
"asarray",
"(",
"dat",
")",
"if",
"(",
"dat",
".",
"ndim",
">",
"2",
")",
":",
"dat",
"=",
"np",
".",
"squeeze",
"(",
"dat",
")",
"if",
"(",
"(",
"dat",
".",
... | returns an array of shape for use with gpke . | train | true |
34,772 | def shaped_arange(shape, xp=cupy, dtype=numpy.float32):
a = numpy.arange(1, (internal.prod(shape) + 1), 1)
if (numpy.dtype(dtype).type == numpy.bool_):
return xp.array(((a % 2) == 0).reshape(shape))
else:
return xp.array(a.astype(dtype).reshape(shape))
| [
"def",
"shaped_arange",
"(",
"shape",
",",
"xp",
"=",
"cupy",
",",
"dtype",
"=",
"numpy",
".",
"float32",
")",
":",
"a",
"=",
"numpy",
".",
"arange",
"(",
"1",
",",
"(",
"internal",
".",
"prod",
"(",
"shape",
")",
"+",
"1",
")",
",",
"1",
")",
... | returns an array with given shape . | train | false |
34,773 | def _api_queue_purge(output, value, kwargs):
removed = NzbQueue.do.remove_all(kwargs.get('search'))
return report(output, keyword='', data={'status': bool(removed), 'nzo_ids': removed})
| [
"def",
"_api_queue_purge",
"(",
"output",
",",
"value",
",",
"kwargs",
")",
":",
"removed",
"=",
"NzbQueue",
".",
"do",
".",
"remove_all",
"(",
"kwargs",
".",
"get",
"(",
"'search'",
")",
")",
"return",
"report",
"(",
"output",
",",
"keyword",
"=",
"''... | api: accepts output . | train | false |
34,774 | def normalize_excludes(rootpath, excludes):
return [path.abspath(exclude) for exclude in excludes]
| [
"def",
"normalize_excludes",
"(",
"rootpath",
",",
"excludes",
")",
":",
"return",
"[",
"path",
".",
"abspath",
"(",
"exclude",
")",
"for",
"exclude",
"in",
"excludes",
"]"
] | normalize the excluded directory list: * must be either an absolute path or start with rootpath . | train | true |
34,775 | def _Same(tool, name, setting_type):
_Renamed(tool, name, name, setting_type)
| [
"def",
"_Same",
"(",
"tool",
",",
"name",
",",
"setting_type",
")",
":",
"_Renamed",
"(",
"tool",
",",
"name",
",",
"name",
",",
"setting_type",
")"
] | defines a setting that has the same name in msvs and msbuild . | train | false |
34,776 | def test_scalar_info():
c = time.Time('2000:001')
cinfo = c.info(out=None)
assert (cinfo['n_bad'] == 0)
assert ('length' not in cinfo)
| [
"def",
"test_scalar_info",
"(",
")",
":",
"c",
"=",
"time",
".",
"Time",
"(",
"'2000:001'",
")",
"cinfo",
"=",
"c",
".",
"info",
"(",
"out",
"=",
"None",
")",
"assert",
"(",
"cinfo",
"[",
"'n_bad'",
"]",
"==",
"0",
")",
"assert",
"(",
"'length'",
... | make sure info works with scalar values . | train | false |
34,777 | def _convert_life_span_string(life_span_string):
(d, h, m, s) = TIME_RE.match(life_span_string).groups()
times = [(s, 1), (m, 60), (h, 3600), (d, 86400)]
return sum(((int((t[0] or 0)) * t[1]) for t in times))
| [
"def",
"_convert_life_span_string",
"(",
"life_span_string",
")",
":",
"(",
"d",
",",
"h",
",",
"m",
",",
"s",
")",
"=",
"TIME_RE",
".",
"match",
"(",
"life_span_string",
")",
".",
"groups",
"(",
")",
"times",
"=",
"[",
"(",
"s",
",",
"1",
")",
","... | converts a time_re compatible life span string . | train | false |
34,778 | def format_freshdesk_note_message(ticket, event_info):
note_type = event_info[1]
content = ('%s <%s> added a %s note to [ticket #%s](%s).' % (ticket.requester_name, ticket.requester_email, note_type, ticket.id, ticket.url))
return content
| [
"def",
"format_freshdesk_note_message",
"(",
"ticket",
",",
"event_info",
")",
":",
"note_type",
"=",
"event_info",
"[",
"1",
"]",
"content",
"=",
"(",
"'%s <%s> added a %s note to [ticket #%s](%s).'",
"%",
"(",
"ticket",
".",
"requester_name",
",",
"ticket",
".",
... | there are public and private note types . | train | false |
34,779 | def s3_filename(filename):
import string
import unicodedata
validFilenameChars = ('-_.() %s%s' % (string.ascii_letters, string.digits))
filename = unicode(filename)
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
return ''.join((c for c in cleanedFilename if (c in validFilenameChars)))
| [
"def",
"s3_filename",
"(",
"filename",
")",
":",
"import",
"string",
"import",
"unicodedata",
"validFilenameChars",
"=",
"(",
"'-_.() %s%s'",
"%",
"(",
"string",
".",
"ascii_letters",
",",
"string",
".",
"digits",
")",
")",
"filename",
"=",
"unicode",
"(",
"... | convert a string into a valid filename on all os URL#698714 - currently unused . | train | false |
34,780 | def _normalizeValue(value, withRefs=False, modFunct=None, titlesRefs=None, namesRefs=None, charactersRefs=None):
if isinstance(value, (unicode, str)):
if (not withRefs):
value = _handleTextNotes(escape4xml(value))
else:
replaceLists = _refsToReplace(value, modFunct, titlesRefs, namesRefs, charactersRefs)
value = modFunct(value, (titlesRefs or {}), (namesRefs or {}), (charactersRefs or {}))
value = _handleTextNotes(escape4xml(value))
for replaceList in replaceLists:
for (toReplace, replaceWith) in replaceList:
value = value.replace(toReplace, replaceWith)
else:
value = unicode(value)
return value
| [
"def",
"_normalizeValue",
"(",
"value",
",",
"withRefs",
"=",
"False",
",",
"modFunct",
"=",
"None",
",",
"titlesRefs",
"=",
"None",
",",
"namesRefs",
"=",
"None",
",",
"charactersRefs",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
... | replace some chars that cant be present in a xml text . | train | false |
34,781 | @utils.arg('network', metavar='<network>', help=_('UUID or label of network.'))
@deprecated_network
def do_network_delete(cs, args):
network = utils.find_resource(cs.networks, args.network)
network.delete()
| [
"@",
"utils",
".",
"arg",
"(",
"'network'",
",",
"metavar",
"=",
"'<network>'",
",",
"help",
"=",
"_",
"(",
"'UUID or label of network.'",
")",
")",
"@",
"deprecated_network",
"def",
"do_network_delete",
"(",
"cs",
",",
"args",
")",
":",
"network",
"=",
"u... | delete network by label or id . | train | false |
34,782 | def ssh_wrapper(opts, functions=None, context=None):
return LazyLoader(_module_dirs(opts, 'wrapper', base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh'))), opts, tag='wrapper', pack={'__salt__': functions, '__grains__': opts.get('grains', {}), '__pillar__': opts.get('pillar', {}), '__context__': context})
| [
"def",
"ssh_wrapper",
"(",
"opts",
",",
"functions",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'wrapper'",
",",
"base_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SALT_BASE_PA... | returns the custom logging handler modules . | train | true |
34,783 | def _in_iterating_context(node):
parent = node.parent
if isinstance(parent, astroid.For):
return True
elif isinstance(parent, astroid.Comprehension):
if (parent.iter == node):
return True
elif isinstance(parent, astroid.CallFunc):
if isinstance(parent.func, astroid.Name):
parent_scope = parent.func.lookup(parent.func.name)[0]
if (_is_builtin(parent_scope) and (parent.func.name in _accepts_iterator)):
return True
elif isinstance(parent.func, astroid.Getattr):
if (parent.func.attrname == 'join'):
return True
elif (isinstance(parent, astroid.Assign) and isinstance(parent.targets[0], (astroid.List, astroid.Tuple))):
if (len(parent.targets[0].elts) > 1):
return True
return False
| [
"def",
"_in_iterating_context",
"(",
"node",
")",
":",
"parent",
"=",
"node",
".",
"parent",
"if",
"isinstance",
"(",
"parent",
",",
"astroid",
".",
"For",
")",
":",
"return",
"True",
"elif",
"isinstance",
"(",
"parent",
",",
"astroid",
".",
"Comprehension... | check if the node is being used as an iterator . | train | false |
34,786 | def _parse_ref(text, link, info):
if (link.find('/title/tt') != (-1)):
yearK = re_yearKind_index.match(info)
if (yearK and (yearK.start() == 0)):
text += (' %s' % info[:yearK.end()])
return (text.replace('\n', ' '), link)
| [
"def",
"_parse_ref",
"(",
"text",
",",
"link",
",",
"info",
")",
":",
"if",
"(",
"link",
".",
"find",
"(",
"'/title/tt'",
")",
"!=",
"(",
"-",
"1",
")",
")",
":",
"yearK",
"=",
"re_yearKind_index",
".",
"match",
"(",
"info",
")",
"if",
"(",
"year... | manage links to references . | train | false |
34,787 | def error_for(response):
klass = error_classes.get(response.status_code)
if (klass is None):
if (400 <= response.status_code < 500):
klass = ClientError
if (500 <= response.status_code < 600):
klass = ServerError
return klass(response)
| [
"def",
"error_for",
"(",
"response",
")",
":",
"klass",
"=",
"error_classes",
".",
"get",
"(",
"response",
".",
"status_code",
")",
"if",
"(",
"klass",
"is",
"None",
")",
":",
"if",
"(",
"400",
"<=",
"response",
".",
"status_code",
"<",
"500",
")",
"... | return the appropriate initialized exception class for a response . | train | false |
34,788 | def vary_on_cookie(func):
def inner_func(*args, **kwargs):
response = func(*args, **kwargs)
patch_vary_headers(response, ('Cookie',))
return response
return inner_func
| [
"def",
"vary_on_cookie",
"(",
"func",
")",
":",
"def",
"inner_func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"response",
"=",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"patch_vary_headers",
"(",
"response",
",",
"(",
"'Cookie'",
",",... | a view decorator that adds "cookie" to the vary header of a response . | train | false |
34,789 | @memoize
def re_compile(regex, *args):
if TIMING:
return TimingRe(re.compile(regex, *args), regex)
else:
return re.compile(regex, *args)
| [
"@",
"memoize",
"def",
"re_compile",
"(",
"regex",
",",
"*",
"args",
")",
":",
"if",
"TIMING",
":",
"return",
"TimingRe",
"(",
"re",
".",
"compile",
"(",
"regex",
",",
"*",
"args",
")",
",",
"regex",
")",
"else",
":",
"return",
"re",
".",
"compile"... | a version of re . | train | false |
34,791 | def test_tab_change(percentage, fake_web_tab):
percentage.set_perc(x=None, y=10)
tab = fake_web_tab(scroll_pos_perc=(0, 20))
percentage.on_tab_changed(tab)
assert (percentage.text() == '[20%]')
| [
"def",
"test_tab_change",
"(",
"percentage",
",",
"fake_web_tab",
")",
":",
"percentage",
".",
"set_perc",
"(",
"x",
"=",
"None",
",",
"y",
"=",
"10",
")",
"tab",
"=",
"fake_web_tab",
"(",
"scroll_pos_perc",
"=",
"(",
"0",
",",
"20",
")",
")",
"percent... | make sure the percentage gets changed correctly when switching tabs . | train | false |
34,792 | def deprecated_xblocks():
return XBlockConfiguration.objects.current_set().filter(deprecated=True)
| [
"def",
"deprecated_xblocks",
"(",
")",
":",
"return",
"XBlockConfiguration",
".",
"objects",
".",
"current_set",
"(",
")",
".",
"filter",
"(",
"deprecated",
"=",
"True",
")"
] | return the queryset of deprecated xblock types . | train | false |
34,798 | @skip('silverlight')
def test_event_lifetime():
def keep_alive(o):
pass
def test_runner():
import _weakref
global called
called = 0
a = IronPythonTest.Events()
def foo():
global called
called += 1
foo.abc = a
a.InstanceTest += foo
a.CallInstance()
AreEqual(called, 1)
ret_val = _weakref.ref(foo)
keep_alive(foo)
import gc
for i in xrange(10):
gc.collect()
a.CallInstance()
AreEqual(called, 2)
return ret_val
func_ref = test_runner()
import gc
for i in xrange(10):
gc.collect()
Assert((not hasattr(func_ref, 'abc')))
AreEqual(func_ref(), None)
AreEqual(called, 2)
| [
"@",
"skip",
"(",
"'silverlight'",
")",
"def",
"test_event_lifetime",
"(",
")",
":",
"def",
"keep_alive",
"(",
"o",
")",
":",
"pass",
"def",
"test_runner",
"(",
")",
":",
"import",
"_weakref",
"global",
"called",
"called",
"=",
"0",
"a",
"=",
"IronPython... | ensures that circular references between an event on an instance and the handling delegate dont call leaks and dont release too soon . | train | false |
34,799 | def request_user_input(prompt='> '):
return raw_input(prompt)
| [
"def",
"request_user_input",
"(",
"prompt",
"=",
"'> '",
")",
":",
"return",
"raw_input",
"(",
"prompt",
")"
] | request input from the user and return what has been entered . | train | false |
34,801 | def delete_stream(client, stream_name, wait=False, wait_timeout=300, check_mode=False):
success = False
changed = False
err_msg = ''
results = dict()
(stream_found, stream_msg, current_stream) = find_stream(client, stream_name, check_mode=check_mode)
if stream_found:
(success, err_msg) = stream_action(client, stream_name, action='delete', check_mode=check_mode)
if success:
changed = True
if wait:
(success, err_msg, results) = wait_for_status(client, stream_name, 'DELETING', wait_timeout, check_mode=check_mode)
err_msg = 'Stream {0} deleted successfully'.format(stream_name)
if (not success):
return (success, True, err_msg, results)
else:
err_msg = 'Stream {0} is in the process of being deleted'.format(stream_name)
else:
success = True
changed = False
err_msg = 'Stream {0} does not exist'.format(stream_name)
return (success, changed, err_msg, results)
| [
"def",
"delete_stream",
"(",
"client",
",",
"stream_name",
",",
"wait",
"=",
"False",
",",
"wait_timeout",
"=",
"300",
",",
"check_mode",
"=",
"False",
")",
":",
"success",
"=",
"False",
"changed",
"=",
"False",
"err_msg",
"=",
"''",
"results",
"=",
"dic... | delete the stream with name stream_name . | train | false |
34,802 | def _recreate_irreducible_unit(cls, names, registered):
registry = get_current_unit_registry().registry
if (names[0] in registry):
return registry[names[0]]
else:
unit = cls(names)
if registered:
get_current_unit_registry().add_enabled_units([unit])
| [
"def",
"_recreate_irreducible_unit",
"(",
"cls",
",",
"names",
",",
"registered",
")",
":",
"registry",
"=",
"get_current_unit_registry",
"(",
")",
".",
"registry",
"if",
"(",
"names",
"[",
"0",
"]",
"in",
"registry",
")",
":",
"return",
"registry",
"[",
"... | this is used to reconstruct units when passed around by multiprocessing . | train | false |
34,803 | def method(name, doc):
params = method_params(doc)
return string.Template(METHOD_TEMPLATE).substitute(name=name, params=params, doc=doc)
| [
"def",
"method",
"(",
"name",
",",
"doc",
")",
":",
"params",
"=",
"method_params",
"(",
"doc",
")",
"return",
"string",
".",
"Template",
"(",
"METHOD_TEMPLATE",
")",
".",
"substitute",
"(",
"name",
"=",
"name",
",",
"params",
"=",
"params",
",",
"doc"... | documents an individual method . | train | false |
34,804 | def load_network_dict():
global network_dict
network_dict = dict([(x[u'doc'][u'network_name'], x[u'doc'][u'timezone']) for x in sickrage.srCore.cacheDB.db.all(u'network_timezones', with_doc=True)])
| [
"def",
"load_network_dict",
"(",
")",
":",
"global",
"network_dict",
"network_dict",
"=",
"dict",
"(",
"[",
"(",
"x",
"[",
"u'doc'",
"]",
"[",
"u'network_name'",
"]",
",",
"x",
"[",
"u'doc'",
"]",
"[",
"u'timezone'",
"]",
")",
"for",
"x",
"in",
"sickra... | return network timezones from db . | train | false |
34,805 | def _policy_config(policy):
if (policy is None):
policy = DEFAULT_POLICY
lines = [POLICY_HEADER]
for entry in policy:
entry.setdefault('log_level', '')
entry.setdefault('burst_limit', '')
lines.append((POLICY_FORMAT % entry))
file('/etc/shorewall/policy', contents=''.join(lines), use_sudo=True)
| [
"def",
"_policy_config",
"(",
"policy",
")",
":",
"if",
"(",
"policy",
"is",
"None",
")",
":",
"policy",
"=",
"DEFAULT_POLICY",
"lines",
"=",
"[",
"POLICY_HEADER",
"]",
"for",
"entry",
"in",
"policy",
":",
"entry",
".",
"setdefault",
"(",
"'log_level'",
... | policy configuration . | train | false |
34,807 | def IsOutOfLineMethodDefinition(clean_lines, linenum):
for i in xrange(linenum, max((-1), (linenum - 10)), (-1)):
if Match('^([^()]*\\w+)\\(', clean_lines.elided[i]):
return (Match('^[^()]*\\w+::\\w+\\(', clean_lines.elided[i]) is not None)
return False
| [
"def",
"IsOutOfLineMethodDefinition",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
",",
"max",
"(",
"(",
"-",
"1",
")",
",",
"(",
"linenum",
"-",
"10",
")",
")",
",",
"(",
"-",
"1",
")",
")",
":",
"if"... | check if current line contains an out-of-line method definition . | train | true |
34,808 | def advanced_indexing_op(input, index):
batch_size = tf.shape(input)[0]
max_length = int(input.get_shape()[1])
dim_size = int(input.get_shape()[2])
index = ((tf.range(0, batch_size) * max_length) + (index - 1))
flat = tf.reshape(input, [(-1), dim_size])
relevant = tf.gather(flat, index)
return relevant
| [
"def",
"advanced_indexing_op",
"(",
"input",
",",
"index",
")",
":",
"batch_size",
"=",
"tf",
".",
"shape",
"(",
"input",
")",
"[",
"0",
"]",
"max_length",
"=",
"int",
"(",
"input",
".",
"get_shape",
"(",
")",
"[",
"1",
"]",
")",
"dim_size",
"=",
"... | advanced indexing for sequences . | train | false |
34,810 | def calculate_page_info(offset, total_students):
if ((not (isinstance(offset, int) or offset.isdigit())) or (int(offset) < 0) or (int(offset) >= total_students)):
offset = 0
else:
offset = int(offset)
next_offset = (offset + MAX_STUDENTS_PER_PAGE_GRADE_BOOK)
previous_offset = (offset - MAX_STUDENTS_PER_PAGE_GRADE_BOOK)
page_num = ((offset / MAX_STUDENTS_PER_PAGE_GRADE_BOOK) + 1)
total_pages = (int(math.ceil((float(total_students) / MAX_STUDENTS_PER_PAGE_GRADE_BOOK))) or 1)
if ((previous_offset < 0) or (offset == 0)):
previous_offset = None
if (next_offset >= total_students):
next_offset = None
return {'previous_offset': previous_offset, 'next_offset': next_offset, 'page_num': page_num, 'offset': offset, 'total_pages': total_pages}
| [
"def",
"calculate_page_info",
"(",
"offset",
",",
"total_students",
")",
":",
"if",
"(",
"(",
"not",
"(",
"isinstance",
"(",
"offset",
",",
"int",
")",
"or",
"offset",
".",
"isdigit",
"(",
")",
")",
")",
"or",
"(",
"int",
"(",
"offset",
")",
"<",
"... | takes care of sanitizing the offset of current page also calculates offsets for next and previous page and information like total number of pages and current page number . | train | false |
34,811 | @FileSystem.in_directory(current_directory, 'django', 'dill')
def test_model_creation():
(status, out) = run_scenario('leaves', 'create')
assert_equals(status, 0, out)
| [
"@",
"FileSystem",
".",
"in_directory",
"(",
"current_directory",
",",
"'django'",
",",
"'dill'",
")",
"def",
"test_model_creation",
"(",
")",
":",
"(",
"status",
",",
"out",
")",
"=",
"run_scenario",
"(",
"'leaves'",
",",
"'create'",
")",
"assert_equals",
"... | models are created through lettuce steps . | train | false |
34,812 | def getMatrixTetragridM(matrixTetragrid, prefix, xmlElement):
matrixKeys = getMatrixKeys(prefix)
evaluatedDictionary = evaluate.getEvaluatedDictionary(matrixKeys, xmlElement)
if (len(evaluatedDictionary.keys()) < 1):
return matrixTetragrid
for row in xrange(4):
for column in xrange(4):
key = getMatrixKey(row, column, prefix)
if (key in evaluatedDictionary):
value = evaluatedDictionary[key]
if ((value == None) or (value == 'None')):
print 'Warning, value in getMatrixTetragridM in matrix is None for key for dictionary:'
print key
print evaluatedDictionary
else:
matrixTetragrid = getIdentityMatrixTetragrid(matrixTetragrid)
matrixTetragrid[row][column] = float(value)
euclidean.removeListFromDictionary(xmlElement.attributeDictionary, matrixKeys)
return matrixTetragrid
| [
"def",
"getMatrixTetragridM",
"(",
"matrixTetragrid",
",",
"prefix",
",",
"xmlElement",
")",
":",
"matrixKeys",
"=",
"getMatrixKeys",
"(",
"prefix",
")",
"evaluatedDictionary",
"=",
"evaluate",
".",
"getEvaluatedDictionary",
"(",
"matrixKeys",
",",
"xmlElement",
")"... | get the matrix tetragrid from the xmlelement m values . | train | false |
34,813 | def fix_view_modes(action):
if (not action.get('views')):
generate_views(action)
if (action.pop('view_type', 'form') != 'form'):
return action
if ('view_mode' in action):
action['view_mode'] = ','.join(((mode if (mode != 'tree') else 'list') for mode in action['view_mode'].split(',')))
action['views'] = [[id, (mode if (mode != 'tree') else 'list')] for (id, mode) in action['views']]
return action
| [
"def",
"fix_view_modes",
"(",
"action",
")",
":",
"if",
"(",
"not",
"action",
".",
"get",
"(",
"'views'",
")",
")",
":",
"generate_views",
"(",
"action",
")",
"if",
"(",
"action",
".",
"pop",
"(",
"'view_type'",
",",
"'form'",
")",
"!=",
"'form'",
")... | for historical reasons . | train | false |
34,815 | def is_simple_callable(obj):
function = inspect.isfunction(obj)
method = inspect.ismethod(obj)
if (not (function or method)):
return False
(args, _, _, defaults) = inspect.getargspec(obj)
len_args = (len(args) if function else (len(args) - 1))
len_defaults = (len(defaults) if defaults else 0)
return (len_args <= len_defaults)
| [
"def",
"is_simple_callable",
"(",
"obj",
")",
":",
"function",
"=",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"method",
"=",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
"if",
"(",
"not",
"(",
"function",
"or",
"method",
")",
")",
":",
"return",
... | true if the object is a callable that takes no arguments . | train | true |
34,818 | def get_usernames(user_ids):
users_settings = get_users_settings(user_ids)
return [(us.username if us else None) for us in users_settings]
| [
"def",
"get_usernames",
"(",
"user_ids",
")",
":",
"users_settings",
"=",
"get_users_settings",
"(",
"user_ids",
")",
"return",
"[",
"(",
"us",
".",
"username",
"if",
"us",
"else",
"None",
")",
"for",
"us",
"in",
"users_settings",
"]"
] | gets usernames corresponding to the given user_ids . | train | false |
34,819 | def getopenfilenames(parent=None, caption='', basedir='', filters='', selectedfilter='', options=None):
return _qfiledialog_wrapper('getOpenFileNames', parent=parent, caption=caption, basedir=basedir, filters=filters, selectedfilter=selectedfilter, options=options)
| [
"def",
"getopenfilenames",
"(",
"parent",
"=",
"None",
",",
"caption",
"=",
"''",
",",
"basedir",
"=",
"''",
",",
"filters",
"=",
"''",
",",
"selectedfilter",
"=",
"''",
",",
"options",
"=",
"None",
")",
":",
"return",
"_qfiledialog_wrapper",
"(",
"'getO... | wrapper around qtgui . | train | true |
34,820 | def test_install_wheel_with_prefix(script, data):
prefix_dir = (script.scratch_path / 'prefix')
result = script.pip('install', 'simple.dist==0.1', '--prefix', prefix_dir, '--no-index', ('--find-links=' + data.find_links))
if hasattr(sys, 'pypy_version_info'):
lib = ((Path('scratch') / 'prefix') / 'site-packages')
else:
lib = ((Path('scratch') / 'prefix') / 'lib')
assert (lib in result.files_created)
| [
"def",
"test_install_wheel_with_prefix",
"(",
"script",
",",
"data",
")",
":",
"prefix_dir",
"=",
"(",
"script",
".",
"scratch_path",
"/",
"'prefix'",
")",
"result",
"=",
"script",
".",
"pip",
"(",
"'install'",
",",
"'simple.dist==0.1'",
",",
"'--prefix'",
","... | test installing a wheel using pip install --prefix . | train | false |
34,821 | def flipCol(argdata, n):
argarr = [list(x) for x in argdata]
for row in range(len(argarr)):
for col in range(len(argarr[0])):
if (col == n):
argarr[row][col] = ('+' if (argarr[row][col] == '-') else '-')
return [''.join(x) for x in argarr]
| [
"def",
"flipCol",
"(",
"argdata",
",",
"n",
")",
":",
"argarr",
"=",
"[",
"list",
"(",
"x",
")",
"for",
"x",
"in",
"argdata",
"]",
"for",
"row",
"in",
"range",
"(",
"len",
"(",
"argarr",
")",
")",
":",
"for",
"col",
"in",
"range",
"(",
"len",
... | flips all bits in a given column . | train | false |
34,823 | def _makepretty(printout, stack):
printout.write('======== Salt Debug Stack Trace =========\n')
traceback.print_stack(stack, file=printout)
printout.write('=========================================\n')
| [
"def",
"_makepretty",
"(",
"printout",
",",
"stack",
")",
":",
"printout",
".",
"write",
"(",
"'======== Salt Debug Stack Trace =========\\n'",
")",
"traceback",
".",
"print_stack",
"(",
"stack",
",",
"file",
"=",
"printout",
")",
"printout",
".",
"write",
"(",
... | pretty print the stack trace and environment information for debugging those hard to reproduce user problems . | train | true |
34,824 | def parse_iso_date(s):
format = '%Y-%m-%dT%H:%M:%SZ'
try:
return datetime.datetime.strptime(s, format).replace(tzinfo=pytz.utc)
except ValueError:
return s
| [
"def",
"parse_iso_date",
"(",
"s",
")",
":",
"format",
"=",
"'%Y-%m-%dT%H:%M:%SZ'",
"try",
":",
"return",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"s",
",",
"format",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"except",
... | parses an iso 8601 date string and returns a utc datetime object . | train | false |
34,826 | def expand_hierarchy_metadata(metadata):
try:
name = metadata['name']
except KeyError:
raise ModelError('Hierarchy has no name')
if (not ('levels' in metadata)):
raise ModelError(("Hierarchy '%s' has no levels" % name))
return metadata
| [
"def",
"expand_hierarchy_metadata",
"(",
"metadata",
")",
":",
"try",
":",
"name",
"=",
"metadata",
"[",
"'name'",
"]",
"except",
"KeyError",
":",
"raise",
"ModelError",
"(",
"'Hierarchy has no name'",
")",
"if",
"(",
"not",
"(",
"'levels'",
"in",
"metadata",
... | returns a hierarchy metadata as a dictionary . | train | false |
34,828 | def float_uint8(inarray):
retVal = numpy.around((255 * (0.5 + (0.5 * numpy.asarray(inarray)))))
return retVal.astype(numpy.uint8)
| [
"def",
"float_uint8",
"(",
"inarray",
")",
":",
"retVal",
"=",
"numpy",
".",
"around",
"(",
"(",
"255",
"*",
"(",
"0.5",
"+",
"(",
"0.5",
"*",
"numpy",
".",
"asarray",
"(",
"inarray",
")",
")",
")",
")",
")",
"return",
"retVal",
".",
"astype",
"(... | converts arrays . | train | false |
34,829 | def parent_is_inet():
result = False
sock = socket.fromfd(sys.__stdin__.fileno(), socket.AF_INET, socket.SOCK_RAW)
try:
sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
result = True
except (OSError, socket.error) as err:
if (not (err.args[0] == errno.ENOTSOCK)):
result = True
return result
| [
"def",
"parent_is_inet",
"(",
")",
":",
"result",
"=",
"False",
"sock",
"=",
"socket",
".",
"fromfd",
"(",
"sys",
".",
"__stdin__",
".",
"fileno",
"(",
")",
",",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_RAW",
")",
"try",
":",
"sock",
".",
... | check if parent is inet check if our parent seems ot be a superserver . | train | true |
34,831 | def _all_the_same_submit(matches):
name = None
value = None
for match in matches:
if (match.type not in ['submit', 'hidden']):
return False
if (name is None):
name = match.name
value = match.value
elif ((match.name != name) or (match.value != value)):
return False
return True
| [
"def",
"_all_the_same_submit",
"(",
"matches",
")",
":",
"name",
"=",
"None",
"value",
"=",
"None",
"for",
"match",
"in",
"matches",
":",
"if",
"(",
"match",
".",
"type",
"not",
"in",
"[",
"'submit'",
",",
"'hidden'",
"]",
")",
":",
"return",
"False",
... | utility function to check to see if a list of controls all really belong to the same control: for use with checkboxes . | train | false |
34,832 | def test_classproperty_docstring():
class A(object, ):
@classproperty
def foo(cls):
u'The foo.'
return 1
assert (A.__dict__[u'foo'].__doc__ == u'The foo.')
class B(object, ):
def _get_foo(cls):
return 1
foo = classproperty(_get_foo, doc=u'The foo.')
assert (B.__dict__[u'foo'].__doc__ == u'The foo.')
| [
"def",
"test_classproperty_docstring",
"(",
")",
":",
"class",
"A",
"(",
"object",
",",
")",
":",
"@",
"classproperty",
"def",
"foo",
"(",
"cls",
")",
":",
"return",
"1",
"assert",
"(",
"A",
".",
"__dict__",
"[",
"u'foo'",
"]",
".",
"__doc__",
"==",
... | tests that the docstring is set correctly on classproperties . | train | false |
34,833 | def test_get_ras_to_neuromag_trans():
rng = np.random.RandomState(0)
anterior = [0, 1, 0]
left = [(-1), 0, 0]
right = [0.8, 0, 0]
up = [0, 0, 1]
rand_pts = rng.uniform((-1), 1, (3, 3))
pts = np.vstack((anterior, left, right, up, rand_pts))
(rx, ry, rz, tx, ty, tz) = rng.uniform(((-2) * np.pi), (2 * np.pi), 6)
trans = np.dot(translation(tx, ty, tz), rotation(rx, ry, rz))
pts_changed = apply_trans(trans, pts)
(nas, lpa, rpa) = pts_changed[:3]
hsp_trans = get_ras_to_neuromag_trans(nas, lpa, rpa)
pts_restored = apply_trans(hsp_trans, pts_changed)
err = 'Neuromag transformation failed'
assert_allclose(pts_restored, pts, atol=1e-06, err_msg=err)
| [
"def",
"test_get_ras_to_neuromag_trans",
"(",
")",
":",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"0",
")",
"anterior",
"=",
"[",
"0",
",",
"1",
",",
"0",
"]",
"left",
"=",
"[",
"(",
"-",
"1",
")",
",",
"0",
",",
"0",
"]",
"righ... | test the coordinate transformation from ras to neuromag . | train | false |
34,836 | def get_price_info(shop, customer, product, quantity):
pricing_mod = get_pricing_module()
pricing_ctx = pricing_mod.get_context_from_data(shop=shop, customer=(customer or AnonymousContact()))
return product.get_price_info(pricing_ctx, quantity=quantity)
| [
"def",
"get_price_info",
"(",
"shop",
",",
"customer",
",",
"product",
",",
"quantity",
")",
":",
"pricing_mod",
"=",
"get_pricing_module",
"(",
")",
"pricing_ctx",
"=",
"pricing_mod",
".",
"get_context_from_data",
"(",
"shop",
"=",
"shop",
",",
"customer",
"=... | get price info of product for given quantity . | train | false |
34,837 | def sm_flavor_create(context, values):
return IMPL.sm_flavor_create(context, values)
| [
"def",
"sm_flavor_create",
"(",
"context",
",",
"values",
")",
":",
"return",
"IMPL",
".",
"sm_flavor_create",
"(",
"context",
",",
"values",
")"
] | create a new sm flavor entry . | train | false |
34,839 | def _get_asset_json(display_name, content_type, date, location, thumbnail_location, locked):
asset_url = StaticContent.serialize_asset_key_with_slash(location)
external_url = (settings.LMS_BASE + asset_url)
return {'display_name': display_name, 'content_type': content_type, 'date_added': get_default_time_display(date), 'url': asset_url, 'external_url': external_url, 'portable_url': StaticContent.get_static_path_from_location(location), 'thumbnail': (StaticContent.serialize_asset_key_with_slash(thumbnail_location) if thumbnail_location else None), 'locked': locked, 'id': unicode(location)}
| [
"def",
"_get_asset_json",
"(",
"display_name",
",",
"content_type",
",",
"date",
",",
"location",
",",
"thumbnail_location",
",",
"locked",
")",
":",
"asset_url",
"=",
"StaticContent",
".",
"serialize_asset_key_with_slash",
"(",
"location",
")",
"external_url",
"=",... | helper method for formatting the asset information to send to client . | train | false |
34,840 | def summary():
assess_tables()
return s3_rest_controller()
| [
"def",
"summary",
"(",
")",
":",
"assess_tables",
"(",
")",
"return",
"s3_rest_controller",
"(",
")"
] | plain text summary of the page . | train | false |
34,841 | def period_break(dates, period):
current = getattr(dates, period)
previous = getattr((dates - 1), period)
return (current - previous).nonzero()[0]
| [
"def",
"period_break",
"(",
"dates",
",",
"period",
")",
":",
"current",
"=",
"getattr",
"(",
"dates",
",",
"period",
")",
"previous",
"=",
"getattr",
"(",
"(",
"dates",
"-",
"1",
")",
",",
"period",
")",
"return",
"(",
"current",
"-",
"previous",
")... | returns the indices where the given period changes . | train | false |
34,843 | def user_pk_to_url_str(user):
User = get_user_model()
if (hasattr(models, 'UUIDField') and issubclass(type(User._meta.pk), models.UUIDField)):
if isinstance(user.pk, six.string_types):
return user.pk
return user.pk.hex
ret = user.pk
if isinstance(ret, six.integer_types):
ret = int_to_base36(user.pk)
return str(ret)
| [
"def",
"user_pk_to_url_str",
"(",
"user",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"if",
"(",
"hasattr",
"(",
"models",
",",
"'UUIDField'",
")",
"and",
"issubclass",
"(",
"type",
"(",
"User",
".",
"_meta",
".",
"pk",
")",
",",
"models",
".",
... | this should return a string . | train | true |
34,844 | def query_user(query_string, order='UserName'):
return query_item('user', query_string, order)
| [
"def",
"query_user",
"(",
"query_string",
",",
"order",
"=",
"'UserName'",
")",
":",
"return",
"query_item",
"(",
"'user'",
",",
"query_string",
",",
"order",
")"
] | update a user cli example: . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.