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 |
|---|---|---|---|---|---|
30,428 | def _yield_all_clusters(emr_conn, *args, **kwargs):
for resp in _repeat(emr_conn.list_clusters, *args, **kwargs):
for cluster in getattr(resp, 'clusters', []):
(yield cluster)
| [
"def",
"_yield_all_clusters",
"(",
"emr_conn",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"for",
"resp",
"in",
"_repeat",
"(",
"emr_conn",
".",
"list_clusters",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"for",
"cluster",
"in",
"getattr",
"... | make successive api calls . | train | false |
30,429 | def unpack_task_input(task):
task_input = task.task_input
for key in ['import_from', 'import_from_format', 'image_properties']:
if (key not in task_input):
msg = (_("Input does not contain '%(key)s' field") % {'key': key})
raise exception.Invalid(msg)
return task_input
| [
"def",
"unpack_task_input",
"(",
"task",
")",
":",
"task_input",
"=",
"task",
".",
"task_input",
"for",
"key",
"in",
"[",
"'import_from'",
",",
"'import_from_format'",
",",
"'image_properties'",
"]",
":",
"if",
"(",
"key",
"not",
"in",
"task_input",
")",
":"... | verifies and returns valid task input dictionary . | train | false |
30,430 | def findRelease(epObj):
release = None
provider = None
failed_db_con = db.DBConnection('failed.db')
results = failed_db_con.select('SELECT release, provider, date FROM history WHERE showid=? AND season=? AND episode=?', [epObj.show.indexerid, epObj.season, epObj.episode])
for result in results:
release = str(result['release'])
provider = str(result['provider'])
date = result['date']
failed_db_con.action('DELETE FROM history WHERE release=? AND date!=?', [release, date])
logger.log(u'Failed release found for season ({0}): ({1})'.format(epObj.season, result['release']), logger.DEBUG)
return (release, provider)
logger.log(u'No releases found for season ({0}) of ({1})'.format(epObj.season, epObj.show.indexerid), logger.DEBUG)
return (release, provider)
| [
"def",
"findRelease",
"(",
"epObj",
")",
":",
"release",
"=",
"None",
"provider",
"=",
"None",
"failed_db_con",
"=",
"db",
".",
"DBConnection",
"(",
"'failed.db'",
")",
"results",
"=",
"failed_db_con",
".",
"select",
"(",
"'SELECT release, provider, date FROM hist... | find releases in history by show id and season . | train | false |
30,431 | def LoadEdges(filename, targets):
file = open('dump.json')
edges = json.load(file)
file.close()
target_edges = {}
to_visit = targets[:]
while to_visit:
src = to_visit.pop()
if (src in target_edges):
continue
target_edges[src] = edges[src]
to_visit.extend(edges[src])
return target_edges
| [
"def",
"LoadEdges",
"(",
"filename",
",",
"targets",
")",
":",
"file",
"=",
"open",
"(",
"'dump.json'",
")",
"edges",
"=",
"json",
".",
"load",
"(",
"file",
")",
"file",
".",
"close",
"(",
")",
"target_edges",
"=",
"{",
"}",
"to_visit",
"=",
"targets... | load the edges map from the dump file . | train | false |
30,434 | def _asset_index(request, course_key):
course_module = modulestore().get_course(course_key)
return render_to_response('asset_index.html', {'context_course': course_module, 'max_file_size_in_mbs': settings.MAX_ASSET_UPLOAD_FILE_SIZE_IN_MB, 'chunk_size_in_mbs': settings.UPLOAD_CHUNK_SIZE_IN_MB, 'max_file_size_redirect_url': settings.MAX_ASSET_UPLOAD_FILE_SIZE_URL, 'asset_callback_url': reverse_course_url('assets_handler', course_key)})
| [
"def",
"_asset_index",
"(",
"request",
",",
"course_key",
")",
":",
"course_module",
"=",
"modulestore",
"(",
")",
".",
"get_course",
"(",
"course_key",
")",
"return",
"render_to_response",
"(",
"'asset_index.html'",
",",
"{",
"'context_course'",
":",
"course_modu... | display an editable asset library . | train | false |
30,436 | def test_mnist():
skip_if_no_gpu()
train = load_train_file(os.path.join(pylearn2.__path__[0], 'scripts/papers/maxout/mnist.yaml'))
init_value = control.load_data
control.load_data = [False]
train.dataset = MNIST(which_set='train', axes=['c', 0, 1, 'b'], start=0, stop=100)
train.algorithm._set_monitoring_dataset(train.dataset)
control.load_data = init_value
train.algorithm.termination_criterion = EpochCounter(max_epochs=1)
train.extensions.pop(0)
train.save_freq = 0
train.main_loop()
| [
"def",
"test_mnist",
"(",
")",
":",
"skip_if_no_gpu",
"(",
")",
"train",
"=",
"load_train_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pylearn2",
".",
"__path__",
"[",
"0",
"]",
",",
"'scripts/papers/maxout/mnist.yaml'",
")",
")",
"init_value",
"=",
"... | test the mnist . | train | false |
30,437 | def render_pages(tasks, dest, opts, notification=(lambda x, y: x)):
(failures, pages) = ([], [])
for (num, path) in tasks:
try:
pages.extend(PageProcessor(path, dest, opts, num))
msg = (_('Rendered %s') % path)
except:
failures.append(path)
msg = (_('Failed %s') % path)
if opts.verbose:
msg += ('\n' + traceback.format_exc())
prints(msg)
notification(0.5, msg)
return (pages, failures)
| [
"def",
"render_pages",
"(",
"tasks",
",",
"dest",
",",
"opts",
",",
"notification",
"=",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
")",
")",
":",
"(",
"failures",
",",
"pages",
")",
"=",
"(",
"[",
"]",
",",
"[",
"]",
")",
"for",
"(",
"num",
","... | entry point for the job server . | train | false |
30,438 | def random_mntd(distmat, n, iters):
means = []
indices = arange(distmat.shape[0])
for i in range(iters):
shuffle(indices)
means.append(mntd(reduce_mtx(distmat, indices[:n])))
return (mean(means), std(means))
| [
"def",
"random_mntd",
"(",
"distmat",
",",
"n",
",",
"iters",
")",
":",
"means",
"=",
"[",
"]",
"indices",
"=",
"arange",
"(",
"distmat",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"iters",
")",
":",
"shuffle",
"(",
"indice... | calc mean . | train | false |
30,443 | def _transformValue(value, policy, transform_type):
t_kwargs = {}
if ('Transform' in policy):
if (transform_type in policy['Transform']):
_policydata = _policy_info()
if ((transform_type + 'Args') in policy['Transform']):
t_kwargs = policy['Transform'][(transform_type + 'Args')]
return getattr(_policydata, policy['Transform'][transform_type])(value, **t_kwargs)
else:
return value
else:
if ('Registry' in policy):
if (value == '(value not set)'):
return 'Not Defined'
return value
| [
"def",
"_transformValue",
"(",
"value",
",",
"policy",
",",
"transform_type",
")",
":",
"t_kwargs",
"=",
"{",
"}",
"if",
"(",
"'Transform'",
"in",
"policy",
")",
":",
"if",
"(",
"transform_type",
"in",
"policy",
"[",
"'Transform'",
"]",
")",
":",
"_polic... | helper function to transform the policy value into something that more closely matches how the policy is displayed in the gpedit gui . | train | false |
30,444 | def pytest_collection_modifyitems(session, config, items):
new_items = []
last_items = []
for item in items:
if hasattr(item.obj, 'first'):
new_items.insert(0, item)
elif hasattr(item.obj, 'last'):
last_items.append(item)
else:
new_items.append(item)
items[:] = (new_items + last_items)
| [
"def",
"pytest_collection_modifyitems",
"(",
"session",
",",
"config",
",",
"items",
")",
":",
"new_items",
"=",
"[",
"]",
"last_items",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"if",
"hasattr",
"(",
"item",
".",
"obj",
",",
"'first'",
")",
":... | apply @qtwebengine_* markers; skip unittests with qute_bdd_webengine . | train | false |
30,445 | def strategy_independent_set(G, colors):
remaining_nodes = set(G)
while (len(remaining_nodes) > 0):
nodes = _maximal_independent_set(G.subgraph(remaining_nodes))
remaining_nodes -= nodes
for v in nodes:
(yield v)
| [
"def",
"strategy_independent_set",
"(",
"G",
",",
"colors",
")",
":",
"remaining_nodes",
"=",
"set",
"(",
"G",
")",
"while",
"(",
"len",
"(",
"remaining_nodes",
")",
">",
"0",
")",
":",
"nodes",
"=",
"_maximal_independent_set",
"(",
"G",
".",
"subgraph",
... | uses a greedy independent set removal strategy to determine the colors . | train | false |
30,446 | def delete_comment(request, comment_id):
(cc_comment, context) = _get_comment_and_context(request, comment_id)
if can_delete(cc_comment, context):
cc_comment.delete()
comment_deleted.send(sender=None, user=request.user, post=cc_comment)
else:
raise PermissionDenied
| [
"def",
"delete_comment",
"(",
"request",
",",
"comment_id",
")",
":",
"(",
"cc_comment",
",",
"context",
")",
"=",
"_get_comment_and_context",
"(",
"request",
",",
"comment_id",
")",
"if",
"can_delete",
"(",
"cc_comment",
",",
"context",
")",
":",
"cc_comment"... | deletes comment . | train | false |
30,447 | def create_groups():
data_dir = settings.DATA_DIR
print ('data_dir = %s' % data_dir)
for course_dir in os.listdir(data_dir):
if course_dir.startswith('.'):
continue
if (not os.path.isdir((path(data_dir) / course_dir))):
continue
cxfn = ((path(data_dir) / course_dir) / 'course.xml')
try:
coursexml = etree.parse(cxfn)
except Exception:
print ('Oops, cannot read %s, skipping' % cxfn)
continue
cxmlroot = coursexml.getroot()
course = cxmlroot.get('course')
if (course is None):
print ("oops, can't get course id for %s" % course_dir)
continue
print ('course=%s for course_dir=%s' % (course, course_dir))
create_group(('staff_%s' % course))
create_group(('instructor_%s' % course))
| [
"def",
"create_groups",
"(",
")",
":",
"data_dir",
"=",
"settings",
".",
"DATA_DIR",
"print",
"(",
"'data_dir = %s'",
"%",
"data_dir",
")",
"for",
"course_dir",
"in",
"os",
".",
"listdir",
"(",
"data_dir",
")",
":",
"if",
"course_dir",
".",
"startswith",
"... | create staff and instructor groups for all classes in the data_dir . | train | false |
30,448 | def password_reset_done(request, response_format='html'):
return render_to_response('core/password_reset_done', context_instance=RequestContext(request), response_format=response_format)
| [
"def",
"password_reset_done",
"(",
"request",
",",
"response_format",
"=",
"'html'",
")",
":",
"return",
"render_to_response",
"(",
"'core/password_reset_done'",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"respons... | shows success message . | train | false |
30,449 | def list_windowsfeatures():
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'list', '--source', 'windowsfeatures']
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if (result['retcode'] != 0):
err = 'Running chocolatey failed: {0}'.format(result['stdout'])
raise CommandExecutionError(err)
return result['stdout']
| [
"def",
"list_windowsfeatures",
"(",
")",
":",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"cmd",
"=",
"[",
"choc_path",
",",
"'list'",
",",
"'--source'",
",",
"'windowsfeatures'",
"]",
"result",
"=",
"__salt__",
"[",
"'cmd.r... | instructs chocolatey to pull a full package list from the windows features list . | train | true |
30,450 | def _read_pfm(handle):
alphabet = dna
counts = {}
letters = 'ACGT'
for (letter, line) in zip(letters, handle):
words = line.split()
if (words[0] == letter):
words = words[1:]
counts[letter] = [float(x) for x in words]
motif = Motif(matrix_id=None, name=None, alphabet=alphabet, counts=counts)
motif.mask = ('*' * motif.length)
record = Record()
record.append(motif)
return record
| [
"def",
"_read_pfm",
"(",
"handle",
")",
":",
"alphabet",
"=",
"dna",
"counts",
"=",
"{",
"}",
"letters",
"=",
"'ACGT'",
"for",
"(",
"letter",
",",
"line",
")",
"in",
"zip",
"(",
"letters",
",",
"handle",
")",
":",
"words",
"=",
"line",
".",
"split"... | read the motif from a jaspar . | train | false |
30,451 | def GetDefaultStyleForDir(dirname):
dirname = os.path.abspath(dirname)
while True:
style_file = os.path.join(dirname, style.LOCAL_STYLE)
if os.path.exists(style_file):
return style_file
config_file = os.path.join(dirname, style.SETUP_CONFIG)
if os.path.exists(config_file):
with open(config_file) as fd:
config = py3compat.ConfigParser()
config.read_file(fd)
if config.has_section('yapf'):
return config_file
dirname = os.path.dirname(dirname)
if ((not dirname) or (not os.path.basename(dirname)) or (dirname == os.path.abspath(os.path.sep))):
break
global_file = os.path.expanduser(style.GLOBAL_STYLE)
if os.path.exists(global_file):
return global_file
return style.DEFAULT_STYLE
| [
"def",
"GetDefaultStyleForDir",
"(",
"dirname",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dirname",
")",
"while",
"True",
":",
"style_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"style",
".",
"LOCAL_STYLE",
... | return default style name for a given directory . | train | false |
30,452 | def mailchimp_subscribe(email, mc_url):
r = requests.post(mc_url, data={'EMAIL': email})
return r.text
| [
"def",
"mailchimp_subscribe",
"(",
"email",
",",
"mc_url",
")",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"mc_url",
",",
"data",
"=",
"{",
"'EMAIL'",
":",
"email",
"}",
")",
"return",
"r",
".",
"text"
] | do the post request to mailchimp . | train | false |
30,453 | def tempest_modules():
return {'compute': compute, 'identity.v2': identity.v2, 'identity.v3': identity.v3, 'image.v1': image.v1, 'image.v2': image.v2, 'network': network, 'volume.v1': volume.v1, 'volume.v2': volume.v2, 'volume.v3': volume.v3}
| [
"def",
"tempest_modules",
"(",
")",
":",
"return",
"{",
"'compute'",
":",
"compute",
",",
"'identity.v2'",
":",
"identity",
".",
"v2",
",",
"'identity.v3'",
":",
"identity",
".",
"v3",
",",
"'image.v1'",
":",
"image",
".",
"v1",
",",
"'image.v2'",
":",
"... | dict of service client modules available in tempest . | train | false |
30,454 | 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])
| [
"def",
"do_get_language_info",
"(",
"parser",
",",
"token",
")",
":",
"args",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"(",
"(",
"len",
"(",
"args",
")",
"!=",
"5",
")",
"or",
"(",
"args",
"[",
"1",
"]",
"!=",
"'for'",
")",
... | this will store the language information dictionary for the given language code in a context variable . | train | false |
30,455 | def cse_separate(r, e):
d = sift(e, (lambda w: (w.is_Equality and w.lhs.is_Symbol)))
r = (r + [w.args for w in d[True]])
e = d[False]
return [reps_toposort(r), e]
| [
"def",
"cse_separate",
"(",
"r",
",",
"e",
")",
":",
"d",
"=",
"sift",
"(",
"e",
",",
"(",
"lambda",
"w",
":",
"(",
"w",
".",
"is_Equality",
"and",
"w",
".",
"lhs",
".",
"is_Symbol",
")",
")",
")",
"r",
"=",
"(",
"r",
"+",
"[",
"w",
".",
... | move expressions that are in the form out of the expressions and sort them into the replacements using the reps_toposort . | train | false |
30,456 | def str2bool(value):
return (value.lower() in (u'yes', u'1', u'true', u't', u'y'))
| [
"def",
"str2bool",
"(",
"value",
")",
":",
"return",
"(",
"value",
".",
"lower",
"(",
")",
"in",
"(",
"u'yes'",
",",
"u'1'",
",",
"u'true'",
",",
"u't'",
",",
"u'y'",
")",
")"
] | returns a boolean reflecting a human-entered string . | train | false |
30,457 | def human_file_size(size):
if hasattr(size, u'unit'):
from .. import units as u
size = size.to(u.byte).value
suffixes = u' kMGTPEZY'
if (size == 0):
num_scale = 0
else:
num_scale = int(math.floor((math.log(size) / math.log(1000))))
if (num_scale > 7):
suffix = u'?'
else:
suffix = suffixes[num_scale]
num_scale = int(math.pow(1000, num_scale))
value = (size / num_scale)
str_value = str(value)
if (suffix == u' '):
str_value = str_value[:str_value.index(u'.')]
elif (str_value[2] == u'.'):
str_value = str_value[:2]
else:
str_value = str_value[:3]
return u'{0:>3s}{1}'.format(str_value, suffix)
| [
"def",
"human_file_size",
"(",
"size",
")",
":",
"if",
"hasattr",
"(",
"size",
",",
"u'unit'",
")",
":",
"from",
".",
".",
"import",
"units",
"as",
"u",
"size",
"=",
"size",
".",
"to",
"(",
"u",
".",
"byte",
")",
".",
"value",
"suffixes",
"=",
"u... | returns a human-friendly string representing a file size that is 2-4 characters long . | train | false |
30,459 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
30,460 | def EncodeVarLengthNumber(value):
byte_str = ''
while (value >= 128):
byte_str += struct.pack('>B', ((value & 127) | 128))
value >>= 7
byte_str += struct.pack('>B', (value & 127))
return byte_str
| [
"def",
"EncodeVarLengthNumber",
"(",
"value",
")",
":",
"byte_str",
"=",
"''",
"while",
"(",
"value",
">=",
"128",
")",
":",
"byte_str",
"+=",
"struct",
".",
"pack",
"(",
"'>B'",
",",
"(",
"(",
"value",
"&",
"127",
")",
"|",
"128",
")",
")",
"value... | uses a variable length encoding scheme . | train | false |
30,461 | def StandardNormalCdf(x):
return ((math.erf((x / ROOT2)) + 1) / 2)
| [
"def",
"StandardNormalCdf",
"(",
"x",
")",
":",
"return",
"(",
"(",
"math",
".",
"erf",
"(",
"(",
"x",
"/",
"ROOT2",
")",
")",
"+",
"1",
")",
"/",
"2",
")"
] | evaluates the cdf of the standard normal distribution . | train | false |
30,462 | def apply_sorting(records, sorting):
result = list(records)
if (not result):
return result
first_record = result[0]
def column(first, record, name):
empty = first.get(name, float('inf'))
subfields = name.split('.')
value = record
for subfield in subfields:
value = value.get(subfield, empty)
if (not isinstance(value, dict)):
break
return value
for sort in reversed(sorting):
result = sorted(result, key=(lambda r: column(first_record, r, sort.field)), reverse=(sort.direction < 0))
return result
| [
"def",
"apply_sorting",
"(",
"records",
",",
"sorting",
")",
":",
"result",
"=",
"list",
"(",
"records",
")",
"if",
"(",
"not",
"result",
")",
":",
"return",
"result",
"first_record",
"=",
"result",
"[",
"0",
"]",
"def",
"column",
"(",
"first",
",",
... | sort the specified records . | train | false |
30,464 | def Mandatory(cls, **_kwargs):
kwargs = dict(min_occurs=1, nillable=False)
if (cls.get_type_name() is not cls.Empty):
kwargs['type_name'] = ('%s%s%s' % (const.MANDATORY_PREFIX, cls.get_type_name(), const.MANDATORY_SUFFIX))
kwargs.update(_kwargs)
if issubclass(cls, Unicode):
kwargs.update(dict(min_len=1))
elif issubclass(cls, Array):
((k, v),) = cls._type_info.items()
if (v.Attributes.min_occurs == 0):
cls._type_info[k] = Mandatory(v)
return cls.customize(**kwargs)
| [
"def",
"Mandatory",
"(",
"cls",
",",
"**",
"_kwargs",
")",
":",
"kwargs",
"=",
"dict",
"(",
"min_occurs",
"=",
"1",
",",
"nillable",
"=",
"False",
")",
"if",
"(",
"cls",
".",
"get_type_name",
"(",
")",
"is",
"not",
"cls",
".",
"Empty",
")",
":",
... | customizes the given type to be a mandatory one . | train | false |
30,465 | def offset_bounds_from_strides(context, builder, arrty, arr, shapes, strides):
itemsize = arr.itemsize
zero = itemsize.type(0)
one = zero.type(1)
if (arrty.layout in 'CF'):
lower = zero
upper = builder.mul(itemsize, arr.nitems)
else:
lower = zero
upper = zero
for i in range(arrty.ndim):
max_axis_offset = builder.mul(strides[i], builder.sub(shapes[i], one))
is_upwards = builder.icmp_signed('>=', max_axis_offset, zero)
upper = builder.select(is_upwards, builder.add(upper, max_axis_offset), upper)
lower = builder.select(is_upwards, lower, builder.add(lower, max_axis_offset))
upper = builder.add(upper, itemsize)
is_empty = builder.icmp_signed('==', arr.nitems, zero)
upper = builder.select(is_empty, zero, upper)
lower = builder.select(is_empty, zero, lower)
return (lower, upper)
| [
"def",
"offset_bounds_from_strides",
"(",
"context",
",",
"builder",
",",
"arrty",
",",
"arr",
",",
"shapes",
",",
"strides",
")",
":",
"itemsize",
"=",
"arr",
".",
"itemsize",
"zero",
"=",
"itemsize",
".",
"type",
"(",
"0",
")",
"one",
"=",
"zero",
".... | compute a half-open range [lower . | train | false |
30,466 | def parse_lt_objects(lt_objects):
text_content = []
for lt_object in lt_objects:
if (isinstance(lt_object, LTTextBox) or isinstance(lt_object, LTTextLine)):
text_content.append(lt_object.get_text().encode('utf-8'))
elif isinstance(lt_object, LTFigure):
text_content.append(parse_lt_objects(lt_object._objs))
return '\n'.join(text_content)
| [
"def",
"parse_lt_objects",
"(",
"lt_objects",
")",
":",
"text_content",
"=",
"[",
"]",
"for",
"lt_object",
"in",
"lt_objects",
":",
"if",
"(",
"isinstance",
"(",
"lt_object",
",",
"LTTextBox",
")",
"or",
"isinstance",
"(",
"lt_object",
",",
"LTTextLine",
")"... | iterate through the list of lt* objects and capture the text data contained in each object . | train | false |
30,468 | def buildTopo(topos, topoStr):
(topo, args, kwargs) = splitArgs(topoStr)
if (topo not in topos):
raise Exception(('Invalid topo name %s' % topo))
return topos[topo](*args, **kwargs)
| [
"def",
"buildTopo",
"(",
"topos",
",",
"topoStr",
")",
":",
"(",
"topo",
",",
"args",
",",
"kwargs",
")",
"=",
"splitArgs",
"(",
"topoStr",
")",
"if",
"(",
"topo",
"not",
"in",
"topos",
")",
":",
"raise",
"Exception",
"(",
"(",
"'Invalid topo name %s'"... | create topology from string with format . | train | false |
30,469 | def set_target(alias, target):
if (alias == ''):
raise SaltInvocationError('alias can not be an empty string')
if (target == ''):
raise SaltInvocationError('target can not be an empty string')
if (get_target(alias) == target):
return True
lines = __parse_aliases()
out = []
ovr = False
for (line_alias, line_target, line_comment) in lines:
if (line_alias == alias):
if (not ovr):
out.append((alias, target, line_comment))
ovr = True
else:
out.append((line_alias, line_target, line_comment))
if (not ovr):
out.append((alias, target, ''))
__write_aliases_file(out)
return True
| [
"def",
"set_target",
"(",
"alias",
",",
"target",
")",
":",
"if",
"(",
"alias",
"==",
"''",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'alias can not be an empty string'",
")",
"if",
"(",
"target",
"==",
"''",
")",
":",
"raise",
"SaltInvocationError",
"... | set the entry in the aliases file for the given alias . | train | true |
30,470 | def bw_usage_get(context, uuid, start_period, mac):
return IMPL.bw_usage_get(context, uuid, start_period, mac)
| [
"def",
"bw_usage_get",
"(",
"context",
",",
"uuid",
",",
"start_period",
",",
"mac",
")",
":",
"return",
"IMPL",
".",
"bw_usage_get",
"(",
"context",
",",
"uuid",
",",
"start_period",
",",
"mac",
")"
] | return bw usage for instance and mac in a given audit period . | train | false |
30,472 | def defdict_to_dict(defdict, constructor=dict):
if isinstance(defdict, dict):
new = constructor()
for (key, value) in defdict.items():
new[key] = defdict_to_dict(value, constructor)
return new
else:
return defdict
| [
"def",
"defdict_to_dict",
"(",
"defdict",
",",
"constructor",
"=",
"dict",
")",
":",
"if",
"isinstance",
"(",
"defdict",
",",
"dict",
")",
":",
"new",
"=",
"constructor",
"(",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"defdict",
".",
"items",
... | recursively convert default dicts to regular dicts . | train | false |
30,473 | def get_versions_list():
return (([('Weblate', '', GIT_VERSION)] + get_versions()) + get_optional_versions())
| [
"def",
"get_versions_list",
"(",
")",
":",
"return",
"(",
"(",
"[",
"(",
"'Weblate'",
",",
"''",
",",
"GIT_VERSION",
")",
"]",
"+",
"get_versions",
"(",
")",
")",
"+",
"get_optional_versions",
"(",
")",
")"
] | returns list with version information summary . | train | false |
30,475 | def find_css_with_wait(context, id_str, **kwargs):
return _find_elem_with_wait(context, (By.CSS_SELECTOR, id_str), **kwargs)
| [
"def",
"find_css_with_wait",
"(",
"context",
",",
"id_str",
",",
"**",
"kwargs",
")",
":",
"return",
"_find_elem_with_wait",
"(",
"context",
",",
"(",
"By",
".",
"CSS_SELECTOR",
",",
"id_str",
")",
",",
"**",
"kwargs",
")"
] | tries to find an element with given css selector with an explicit timeout . | train | false |
30,476 | def _GetDriver(driver_name=None):
if (not driver_name):
base_pkg_path = 'google.storage.speckle.python.api.'
if apiproxy_stub_map.apiproxy.GetStub('rdbms'):
driver_name = (base_pkg_path + 'rdbms_apiproxy')
else:
driver_name = (base_pkg_path + 'rdbms_googleapi')
__import__(driver_name)
return sys.modules[driver_name]
| [
"def",
"_GetDriver",
"(",
"driver_name",
"=",
"None",
")",
":",
"if",
"(",
"not",
"driver_name",
")",
":",
"base_pkg_path",
"=",
"'google.storage.speckle.python.api.'",
"if",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"GetStub",
"(",
"'rdbms'",
")",
":",
"driver... | imports the driver module specified by the given module name . | train | false |
30,477 | def insert_into_pipeline(pipeline, transform, before=None, after=None):
assert (before or after)
cls = (before or after)
for (i, t) in enumerate(pipeline):
if isinstance(t, cls):
break
if after:
i += 1
return ((pipeline[:i] + [transform]) + pipeline[i:])
| [
"def",
"insert_into_pipeline",
"(",
"pipeline",
",",
"transform",
",",
"before",
"=",
"None",
",",
"after",
"=",
"None",
")",
":",
"assert",
"(",
"before",
"or",
"after",
")",
"cls",
"=",
"(",
"before",
"or",
"after",
")",
"for",
"(",
"i",
",",
"t",
... | insert a new transform into the pipeline after or before an instance of the given class . | train | false |
30,478 | def comb(N, k, exact=False, repetition=False):
if repetition:
return comb(((N + k) - 1), k, exact)
if exact:
return _comb_int(N, k)
else:
(k, N) = (asarray(k), asarray(N))
cond = (((k <= N) & (N >= 0)) & (k >= 0))
vals = binom(N, k)
if isinstance(vals, np.ndarray):
vals[(~ cond)] = 0
elif (not cond):
vals = np.float64(0)
return vals
| [
"def",
"comb",
"(",
"N",
",",
"k",
",",
"exact",
"=",
"False",
",",
"repetition",
"=",
"False",
")",
":",
"if",
"repetition",
":",
"return",
"comb",
"(",
"(",
"(",
"N",
"+",
"k",
")",
"-",
"1",
")",
",",
"k",
",",
"exact",
")",
"if",
"exact",... | the number of combinations of n things taken k at a time . | train | false |
30,479 | def str_rsplit(arr, pat=None, n=None):
if ((n is None) or (n == 0)):
n = (-1)
f = (lambda x: x.rsplit(pat, n))
res = _na_map(f, arr)
return res
| [
"def",
"str_rsplit",
"(",
"arr",
",",
"pat",
"=",
"None",
",",
"n",
"=",
"None",
")",
":",
"if",
"(",
"(",
"n",
"is",
"None",
")",
"or",
"(",
"n",
"==",
"0",
")",
")",
":",
"n",
"=",
"(",
"-",
"1",
")",
"f",
"=",
"(",
"lambda",
"x",
":"... | split each string in the series/index by the given delimiter string . | train | true |
30,482 | def _find_all_vdis_and_system_vdis(xenapi, all_vdi_uuids, connected_vdi_uuids):
def _system_owned(vdi_rec):
vdi_name = vdi_rec['name_label']
return (vdi_name.startswith('USB') or vdi_name.endswith('.iso') or (vdi_rec['type'] == 'system'))
for vdi_ref in call_xenapi(xenapi, 'VDI.get_all'):
try:
vdi_rec = call_xenapi(xenapi, 'VDI.get_record', vdi_ref)
except XenAPI.Failure as e:
if (e.details[0] != 'HANDLE_INVALID'):
raise
continue
vdi_uuid = vdi_rec['uuid']
all_vdi_uuids.add(vdi_uuid)
if _system_owned(vdi_rec):
print_xen_object('SYSTEM VDI', vdi_rec, indent_level=0)
connected_vdi_uuids.add(vdi_uuid)
elif (not vdi_rec['managed']):
print_xen_object('UNMANAGED VDI', vdi_rec, indent_level=0)
connected_vdi_uuids.add(vdi_uuid)
| [
"def",
"_find_all_vdis_and_system_vdis",
"(",
"xenapi",
",",
"all_vdi_uuids",
",",
"connected_vdi_uuids",
")",
":",
"def",
"_system_owned",
"(",
"vdi_rec",
")",
":",
"vdi_name",
"=",
"vdi_rec",
"[",
"'name_label'",
"]",
"return",
"(",
"vdi_name",
".",
"startswith"... | collects all vdis and adds system vdis to the connected set . | train | false |
30,483 | def get_system_runners_base_path():
return cfg.CONF.content.system_runners_base_path
| [
"def",
"get_system_runners_base_path",
"(",
")",
":",
"return",
"cfg",
".",
"CONF",
".",
"content",
".",
"system_runners_base_path"
] | return a path to the directory where system runners are stored . | train | false |
30,484 | def build_markdown_header(title, date, author, categories, tags, slug, status=None, attachments=None):
header = (u'Title: %s\n' % title)
if date:
header += (u'Date: %s\n' % date)
if author:
header += (u'Author: %s\n' % author)
if categories:
header += (u'Category: %s\n' % u', '.join(categories))
if tags:
header += (u'Tags: %s\n' % u', '.join(tags))
if slug:
header += (u'Slug: %s\n' % slug)
if status:
header += (u'Status: %s\n' % status)
if attachments:
header += (u'Attachments: %s\n' % u', '.join(attachments))
header += u'\n'
return header
| [
"def",
"build_markdown_header",
"(",
"title",
",",
"date",
",",
"author",
",",
"categories",
",",
"tags",
",",
"slug",
",",
"status",
"=",
"None",
",",
"attachments",
"=",
"None",
")",
":",
"header",
"=",
"(",
"u'Title: %s\\n'",
"%",
"title",
")",
"if",
... | build a header from a list of fields . | train | false |
30,485 | def GetFieldInDocument(document, field_name, return_type=None):
if (return_type is not None):
field_list = [f for f in document.field_list() if (f.name() == field_name)]
field_types_dict = {}
for f in field_list:
field_types_dict.setdefault(f.value().type(), f)
if (return_type == EXPRESSION_RETURN_TYPE_TEXT):
if (document_pb.FieldValue.HTML in field_types_dict):
return field_types_dict[document_pb.FieldValue.HTML]
if (document_pb.FieldValue.ATOM in field_types_dict):
return field_types_dict[document_pb.FieldValue.ATOM]
return field_types_dict.get(document_pb.FieldValue.TEXT)
elif (return_type == EXPRESSION_RETURN_TYPE_NUMERIC):
if (document_pb.FieldValue.NUMBER in field_types_dict):
return field_types_dict[document_pb.FieldValue.NUMBER]
return field_types_dict.get(document_pb.FieldValue.DATE)
else:
return field_types_dict.get(return_type)
else:
for f in document.field_list():
if (f.name() == field_name):
return f
return None
| [
"def",
"GetFieldInDocument",
"(",
"document",
",",
"field_name",
",",
"return_type",
"=",
"None",
")",
":",
"if",
"(",
"return_type",
"is",
"not",
"None",
")",
":",
"field_list",
"=",
"[",
"f",
"for",
"f",
"in",
"document",
".",
"field_list",
"(",
")",
... | find and return the field with the provided name and type . | train | false |
30,488 | def _poll_for_status(poll_fn, obj_id, action, final_ok_states, poll_period=5, show_progress=True, status_field='status', silent=False):
def print_progress(progress):
if show_progress:
msg = (_('\rServer %(action)s... %(progress)s%% complete') % dict(action=action, progress=progress))
else:
msg = (_('\rServer %(action)s...') % dict(action=action))
sys.stdout.write(msg)
sys.stdout.flush()
if (not silent):
print()
while True:
obj = poll_fn(obj_id)
status = getattr(obj, status_field)
if status:
status = status.lower()
progress = (getattr(obj, 'progress', None) or 0)
if (status in final_ok_states):
if (not silent):
print_progress(100)
print(_('\nFinished'))
break
elif (status == 'error'):
if (not silent):
print((_('\nError %s server') % action))
raise exceptions.ResourceInErrorState(obj)
elif (status == 'deleted'):
if (not silent):
print((_('\nDeleted %s server') % action))
raise exceptions.InstanceInDeletedState(obj.fault['message'])
if (not silent):
print_progress(progress)
time.sleep(poll_period)
| [
"def",
"_poll_for_status",
"(",
"poll_fn",
",",
"obj_id",
",",
"action",
",",
"final_ok_states",
",",
"poll_period",
"=",
"5",
",",
"show_progress",
"=",
"True",
",",
"status_field",
"=",
"'status'",
",",
"silent",
"=",
"False",
")",
":",
"def",
"print_progr... | block while an action is being performed . | train | false |
30,489 | def _group_name_from_id(project, group_id):
return 'projects/{project}/groups/{group_id}'.format(project=project, group_id=group_id)
| [
"def",
"_group_name_from_id",
"(",
"project",
",",
"group_id",
")",
":",
"return",
"'projects/{project}/groups/{group_id}'",
".",
"format",
"(",
"project",
"=",
"project",
",",
"group_id",
"=",
"group_id",
")"
] | build the group name given the project and group id . | train | false |
30,490 | def parse_afm(fh):
_sanity_check(fh)
dhead = _parse_header(fh)
(dcmetrics_ascii, dcmetrics_name) = _parse_char_metrics(fh)
doptional = _parse_optional(fh)
return (dhead, dcmetrics_ascii, dcmetrics_name, doptional[0], doptional[1])
| [
"def",
"parse_afm",
"(",
"fh",
")",
":",
"_sanity_check",
"(",
"fh",
")",
"dhead",
"=",
"_parse_header",
"(",
"fh",
")",
"(",
"dcmetrics_ascii",
",",
"dcmetrics_name",
")",
"=",
"_parse_char_metrics",
"(",
"fh",
")",
"doptional",
"=",
"_parse_optional",
"(",... | parse the adobe font metics file in file handle *fh* . | train | false |
30,491 | def _unserialize_packer_dict(serialized_packer_dict):
packer_dict = {}
for item in serialized_packer_dict.split('%!(PACKER_COMMA)'):
(key, value) = item.split(':')
packer_dict[key] = value
return freeze(packer_dict)
| [
"def",
"_unserialize_packer_dict",
"(",
"serialized_packer_dict",
")",
":",
"packer_dict",
"=",
"{",
"}",
"for",
"item",
"in",
"serialized_packer_dict",
".",
"split",
"(",
"'%!(PACKER_COMMA)'",
")",
":",
"(",
"key",
",",
"value",
")",
"=",
"item",
".",
"split"... | parse a packer serialized dictionary . | train | false |
30,492 | def parse_lang(rule):
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
parser.add_argument('lang')
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args
| [
"def",
"parse_lang",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"parser",
".",
"add_argument",
"(",
"'lang'",
")",
"arg... | parse the lang line . | train | true |
30,494 | def _wait_until_complete(operation, max_attempts=5):
def _operation_complete(result):
return result
retry = RetryResult(_operation_complete, max_tries=max_attempts)
return retry(operation.poll)()
| [
"def",
"_wait_until_complete",
"(",
"operation",
",",
"max_attempts",
"=",
"5",
")",
":",
"def",
"_operation_complete",
"(",
"result",
")",
":",
"return",
"result",
"retry",
"=",
"RetryResult",
"(",
"_operation_complete",
",",
"max_tries",
"=",
"max_attempts",
"... | wait until an operation has completed . | train | false |
30,495 | def _getattr(obj, name, default):
value = getattr(obj, name, default)
if value:
return value
else:
return default
| [
"def",
"_getattr",
"(",
"obj",
",",
"name",
",",
"default",
")",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"name",
",",
"default",
")",
"if",
"value",
":",
"return",
"value",
"else",
":",
"return",
"default"
] | like getattr but return default if none or false . | train | true |
30,497 | def _parse_nested_sequence(context, typ):
if isinstance(typ, (types.Buffer,)):
raise TypingError('%r not allowed in a homogenous sequence')
elif isinstance(typ, (types.Sequence,)):
(n, dtype) = _parse_nested_sequence(context, typ.dtype)
return ((n + 1), dtype)
elif isinstance(typ, (types.BaseTuple,)):
if (typ.count == 0):
return (1, types.float64)
(n, dtype) = _parse_nested_sequence(context, typ[0])
dtypes = [dtype]
for i in range(1, typ.count):
(_n, dtype) = _parse_nested_sequence(context, typ[i])
if (_n != n):
raise TypingError(('type %r does not have a regular shape' % (typ,)))
dtypes.append(dtype)
dtype = context.unify_types(*dtypes)
if (dtype is None):
raise TypingError('cannot convert %r to a homogenous type')
return ((n + 1), dtype)
else:
as_dtype(typ)
return (0, typ)
| [
"def",
"_parse_nested_sequence",
"(",
"context",
",",
"typ",
")",
":",
"if",
"isinstance",
"(",
"typ",
",",
"(",
"types",
".",
"Buffer",
",",
")",
")",
":",
"raise",
"TypingError",
"(",
"'%r not allowed in a homogenous sequence'",
")",
"elif",
"isinstance",
"(... | parse a nested sequence type . | train | false |
30,499 | def GetScriptModuleName(handler_path):
if handler_path.startswith((PYTHON_LIB_VAR + '/')):
handler_path = handler_path[len(PYTHON_LIB_VAR):]
handler_path = os.path.normpath(handler_path)
extension_index = handler_path.rfind('.py')
if (extension_index != (-1)):
handler_path = handler_path[:extension_index]
module_fullname = handler_path.replace(os.sep, '.')
module_fullname = module_fullname.strip('.')
module_fullname = re.sub('\\.+', '.', module_fullname)
if module_fullname.endswith('.__init__'):
module_fullname = module_fullname[:(- len('.__init__'))]
return module_fullname
| [
"def",
"GetScriptModuleName",
"(",
"handler_path",
")",
":",
"if",
"handler_path",
".",
"startswith",
"(",
"(",
"PYTHON_LIB_VAR",
"+",
"'/'",
")",
")",
":",
"handler_path",
"=",
"handler_path",
"[",
"len",
"(",
"PYTHON_LIB_VAR",
")",
":",
"]",
"handler_path",
... | determines the fully-qualified python module name of a script on disk . | train | false |
30,500 | def windows_memory_usage():
from ctypes import windll, Structure, c_uint64, sizeof, byref
from ctypes.wintypes import DWORD
class MemoryStatus(Structure, ):
_fields_ = [('dwLength', DWORD), ('dwMemoryLoad', DWORD), ('ullTotalPhys', c_uint64), ('ullAvailPhys', c_uint64), ('ullTotalPageFile', c_uint64), ('ullAvailPageFile', c_uint64), ('ullTotalVirtual', c_uint64), ('ullAvailVirtual', c_uint64), ('ullAvailExtendedVirtual', c_uint64)]
memorystatus = MemoryStatus()
memorystatus.dwLength = sizeof(memorystatus)
windll.kernel32.GlobalMemoryStatusEx(byref(memorystatus))
return float(memorystatus.dwMemoryLoad)
| [
"def",
"windows_memory_usage",
"(",
")",
":",
"from",
"ctypes",
"import",
"windll",
",",
"Structure",
",",
"c_uint64",
",",
"sizeof",
",",
"byref",
"from",
"ctypes",
".",
"wintypes",
"import",
"DWORD",
"class",
"MemoryStatus",
"(",
"Structure",
",",
")",
":"... | return physical memory usage works on windows platforms only . | train | true |
30,501 | def parse_string(text):
if ((len(text) >= 2) and (text[0] in ('"', "'")) and (text[(-1)] in ('"', "'"))):
text = text[1:(-1)]
return text.strip()
| [
"def",
"parse_string",
"(",
"text",
")",
":",
"if",
"(",
"(",
"len",
"(",
"text",
")",
">=",
"2",
")",
"and",
"(",
"text",
"[",
"0",
"]",
"in",
"(",
"'\"'",
",",
"\"'\"",
")",
")",
"and",
"(",
"text",
"[",
"(",
"-",
"1",
")",
"]",
"in",
"... | parse a string to a string . | train | false |
30,505 | def save_all_figures(image_path):
figure_list = []
(image_dir, image_fmt_str) = image_path.psplit()
fig_mngr = matplotlib._pylab_helpers.Gcf.get_all_fig_managers()
for fig_num in (m.num for m in fig_mngr):
plt.figure(fig_num)
plt.savefig(image_path.format(fig_num))
figure_list.append(image_fmt_str.format(fig_num))
return figure_list
| [
"def",
"save_all_figures",
"(",
"image_path",
")",
":",
"figure_list",
"=",
"[",
"]",
"(",
"image_dir",
",",
"image_fmt_str",
")",
"=",
"image_path",
".",
"psplit",
"(",
")",
"fig_mngr",
"=",
"matplotlib",
".",
"_pylab_helpers",
".",
"Gcf",
".",
"get_all_fig... | save all matplotlib figures . | train | false |
30,510 | def test_config_noastropy_fallback(monkeypatch):
from ...tests.helper import pytest
monkeypatch.setenv(str(u'XDG_CONFIG_HOME'), u'foo')
monkeypatch.delenv(str(u'XDG_CONFIG_HOME'))
monkeypatch.setattr(paths.set_temp_config, u'_temp_path', None)
def osraiser(dirnm, linkto):
raise OSError
monkeypatch.setattr(paths, u'_find_or_create_astropy_dir', osraiser)
monkeypatch.setattr(configuration, u'_cfgobjs', {})
with pytest.raises(OSError):
paths.get_config_dir()
with catch_warnings(configuration.ConfigurationMissingWarning) as w:
test_configitem()
assert (len(w) == 1)
w = w[0]
assert (u'Configuration defaults will be used' in str(w.message))
| [
"def",
"test_config_noastropy_fallback",
"(",
"monkeypatch",
")",
":",
"from",
"...",
"tests",
".",
"helper",
"import",
"pytest",
"monkeypatch",
".",
"setenv",
"(",
"str",
"(",
"u'XDG_CONFIG_HOME'",
")",
",",
"u'foo'",
")",
"monkeypatch",
".",
"delenv",
"(",
"... | tests to make sure configuration items fall back to their defaults when theres a problem accessing the astropy directory . | train | false |
30,511 | def on_color(clip, size=None, color=(0, 0, 0), pos=None, col_opacity=None):
if (size is None):
size = clip.size
if (pos is None):
pos = 'center'
colorclip = ColorClip(size, color)
if col_opacity:
colorclip = colorclip.with_mask().set_opacity(col_opacity)
return CompositeVideoClip([colorclip, clip.set_pos(pos)], transparent=(col_opacity is not None))
| [
"def",
"on_color",
"(",
"clip",
",",
"size",
"=",
"None",
",",
"color",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"pos",
"=",
"None",
",",
"col_opacity",
"=",
"None",
")",
":",
"if",
"(",
"size",
"is",
"None",
")",
":",
"size",
"=",
"clip"... | returns a clip made of the current clip overlaid on a color clip of a possibly bigger size . | train | false |
30,512 | def all_pairs(singles):
pairs = []
singles = list(singles)
while singles:
suitor = singles.pop(0)
pairs.extend(((suitor, single) for single in singles))
return pairs
| [
"def",
"all_pairs",
"(",
"singles",
")",
":",
"pairs",
"=",
"[",
"]",
"singles",
"=",
"list",
"(",
"singles",
")",
"while",
"singles",
":",
"suitor",
"=",
"singles",
".",
"pop",
"(",
"0",
")",
"pairs",
".",
"extend",
"(",
"(",
"(",
"suitor",
",",
... | generate pairs list for all-against-all alignments . | train | false |
30,513 | def set_name_reuse(enable=True):
set_keep['name_reuse'] = enable
| [
"def",
"set_name_reuse",
"(",
"enable",
"=",
"True",
")",
":",
"set_keep",
"[",
"'name_reuse'",
"]",
"=",
"enable"
] | enable or disable reuse layer name . | train | false |
30,516 | def make_shell(init_func=None, banner=None, use_ipython=True):
if (banner is None):
banner = 'Interactive Werkzeug Shell'
if (init_func is None):
init_func = dict
def action(ipython=use_ipython):
'Start a new interactive python session.'
namespace = init_func()
if ipython:
try:
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
sh = InteractiveShellEmbed(banner1=banner)
except ImportError:
from IPython.Shell import IPShellEmbed
sh = IPShellEmbed(banner=banner)
except ImportError:
pass
else:
sh(global_ns={}, local_ns=namespace)
return
from code import interact
interact(banner, local=namespace)
return action
| [
"def",
"make_shell",
"(",
"init_func",
"=",
"None",
",",
"banner",
"=",
"None",
",",
"use_ipython",
"=",
"True",
")",
":",
"if",
"(",
"banner",
"is",
"None",
")",
":",
"banner",
"=",
"'Interactive Werkzeug Shell'",
"if",
"(",
"init_func",
"is",
"None",
"... | returns an action callback that spawns a new interactive python shell . | train | true |
30,517 | def pass1(arg, *args, **kwargs):
return arg
| [
"def",
"pass1",
"(",
"arg",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"arg"
] | parse the bytecode int a list of easy-usable tokens: . | train | false |
30,518 | def remove_notifications(email_notification_ids=None):
for email_id in email_notification_ids:
NotificationDigest.remove(Q('_id', 'eq', email_id))
| [
"def",
"remove_notifications",
"(",
"email_notification_ids",
"=",
"None",
")",
":",
"for",
"email_id",
"in",
"email_notification_ids",
":",
"NotificationDigest",
".",
"remove",
"(",
"Q",
"(",
"'_id'",
",",
"'eq'",
",",
"email_id",
")",
")"
] | remove sent emails . | train | false |
30,521 | @requires_application()
def test_arrow_transform_draw():
if (os.getenv('APPVEYOR', '').lower() == 'true'):
raise SkipTest('AppVeyor has unknown failure')
old_numpy = (LooseVersion(np.__version__) < '1.8')
if ((os.getenv('TRAVIS', 'false') == 'true') and ((sys.version[:3] == '2.6') or old_numpy)):
raise SkipTest('Travis fails due to FB stack problem')
with TestingCanvas() as c:
for arrow_type in ARROW_TYPES:
arrow = visuals.Arrow(pos=vertices, arrow_type=arrow_type, arrows=arrows, arrow_size=10, color='red', connect='segments', parent=c.scene)
arrow.transform = transforms.STTransform(scale=(0.5, 0.75), translate=((-20), (-20)))
assert_image_approved(c.render(), ('visuals/arrow_transform_type_%s.png' % arrow_type))
arrow.parent = None
| [
"@",
"requires_application",
"(",
")",
"def",
"test_arrow_transform_draw",
"(",
")",
":",
"if",
"(",
"os",
".",
"getenv",
"(",
"'APPVEYOR'",
",",
"''",
")",
".",
"lower",
"(",
")",
"==",
"'true'",
")",
":",
"raise",
"SkipTest",
"(",
"'AppVeyor has unknown ... | tests the arrowvisual when a transform is applied . | train | false |
30,522 | def is_task_module(a):
if (isinstance(a, types.ModuleType) and (a not in _seen)):
_seen.add(a)
return True
| [
"def",
"is_task_module",
"(",
"a",
")",
":",
"if",
"(",
"isinstance",
"(",
"a",
",",
"types",
".",
"ModuleType",
")",
"and",
"(",
"a",
"not",
"in",
"_seen",
")",
")",
":",
"_seen",
".",
"add",
"(",
"a",
")",
"return",
"True"
] | determine if the provided value is a task module . | train | false |
30,524 | def Client(version=None, unstable=False, session=None, **kwargs):
if (not session):
session = client_session.Session._construct(kwargs)
d = discover.Discover(session=session, **kwargs)
return d.create_client(version=version, unstable=unstable)
| [
"def",
"Client",
"(",
"version",
"=",
"None",
",",
"unstable",
"=",
"False",
",",
"session",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"session",
")",
":",
"session",
"=",
"client_session",
".",
"Session",
".",
"_construct",
"(",
... | create new http client . | train | false |
30,526 | def _GetPropertyValue(entity, property):
if (property in datastore_types._SPECIAL_PROPERTIES):
if (property == datastore_types._UNAPPLIED_LOG_TIMESTAMP_SPECIAL_PROPERTY):
raise KeyError(property)
assert (property == datastore_types.KEY_SPECIAL_PROPERTY)
return entity.key()
else:
return entity[property]
| [
"def",
"_GetPropertyValue",
"(",
"entity",
",",
"property",
")",
":",
"if",
"(",
"property",
"in",
"datastore_types",
".",
"_SPECIAL_PROPERTIES",
")",
":",
"if",
"(",
"property",
"==",
"datastore_types",
".",
"_UNAPPLIED_LOG_TIMESTAMP_SPECIAL_PROPERTY",
")",
":",
... | returns an entitys value for a given property name . | train | false |
30,527 | def get_test_cases(test_files, cfg, tracer=None):
matcher = compile_matcher(cfg.test_regex)
results = []
for file in test_files:
module = import_module(file, cfg, tracer=tracer)
if (tracer is not None):
test_suite = tracer.runfunc(module.test_suite)
else:
test_suite = module.test_suite()
if (test_suite is None):
continue
if cfg.warn_omitted:
all_classes = set(get_all_test_cases(module))
classes_in_suite = get_test_classes_from_testsuite(test_suite)
difference = (all_classes - classes_in_suite)
for test_class in difference:
stderr(('\n%s: WARNING: %s not in test suite\n' % (file, test_class.__name__)))
if ((cfg.level is not None) and (getattr(test_suite, 'level', 0) > cfg.level)):
continue
filtered = filter_testsuite(test_suite, matcher, cfg.level)
results.extend(filtered)
return results
| [
"def",
"get_test_cases",
"(",
"test_files",
",",
"cfg",
",",
"tracer",
"=",
"None",
")",
":",
"matcher",
"=",
"compile_matcher",
"(",
"cfg",
".",
"test_regex",
")",
"results",
"=",
"[",
"]",
"for",
"file",
"in",
"test_files",
":",
"module",
"=",
"import_... | returns a list of test cases from a given list of test modules . | train | false |
30,528 | def places_nearby(client, location, radius=None, keyword=None, language=None, min_price=None, max_price=None, name=None, open_now=False, rank_by=None, type=None, page_token=None):
if (rank_by == 'distance'):
if (not (keyword or name or type)):
raise ValueError('either a keyword, name, or type arg is required when rank_by is set to distance')
elif (radius is not None):
raise ValueError('radius cannot be specified when rank_by is set to distance')
return _places(client, 'nearby', location=location, radius=radius, keyword=keyword, language=language, min_price=min_price, max_price=max_price, name=name, open_now=open_now, rank_by=rank_by, type=type, page_token=page_token)
| [
"def",
"places_nearby",
"(",
"client",
",",
"location",
",",
"radius",
"=",
"None",
",",
"keyword",
"=",
"None",
",",
"language",
"=",
"None",
",",
"min_price",
"=",
"None",
",",
"max_price",
"=",
"None",
",",
"name",
"=",
"None",
",",
"open_now",
"=",... | performs nearby search for places . | train | true |
30,529 | def authenticate_with_password(request, page_view_restriction_id, page_id):
restriction = get_object_or_404(PageViewRestriction, id=page_view_restriction_id)
page = get_object_or_404(Page, id=page_id).specific
if (request.method == u'POST'):
form = PasswordPageViewRestrictionForm(request.POST, instance=restriction)
if form.is_valid():
has_existing_session = (settings.SESSION_COOKIE_NAME in request.COOKIES)
passed_restrictions = request.session.setdefault(u'passed_page_view_restrictions', [])
if (restriction.id not in passed_restrictions):
passed_restrictions.append(restriction.id)
request.session[u'passed_page_view_restrictions'] = passed_restrictions
if (not has_existing_session):
request.session.set_expiry(0)
return redirect(form.cleaned_data[u'return_url'])
else:
form = PasswordPageViewRestrictionForm(instance=restriction)
action_url = reverse(u'wagtailcore_authenticate_with_password', args=[restriction.id, page.id])
return page.serve_password_required_response(request, form, action_url)
| [
"def",
"authenticate_with_password",
"(",
"request",
",",
"page_view_restriction_id",
",",
"page_id",
")",
":",
"restriction",
"=",
"get_object_or_404",
"(",
"PageViewRestriction",
",",
"id",
"=",
"page_view_restriction_id",
")",
"page",
"=",
"get_object_or_404",
"(",
... | handle a submission of passwordpageviewrestrictionform to grant view access over a subtree that is protected by a pageviewrestriction . | train | false |
30,530 | def get_colormap(name, *args, **kwargs):
if isinstance(name, BaseColormap):
cmap = name
else:
if (not isinstance(name, string_types)):
raise TypeError('colormap must be a Colormap or string name')
if (name not in _colormaps):
raise KeyError(('colormap name %s not found' % name))
cmap = _colormaps[name]
if inspect.isclass(cmap):
cmap = cmap(*args, **kwargs)
return cmap
| [
"def",
"get_colormap",
"(",
"name",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"BaseColormap",
")",
":",
"cmap",
"=",
"name",
"else",
":",
"if",
"(",
"not",
"isinstance",
"(",
"name",
",",
"string_types",
"... | obtain a colormap some colormaps can have additional configuration parameters . | train | true |
30,531 | def _mul_as_two_parts(f):
gs = _mul_args(f)
if (len(gs) < 2):
return None
if (len(gs) == 2):
return [tuple(gs)]
return [(Mul(*x), Mul(*y)) for (x, y) in multiset_partitions(gs, 2)]
| [
"def",
"_mul_as_two_parts",
"(",
"f",
")",
":",
"gs",
"=",
"_mul_args",
"(",
"f",
")",
"if",
"(",
"len",
"(",
"gs",
")",
"<",
"2",
")",
":",
"return",
"None",
"if",
"(",
"len",
"(",
"gs",
")",
"==",
"2",
")",
":",
"return",
"[",
"tuple",
"(",... | find all the ways to split f into a product of two terms . | train | false |
30,532 | def test_binary_descriptors_unequal_descriptor_sizes_error():
descs1 = np.array([[True, True, False, True], [False, True, False, True]])
descs2 = np.array([[True, False, False, True, False], [False, True, True, True, False]])
assert_raises(ValueError, match_descriptors, descs1, descs2)
| [
"def",
"test_binary_descriptors_unequal_descriptor_sizes_error",
"(",
")",
":",
"descs1",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"True",
",",
"True",
",",
"False",
",",
"True",
"]",
",",
"[",
"False",
",",
"True",
",",
"False",
",",
"True",
"]",
"]",
... | sizes of descriptors of keypoints to be matched should be equal . | train | false |
30,533 | def is_quad_residue(a, p):
(a, p) = (as_int(a), as_int(p))
if (p < 1):
raise ValueError('p must be > 0')
if ((a >= p) or (a < 0)):
a = (a % p)
if ((a < 2) or (p < 3)):
return True
if (not isprime(p)):
if ((p % 2) and (jacobi_symbol(a, p) == (-1))):
return False
r = sqrt_mod(a, p)
if (r is None):
return False
else:
return True
return (pow(a, ((p - 1) // 2), p) == 1)
| [
"def",
"is_quad_residue",
"(",
"a",
",",
"p",
")",
":",
"(",
"a",
",",
"p",
")",
"=",
"(",
"as_int",
"(",
"a",
")",
",",
"as_int",
"(",
"p",
")",
")",
"if",
"(",
"p",
"<",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'p must be > 0'",
")",
"if... | returns true if a is in the set of squares mod p . | train | false |
30,534 | def action_finish(context, values):
return IMPL.action_finish(context, values)
| [
"def",
"action_finish",
"(",
"context",
",",
"values",
")",
":",
"return",
"IMPL",
".",
"action_finish",
"(",
"context",
",",
"values",
")"
] | finish an action for an instance . | train | false |
30,535 | @register.tag
def get_latest_posts(parser, token):
try:
(tag_name, arg) = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError, ('%s tag requires arguments' % token.contents.split()[0])
m = re.search('(.*?) as (\\w+)', arg)
if (not m):
raise template.TemplateSyntaxError, ('%s tag had invalid arguments' % tag_name)
(format_string, var_name) = m.groups()
return LatestPosts(format_string, var_name)
| [
"@",
"register",
".",
"tag",
"def",
"get_latest_posts",
"(",
"parser",
",",
"token",
")",
":",
"try",
":",
"(",
"tag_name",
",",
"arg",
")",
"=",
"token",
".",
"contents",
".",
"split",
"(",
"None",
",",
"1",
")",
"except",
"ValueError",
":",
"raise"... | gets any number of latest posts and stores them in a varable . | train | false |
30,537 | @register_opt()
@local_optimizer([GpuFromHost, tensor.blas.Dot22Scalar])
def local_gpu_dot22scalar(node):
if isinstance(node.op, GpuFromHost):
host_input = node.inputs[0]
if (host_input.owner and isinstance(host_input.owner.op, tensor.blas.Dot22Scalar)):
(x, y, scalar) = host_input.owner.inputs
return [gpu_dot22scalar(as_cuda_ndarray_variable(x), as_cuda_ndarray_variable(y), tensor.blas._as_scalar(scalar))]
if isinstance(node.op, tensor.blas.Dot22Scalar):
if any([(i.owner and isinstance(i.owner.op, HostFromGpu)) for i in node.inputs]):
(x, y, scalar) = node.inputs
return [host_from_gpu(gpu_dot22scalar(as_cuda_ndarray_variable(x), as_cuda_ndarray_variable(y), tensor.blas._as_scalar(scalar)))]
return False
| [
"@",
"register_opt",
"(",
")",
"@",
"local_optimizer",
"(",
"[",
"GpuFromHost",
",",
"tensor",
".",
"blas",
".",
"Dot22Scalar",
"]",
")",
"def",
"local_gpu_dot22scalar",
"(",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"op",
",",
"GpuFromHost",... | gpu_from_host -> gpudot dot -> host_from_gpu . | train | false |
30,538 | def get_time_server():
ret = salt.utils.mac_utils.execute_return_result('systemsetup -getnetworktimeserver')
return salt.utils.mac_utils.parse_return(ret)
| [
"def",
"get_time_server",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getnetworktimeserver'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | display the currently set network time server . | train | true |
30,539 | def uses_mandrill(func):
@wraps(func)
def wrapped_func(*args, **kwargs):
kwargs['mail_client'] = get_mandrill_client()
return func(*args, **kwargs)
return wrapped_func
| [
"def",
"uses_mandrill",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"kwargs",
"[",
"'mail_client'",
"]",
"=",
"get_mandrill_client",
"(",
")",
"return",
"func",
"(",
"*"... | this decorator takes a function with keyword argument "mail_client" and fills it in with the mail_client for the mandrill account . | train | false |
30,541 | def maximum(image, selem, out=None, mask=None, shift_x=False, shift_y=False):
return _apply_scalar_per_pixel(generic_cy._maximum, image, selem, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y)
| [
"def",
"maximum",
"(",
"image",
",",
"selem",
",",
"out",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"shift_x",
"=",
"False",
",",
"shift_y",
"=",
"False",
")",
":",
"return",
"_apply_scalar_per_pixel",
"(",
"generic_cy",
".",
"_maximum",
",",
"image",
... | element-wise maximum of input variables . | train | false |
30,542 | def skipped(*a, **kw):
item = a[0]
if (type(item) != dict):
raise errors.AnsibleFilterError('|skipped expects a dictionary')
skipped = item.get('skipped', False)
return skipped
| [
"def",
"skipped",
"(",
"*",
"a",
",",
"**",
"kw",
")",
":",
"item",
"=",
"a",
"[",
"0",
"]",
"if",
"(",
"type",
"(",
"item",
")",
"!=",
"dict",
")",
":",
"raise",
"errors",
".",
"AnsibleFilterError",
"(",
"'|skipped expects a dictionary'",
")",
"skip... | test if task result yields skipped . | train | false |
30,544 | @pytest.mark.network
def test_download_should_download_dependencies(script):
result = script.pip('download', 'Paste[openid]==1.7.5.1', '-d', '.', expect_error=True)
assert ((Path('scratch') / 'Paste-1.7.5.1.tar.gz') in result.files_created)
openid_tarball_prefix = str((Path('scratch') / 'python-openid-'))
assert any((path.startswith(openid_tarball_prefix) for path in result.files_created))
assert ((script.site_packages / 'openid') not in result.files_created)
| [
"@",
"pytest",
".",
"mark",
".",
"network",
"def",
"test_download_should_download_dependencies",
"(",
"script",
")",
":",
"result",
"=",
"script",
".",
"pip",
"(",
"'download'",
",",
"'Paste[openid]==1.7.5.1'",
",",
"'-d'",
",",
"'.'",
",",
"expect_error",
"=",
... | it should download dependencies . | train | false |
30,545 | def _GetConnection():
__InitConnection()
return _thread_local.connection_stack[(-1)]
| [
"def",
"_GetConnection",
"(",
")",
":",
"__InitConnection",
"(",
")",
"return",
"_thread_local",
".",
"connection_stack",
"[",
"(",
"-",
"1",
")",
"]"
] | internal method to retrieve a datastore connection local to the thread . | train | false |
30,546 | def setup_path(invoke_minversion=None):
if (not os.path.isdir(TASKS_VENDOR_DIR)):
print(('SKIP: TASKS_VENDOR_DIR=%s is missing' % TASKS_VENDOR_DIR))
return
elif (os.path.abspath(TASKS_VENDOR_DIR) in sys.path):
pass
use_vendor_bundles = os.environ.get('INVOKE_TASKS_USE_VENDOR_BUNDLES', 'no')
if need_vendor_bundles(invoke_minversion):
use_vendor_bundles = 'yes'
if (use_vendor_bundles == 'yes'):
syspath_insert(0, os.path.abspath(TASKS_VENDOR_DIR))
if setup_path_for_bundle(INVOKE_BUNDLE, pos=1):
import invoke
bundle_path = os.path.relpath(INVOKE_BUNDLE, os.getcwd())
print(('USING: %s (version: %s)' % (bundle_path, invoke.__version__)))
else:
syspath_append(os.path.abspath(TASKS_VENDOR_DIR))
setup_path_for_bundle(INVOKE_BUNDLE, pos=len(sys.path))
if DEBUG_SYSPATH:
for (index, p) in enumerate(sys.path):
print((' %d. %s' % (index, p)))
| [
"def",
"setup_path",
"(",
"invoke_minversion",
"=",
"None",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"TASKS_VENDOR_DIR",
")",
")",
":",
"print",
"(",
"(",
"'SKIP: TASKS_VENDOR_DIR=%s is missing'",
"%",
"TASKS_VENDOR_DIR",
")",
")",
"... | setup python search and add tasks_vendor_dir . | train | true |
30,547 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | return a fresh instance of a shake256 object . | train | false |
30,548 | def _hmac_etag(key, etag):
result = hmac.new(key, etag, digestmod=hashlib.sha256).digest()
return base64.b64encode(result).decode()
| [
"def",
"_hmac_etag",
"(",
"key",
",",
"etag",
")",
":",
"result",
"=",
"hmac",
".",
"new",
"(",
"key",
",",
"etag",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
".",
"digest",
"(",
")",
"return",
"base64",
".",
"b64encode",
"(",
"result",
... | compute an hmac-sha256 using given key and etag . | train | false |
30,549 | def parse_etag_response(value):
if (value and (not value.startswith('W/'))):
unquote_match = QUOTES_RE.match(value)
if (unquote_match is not None):
value = unquote_match.group(1)
value = value.replace('\\"', '"')
return value
| [
"def",
"parse_etag_response",
"(",
"value",
")",
":",
"if",
"(",
"value",
"and",
"(",
"not",
"value",
".",
"startswith",
"(",
"'W/'",
")",
")",
")",
":",
"unquote_match",
"=",
"QUOTES_RE",
".",
"match",
"(",
"value",
")",
"if",
"(",
"unquote_match",
"i... | parse a response etag . | train | false |
30,550 | def lock(instance_id, profile=None):
conn = _auth(profile)
return conn.lock(instance_id)
| [
"def",
"lock",
"(",
"instance_id",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"lock",
"(",
"instance_id",
")"
] | get lock path the path in zookeeper where the lock is zk_hosts zookeeper connect string identifier name to identify this minion . | train | true |
30,551 | @sync_performer
@do
def perform_upload_s3_key_recursively(dispatcher, intent):
for child in intent.files:
path = intent.source_path.preauthChild(child)
if path.isfile():
(yield Effect(UploadToS3(source_path=intent.source_path, target_bucket=intent.target_bucket, target_key=('%s/%s' % (intent.target_key, child)), file=path)))
| [
"@",
"sync_performer",
"@",
"do",
"def",
"perform_upload_s3_key_recursively",
"(",
"dispatcher",
",",
"intent",
")",
":",
"for",
"child",
"in",
"intent",
".",
"files",
":",
"path",
"=",
"intent",
".",
"source_path",
".",
"preauthChild",
"(",
"child",
")",
"i... | see :class:uploadtos3recursively . | train | false |
30,552 | @image_comparison(baseline_images=[u'colorbar_extensions_shape_uniform', u'colorbar_extensions_shape_proportional'], extensions=[u'png'])
def test_colorbar_extension_shape():
_colorbar_extension_shape(u'uniform')
_colorbar_extension_shape(u'proportional')
| [
"@",
"image_comparison",
"(",
"baseline_images",
"=",
"[",
"u'colorbar_extensions_shape_uniform'",
",",
"u'colorbar_extensions_shape_proportional'",
"]",
",",
"extensions",
"=",
"[",
"u'png'",
"]",
")",
"def",
"test_colorbar_extension_shape",
"(",
")",
":",
"_colorbar_ext... | test rectangular colorbar extensions . | train | false |
30,554 | def RenderValue(value, limit_lists=(-1)):
if (value is None):
return None
renderer = ApiValueRenderer.GetRendererForValueOrClass(value, limit_lists=limit_lists)
return renderer.RenderValue(value)
| [
"def",
"RenderValue",
"(",
"value",
",",
"limit_lists",
"=",
"(",
"-",
"1",
")",
")",
":",
"if",
"(",
"value",
"is",
"None",
")",
":",
"return",
"None",
"renderer",
"=",
"ApiValueRenderer",
".",
"GetRendererForValueOrClass",
"(",
"value",
",",
"limit_lists... | render given rdfvalue as plain old python objects . | train | true |
30,555 | def getComplexByWords(words, wordIndex=0):
try:
return complex(float(words[wordIndex]), float(words[(wordIndex + 1)]))
except:
pass
return None
| [
"def",
"getComplexByWords",
"(",
"words",
",",
"wordIndex",
"=",
"0",
")",
":",
"try",
":",
"return",
"complex",
"(",
"float",
"(",
"words",
"[",
"wordIndex",
"]",
")",
",",
"float",
"(",
"words",
"[",
"(",
"wordIndex",
"+",
"1",
")",
"]",
")",
")"... | get the complex by the first two words . | train | false |
30,556 | def moments_normalized(mu, order=3):
if (mu.ndim != 2):
raise TypeError('Image moments must be 2-dimension')
if ((mu.shape[0] <= order) or (mu.shape[1] <= order)):
raise TypeError('Shape of image moments must be >= `order`')
return _moments_cy.moments_normalized(mu.astype(np.double), order)
| [
"def",
"moments_normalized",
"(",
"mu",
",",
"order",
"=",
"3",
")",
":",
"if",
"(",
"mu",
".",
"ndim",
"!=",
"2",
")",
":",
"raise",
"TypeError",
"(",
"'Image moments must be 2-dimension'",
")",
"if",
"(",
"(",
"mu",
".",
"shape",
"[",
"0",
"]",
"<=... | calculate all normalized central image moments up to a certain order . | train | false |
30,557 | def to_unicode_from_fs(string):
if (not is_string(string)):
string = to_text_string(string.toUtf8(), 'utf-8')
elif is_binary_string(string):
try:
unic = string.decode(FS_ENCODING)
except (UnicodeError, TypeError):
pass
else:
return unic
return string
| [
"def",
"to_unicode_from_fs",
"(",
"string",
")",
":",
"if",
"(",
"not",
"is_string",
"(",
"string",
")",
")",
":",
"string",
"=",
"to_text_string",
"(",
"string",
".",
"toUtf8",
"(",
")",
",",
"'utf-8'",
")",
"elif",
"is_binary_string",
"(",
"string",
")... | return a unicode version of string decoded using the file system encoding . | train | true |
30,558 | def parse_lookaround(source, info, behind, positive):
saved_flags = info.flags
try:
subpattern = _parse_pattern(source, info)
source.expect(')')
finally:
info.flags = saved_flags
source.ignore_space = bool((info.flags & VERBOSE))
return LookAround(behind, positive, subpattern)
| [
"def",
"parse_lookaround",
"(",
"source",
",",
"info",
",",
"behind",
",",
"positive",
")",
":",
"saved_flags",
"=",
"info",
".",
"flags",
"try",
":",
"subpattern",
"=",
"_parse_pattern",
"(",
"source",
",",
"info",
")",
"source",
".",
"expect",
"(",
"')... | parses a lookaround . | train | false |
30,559 | def label_sign_flip(label, src):
if (len(src) != 2):
raise ValueError('Only source spaces with 2 hemisphers are accepted')
lh_vertno = src[0]['vertno']
rh_vertno = src[1]['vertno']
if (label.hemi == 'lh'):
vertno_sel = np.intersect1d(lh_vertno, label.vertices)
if (len(vertno_sel) == 0):
return np.array([], int)
ori = src[0]['nn'][vertno_sel]
elif (label.hemi == 'rh'):
vertno_sel = np.intersect1d(rh_vertno, label.vertices)
if (len(vertno_sel) == 0):
return np.array([], int)
ori = src[1]['nn'][vertno_sel]
else:
raise Exception('Unknown hemisphere type')
(_, _, Vh) = linalg.svd(ori, full_matrices=False)
flip = np.sign(np.dot(ori, Vh[0]))
return flip
| [
"def",
"label_sign_flip",
"(",
"label",
",",
"src",
")",
":",
"if",
"(",
"len",
"(",
"src",
")",
"!=",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'Only source spaces with 2 hemisphers are accepted'",
")",
"lh_vertno",
"=",
"src",
"[",
"0",
"]",
"[",
"'ver... | compute sign for label averaging . | train | false |
30,560 | def indent_block(text, indention=' '):
temp = ''
while (text and (text[(-1)] == '\n')):
temp += text[(-1)]
text = text[:(-1)]
lines = text.split('\n')
return ('\n'.join(map((lambda s: (indention + s)), lines)) + temp)
| [
"def",
"indent_block",
"(",
"text",
",",
"indention",
"=",
"' '",
")",
":",
"temp",
"=",
"''",
"while",
"(",
"text",
"and",
"(",
"text",
"[",
"(",
"-",
"1",
")",
"]",
"==",
"'\\n'",
")",
")",
":",
"temp",
"+=",
"text",
"[",
"(",
"-",
"1",
... | this function indents a text block with a default of four spaces . | train | false |
30,561 | def getAroundsFromPathPoints(points, radius, thresholdRatio=0.9):
centers = getCentersFromPoints(points, (0.8 * radius))
arounds = []
for center in centers:
if euclidean.isWiddershins(center):
arounds.append(euclidean.getSimplifiedPath(center, radius))
return arounds
| [
"def",
"getAroundsFromPathPoints",
"(",
"points",
",",
"radius",
",",
"thresholdRatio",
"=",
"0.9",
")",
":",
"centers",
"=",
"getCentersFromPoints",
"(",
"points",
",",
"(",
"0.8",
"*",
"radius",
")",
")",
"arounds",
"=",
"[",
"]",
"for",
"center",
"in",
... | get the arounds from the path . | train | false |
30,562 | def parse_image_id(image_ref):
return image_ref.rsplit('/')[(-1)]
| [
"def",
"parse_image_id",
"(",
"image_ref",
")",
":",
"return",
"image_ref",
".",
"rsplit",
"(",
"'/'",
")",
"[",
"(",
"-",
"1",
")",
"]"
] | return the image id from a given image ref this function just returns the last word of the given image ref string splitting with / . | train | false |
30,564 | def read_feather(path):
feather = _try_import()
return feather.read_dataframe(path)
| [
"def",
"read_feather",
"(",
"path",
")",
":",
"feather",
"=",
"_try_import",
"(",
")",
"return",
"feather",
".",
"read_dataframe",
"(",
"path",
")"
] | load a feather-format object from the file path . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.