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 |
|---|---|---|---|---|---|
17,655 | def reset_worker_optimizations():
global trace_task_ret
trace_task_ret = _trace_task_ret
try:
delattr(BaseTask, u'_stackprotected')
except AttributeError:
pass
try:
BaseTask.__call__ = _patched.pop(u'BaseTask.__call__')
except KeyError:
pass
from celery.worker import request as request_module
request_module.trace_task_ret = _trace_task_ret
| [
"def",
"reset_worker_optimizations",
"(",
")",
":",
"global",
"trace_task_ret",
"trace_task_ret",
"=",
"_trace_task_ret",
"try",
":",
"delattr",
"(",
"BaseTask",
",",
"u'_stackprotected'",
")",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"BaseTask",
".",
"__call__",
"=",
"_patched",
".",
"pop",
"(",
"u'BaseTask.__call__'",
")",
"except",
"KeyError",
":",
"pass",
"from",
"celery",
".",
"worker",
"import",
"request",
"as",
"request_module",
"request_module",
".",
"trace_task_ret",
"=",
"_trace_task_ret"
] | reset previously configured optimizations . | train | false |
17,656 | def nopackage(pkg_name):
if is_installed(pkg_name):
uninstall(pkg_name)
| [
"def",
"nopackage",
"(",
"pkg_name",
")",
":",
"if",
"is_installed",
"(",
"pkg_name",
")",
":",
"uninstall",
"(",
"pkg_name",
")"
] | require an rpm package to be uninstalled . | train | false |
17,657 | def fetch_requirements(requirements_file_path):
links = []
reqs = []
for req in parse_requirements(requirements_file_path, session=False):
if req.link:
links.append(str(req.link))
reqs.append(str(req.req))
return (reqs, links)
| [
"def",
"fetch_requirements",
"(",
"requirements_file_path",
")",
":",
"links",
"=",
"[",
"]",
"reqs",
"=",
"[",
"]",
"for",
"req",
"in",
"parse_requirements",
"(",
"requirements_file_path",
",",
"session",
"=",
"False",
")",
":",
"if",
"req",
".",
"link",
":",
"links",
".",
"append",
"(",
"str",
"(",
"req",
".",
"link",
")",
")",
"reqs",
".",
"append",
"(",
"str",
"(",
"req",
".",
"req",
")",
")",
"return",
"(",
"reqs",
",",
"links",
")"
] | return a list of requirements and links by parsing the provided requirements file . | train | false |
17,658 | def concatenate3(arrays):
arrays = concrete(arrays)
ndim = ndimlist(arrays)
if (not ndim):
return arrays
if (not arrays):
return np.empty(0)
chunks = chunks_from_arrays(arrays)
shape = tuple(map(sum, chunks))
def dtype(x):
try:
return x.dtype
except AttributeError:
return type(x)
result = np.empty(shape=shape, dtype=dtype(deepfirst(arrays)))
for (idx, arr) in zip(slices_from_chunks(chunks), core.flatten(arrays)):
if hasattr(arr, 'ndim'):
while (arr.ndim < ndim):
arr = arr[None, ...]
result[idx] = arr
return result
| [
"def",
"concatenate3",
"(",
"arrays",
")",
":",
"arrays",
"=",
"concrete",
"(",
"arrays",
")",
"ndim",
"=",
"ndimlist",
"(",
"arrays",
")",
"if",
"(",
"not",
"ndim",
")",
":",
"return",
"arrays",
"if",
"(",
"not",
"arrays",
")",
":",
"return",
"np",
".",
"empty",
"(",
"0",
")",
"chunks",
"=",
"chunks_from_arrays",
"(",
"arrays",
")",
"shape",
"=",
"tuple",
"(",
"map",
"(",
"sum",
",",
"chunks",
")",
")",
"def",
"dtype",
"(",
"x",
")",
":",
"try",
":",
"return",
"x",
".",
"dtype",
"except",
"AttributeError",
":",
"return",
"type",
"(",
"x",
")",
"result",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"shape",
",",
"dtype",
"=",
"dtype",
"(",
"deepfirst",
"(",
"arrays",
")",
")",
")",
"for",
"(",
"idx",
",",
"arr",
")",
"in",
"zip",
"(",
"slices_from_chunks",
"(",
"chunks",
")",
",",
"core",
".",
"flatten",
"(",
"arrays",
")",
")",
":",
"if",
"hasattr",
"(",
"arr",
",",
"'ndim'",
")",
":",
"while",
"(",
"arr",
".",
"ndim",
"<",
"ndim",
")",
":",
"arr",
"=",
"arr",
"[",
"None",
",",
"...",
"]",
"result",
"[",
"idx",
"]",
"=",
"arr",
"return",
"result"
] | recursive np . | train | false |
17,659 | def find_file(path, saltenv='base', **kwargs):
if ('env' in kwargs):
salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.")
kwargs.pop('env')
path = os.path.normpath(path)
fnd = {'path': '', 'rel': ''}
if os.path.isabs(path):
return fnd
if (saltenv not in __opts__['file_roots']):
return fnd
def _add_file_stat(fnd):
'\n Stat the file and, assuming no errors were found, convert the stat\n result to a list of values and add to the return dict.\n\n Converting the stat result to a list, the elements of the list\n correspond to the following stat_result params:\n\n 0 => st_mode=33188\n 1 => st_ino=10227377\n 2 => st_dev=65026\n 3 => st_nlink=1\n 4 => st_uid=1000\n 5 => st_gid=1000\n 6 => st_size=1056233\n 7 => st_atime=1468284229\n 8 => st_mtime=1456338235\n 9 => st_ctime=1456338235\n '
try:
fnd['stat'] = list(os.stat(fnd['path']))
except Exception:
pass
return fnd
if ('index' in kwargs):
try:
root = __opts__['file_roots'][saltenv][int(kwargs['index'])]
except IndexError:
return fnd
except ValueError:
return fnd
full = os.path.join(root, path)
if (os.path.isfile(full) and (not salt.fileserver.is_file_ignored(__opts__, full))):
fnd['path'] = full
fnd['rel'] = path
return _add_file_stat(fnd)
return fnd
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if (os.path.isfile(full) and (not salt.fileserver.is_file_ignored(__opts__, full))):
fnd['path'] = full
fnd['rel'] = path
return _add_file_stat(fnd)
return fnd
| [
"def",
"find_file",
"(",
"path",
",",
"saltenv",
"=",
"'base'",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"'env'",
"in",
"kwargs",
")",
":",
"salt",
".",
"utils",
".",
"warn_until",
"(",
"'Oxygen'",
",",
"\"Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.\"",
")",
"kwargs",
".",
"pop",
"(",
"'env'",
")",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"fnd",
"=",
"{",
"'path'",
":",
"''",
",",
"'rel'",
":",
"''",
"}",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"return",
"fnd",
"if",
"(",
"saltenv",
"not",
"in",
"__opts__",
"[",
"'file_roots'",
"]",
")",
":",
"return",
"fnd",
"def",
"_add_file_stat",
"(",
"fnd",
")",
":",
"try",
":",
"fnd",
"[",
"'stat'",
"]",
"=",
"list",
"(",
"os",
".",
"stat",
"(",
"fnd",
"[",
"'path'",
"]",
")",
")",
"except",
"Exception",
":",
"pass",
"return",
"fnd",
"if",
"(",
"'index'",
"in",
"kwargs",
")",
":",
"try",
":",
"root",
"=",
"__opts__",
"[",
"'file_roots'",
"]",
"[",
"saltenv",
"]",
"[",
"int",
"(",
"kwargs",
"[",
"'index'",
"]",
")",
"]",
"except",
"IndexError",
":",
"return",
"fnd",
"except",
"ValueError",
":",
"return",
"fnd",
"full",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"path",
")",
"if",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"full",
")",
"and",
"(",
"not",
"salt",
".",
"fileserver",
".",
"is_file_ignored",
"(",
"__opts__",
",",
"full",
")",
")",
")",
":",
"fnd",
"[",
"'path'",
"]",
"=",
"full",
"fnd",
"[",
"'rel'",
"]",
"=",
"path",
"return",
"_add_file_stat",
"(",
"fnd",
")",
"return",
"fnd",
"for",
"root",
"in",
"__opts__",
"[",
"'file_roots'",
"]",
"[",
"saltenv",
"]",
":",
"full",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"path",
")",
"if",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"full",
")",
"and",
"(",
"not",
"salt",
".",
"fileserver",
".",
"is_file_ignored",
"(",
"__opts__",
",",
"full",
")",
")",
")",
":",
"fnd",
"[",
"'path'",
"]",
"=",
"full",
"fnd",
"[",
"'rel'",
"]",
"=",
"path",
"return",
"_add_file_stat",
"(",
"fnd",
")",
"return",
"fnd"
] | recursively find matching file from the current working path . | train | true |
17,660 | def start_version(module, version):
rpc = start_version_async(module, version)
rpc.get_result()
| [
"def",
"start_version",
"(",
"module",
",",
"version",
")",
":",
"rpc",
"=",
"start_version_async",
"(",
"module",
",",
"version",
")",
"rpc",
".",
"get_result",
"(",
")"
] | start all instances for the given version of the module . | train | false |
17,661 | def _is_national_number_suffix_of_other(numobj1, numobj2):
nn1 = str(numobj1.national_number)
nn2 = str(numobj2.national_number)
return (nn1.endswith(nn2) or nn2.endswith(nn1))
| [
"def",
"_is_national_number_suffix_of_other",
"(",
"numobj1",
",",
"numobj2",
")",
":",
"nn1",
"=",
"str",
"(",
"numobj1",
".",
"national_number",
")",
"nn2",
"=",
"str",
"(",
"numobj2",
".",
"national_number",
")",
"return",
"(",
"nn1",
".",
"endswith",
"(",
"nn2",
")",
"or",
"nn2",
".",
"endswith",
"(",
"nn1",
")",
")"
] | returns true when one national number is the suffix of the other or both are the same . | train | true |
17,662 | def rotation_angles(m):
x = np.arctan2(m[(2, 1)], m[(2, 2)])
c2 = np.sqrt(((m[(0, 0)] ** 2) + (m[(1, 0)] ** 2)))
y = np.arctan2((- m[(2, 0)]), c2)
s1 = np.sin(x)
c1 = np.cos(x)
z = np.arctan2(((s1 * m[(0, 2)]) - (c1 * m[(0, 1)])), ((c1 * m[(1, 1)]) - (s1 * m[(1, 2)])))
return (x, y, z)
| [
"def",
"rotation_angles",
"(",
"m",
")",
":",
"x",
"=",
"np",
".",
"arctan2",
"(",
"m",
"[",
"(",
"2",
",",
"1",
")",
"]",
",",
"m",
"[",
"(",
"2",
",",
"2",
")",
"]",
")",
"c2",
"=",
"np",
".",
"sqrt",
"(",
"(",
"(",
"m",
"[",
"(",
"0",
",",
"0",
")",
"]",
"**",
"2",
")",
"+",
"(",
"m",
"[",
"(",
"1",
",",
"0",
")",
"]",
"**",
"2",
")",
")",
")",
"y",
"=",
"np",
".",
"arctan2",
"(",
"(",
"-",
"m",
"[",
"(",
"2",
",",
"0",
")",
"]",
")",
",",
"c2",
")",
"s1",
"=",
"np",
".",
"sin",
"(",
"x",
")",
"c1",
"=",
"np",
".",
"cos",
"(",
"x",
")",
"z",
"=",
"np",
".",
"arctan2",
"(",
"(",
"(",
"s1",
"*",
"m",
"[",
"(",
"0",
",",
"2",
")",
"]",
")",
"-",
"(",
"c1",
"*",
"m",
"[",
"(",
"0",
",",
"1",
")",
"]",
")",
")",
",",
"(",
"(",
"c1",
"*",
"m",
"[",
"(",
"1",
",",
"1",
")",
"]",
")",
"-",
"(",
"s1",
"*",
"m",
"[",
"(",
"1",
",",
"2",
")",
"]",
")",
")",
")",
"return",
"(",
"x",
",",
"y",
",",
"z",
")"
] | find rotation angles from a transformation matrix . | train | false |
17,663 | def _jobs():
response = salt.utils.http.query('{0}/scheduler/jobs'.format(_base_url()), decode_type='json', decode=True)
jobs = {}
for job in response['dict']:
jobs[job.pop('name')] = job
return jobs
| [
"def",
"_jobs",
"(",
")",
":",
"response",
"=",
"salt",
".",
"utils",
".",
"http",
".",
"query",
"(",
"'{0}/scheduler/jobs'",
".",
"format",
"(",
"_base_url",
"(",
")",
")",
",",
"decode_type",
"=",
"'json'",
",",
"decode",
"=",
"True",
")",
"jobs",
"=",
"{",
"}",
"for",
"job",
"in",
"response",
"[",
"'dict'",
"]",
":",
"jobs",
"[",
"job",
".",
"pop",
"(",
"'name'",
")",
"]",
"=",
"job",
"return",
"jobs"
] | return the currently configured jobs . | train | true |
17,664 | def get_next_url_for_login_page(request):
redirect_to = request.GET.get('next', None)
if (redirect_to and (not http.is_safe_url(redirect_to))):
log.error(u'Unsafe redirect parameter detected: %(redirect_to)r', {'redirect_to': redirect_to})
redirect_to = None
if (not redirect_to):
try:
redirect_to = reverse('dashboard')
except NoReverseMatch:
redirect_to = reverse('home')
if any(((param in request.GET) for param in POST_AUTH_PARAMS)):
params = [(param, request.GET[param]) for param in POST_AUTH_PARAMS if (param in request.GET)]
params.append(('next', redirect_to))
redirect_to = '{}?{}'.format(reverse('finish_auth'), urllib.urlencode(params))
return redirect_to
| [
"def",
"get_next_url_for_login_page",
"(",
"request",
")",
":",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"None",
")",
"if",
"(",
"redirect_to",
"and",
"(",
"not",
"http",
".",
"is_safe_url",
"(",
"redirect_to",
")",
")",
")",
":",
"log",
".",
"error",
"(",
"u'Unsafe redirect parameter detected: %(redirect_to)r'",
",",
"{",
"'redirect_to'",
":",
"redirect_to",
"}",
")",
"redirect_to",
"=",
"None",
"if",
"(",
"not",
"redirect_to",
")",
":",
"try",
":",
"redirect_to",
"=",
"reverse",
"(",
"'dashboard'",
")",
"except",
"NoReverseMatch",
":",
"redirect_to",
"=",
"reverse",
"(",
"'home'",
")",
"if",
"any",
"(",
"(",
"(",
"param",
"in",
"request",
".",
"GET",
")",
"for",
"param",
"in",
"POST_AUTH_PARAMS",
")",
")",
":",
"params",
"=",
"[",
"(",
"param",
",",
"request",
".",
"GET",
"[",
"param",
"]",
")",
"for",
"param",
"in",
"POST_AUTH_PARAMS",
"if",
"(",
"param",
"in",
"request",
".",
"GET",
")",
"]",
"params",
".",
"append",
"(",
"(",
"'next'",
",",
"redirect_to",
")",
")",
"redirect_to",
"=",
"'{}?{}'",
".",
"format",
"(",
"reverse",
"(",
"'finish_auth'",
")",
",",
"urllib",
".",
"urlencode",
"(",
"params",
")",
")",
"return",
"redirect_to"
] | determine the url to redirect to following login/registration/third_party_auth the user is currently on a login or registration page . | train | false |
17,665 | def cycle_list(k, n):
k = (k % n)
return (list(range(k, n)) + list(range(k)))
| [
"def",
"cycle_list",
"(",
"k",
",",
"n",
")",
":",
"k",
"=",
"(",
"k",
"%",
"n",
")",
"return",
"(",
"list",
"(",
"range",
"(",
"k",
",",
"n",
")",
")",
"+",
"list",
"(",
"range",
"(",
"k",
")",
")",
")"
] | returns the elements of the list range(n) shifted to the left by k (so the list starts with k ) . | train | false |
17,666 | def jssafe(text=u''):
if (text.__class__ != unicode):
text = _force_unicode(text)
return _Unsafe(text.translate(_js_escapes))
| [
"def",
"jssafe",
"(",
"text",
"=",
"u''",
")",
":",
"if",
"(",
"text",
".",
"__class__",
"!=",
"unicode",
")",
":",
"text",
"=",
"_force_unicode",
"(",
"text",
")",
"return",
"_Unsafe",
"(",
"text",
".",
"translate",
"(",
"_js_escapes",
")",
")"
] | prevents text from breaking outside of string literals in js . | train | false |
17,668 | def action_event_start(context, values):
return IMPL.action_event_start(context, values)
| [
"def",
"action_event_start",
"(",
"context",
",",
"values",
")",
":",
"return",
"IMPL",
".",
"action_event_start",
"(",
"context",
",",
"values",
")"
] | start an event on an instance action . | train | false |
17,669 | def check_regexs(filename, matchers):
extras = []
for expressions in matchers:
(expression, extramatchers) = expressions
match1 = expression.search(filename)
if match1:
for m in extramatchers:
match2 = m.findall(filename, match1.end())
if match2:
for match in match2:
if ((type(match) == type(())) and (len(match) > 1)):
extras.append(match[1])
else:
extras.append(match)
break
return (match1, extras)
return (None, None)
| [
"def",
"check_regexs",
"(",
"filename",
",",
"matchers",
")",
":",
"extras",
"=",
"[",
"]",
"for",
"expressions",
"in",
"matchers",
":",
"(",
"expression",
",",
"extramatchers",
")",
"=",
"expressions",
"match1",
"=",
"expression",
".",
"search",
"(",
"filename",
")",
"if",
"match1",
":",
"for",
"m",
"in",
"extramatchers",
":",
"match2",
"=",
"m",
".",
"findall",
"(",
"filename",
",",
"match1",
".",
"end",
"(",
")",
")",
"if",
"match2",
":",
"for",
"match",
"in",
"match2",
":",
"if",
"(",
"(",
"type",
"(",
"match",
")",
"==",
"type",
"(",
"(",
")",
")",
")",
"and",
"(",
"len",
"(",
"match",
")",
">",
"1",
")",
")",
":",
"extras",
".",
"append",
"(",
"match",
"[",
"1",
"]",
")",
"else",
":",
"extras",
".",
"append",
"(",
"match",
")",
"break",
"return",
"(",
"match1",
",",
"extras",
")",
"return",
"(",
"None",
",",
"None",
")"
] | regular expression match for a list of regexes returns the matchobject if a match is made this version checks for an additional match . | train | false |
17,670 | def prefix_indexes(config):
if hasattr(config, 'slaveinput'):
prefix = 'test_{[slaveid]}'.format(config.slaveinput)
else:
prefix = 'test'
for (key, index) in settings.ES_INDEXES.items():
if (not index.startswith(prefix)):
settings.ES_INDEXES[key] = '{prefix}_amo_{index}'.format(prefix=prefix, index=index)
settings.CACHE_PREFIX = 'amo:{0}:'.format(prefix)
settings.KEY_PREFIX = settings.CACHE_PREFIX
| [
"def",
"prefix_indexes",
"(",
"config",
")",
":",
"if",
"hasattr",
"(",
"config",
",",
"'slaveinput'",
")",
":",
"prefix",
"=",
"'test_{[slaveid]}'",
".",
"format",
"(",
"config",
".",
"slaveinput",
")",
"else",
":",
"prefix",
"=",
"'test'",
"for",
"(",
"key",
",",
"index",
")",
"in",
"settings",
".",
"ES_INDEXES",
".",
"items",
"(",
")",
":",
"if",
"(",
"not",
"index",
".",
"startswith",
"(",
"prefix",
")",
")",
":",
"settings",
".",
"ES_INDEXES",
"[",
"key",
"]",
"=",
"'{prefix}_amo_{index}'",
".",
"format",
"(",
"prefix",
"=",
"prefix",
",",
"index",
"=",
"index",
")",
"settings",
".",
"CACHE_PREFIX",
"=",
"'amo:{0}:'",
".",
"format",
"(",
"prefix",
")",
"settings",
".",
"KEY_PREFIX",
"=",
"settings",
".",
"CACHE_PREFIX"
] | prefix all es index names and cache keys with test_ and . | train | false |
17,671 | @docfiller
def whosmat(file_name, appendmat=True, **kwargs):
ML = mat_reader_factory(file_name, **kwargs)
variables = ML.list_variables()
if isinstance(file_name, string_types):
ML.mat_stream.close()
return variables
| [
"@",
"docfiller",
"def",
"whosmat",
"(",
"file_name",
",",
"appendmat",
"=",
"True",
",",
"**",
"kwargs",
")",
":",
"ML",
"=",
"mat_reader_factory",
"(",
"file_name",
",",
"**",
"kwargs",
")",
"variables",
"=",
"ML",
".",
"list_variables",
"(",
")",
"if",
"isinstance",
"(",
"file_name",
",",
"string_types",
")",
":",
"ML",
".",
"mat_stream",
".",
"close",
"(",
")",
"return",
"variables"
] | list variables inside a matlab file . | train | false |
17,672 | def get_code2lang_map(lang_code=None, force=False):
global CODE2LANG_MAP
if (force or (not CODE2LANG_MAP)):
lmap = softload_json(settings.LANG_LOOKUP_FILEPATH, logger=logging.debug)
CODE2LANG_MAP = {}
for (lc, entry) in lmap.iteritems():
CODE2LANG_MAP[lcode_to_ietf(lc)] = entry
return (CODE2LANG_MAP.get(lcode_to_ietf(lang_code)) if lang_code else CODE2LANG_MAP)
| [
"def",
"get_code2lang_map",
"(",
"lang_code",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"global",
"CODE2LANG_MAP",
"if",
"(",
"force",
"or",
"(",
"not",
"CODE2LANG_MAP",
")",
")",
":",
"lmap",
"=",
"softload_json",
"(",
"settings",
".",
"LANG_LOOKUP_FILEPATH",
",",
"logger",
"=",
"logging",
".",
"debug",
")",
"CODE2LANG_MAP",
"=",
"{",
"}",
"for",
"(",
"lc",
",",
"entry",
")",
"in",
"lmap",
".",
"iteritems",
"(",
")",
":",
"CODE2LANG_MAP",
"[",
"lcode_to_ietf",
"(",
"lc",
")",
"]",
"=",
"entry",
"return",
"(",
"CODE2LANG_MAP",
".",
"get",
"(",
"lcode_to_ietf",
"(",
"lang_code",
")",
")",
"if",
"lang_code",
"else",
"CODE2LANG_MAP",
")"
] | given a language code . | train | false |
17,673 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
17,676 | def flattenString(request, root):
io = StringIO()
d = flatten(request, root, io.write)
d.addCallback((lambda _: io.getvalue()))
return d
| [
"def",
"flattenString",
"(",
"request",
",",
"root",
")",
":",
"io",
"=",
"StringIO",
"(",
")",
"d",
"=",
"flatten",
"(",
"request",
",",
"root",
",",
"io",
".",
"write",
")",
"d",
".",
"addCallback",
"(",
"(",
"lambda",
"_",
":",
"io",
".",
"getvalue",
"(",
")",
")",
")",
"return",
"d"
] | collate a string representation of c{root} into a single string . | train | false |
17,677 | def adjusted_mutual_info_score(labels_true, labels_pred):
(labels_true, labels_pred) = check_clusterings(labels_true, labels_pred)
n_samples = labels_true.shape[0]
classes = np.unique(labels_true)
clusters = np.unique(labels_pred)
if ((classes.shape[0] == clusters.shape[0] == 1) or (classes.shape[0] == clusters.shape[0] == 0)):
return 1.0
contingency = contingency_matrix(labels_true, labels_pred, sparse=True)
contingency = contingency.astype(np.float64)
mi = mutual_info_score(labels_true, labels_pred, contingency=contingency)
emi = expected_mutual_information(contingency, n_samples)
(h_true, h_pred) = (entropy(labels_true), entropy(labels_pred))
ami = ((mi - emi) / (max(h_true, h_pred) - emi))
return ami
| [
"def",
"adjusted_mutual_info_score",
"(",
"labels_true",
",",
"labels_pred",
")",
":",
"(",
"labels_true",
",",
"labels_pred",
")",
"=",
"check_clusterings",
"(",
"labels_true",
",",
"labels_pred",
")",
"n_samples",
"=",
"labels_true",
".",
"shape",
"[",
"0",
"]",
"classes",
"=",
"np",
".",
"unique",
"(",
"labels_true",
")",
"clusters",
"=",
"np",
".",
"unique",
"(",
"labels_pred",
")",
"if",
"(",
"(",
"classes",
".",
"shape",
"[",
"0",
"]",
"==",
"clusters",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
")",
"or",
"(",
"classes",
".",
"shape",
"[",
"0",
"]",
"==",
"clusters",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
")",
")",
":",
"return",
"1.0",
"contingency",
"=",
"contingency_matrix",
"(",
"labels_true",
",",
"labels_pred",
",",
"sparse",
"=",
"True",
")",
"contingency",
"=",
"contingency",
".",
"astype",
"(",
"np",
".",
"float64",
")",
"mi",
"=",
"mutual_info_score",
"(",
"labels_true",
",",
"labels_pred",
",",
"contingency",
"=",
"contingency",
")",
"emi",
"=",
"expected_mutual_information",
"(",
"contingency",
",",
"n_samples",
")",
"(",
"h_true",
",",
"h_pred",
")",
"=",
"(",
"entropy",
"(",
"labels_true",
")",
",",
"entropy",
"(",
"labels_pred",
")",
")",
"ami",
"=",
"(",
"(",
"mi",
"-",
"emi",
")",
"/",
"(",
"max",
"(",
"h_true",
",",
"h_pred",
")",
"-",
"emi",
")",
")",
"return",
"ami"
] | adjusted mutual information between two clusterings . | train | false |
17,678 | def replace_nonprintables(string):
new_string = ''
modified = 0
for c in string:
o = ord(c)
if (o <= 31):
new_string += ('^' + chr((ord('@') + o)))
modified += 1
elif (o == 127):
new_string += '^?'
modified += 1
else:
new_string += c
if (modified and (S3.Config.Config().urlencoding_mode != 'fixbucket')):
warning(('%d non-printable characters replaced in: %s' % (modified, new_string)))
return new_string
| [
"def",
"replace_nonprintables",
"(",
"string",
")",
":",
"new_string",
"=",
"''",
"modified",
"=",
"0",
"for",
"c",
"in",
"string",
":",
"o",
"=",
"ord",
"(",
"c",
")",
"if",
"(",
"o",
"<=",
"31",
")",
":",
"new_string",
"+=",
"(",
"'^'",
"+",
"chr",
"(",
"(",
"ord",
"(",
"'@'",
")",
"+",
"o",
")",
")",
")",
"modified",
"+=",
"1",
"elif",
"(",
"o",
"==",
"127",
")",
":",
"new_string",
"+=",
"'^?'",
"modified",
"+=",
"1",
"else",
":",
"new_string",
"+=",
"c",
"if",
"(",
"modified",
"and",
"(",
"S3",
".",
"Config",
".",
"Config",
"(",
")",
".",
"urlencoding_mode",
"!=",
"'fixbucket'",
")",
")",
":",
"warning",
"(",
"(",
"'%d non-printable characters replaced in: %s'",
"%",
"(",
"modified",
",",
"new_string",
")",
")",
")",
"return",
"new_string"
] | replace_nonprintables replaces all non-printable characters ch in string where ord <= 26 with ^@ . | train | false |
17,679 | def handle_sigint(signal, frame):
for thread in threading.enumerate():
if thread.isAlive():
thread._Thread__stop()
sys.exit(0)
| [
"def",
"handle_sigint",
"(",
"signal",
",",
"frame",
")",
":",
"for",
"thread",
"in",
"threading",
".",
"enumerate",
"(",
")",
":",
"if",
"thread",
".",
"isAlive",
"(",
")",
":",
"thread",
".",
"_Thread__stop",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | attempt to kill all child threads and exit . | train | false |
17,680 | def strategy_connected_sequential_dfs(G, colors):
return strategy_connected_sequential(G, colors, 'dfs')
| [
"def",
"strategy_connected_sequential_dfs",
"(",
"G",
",",
"colors",
")",
":",
"return",
"strategy_connected_sequential",
"(",
"G",
",",
"colors",
",",
"'dfs'",
")"
] | returns an iterable over nodes in g in the order given by a depth-first traversal . | train | false |
17,681 | def mod_run_check_cmd(cmd, filename, **check_cmd_opts):
log.debug('running our check_cmd')
_cmd = '{0} {1}'.format(cmd, filename)
cret = __salt__['cmd.run_all'](_cmd, **check_cmd_opts)
if (cret['retcode'] != 0):
ret = {'comment': 'check_cmd execution failed', 'skip_watch': True, 'result': False}
if cret.get('stdout'):
ret['comment'] += ('\n' + cret['stdout'])
if cret.get('stderr'):
ret['comment'] += ('\n' + cret['stderr'])
return ret
return True
| [
"def",
"mod_run_check_cmd",
"(",
"cmd",
",",
"filename",
",",
"**",
"check_cmd_opts",
")",
":",
"log",
".",
"debug",
"(",
"'running our check_cmd'",
")",
"_cmd",
"=",
"'{0} {1}'",
".",
"format",
"(",
"cmd",
",",
"filename",
")",
"cret",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"_cmd",
",",
"**",
"check_cmd_opts",
")",
"if",
"(",
"cret",
"[",
"'retcode'",
"]",
"!=",
"0",
")",
":",
"ret",
"=",
"{",
"'comment'",
":",
"'check_cmd execution failed'",
",",
"'skip_watch'",
":",
"True",
",",
"'result'",
":",
"False",
"}",
"if",
"cret",
".",
"get",
"(",
"'stdout'",
")",
":",
"ret",
"[",
"'comment'",
"]",
"+=",
"(",
"'\\n'",
"+",
"cret",
"[",
"'stdout'",
"]",
")",
"if",
"cret",
".",
"get",
"(",
"'stderr'",
")",
":",
"ret",
"[",
"'comment'",
"]",
"+=",
"(",
"'\\n'",
"+",
"cret",
"[",
"'stderr'",
"]",
")",
"return",
"ret",
"return",
"True"
] | execute the check_cmd logic . | train | true |
17,682 | def pre_upgrade(name):
if (name not in _tracker['pre_upgrade']):
return False
return _tracker['pre_upgrade'][name]
| [
"def",
"pre_upgrade",
"(",
"name",
")",
":",
"if",
"(",
"name",
"not",
"in",
"_tracker",
"[",
"'pre_upgrade'",
"]",
")",
":",
"return",
"False",
"return",
"_tracker",
"[",
"'pre_upgrade'",
"]",
"[",
"name",
"]"
] | check if a package is about to be upgraded (in plugin_unloaded()) . | train | false |
17,683 | def send_commit():
return s3db.req_send_commit()
| [
"def",
"send_commit",
"(",
")",
":",
"return",
"s3db",
".",
"req_send_commit",
"(",
")"
] | send a shipment containing all items in a commitment . | train | false |
17,684 | def sql_destroy_indexes(app, style, connection):
output = []
for model in models.get_models(app, include_auto_created=True):
output.extend(connection.creation.sql_destroy_indexes_for_model(model, style))
return output
| [
"def",
"sql_destroy_indexes",
"(",
"app",
",",
"style",
",",
"connection",
")",
":",
"output",
"=",
"[",
"]",
"for",
"model",
"in",
"models",
".",
"get_models",
"(",
"app",
",",
"include_auto_created",
"=",
"True",
")",
":",
"output",
".",
"extend",
"(",
"connection",
".",
"creation",
".",
"sql_destroy_indexes_for_model",
"(",
"model",
",",
"style",
")",
")",
"return",
"output"
] | returns a list of the drop index sql statements for all models in the given app . | train | false |
17,685 | @real_memoize
def is_freebsd():
return sys.platform.startswith('freebsd')
| [
"@",
"real_memoize",
"def",
"is_freebsd",
"(",
")",
":",
"return",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'freebsd'",
")"
] | simple function to return if host is freebsd or not . | train | false |
17,686 | def to_dict_of_dicts(G, nodelist=None, edge_data=None):
dod = {}
if (nodelist is None):
if (edge_data is None):
for (u, nbrdict) in G.adjacency():
dod[u] = nbrdict.copy()
else:
for (u, nbrdict) in G.adjacency():
dod[u] = dod.fromkeys(nbrdict, edge_data)
elif (edge_data is None):
for u in nodelist:
dod[u] = {}
for (v, data) in ((v, data) for (v, data) in G[u].items() if (v in nodelist)):
dod[u][v] = data
else:
for u in nodelist:
dod[u] = {}
for v in (v for v in G[u] if (v in nodelist)):
dod[u][v] = edge_data
return dod
| [
"def",
"to_dict_of_dicts",
"(",
"G",
",",
"nodelist",
"=",
"None",
",",
"edge_data",
"=",
"None",
")",
":",
"dod",
"=",
"{",
"}",
"if",
"(",
"nodelist",
"is",
"None",
")",
":",
"if",
"(",
"edge_data",
"is",
"None",
")",
":",
"for",
"(",
"u",
",",
"nbrdict",
")",
"in",
"G",
".",
"adjacency",
"(",
")",
":",
"dod",
"[",
"u",
"]",
"=",
"nbrdict",
".",
"copy",
"(",
")",
"else",
":",
"for",
"(",
"u",
",",
"nbrdict",
")",
"in",
"G",
".",
"adjacency",
"(",
")",
":",
"dod",
"[",
"u",
"]",
"=",
"dod",
".",
"fromkeys",
"(",
"nbrdict",
",",
"edge_data",
")",
"elif",
"(",
"edge_data",
"is",
"None",
")",
":",
"for",
"u",
"in",
"nodelist",
":",
"dod",
"[",
"u",
"]",
"=",
"{",
"}",
"for",
"(",
"v",
",",
"data",
")",
"in",
"(",
"(",
"v",
",",
"data",
")",
"for",
"(",
"v",
",",
"data",
")",
"in",
"G",
"[",
"u",
"]",
".",
"items",
"(",
")",
"if",
"(",
"v",
"in",
"nodelist",
")",
")",
":",
"dod",
"[",
"u",
"]",
"[",
"v",
"]",
"=",
"data",
"else",
":",
"for",
"u",
"in",
"nodelist",
":",
"dod",
"[",
"u",
"]",
"=",
"{",
"}",
"for",
"v",
"in",
"(",
"v",
"for",
"v",
"in",
"G",
"[",
"u",
"]",
"if",
"(",
"v",
"in",
"nodelist",
")",
")",
":",
"dod",
"[",
"u",
"]",
"[",
"v",
"]",
"=",
"edge_data",
"return",
"dod"
] | return adjacency representation of graph as a dictionary of dictionaries . | train | false |
17,688 | def group_connections(connections):
grouped_conns = defaultdict(list)
if isinstance(connections, QuerySet):
languages = connections.values_list('contact__language', flat=True)
for language in languages.distinct():
lang_conns = connections.filter(contact__language=language)
grouped_conns[language].extend(lang_conns)
else:
for connection in connections:
language = connection.contact.language
grouped_conns[language].append(connection)
for (lang, conns) in grouped_conns.items():
(yield (lang, conns))
| [
"def",
"group_connections",
"(",
"connections",
")",
":",
"grouped_conns",
"=",
"defaultdict",
"(",
"list",
")",
"if",
"isinstance",
"(",
"connections",
",",
"QuerySet",
")",
":",
"languages",
"=",
"connections",
".",
"values_list",
"(",
"'contact__language'",
",",
"flat",
"=",
"True",
")",
"for",
"language",
"in",
"languages",
".",
"distinct",
"(",
")",
":",
"lang_conns",
"=",
"connections",
".",
"filter",
"(",
"contact__language",
"=",
"language",
")",
"grouped_conns",
"[",
"language",
"]",
".",
"extend",
"(",
"lang_conns",
")",
"else",
":",
"for",
"connection",
"in",
"connections",
":",
"language",
"=",
"connection",
".",
"contact",
".",
"language",
"grouped_conns",
"[",
"language",
"]",
".",
"append",
"(",
"connection",
")",
"for",
"(",
"lang",
",",
"conns",
")",
"in",
"grouped_conns",
".",
"items",
"(",
")",
":",
"(",
"yield",
"(",
"lang",
",",
"conns",
")",
")"
] | return a list of pairs . | train | false |
17,690 | def unique_window(iterable, window, key=None):
seen = collections.deque(maxlen=window)
seen_add = seen.append
if (key is None):
for element in iterable:
if (element not in seen):
(yield element)
seen_add(element)
else:
for element in iterable:
k = key(element)
if (k not in seen):
(yield element)
seen_add(k)
| [
"def",
"unique_window",
"(",
"iterable",
",",
"window",
",",
"key",
"=",
"None",
")",
":",
"seen",
"=",
"collections",
".",
"deque",
"(",
"maxlen",
"=",
"window",
")",
"seen_add",
"=",
"seen",
".",
"append",
"if",
"(",
"key",
"is",
"None",
")",
":",
"for",
"element",
"in",
"iterable",
":",
"if",
"(",
"element",
"not",
"in",
"seen",
")",
":",
"(",
"yield",
"element",
")",
"seen_add",
"(",
"element",
")",
"else",
":",
"for",
"element",
"in",
"iterable",
":",
"k",
"=",
"key",
"(",
"element",
")",
"if",
"(",
"k",
"not",
"in",
"seen",
")",
":",
"(",
"yield",
"element",
")",
"seen_add",
"(",
"k",
")"
] | unique_everseen -> iterator get unique elements . | train | false |
17,692 | @should_dump_processes
def start_process_dump():
dump_data_every_thread(dump_processes, DELAY_MINUTES, SAVE_PROCESS_PTR)
| [
"@",
"should_dump_processes",
"def",
"start_process_dump",
"(",
")",
":",
"dump_data_every_thread",
"(",
"dump_processes",
",",
"DELAY_MINUTES",
",",
"SAVE_PROCESS_PTR",
")"
] | if the environment variable w3af_processes is set to 1 . | train | false |
17,693 | def _stream_encoding(stream, default='utf-8'):
encoding = config['terminal_encoding'].get()
if encoding:
return encoding
if (not hasattr(stream, 'encoding')):
return default
return (stream.encoding or default)
| [
"def",
"_stream_encoding",
"(",
"stream",
",",
"default",
"=",
"'utf-8'",
")",
":",
"encoding",
"=",
"config",
"[",
"'terminal_encoding'",
"]",
".",
"get",
"(",
")",
"if",
"encoding",
":",
"return",
"encoding",
"if",
"(",
"not",
"hasattr",
"(",
"stream",
",",
"'encoding'",
")",
")",
":",
"return",
"default",
"return",
"(",
"stream",
".",
"encoding",
"or",
"default",
")"
] | a helper for _in_encoding and _out_encoding: get the streams preferred encoding . | train | false |
17,694 | def bw_usage_get_by_uuids(context, uuids, start_period):
return IMPL.bw_usage_get_by_uuids(context, uuids, start_period)
| [
"def",
"bw_usage_get_by_uuids",
"(",
"context",
",",
"uuids",
",",
"start_period",
")",
":",
"return",
"IMPL",
".",
"bw_usage_get_by_uuids",
"(",
"context",
",",
"uuids",
",",
"start_period",
")"
] | return bw usages for instance(s) in a given audit period . | train | false |
17,695 | def block_device_mapping_update(context, bdm_id, values, legacy=True):
return IMPL.block_device_mapping_update(context, bdm_id, values, legacy)
| [
"def",
"block_device_mapping_update",
"(",
"context",
",",
"bdm_id",
",",
"values",
",",
"legacy",
"=",
"True",
")",
":",
"return",
"IMPL",
".",
"block_device_mapping_update",
"(",
"context",
",",
"bdm_id",
",",
"values",
",",
"legacy",
")"
] | update an entry of block device mapping . | train | false |
17,701 | @check_login_required
@check_local_site_access
def download_orig_file(*args, **kwargs):
return _download_diff_file(False, *args, **kwargs)
| [
"@",
"check_login_required",
"@",
"check_local_site_access",
"def",
"download_orig_file",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"_download_diff_file",
"(",
"False",
",",
"*",
"args",
",",
"**",
"kwargs",
")"
] | downloads an original file from a diff . | train | false |
17,703 | def scalar_potential(field, frame):
if (not is_conservative(field)):
raise ValueError('Field is not conservative')
if (field == Vector(0)):
return S(0)
_check_frame(frame)
field = express(field, frame, variables=True)
dimensions = [x for x in frame]
temp_function = integrate(field.dot(dimensions[0]), frame[0])
for (i, dim) in enumerate(dimensions[1:]):
partial_diff = diff(temp_function, frame[(i + 1)])
partial_diff = (field.dot(dim) - partial_diff)
temp_function += integrate(partial_diff, frame[(i + 1)])
return temp_function
| [
"def",
"scalar_potential",
"(",
"field",
",",
"frame",
")",
":",
"if",
"(",
"not",
"is_conservative",
"(",
"field",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Field is not conservative'",
")",
"if",
"(",
"field",
"==",
"Vector",
"(",
"0",
")",
")",
":",
"return",
"S",
"(",
"0",
")",
"_check_frame",
"(",
"frame",
")",
"field",
"=",
"express",
"(",
"field",
",",
"frame",
",",
"variables",
"=",
"True",
")",
"dimensions",
"=",
"[",
"x",
"for",
"x",
"in",
"frame",
"]",
"temp_function",
"=",
"integrate",
"(",
"field",
".",
"dot",
"(",
"dimensions",
"[",
"0",
"]",
")",
",",
"frame",
"[",
"0",
"]",
")",
"for",
"(",
"i",
",",
"dim",
")",
"in",
"enumerate",
"(",
"dimensions",
"[",
"1",
":",
"]",
")",
":",
"partial_diff",
"=",
"diff",
"(",
"temp_function",
",",
"frame",
"[",
"(",
"i",
"+",
"1",
")",
"]",
")",
"partial_diff",
"=",
"(",
"field",
".",
"dot",
"(",
"dim",
")",
"-",
"partial_diff",
")",
"temp_function",
"+=",
"integrate",
"(",
"partial_diff",
",",
"frame",
"[",
"(",
"i",
"+",
"1",
")",
"]",
")",
"return",
"temp_function"
] | returns the scalar potential function of a field in a given coordinate system . | train | false |
17,706 | def gaussian_nll(x, mean, ln_var):
assert isinstance(x, variable.Variable)
assert isinstance(mean, variable.Variable)
assert isinstance(ln_var, variable.Variable)
D = x.size
x_prec = exponential.exp((- ln_var))
x_diff = (x - mean)
x_power = (((x_diff * x_diff) * x_prec) * (-0.5))
return (((sum.sum(ln_var) + (D * math.log((2 * math.pi)))) / 2) - sum.sum(x_power))
| [
"def",
"gaussian_nll",
"(",
"x",
",",
"mean",
",",
"ln_var",
")",
":",
"assert",
"isinstance",
"(",
"x",
",",
"variable",
".",
"Variable",
")",
"assert",
"isinstance",
"(",
"mean",
",",
"variable",
".",
"Variable",
")",
"assert",
"isinstance",
"(",
"ln_var",
",",
"variable",
".",
"Variable",
")",
"D",
"=",
"x",
".",
"size",
"x_prec",
"=",
"exponential",
".",
"exp",
"(",
"(",
"-",
"ln_var",
")",
")",
"x_diff",
"=",
"(",
"x",
"-",
"mean",
")",
"x_power",
"=",
"(",
"(",
"(",
"x_diff",
"*",
"x_diff",
")",
"*",
"x_prec",
")",
"*",
"(",
"-",
"0.5",
")",
")",
"return",
"(",
"(",
"(",
"sum",
".",
"sum",
"(",
"ln_var",
")",
"+",
"(",
"D",
"*",
"math",
".",
"log",
"(",
"(",
"2",
"*",
"math",
".",
"pi",
")",
")",
")",
")",
"/",
"2",
")",
"-",
"sum",
".",
"sum",
"(",
"x_power",
")",
")"
] | computes the negative log-likelihood of a gaussian distribution . | train | false |
17,707 | def set_current_comp(info, comp):
comp_now = get_current_comp(info)
for (k, chan) in enumerate(info['chs']):
if (chan['kind'] == FIFF.FIFFV_MEG_CH):
rem = (chan['coil_type'] - (comp_now << 16))
chan['coil_type'] = int((rem + (comp << 16)))
| [
"def",
"set_current_comp",
"(",
"info",
",",
"comp",
")",
":",
"comp_now",
"=",
"get_current_comp",
"(",
"info",
")",
"for",
"(",
"k",
",",
"chan",
")",
"in",
"enumerate",
"(",
"info",
"[",
"'chs'",
"]",
")",
":",
"if",
"(",
"chan",
"[",
"'kind'",
"]",
"==",
"FIFF",
".",
"FIFFV_MEG_CH",
")",
":",
"rem",
"=",
"(",
"chan",
"[",
"'coil_type'",
"]",
"-",
"(",
"comp_now",
"<<",
"16",
")",
")",
"chan",
"[",
"'coil_type'",
"]",
"=",
"int",
"(",
"(",
"rem",
"+",
"(",
"comp",
"<<",
"16",
")",
")",
")"
] | set the current compensation in effect in the data . | train | false |
17,708 | def save_to_db(item, msg='Saved to db', print_error=True):
try:
logging.info(msg)
db.session.add(item)
logging.info('added to session')
db.session.commit()
return True
except Exception as e:
if print_error:
print e
traceback.print_exc()
logging.error(('DB Exception! %s' % e))
db.session.rollback()
return False
| [
"def",
"save_to_db",
"(",
"item",
",",
"msg",
"=",
"'Saved to db'",
",",
"print_error",
"=",
"True",
")",
":",
"try",
":",
"logging",
".",
"info",
"(",
"msg",
")",
"db",
".",
"session",
".",
"add",
"(",
"item",
")",
"logging",
".",
"info",
"(",
"'added to session'",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"if",
"print_error",
":",
"print",
"e",
"traceback",
".",
"print_exc",
"(",
")",
"logging",
".",
"error",
"(",
"(",
"'DB Exception! %s'",
"%",
"e",
")",
")",
"db",
".",
"session",
".",
"rollback",
"(",
")",
"return",
"False"
] | convenience function to wrap a proper db save . | train | false |
17,711 | def nice_size(size, include_bytes=False):
niced = False
nice_string = ('%s bytes' % size)
try:
nsize = Decimal(size)
for x in ['bytes', 'KB', 'MB', 'GB']:
if (nsize.compare(Decimal('1024.0')) == Decimal('-1')):
nice_string = ('%3.1f %s' % (nsize, x))
niced = True
break
nsize /= Decimal('1024.0')
if (not niced):
nice_string = ('%3.1f %s' % (nsize, 'TB'))
niced = True
if (include_bytes and (x != 'bytes')):
nice_string = ('%s (%s bytes)' % (nice_string, size))
except:
pass
return nice_string
| [
"def",
"nice_size",
"(",
"size",
",",
"include_bytes",
"=",
"False",
")",
":",
"niced",
"=",
"False",
"nice_string",
"=",
"(",
"'%s bytes'",
"%",
"size",
")",
"try",
":",
"nsize",
"=",
"Decimal",
"(",
"size",
")",
"for",
"x",
"in",
"[",
"'bytes'",
",",
"'KB'",
",",
"'MB'",
",",
"'GB'",
"]",
":",
"if",
"(",
"nsize",
".",
"compare",
"(",
"Decimal",
"(",
"'1024.0'",
")",
")",
"==",
"Decimal",
"(",
"'-1'",
")",
")",
":",
"nice_string",
"=",
"(",
"'%3.1f %s'",
"%",
"(",
"nsize",
",",
"x",
")",
")",
"niced",
"=",
"True",
"break",
"nsize",
"/=",
"Decimal",
"(",
"'1024.0'",
")",
"if",
"(",
"not",
"niced",
")",
":",
"nice_string",
"=",
"(",
"'%3.1f %s'",
"%",
"(",
"nsize",
",",
"'TB'",
")",
")",
"niced",
"=",
"True",
"if",
"(",
"include_bytes",
"and",
"(",
"x",
"!=",
"'bytes'",
")",
")",
":",
"nice_string",
"=",
"(",
"'%s (%s bytes)'",
"%",
"(",
"nice_string",
",",
"size",
")",
")",
"except",
":",
"pass",
"return",
"nice_string"
] | returns a readably formatted string with the size . | train | false |
17,712 | def is_position_inf(pos1, pos2):
return (pos1 < pos2)
| [
"def",
"is_position_inf",
"(",
"pos1",
",",
"pos2",
")",
":",
"return",
"(",
"pos1",
"<",
"pos2",
")"
] | return true is pos1 < pos2 . | train | false |
17,713 | def load_tile_features(lock, host, port, path_fmt, tiles, features):
while True:
try:
tile = tiles.pop()
except IndexError:
break
conn = HTTPConnection(host, port)
head = {'Accept-Encoding': 'gzip'}
path = (path_fmt % tile)
conn.request('GET', path, headers=head)
resp = conn.getresponse()
file = StringIO(resp.read())
if (resp.getheader('Content-Encoding') == 'gzip'):
file = GzipFile(fileobj=file, mode='r')
with lock:
mime_type = resp.getheader('Content-Type')
if (mime_type in ('text/json', 'application/json')):
file_features = geojson.decode(file)
elif (mime_type == 'application/octet-stream+mvt'):
file_features = mvt.decode(file)
else:
logging.error(('Unknown MIME-Type "%s" from %s:%d%s' % (mime_type, host, port, path)))
return
logging.debug(('%d features in %s:%d%s' % (len(file_features), host, port, path)))
features.extend(file_features)
| [
"def",
"load_tile_features",
"(",
"lock",
",",
"host",
",",
"port",
",",
"path_fmt",
",",
"tiles",
",",
"features",
")",
":",
"while",
"True",
":",
"try",
":",
"tile",
"=",
"tiles",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"break",
"conn",
"=",
"HTTPConnection",
"(",
"host",
",",
"port",
")",
"head",
"=",
"{",
"'Accept-Encoding'",
":",
"'gzip'",
"}",
"path",
"=",
"(",
"path_fmt",
"%",
"tile",
")",
"conn",
".",
"request",
"(",
"'GET'",
",",
"path",
",",
"headers",
"=",
"head",
")",
"resp",
"=",
"conn",
".",
"getresponse",
"(",
")",
"file",
"=",
"StringIO",
"(",
"resp",
".",
"read",
"(",
")",
")",
"if",
"(",
"resp",
".",
"getheader",
"(",
"'Content-Encoding'",
")",
"==",
"'gzip'",
")",
":",
"file",
"=",
"GzipFile",
"(",
"fileobj",
"=",
"file",
",",
"mode",
"=",
"'r'",
")",
"with",
"lock",
":",
"mime_type",
"=",
"resp",
".",
"getheader",
"(",
"'Content-Type'",
")",
"if",
"(",
"mime_type",
"in",
"(",
"'text/json'",
",",
"'application/json'",
")",
")",
":",
"file_features",
"=",
"geojson",
".",
"decode",
"(",
"file",
")",
"elif",
"(",
"mime_type",
"==",
"'application/octet-stream+mvt'",
")",
":",
"file_features",
"=",
"mvt",
".",
"decode",
"(",
"file",
")",
"else",
":",
"logging",
".",
"error",
"(",
"(",
"'Unknown MIME-Type \"%s\" from %s:%d%s'",
"%",
"(",
"mime_type",
",",
"host",
",",
"port",
",",
"path",
")",
")",
")",
"return",
"logging",
".",
"debug",
"(",
"(",
"'%d features in %s:%d%s'",
"%",
"(",
"len",
"(",
"file_features",
")",
",",
"host",
",",
"port",
",",
"path",
")",
")",
")",
"features",
".",
"extend",
"(",
"file_features",
")"
] | load data from tiles to features . | train | false |
17,714 | def dmp_rr_lcm(f, g, u, K):
(fc, f) = dmp_ground_primitive(f, u, K)
(gc, g) = dmp_ground_primitive(g, u, K)
c = K.lcm(fc, gc)
h = dmp_quo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K)
return dmp_mul_ground(h, c, u, K)
| [
"def",
"dmp_rr_lcm",
"(",
"f",
",",
"g",
",",
"u",
",",
"K",
")",
":",
"(",
"fc",
",",
"f",
")",
"=",
"dmp_ground_primitive",
"(",
"f",
",",
"u",
",",
"K",
")",
"(",
"gc",
",",
"g",
")",
"=",
"dmp_ground_primitive",
"(",
"g",
",",
"u",
",",
"K",
")",
"c",
"=",
"K",
".",
"lcm",
"(",
"fc",
",",
"gc",
")",
"h",
"=",
"dmp_quo",
"(",
"dmp_mul",
"(",
"f",
",",
"g",
",",
"u",
",",
"K",
")",
",",
"dmp_gcd",
"(",
"f",
",",
"g",
",",
"u",
",",
"K",
")",
",",
"u",
",",
"K",
")",
"return",
"dmp_mul_ground",
"(",
"h",
",",
"c",
",",
"u",
",",
"K",
")"
] | computes polynomial lcm over a ring in k[x] . | train | false |
17,716 | def makeopts_contains(value):
return var_contains('MAKEOPTS', value)
| [
"def",
"makeopts_contains",
"(",
"value",
")",
":",
"return",
"var_contains",
"(",
"'MAKEOPTS'",
",",
"value",
")"
] | verify if makeopts variable contains a value in make . | train | false |
17,717 | def text_filter(regex_base, value):
regex = (regex_base % {u're_cap': u'[a-zA-Z0-9\\.\\,:;/_ \\(\\)\\-\\!\\?"]+', u're_img': u'[a-zA-Z0-9\\.:/_\\-\\% ]+'})
images = re.findall(regex, value)
for i in images:
image = i[1]
if image.startswith(settings.MEDIA_URL):
image = image[len(settings.MEDIA_URL):]
im = get_thumbnail(image, str(sorl_settings.THUMBNAIL_FILTER_WIDTH))
value = value.replace(i[1], im.url)
return value
| [
"def",
"text_filter",
"(",
"regex_base",
",",
"value",
")",
":",
"regex",
"=",
"(",
"regex_base",
"%",
"{",
"u're_cap'",
":",
"u'[a-zA-Z0-9\\\\.\\\\,:;/_ \\\\(\\\\)\\\\-\\\\!\\\\?\"]+'",
",",
"u're_img'",
":",
"u'[a-zA-Z0-9\\\\.:/_\\\\-\\\\% ]+'",
"}",
")",
"images",
"=",
"re",
".",
"findall",
"(",
"regex",
",",
"value",
")",
"for",
"i",
"in",
"images",
":",
"image",
"=",
"i",
"[",
"1",
"]",
"if",
"image",
".",
"startswith",
"(",
"settings",
".",
"MEDIA_URL",
")",
":",
"image",
"=",
"image",
"[",
"len",
"(",
"settings",
".",
"MEDIA_URL",
")",
":",
"]",
"im",
"=",
"get_thumbnail",
"(",
"image",
",",
"str",
"(",
"sorl_settings",
".",
"THUMBNAIL_FILTER_WIDTH",
")",
")",
"value",
"=",
"value",
".",
"replace",
"(",
"i",
"[",
"1",
"]",
",",
"im",
".",
"url",
")",
"return",
"value"
] | helper method to regex replace images with captions in different markups . | train | false |
17,718 | def text_blocks_to_pandas(reader, block_lists, header, head, kwargs, collection=True, enforce=False):
dtypes = head.dtypes.to_dict()
columns = list(head.columns)
delayed_pandas_read_text = delayed(pandas_read_text)
dfs = []
for blocks in block_lists:
if (not blocks):
continue
df = delayed_pandas_read_text(reader, blocks[0], header, kwargs, dtypes, columns, write_header=False, enforce=enforce)
dfs.append(df)
for b in blocks[1:]:
dfs.append(delayed_pandas_read_text(reader, b, header, kwargs, dtypes, columns, enforce=enforce))
if collection:
head = clear_known_categories(head)
return from_delayed(dfs, head)
else:
return dfs
| [
"def",
"text_blocks_to_pandas",
"(",
"reader",
",",
"block_lists",
",",
"header",
",",
"head",
",",
"kwargs",
",",
"collection",
"=",
"True",
",",
"enforce",
"=",
"False",
")",
":",
"dtypes",
"=",
"head",
".",
"dtypes",
".",
"to_dict",
"(",
")",
"columns",
"=",
"list",
"(",
"head",
".",
"columns",
")",
"delayed_pandas_read_text",
"=",
"delayed",
"(",
"pandas_read_text",
")",
"dfs",
"=",
"[",
"]",
"for",
"blocks",
"in",
"block_lists",
":",
"if",
"(",
"not",
"blocks",
")",
":",
"continue",
"df",
"=",
"delayed_pandas_read_text",
"(",
"reader",
",",
"blocks",
"[",
"0",
"]",
",",
"header",
",",
"kwargs",
",",
"dtypes",
",",
"columns",
",",
"write_header",
"=",
"False",
",",
"enforce",
"=",
"enforce",
")",
"dfs",
".",
"append",
"(",
"df",
")",
"for",
"b",
"in",
"blocks",
"[",
"1",
":",
"]",
":",
"dfs",
".",
"append",
"(",
"delayed_pandas_read_text",
"(",
"reader",
",",
"b",
",",
"header",
",",
"kwargs",
",",
"dtypes",
",",
"columns",
",",
"enforce",
"=",
"enforce",
")",
")",
"if",
"collection",
":",
"head",
"=",
"clear_known_categories",
"(",
"head",
")",
"return",
"from_delayed",
"(",
"dfs",
",",
"head",
")",
"else",
":",
"return",
"dfs"
] | convert blocks of bytes to a dask . | train | false |
17,719 | def database(dburl=None, **params):
dbn = params.pop('dbn')
if (dbn in _databases):
return _databases[dbn](**params)
else:
raise UnknownDB, dbn
| [
"def",
"database",
"(",
"dburl",
"=",
"None",
",",
"**",
"params",
")",
":",
"dbn",
"=",
"params",
".",
"pop",
"(",
"'dbn'",
")",
"if",
"(",
"dbn",
"in",
"_databases",
")",
":",
"return",
"_databases",
"[",
"dbn",
"]",
"(",
"**",
"params",
")",
"else",
":",
"raise",
"UnknownDB",
",",
"dbn"
] | database setup . | train | false |
17,720 | @login_required
@require_POST
@xframe_options_sameorigin
def upload_async(request, media_type='image'):
try:
if (media_type == 'image'):
file_info = upload_image(request)
else:
msg = _(u'Unrecognized media type.')
return HttpResponseBadRequest(json.dumps({'status': 'error', 'message': msg}))
except FileTooLargeError as e:
return HttpResponseBadRequest(json.dumps({'status': 'error', 'message': e.args[0]}))
if (isinstance(file_info, dict) and ('thumbnail_url' in file_info)):
schedule_rebuild_kb()
return HttpResponse(json.dumps({'status': 'success', 'file': file_info}))
message = _(u'Could not upload your image.')
return HttpResponseBadRequest(json.dumps({'status': 'error', 'message': unicode(message), 'errors': file_info}))
| [
"@",
"login_required",
"@",
"require_POST",
"@",
"xframe_options_sameorigin",
"def",
"upload_async",
"(",
"request",
",",
"media_type",
"=",
"'image'",
")",
":",
"try",
":",
"if",
"(",
"media_type",
"==",
"'image'",
")",
":",
"file_info",
"=",
"upload_image",
"(",
"request",
")",
"else",
":",
"msg",
"=",
"_",
"(",
"u'Unrecognized media type.'",
")",
"return",
"HttpResponseBadRequest",
"(",
"json",
".",
"dumps",
"(",
"{",
"'status'",
":",
"'error'",
",",
"'message'",
":",
"msg",
"}",
")",
")",
"except",
"FileTooLargeError",
"as",
"e",
":",
"return",
"HttpResponseBadRequest",
"(",
"json",
".",
"dumps",
"(",
"{",
"'status'",
":",
"'error'",
",",
"'message'",
":",
"e",
".",
"args",
"[",
"0",
"]",
"}",
")",
")",
"if",
"(",
"isinstance",
"(",
"file_info",
",",
"dict",
")",
"and",
"(",
"'thumbnail_url'",
"in",
"file_info",
")",
")",
":",
"schedule_rebuild_kb",
"(",
")",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"{",
"'status'",
":",
"'success'",
",",
"'file'",
":",
"file_info",
"}",
")",
")",
"message",
"=",
"_",
"(",
"u'Could not upload your image.'",
")",
"return",
"HttpResponseBadRequest",
"(",
"json",
".",
"dumps",
"(",
"{",
"'status'",
":",
"'error'",
",",
"'message'",
":",
"unicode",
"(",
"message",
")",
",",
"'errors'",
":",
"file_info",
"}",
")",
")"
] | upload images or videos from request . | train | false |
17,722 | def set_enabled_units(units):
context = _UnitContext(equivalencies=get_current_unit_registry().equivalencies)
get_current_unit_registry().set_enabled_units(units)
return context
| [
"def",
"set_enabled_units",
"(",
"units",
")",
":",
"context",
"=",
"_UnitContext",
"(",
"equivalencies",
"=",
"get_current_unit_registry",
"(",
")",
".",
"equivalencies",
")",
"get_current_unit_registry",
"(",
")",
".",
"set_enabled_units",
"(",
"units",
")",
"return",
"context"
] | sets the units enabled in the unit registry . | train | false |
17,725 | def circmean(samples, high=(2 * pi), low=0, axis=None):
(samples, ang) = _circfuncs_common(samples, high, low)
S = sin(ang).sum(axis=axis)
C = cos(ang).sum(axis=axis)
res = arctan2(S, C)
mask = (res < 0)
if (mask.ndim > 0):
res[mask] += (2 * pi)
elif mask:
res += (2 * pi)
return ((((res * (high - low)) / 2.0) / pi) + low)
| [
"def",
"circmean",
"(",
"samples",
",",
"high",
"=",
"(",
"2",
"*",
"pi",
")",
",",
"low",
"=",
"0",
",",
"axis",
"=",
"None",
")",
":",
"(",
"samples",
",",
"ang",
")",
"=",
"_circfuncs_common",
"(",
"samples",
",",
"high",
",",
"low",
")",
"S",
"=",
"sin",
"(",
"ang",
")",
".",
"sum",
"(",
"axis",
"=",
"axis",
")",
"C",
"=",
"cos",
"(",
"ang",
")",
".",
"sum",
"(",
"axis",
"=",
"axis",
")",
"res",
"=",
"arctan2",
"(",
"S",
",",
"C",
")",
"mask",
"=",
"(",
"res",
"<",
"0",
")",
"if",
"(",
"mask",
".",
"ndim",
">",
"0",
")",
":",
"res",
"[",
"mask",
"]",
"+=",
"(",
"2",
"*",
"pi",
")",
"elif",
"mask",
":",
"res",
"+=",
"(",
"2",
"*",
"pi",
")",
"return",
"(",
"(",
"(",
"(",
"res",
"*",
"(",
"high",
"-",
"low",
")",
")",
"/",
"2.0",
")",
"/",
"pi",
")",
"+",
"low",
")"
] | computes the circular mean angle of an array of circular data . | train | false |
17,726 | def delete_thumbnails(relative_source_path, root=None, basedir=None, subdir=None, prefix=None):
thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir, prefix)
return _delete_using_thumbs_list(thumbs)
| [
"def",
"delete_thumbnails",
"(",
"relative_source_path",
",",
"root",
"=",
"None",
",",
"basedir",
"=",
"None",
",",
"subdir",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"thumbs",
"=",
"thumbnails_for_file",
"(",
"relative_source_path",
",",
"root",
",",
"basedir",
",",
"subdir",
",",
"prefix",
")",
"return",
"_delete_using_thumbs_list",
"(",
"thumbs",
")"
] | delete all thumbnails for a source image . | train | true |
17,727 | def map_dict_keys(dict_, key_map):
mapped = {}
for (key, value) in dict_.iteritems():
mapped_key = (key_map[key] if (key in key_map) else key)
mapped[mapped_key] = value
return mapped
| [
"def",
"map_dict_keys",
"(",
"dict_",
",",
"key_map",
")",
":",
"mapped",
"=",
"{",
"}",
"for",
"(",
"key",
",",
"value",
")",
"in",
"dict_",
".",
"iteritems",
"(",
")",
":",
"mapped_key",
"=",
"(",
"key_map",
"[",
"key",
"]",
"if",
"(",
"key",
"in",
"key_map",
")",
"else",
"key",
")",
"mapped",
"[",
"mapped_key",
"]",
"=",
"value",
"return",
"mapped"
] | return a dict in which the dictionaries keys are mapped to new keys . | train | false |
17,729 | def generate_names():
adjectives = ['Exquisite', 'Delicious', 'Elegant', 'Swanky', 'Spicy', 'Food Truck', 'Artisanal', 'Tasty']
nouns = ['Sandwich', 'Pizza', 'Curry', 'Pierogi', 'Sushi', 'Salad', 'Stew', 'Pasta', 'Barbeque', 'Bacon', 'Pancake', 'Waffle', 'Chocolate', 'Gyro', 'Cookie', 'Burrito', 'Pie']
return [' '.join(parts) for parts in product(adjectives, nouns)]
| [
"def",
"generate_names",
"(",
")",
":",
"adjectives",
"=",
"[",
"'Exquisite'",
",",
"'Delicious'",
",",
"'Elegant'",
",",
"'Swanky'",
",",
"'Spicy'",
",",
"'Food Truck'",
",",
"'Artisanal'",
",",
"'Tasty'",
"]",
"nouns",
"=",
"[",
"'Sandwich'",
",",
"'Pizza'",
",",
"'Curry'",
",",
"'Pierogi'",
",",
"'Sushi'",
",",
"'Salad'",
",",
"'Stew'",
",",
"'Pasta'",
",",
"'Barbeque'",
",",
"'Bacon'",
",",
"'Pancake'",
",",
"'Waffle'",
",",
"'Chocolate'",
",",
"'Gyro'",
",",
"'Cookie'",
",",
"'Burrito'",
",",
"'Pie'",
"]",
"return",
"[",
"' '",
".",
"join",
"(",
"parts",
")",
"for",
"parts",
"in",
"product",
"(",
"adjectives",
",",
"nouns",
")",
"]"
] | generate a list of random adjective + noun strings . | train | false |
17,730 | def linkify(text, nofollow=True, target=None, filter_url=identity, filter_text=identity, skip_pre=False, parse_email=False, tokenizer=HTMLSanitizer):
text = force_unicode(text)
if (not text):
return u''
parser = html5lib.HTMLParser(tokenizer=tokenizer)
forest = parser.parseFragment(text)
if nofollow:
rel = u'rel="nofollow"'
else:
rel = u''
def replace_nodes(tree, new_frag, node):
new_tree = parser.parseFragment(new_frag)
for n in new_tree.childNodes:
tree.insertBefore(n, node)
tree.removeChild(node)
def strip_wrapping_parentheses(fragment):
'Strips wrapping parentheses.\n\n Returns a tuple of the following format::\n\n (string stripped from wrapping parentheses,\n count of stripped opening parentheses,\n count of stripped closing parentheses)\n '
opening_parentheses = closing_parentheses = 0
for char in fragment:
if (char == '('):
opening_parentheses += 1
else:
break
if opening_parentheses:
newer_frag = ''
fragment = fragment[opening_parentheses:]
reverse_fragment = fragment[::(-1)]
skip = False
for char in reverse_fragment:
if ((char == ')') and (closing_parentheses < opening_parentheses) and (not skip)):
closing_parentheses += 1
continue
elif (char != ')'):
skip = True
newer_frag += char
fragment = newer_frag[::(-1)]
return (fragment, opening_parentheses, closing_parentheses)
def linkify_nodes(tree, parse_text=True):
for node in tree.childNodes:
if ((node.type == NODE_TEXT) and parse_text):
new_frag = node.toxml()
if parse_email:
new_frag = re.sub(email_re, email_repl, new_frag)
if (new_frag != node.toxml()):
replace_nodes(tree, new_frag, node)
linkify_nodes(tree)
continue
new_frag = re.sub(url_re, link_repl, new_frag)
replace_nodes(tree, new_frag, node)
elif (node.name == 'a'):
if ('href' in node.attributes):
if nofollow:
node.attributes['rel'] = 'nofollow'
if (target is not None):
node.attributes['target'] = target
href = node.attributes['href']
node.attributes['href'] = filter_url(href)
elif (skip_pre and (node.name == 'pre')):
linkify_nodes(node, False)
else:
linkify_nodes(node)
def email_repl(match):
repl = u'<a href="mailto:%(mail)s">%(mail)s</a>'
return (repl % {'mail': match.group(0).replace('"', '"')})
def link_repl(match):
url = match.group(0)
open_brackets = close_brackets = 0
if url.startswith('('):
(url, open_brackets, close_brackets) = strip_wrapping_parentheses(url)
end = u''
m = re.search(punct_re, url)
if m:
end = m.group(0)
url = url[0:m.start()]
if re.search(proto_re, url):
href = url
else:
href = u''.join([u'http://', url])
repl = u'%s<a href="%s" %s>%s</a>%s%s'
attribs = [rel]
if (target is not None):
attribs.append(('target="%s"' % target))
return (repl % (('(' * open_brackets), filter_url(href), ' '.join(attribs), filter_text(url), end, (')' * close_brackets)))
linkify_nodes(forest)
return _render(forest)
| [
"def",
"linkify",
"(",
"text",
",",
"nofollow",
"=",
"True",
",",
"target",
"=",
"None",
",",
"filter_url",
"=",
"identity",
",",
"filter_text",
"=",
"identity",
",",
"skip_pre",
"=",
"False",
",",
"parse_email",
"=",
"False",
",",
"tokenizer",
"=",
"HTMLSanitizer",
")",
":",
"text",
"=",
"force_unicode",
"(",
"text",
")",
"if",
"(",
"not",
"text",
")",
":",
"return",
"u''",
"parser",
"=",
"html5lib",
".",
"HTMLParser",
"(",
"tokenizer",
"=",
"tokenizer",
")",
"forest",
"=",
"parser",
".",
"parseFragment",
"(",
"text",
")",
"if",
"nofollow",
":",
"rel",
"=",
"u'rel=\"nofollow\"'",
"else",
":",
"rel",
"=",
"u''",
"def",
"replace_nodes",
"(",
"tree",
",",
"new_frag",
",",
"node",
")",
":",
"new_tree",
"=",
"parser",
".",
"parseFragment",
"(",
"new_frag",
")",
"for",
"n",
"in",
"new_tree",
".",
"childNodes",
":",
"tree",
".",
"insertBefore",
"(",
"n",
",",
"node",
")",
"tree",
".",
"removeChild",
"(",
"node",
")",
"def",
"strip_wrapping_parentheses",
"(",
"fragment",
")",
":",
"opening_parentheses",
"=",
"closing_parentheses",
"=",
"0",
"for",
"char",
"in",
"fragment",
":",
"if",
"(",
"char",
"==",
"'('",
")",
":",
"opening_parentheses",
"+=",
"1",
"else",
":",
"break",
"if",
"opening_parentheses",
":",
"newer_frag",
"=",
"''",
"fragment",
"=",
"fragment",
"[",
"opening_parentheses",
":",
"]",
"reverse_fragment",
"=",
"fragment",
"[",
":",
":",
"(",
"-",
"1",
")",
"]",
"skip",
"=",
"False",
"for",
"char",
"in",
"reverse_fragment",
":",
"if",
"(",
"(",
"char",
"==",
"')'",
")",
"and",
"(",
"closing_parentheses",
"<",
"opening_parentheses",
")",
"and",
"(",
"not",
"skip",
")",
")",
":",
"closing_parentheses",
"+=",
"1",
"continue",
"elif",
"(",
"char",
"!=",
"')'",
")",
":",
"skip",
"=",
"True",
"newer_frag",
"+=",
"char",
"fragment",
"=",
"newer_frag",
"[",
":",
":",
"(",
"-",
"1",
")",
"]",
"return",
"(",
"fragment",
",",
"opening_parentheses",
",",
"closing_parentheses",
")",
"def",
"linkify_nodes",
"(",
"tree",
",",
"parse_text",
"=",
"True",
")",
":",
"for",
"node",
"in",
"tree",
".",
"childNodes",
":",
"if",
"(",
"(",
"node",
".",
"type",
"==",
"NODE_TEXT",
")",
"and",
"parse_text",
")",
":",
"new_frag",
"=",
"node",
".",
"toxml",
"(",
")",
"if",
"parse_email",
":",
"new_frag",
"=",
"re",
".",
"sub",
"(",
"email_re",
",",
"email_repl",
",",
"new_frag",
")",
"if",
"(",
"new_frag",
"!=",
"node",
".",
"toxml",
"(",
")",
")",
":",
"replace_nodes",
"(",
"tree",
",",
"new_frag",
",",
"node",
")",
"linkify_nodes",
"(",
"tree",
")",
"continue",
"new_frag",
"=",
"re",
".",
"sub",
"(",
"url_re",
",",
"link_repl",
",",
"new_frag",
")",
"replace_nodes",
"(",
"tree",
",",
"new_frag",
",",
"node",
")",
"elif",
"(",
"node",
".",
"name",
"==",
"'a'",
")",
":",
"if",
"(",
"'href'",
"in",
"node",
".",
"attributes",
")",
":",
"if",
"nofollow",
":",
"node",
".",
"attributes",
"[",
"'rel'",
"]",
"=",
"'nofollow'",
"if",
"(",
"target",
"is",
"not",
"None",
")",
":",
"node",
".",
"attributes",
"[",
"'target'",
"]",
"=",
"target",
"href",
"=",
"node",
".",
"attributes",
"[",
"'href'",
"]",
"node",
".",
"attributes",
"[",
"'href'",
"]",
"=",
"filter_url",
"(",
"href",
")",
"elif",
"(",
"skip_pre",
"and",
"(",
"node",
".",
"name",
"==",
"'pre'",
")",
")",
":",
"linkify_nodes",
"(",
"node",
",",
"False",
")",
"else",
":",
"linkify_nodes",
"(",
"node",
")",
"def",
"email_repl",
"(",
"match",
")",
":",
"repl",
"=",
"u'<a href=\"mailto:%(mail)s\">%(mail)s</a>'",
"return",
"(",
"repl",
"%",
"{",
"'mail'",
":",
"match",
".",
"group",
"(",
"0",
")",
".",
"replace",
"(",
"'\"'",
",",
"'"'",
")",
"}",
")",
"def",
"link_repl",
"(",
"match",
")",
":",
"url",
"=",
"match",
".",
"group",
"(",
"0",
")",
"open_brackets",
"=",
"close_brackets",
"=",
"0",
"if",
"url",
".",
"startswith",
"(",
"'('",
")",
":",
"(",
"url",
",",
"open_brackets",
",",
"close_brackets",
")",
"=",
"strip_wrapping_parentheses",
"(",
"url",
")",
"end",
"=",
"u''",
"m",
"=",
"re",
".",
"search",
"(",
"punct_re",
",",
"url",
")",
"if",
"m",
":",
"end",
"=",
"m",
".",
"group",
"(",
"0",
")",
"url",
"=",
"url",
"[",
"0",
":",
"m",
".",
"start",
"(",
")",
"]",
"if",
"re",
".",
"search",
"(",
"proto_re",
",",
"url",
")",
":",
"href",
"=",
"url",
"else",
":",
"href",
"=",
"u''",
".",
"join",
"(",
"[",
"u'http://'",
",",
"url",
"]",
")",
"repl",
"=",
"u'%s<a href=\"%s\" %s>%s</a>%s%s'",
"attribs",
"=",
"[",
"rel",
"]",
"if",
"(",
"target",
"is",
"not",
"None",
")",
":",
"attribs",
".",
"append",
"(",
"(",
"'target=\"%s\"'",
"%",
"target",
")",
")",
"return",
"(",
"repl",
"%",
"(",
"(",
"'('",
"*",
"open_brackets",
")",
",",
"filter_url",
"(",
"href",
")",
",",
"' '",
".",
"join",
"(",
"attribs",
")",
",",
"filter_text",
"(",
"url",
")",
",",
"end",
",",
"(",
"')'",
"*",
"close_brackets",
")",
")",
")",
"linkify_nodes",
"(",
"forest",
")",
"return",
"_render",
"(",
"forest",
")"
] | adds the documentation site root to doc paths . | train | false |
17,731 | def accept_key(pki_dir, pub, id_):
for key_dir in ('minions', 'minions_pre', 'minions_rejected'):
key_path = os.path.join(pki_dir, key_dir)
if (not os.path.exists(key_path)):
os.makedirs(key_path)
key = os.path.join(pki_dir, 'minions', id_)
with salt.utils.fopen(key, 'w+') as fp_:
fp_.write(pub)
oldkey = os.path.join(pki_dir, 'minions_pre', id_)
if os.path.isfile(oldkey):
with salt.utils.fopen(oldkey) as fp_:
if (fp_.read() == pub):
os.remove(oldkey)
| [
"def",
"accept_key",
"(",
"pki_dir",
",",
"pub",
",",
"id_",
")",
":",
"for",
"key_dir",
"in",
"(",
"'minions'",
",",
"'minions_pre'",
",",
"'minions_rejected'",
")",
":",
"key_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pki_dir",
",",
"key_dir",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"key_path",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"key_path",
")",
"key",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pki_dir",
",",
"'minions'",
",",
"id_",
")",
"with",
"salt",
".",
"utils",
".",
"fopen",
"(",
"key",
",",
"'w+'",
")",
"as",
"fp_",
":",
"fp_",
".",
"write",
"(",
"pub",
")",
"oldkey",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pki_dir",
",",
"'minions_pre'",
",",
"id_",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"oldkey",
")",
":",
"with",
"salt",
".",
"utils",
".",
"fopen",
"(",
"oldkey",
")",
"as",
"fp_",
":",
"if",
"(",
"fp_",
".",
"read",
"(",
")",
"==",
"pub",
")",
":",
"os",
".",
"remove",
"(",
"oldkey",
")"
] | if the master config was available then we will have a pki_dir key in the opts directory . | train | true |
17,732 | def worker_edit(worker, lbn, settings, profile='default'):
settings['cmd'] = 'update'
settings['mime'] = 'prop'
settings['w'] = lbn
settings['sw'] = worker
return (_do_http(settings, profile)['worker.result.type'] == 'OK')
| [
"def",
"worker_edit",
"(",
"worker",
",",
"lbn",
",",
"settings",
",",
"profile",
"=",
"'default'",
")",
":",
"settings",
"[",
"'cmd'",
"]",
"=",
"'update'",
"settings",
"[",
"'mime'",
"]",
"=",
"'prop'",
"settings",
"[",
"'w'",
"]",
"=",
"lbn",
"settings",
"[",
"'sw'",
"]",
"=",
"worker",
"return",
"(",
"_do_http",
"(",
"settings",
",",
"profile",
")",
"[",
"'worker.result.type'",
"]",
"==",
"'OK'",
")"
] | edit the worker settings note: URL data parameters for the standard update action cli examples: . | train | true |
17,733 | def write_request_load_scenario(reactor, cluster, request_rate=10, sample_size=DEFAULT_SAMPLE_SIZE, timeout=45, tolerance_percentage=0.2):
return RequestLoadScenario(reactor, WriteRequest(reactor, cluster.get_control_service(reactor)), request_rate=request_rate, sample_size=sample_size, timeout=timeout, tolerance_percentage=tolerance_percentage)
| [
"def",
"write_request_load_scenario",
"(",
"reactor",
",",
"cluster",
",",
"request_rate",
"=",
"10",
",",
"sample_size",
"=",
"DEFAULT_SAMPLE_SIZE",
",",
"timeout",
"=",
"45",
",",
"tolerance_percentage",
"=",
"0.2",
")",
":",
"return",
"RequestLoadScenario",
"(",
"reactor",
",",
"WriteRequest",
"(",
"reactor",
",",
"cluster",
".",
"get_control_service",
"(",
"reactor",
")",
")",
",",
"request_rate",
"=",
"request_rate",
",",
"sample_size",
"=",
"sample_size",
",",
"timeout",
"=",
"timeout",
",",
"tolerance_percentage",
"=",
"tolerance_percentage",
")"
] | factory that will initialise and return a scenario that places load on the cluster by performing write requests at a specified rate . | train | false |
17,734 | def check_key_path_and_mode(provider, key_path):
if (not os.path.exists(key_path)):
log.error("The key file '{0}' used in the '{1}' provider configuration does not exist.\n".format(key_path, provider))
return False
key_mode = str(oct(stat.S_IMODE(os.stat(key_path).st_mode)))
if (key_mode not in ('0400', '0600')):
log.error("The key file '{0}' used in the '{1}' provider configuration needs to be set to mode 0400 or 0600.\n".format(key_path, provider))
return False
return True
| [
"def",
"check_key_path_and_mode",
"(",
"provider",
",",
"key_path",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"key_path",
")",
")",
":",
"log",
".",
"error",
"(",
"\"The key file '{0}' used in the '{1}' provider configuration does not exist.\\n\"",
".",
"format",
"(",
"key_path",
",",
"provider",
")",
")",
"return",
"False",
"key_mode",
"=",
"str",
"(",
"oct",
"(",
"stat",
".",
"S_IMODE",
"(",
"os",
".",
"stat",
"(",
"key_path",
")",
".",
"st_mode",
")",
")",
")",
"if",
"(",
"key_mode",
"not",
"in",
"(",
"'0400'",
",",
"'0600'",
")",
")",
":",
"log",
".",
"error",
"(",
"\"The key file '{0}' used in the '{1}' provider configuration needs to be set to mode 0400 or 0600.\\n\"",
".",
"format",
"(",
"key_path",
",",
"provider",
")",
")",
"return",
"False",
"return",
"True"
] | checks that the key_path exists and the key_mode is either 0400 or 0600 . | train | true |
17,736 | def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None):
from matplotlib import figure
from matplotlib.backends import backend_agg
if (prop is None):
prop = FontProperties()
parser = MathTextParser(u'path')
(width, height, depth, _, _) = parser.parse(s, dpi=72, prop=prop)
fig = figure.Figure(figsize=((width / 72.0), (height / 72.0)))
fig.text(0, (depth / height), s, fontproperties=prop)
backend_agg.FigureCanvasAgg(fig)
fig.savefig(filename_or_obj, dpi=dpi, format=format)
return depth
| [
"def",
"math_to_image",
"(",
"s",
",",
"filename_or_obj",
",",
"prop",
"=",
"None",
",",
"dpi",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"from",
"matplotlib",
"import",
"figure",
"from",
"matplotlib",
".",
"backends",
"import",
"backend_agg",
"if",
"(",
"prop",
"is",
"None",
")",
":",
"prop",
"=",
"FontProperties",
"(",
")",
"parser",
"=",
"MathTextParser",
"(",
"u'path'",
")",
"(",
"width",
",",
"height",
",",
"depth",
",",
"_",
",",
"_",
")",
"=",
"parser",
".",
"parse",
"(",
"s",
",",
"dpi",
"=",
"72",
",",
"prop",
"=",
"prop",
")",
"fig",
"=",
"figure",
".",
"Figure",
"(",
"figsize",
"=",
"(",
"(",
"width",
"/",
"72.0",
")",
",",
"(",
"height",
"/",
"72.0",
")",
")",
")",
"fig",
".",
"text",
"(",
"0",
",",
"(",
"depth",
"/",
"height",
")",
",",
"s",
",",
"fontproperties",
"=",
"prop",
")",
"backend_agg",
".",
"FigureCanvasAgg",
"(",
"fig",
")",
"fig",
".",
"savefig",
"(",
"filename_or_obj",
",",
"dpi",
"=",
"dpi",
",",
"format",
"=",
"format",
")",
"return",
"depth"
] | given a math expression . | train | true |
17,737 | def assert_array_index_eq(left, right):
assert_eq(left, (pd.Index(right) if isinstance(right, np.ndarray) else right))
| [
"def",
"assert_array_index_eq",
"(",
"left",
",",
"right",
")",
":",
"assert_eq",
"(",
"left",
",",
"(",
"pd",
".",
"Index",
"(",
"right",
")",
"if",
"isinstance",
"(",
"right",
",",
"np",
".",
"ndarray",
")",
"else",
"right",
")",
")"
] | left and right are equal . | train | false |
17,740 | @default_selem
def erosion(image, selem=None, out=None, shift_x=False, shift_y=False):
selem = np.array(selem)
selem = _shift_selem(selem, shift_x, shift_y)
if (out is None):
out = np.empty_like(image)
ndi.grey_erosion(image, footprint=selem, output=out)
return out
| [
"@",
"default_selem",
"def",
"erosion",
"(",
"image",
",",
"selem",
"=",
"None",
",",
"out",
"=",
"None",
",",
"shift_x",
"=",
"False",
",",
"shift_y",
"=",
"False",
")",
":",
"selem",
"=",
"np",
".",
"array",
"(",
"selem",
")",
"selem",
"=",
"_shift_selem",
"(",
"selem",
",",
"shift_x",
",",
"shift_y",
")",
"if",
"(",
"out",
"is",
"None",
")",
":",
"out",
"=",
"np",
".",
"empty_like",
"(",
"image",
")",
"ndi",
".",
"grey_erosion",
"(",
"image",
",",
"footprint",
"=",
"selem",
",",
"output",
"=",
"out",
")",
"return",
"out"
] | return greyscale morphological erosion of an image . | train | false |
17,741 | def job_get_by_id(job_id):
try:
job = Job.objects.get(pk=job_id)
return job
except Job.DoesNotExist:
return None
| [
"def",
"job_get_by_id",
"(",
"job_id",
")",
":",
"try",
":",
"job",
"=",
"Job",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"job_id",
")",
"return",
"job",
"except",
"Job",
".",
"DoesNotExist",
":",
"return",
"None"
] | return a job based on its id . | train | false |
17,742 | def read_uint16(fid):
return _unpack_simple(fid, '>u2', np.uint16)
| [
"def",
"read_uint16",
"(",
"fid",
")",
":",
"return",
"_unpack_simple",
"(",
"fid",
",",
"'>u2'",
",",
"np",
".",
"uint16",
")"
] | read unsigned 16bit integer from bti file . | train | false |
17,743 | def on_create(connection):
def on_connect(session):
session.on_join(on_join)
session.join(u'public')
connection.on_connect(on_connect)
| [
"def",
"on_create",
"(",
"connection",
")",
":",
"def",
"on_connect",
"(",
"session",
")",
":",
"session",
".",
"on_join",
"(",
"on_join",
")",
"session",
".",
"join",
"(",
"u'public'",
")",
"connection",
".",
"on_connect",
"(",
"on_connect",
")"
] | this is the main entry into user code . | train | false |
17,744 | def iterate_base4(d):
return product(xrange(4), repeat=d)
| [
"def",
"iterate_base4",
"(",
"d",
")",
":",
"return",
"product",
"(",
"xrange",
"(",
"4",
")",
",",
"repeat",
"=",
"d",
")"
] | iterates over a base 4 number with d digits . | train | false |
17,745 | def sync_ldap_groups(connection, failed_users=None):
groups = Group.objects.filter(group__in=LdapGroup.objects.all())
for group in groups:
_import_ldap_groups(connection, group.name, failed_users=failed_users)
return groups
| [
"def",
"sync_ldap_groups",
"(",
"connection",
",",
"failed_users",
"=",
"None",
")",
":",
"groups",
"=",
"Group",
".",
"objects",
".",
"filter",
"(",
"group__in",
"=",
"LdapGroup",
".",
"objects",
".",
"all",
"(",
")",
")",
"for",
"group",
"in",
"groups",
":",
"_import_ldap_groups",
"(",
"connection",
",",
"group",
".",
"name",
",",
"failed_users",
"=",
"failed_users",
")",
"return",
"groups"
] | syncs ldap group memberships . | train | false |
17,748 | def volume_create(**kwargs):
return create_volume(kwargs, 'function')
| [
"def",
"volume_create",
"(",
"**",
"kwargs",
")",
":",
"return",
"create_volume",
"(",
"kwargs",
",",
"'function'",
")"
] | create a volume from the values dictionary . | train | false |
17,749 | def logistic(x, A, u, d, v, y0):
y = ((A / (1 + np.exp(((((4 * u) / A) * (d - x)) + 2)))) + y0)
return y
| [
"def",
"logistic",
"(",
"x",
",",
"A",
",",
"u",
",",
"d",
",",
"v",
",",
"y0",
")",
":",
"y",
"=",
"(",
"(",
"A",
"/",
"(",
"1",
"+",
"np",
".",
"exp",
"(",
"(",
"(",
"(",
"(",
"4",
"*",
"u",
")",
"/",
"A",
")",
"*",
"(",
"d",
"-",
"x",
")",
")",
"+",
"2",
")",
")",
")",
")",
"+",
"y0",
")",
"return",
"y"
] | logistic growth model proposed in zwietering et al . | train | false |
17,751 | def grep(pattern, items, squash=True):
isdict = (type(items) is dict)
if (pattern in __grep_cache):
regex = __grep_cache[pattern]
else:
regex = __grep_cache[pattern] = re.compile(pattern)
matched = []
matchdict = {}
for item in items:
match = regex.match(item)
if (not match):
continue
groups = match.groups()
if (not groups):
subitems = match.group(0)
elif (len(groups) == 1):
subitems = groups[0]
else:
subitems = list(groups)
if isdict:
matchdict[item] = items[item]
else:
matched.append(subitems)
if isdict:
return matchdict
elif (squash and (len(matched) == 1)):
return matched[0]
else:
return matched
| [
"def",
"grep",
"(",
"pattern",
",",
"items",
",",
"squash",
"=",
"True",
")",
":",
"isdict",
"=",
"(",
"type",
"(",
"items",
")",
"is",
"dict",
")",
"if",
"(",
"pattern",
"in",
"__grep_cache",
")",
":",
"regex",
"=",
"__grep_cache",
"[",
"pattern",
"]",
"else",
":",
"regex",
"=",
"__grep_cache",
"[",
"pattern",
"]",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"matched",
"=",
"[",
"]",
"matchdict",
"=",
"{",
"}",
"for",
"item",
"in",
"items",
":",
"match",
"=",
"regex",
".",
"match",
"(",
"item",
")",
"if",
"(",
"not",
"match",
")",
":",
"continue",
"groups",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"(",
"not",
"groups",
")",
":",
"subitems",
"=",
"match",
".",
"group",
"(",
"0",
")",
"elif",
"(",
"len",
"(",
"groups",
")",
"==",
"1",
")",
":",
"subitems",
"=",
"groups",
"[",
"0",
"]",
"else",
":",
"subitems",
"=",
"list",
"(",
"groups",
")",
"if",
"isdict",
":",
"matchdict",
"[",
"item",
"]",
"=",
"items",
"[",
"item",
"]",
"else",
":",
"matched",
".",
"append",
"(",
"subitems",
")",
"if",
"isdict",
":",
"return",
"matchdict",
"elif",
"(",
"squash",
"and",
"(",
"len",
"(",
"matched",
")",
"==",
"1",
")",
")",
":",
"return",
"matched",
"[",
"0",
"]",
"else",
":",
"return",
"matched"
] | search for ports using a regular expression . | train | false |
17,752 | @inspect_command(alias=u'dump_revoked')
def revoked(state, **kwargs):
return list(worker_state.revoked)
| [
"@",
"inspect_command",
"(",
"alias",
"=",
"u'dump_revoked'",
")",
"def",
"revoked",
"(",
"state",
",",
"**",
"kwargs",
")",
":",
"return",
"list",
"(",
"worker_state",
".",
"revoked",
")"
] | list of revoked task-ids . | train | false |
17,753 | def upcast_char(*args):
t = _upcast_memo.get(args)
if (t is not None):
return t
t = upcast(*map(np.dtype, args))
_upcast_memo[args] = t
return t
| [
"def",
"upcast_char",
"(",
"*",
"args",
")",
":",
"t",
"=",
"_upcast_memo",
".",
"get",
"(",
"args",
")",
"if",
"(",
"t",
"is",
"not",
"None",
")",
":",
"return",
"t",
"t",
"=",
"upcast",
"(",
"*",
"map",
"(",
"np",
".",
"dtype",
",",
"args",
")",
")",
"_upcast_memo",
"[",
"args",
"]",
"=",
"t",
"return",
"t"
] | same as upcast but taking dtype . | train | false |
17,755 | def _load_and_process_metadata(captions_file, image_dir):
with tf.gfile.FastGFile(captions_file, 'r') as f:
caption_data = json.load(f)
id_to_filename = [(x['id'], x['file_name']) for x in caption_data['images']]
id_to_captions = {}
for annotation in caption_data['annotations']:
image_id = annotation['image_id']
caption = annotation['caption']
id_to_captions.setdefault(image_id, [])
id_to_captions[image_id].append(caption)
assert (len(id_to_filename) == len(id_to_captions))
assert (set([x[0] for x in id_to_filename]) == set(id_to_captions.keys()))
print(('Loaded caption metadata for %d images from %s' % (len(id_to_filename), captions_file)))
print('Proccessing captions.')
image_metadata = []
num_captions = 0
for (image_id, base_filename) in id_to_filename:
filename = os.path.join(image_dir, base_filename)
captions = [_process_caption(c) for c in id_to_captions[image_id]]
image_metadata.append(ImageMetadata(image_id, filename, captions))
num_captions += len(captions)
print(('Finished processing %d captions for %d images in %s' % (num_captions, len(id_to_filename), captions_file)))
return image_metadata
| [
"def",
"_load_and_process_metadata",
"(",
"captions_file",
",",
"image_dir",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"FastGFile",
"(",
"captions_file",
",",
"'r'",
")",
"as",
"f",
":",
"caption_data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"id_to_filename",
"=",
"[",
"(",
"x",
"[",
"'id'",
"]",
",",
"x",
"[",
"'file_name'",
"]",
")",
"for",
"x",
"in",
"caption_data",
"[",
"'images'",
"]",
"]",
"id_to_captions",
"=",
"{",
"}",
"for",
"annotation",
"in",
"caption_data",
"[",
"'annotations'",
"]",
":",
"image_id",
"=",
"annotation",
"[",
"'image_id'",
"]",
"caption",
"=",
"annotation",
"[",
"'caption'",
"]",
"id_to_captions",
".",
"setdefault",
"(",
"image_id",
",",
"[",
"]",
")",
"id_to_captions",
"[",
"image_id",
"]",
".",
"append",
"(",
"caption",
")",
"assert",
"(",
"len",
"(",
"id_to_filename",
")",
"==",
"len",
"(",
"id_to_captions",
")",
")",
"assert",
"(",
"set",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"id_to_filename",
"]",
")",
"==",
"set",
"(",
"id_to_captions",
".",
"keys",
"(",
")",
")",
")",
"print",
"(",
"(",
"'Loaded caption metadata for %d images from %s'",
"%",
"(",
"len",
"(",
"id_to_filename",
")",
",",
"captions_file",
")",
")",
")",
"print",
"(",
"'Proccessing captions.'",
")",
"image_metadata",
"=",
"[",
"]",
"num_captions",
"=",
"0",
"for",
"(",
"image_id",
",",
"base_filename",
")",
"in",
"id_to_filename",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"image_dir",
",",
"base_filename",
")",
"captions",
"=",
"[",
"_process_caption",
"(",
"c",
")",
"for",
"c",
"in",
"id_to_captions",
"[",
"image_id",
"]",
"]",
"image_metadata",
".",
"append",
"(",
"ImageMetadata",
"(",
"image_id",
",",
"filename",
",",
"captions",
")",
")",
"num_captions",
"+=",
"len",
"(",
"captions",
")",
"print",
"(",
"(",
"'Finished processing %d captions for %d images in %s'",
"%",
"(",
"num_captions",
",",
"len",
"(",
"id_to_filename",
")",
",",
"captions_file",
")",
")",
")",
"return",
"image_metadata"
] | loads image metadata from a json file and processes the captions . | train | false |
17,756 | def cluster_quorum(**kwargs):
return ceph_cfg.cluster_quorum(**kwargs)
| [
"def",
"cluster_quorum",
"(",
"**",
"kwargs",
")",
":",
"return",
"ceph_cfg",
".",
"cluster_quorum",
"(",
"**",
"kwargs",
")"
] | get the clusters quorum status cli example: . | train | false |
17,757 | def regexp_extract(pattern, method=re.match, group=1):
def regexp_extract_lambda(value):
if (not value):
return None
matches = method(pattern, value)
if (not matches):
return None
return matches.group(group)
return regexp_extract_lambda
| [
"def",
"regexp_extract",
"(",
"pattern",
",",
"method",
"=",
"re",
".",
"match",
",",
"group",
"=",
"1",
")",
":",
"def",
"regexp_extract_lambda",
"(",
"value",
")",
":",
"if",
"(",
"not",
"value",
")",
":",
"return",
"None",
"matches",
"=",
"method",
"(",
"pattern",
",",
"value",
")",
"if",
"(",
"not",
"matches",
")",
":",
"return",
"None",
"return",
"matches",
".",
"group",
"(",
"group",
")",
"return",
"regexp_extract_lambda"
] | return first group in the value matching the pattern using re . | train | false |
17,758 | def _ParseInputSpec(input_spec):
pattern = re.compile('(\\d+),(\\d+),(\\d+),(\\d+)')
m = pattern.match(input_spec)
if (m is None):
raise ValueError(('Failed to parse input spec:' + input_spec))
batch_size = int(m.group(1))
y_size = (int(m.group(2)) if (int(m.group(2)) > 0) else None)
x_size = (int(m.group(3)) if (int(m.group(3)) > 0) else None)
depth = int(m.group(4))
if (depth not in [1, 3]):
raise ValueError('Depth must be 1 or 3, had:', depth)
return vgsl_input.ImageShape(batch_size, y_size, x_size, depth)
| [
"def",
"_ParseInputSpec",
"(",
"input_spec",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'(\\\\d+),(\\\\d+),(\\\\d+),(\\\\d+)'",
")",
"m",
"=",
"pattern",
".",
"match",
"(",
"input_spec",
")",
"if",
"(",
"m",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Failed to parse input spec:'",
"+",
"input_spec",
")",
")",
"batch_size",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"y_size",
"=",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"2",
")",
")",
"if",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"2",
")",
")",
">",
"0",
")",
"else",
"None",
")",
"x_size",
"=",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"3",
")",
")",
"if",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"3",
")",
")",
">",
"0",
")",
"else",
"None",
")",
"depth",
"=",
"int",
"(",
"m",
".",
"group",
"(",
"4",
")",
")",
"if",
"(",
"depth",
"not",
"in",
"[",
"1",
",",
"3",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'Depth must be 1 or 3, had:'",
",",
"depth",
")",
"return",
"vgsl_input",
".",
"ImageShape",
"(",
"batch_size",
",",
"y_size",
",",
"x_size",
",",
"depth",
")"
] | parses input_spec and returns the numbers obtained therefrom . | train | false |
17,760 | def send_request(url, method='GET', headers=None, param_get=None, data=None):
final_hostname = urlsplit(url).netloc
dbgprint('FinalRequestUrl', url, 'FinalHostname', final_hostname)
if ((final_hostname not in allowed_domains_set) and (not developer_temporary_disable_ssrf_prevention)):
raise ConnectionAbortedError('Trying to access an OUT-OF-ZONE domain(SSRF Layer 2):', final_hostname)
if (not data):
data = None
prepped_req = requests.Request(method, url, headers=headers, params=param_get, data=data).prepare()
if enable_connection_keep_alive:
_session = connection_pool.get_session(final_hostname)
else:
_session = requests.Session()
parse.time['req_start_time'] = time()
r = _session.send(prepped_req, proxies=requests_proxies, allow_redirects=False, stream=enable_stream_content_transfer, verify=(not developer_do_not_verify_ssl))
parse.time['req_time_header'] = (time() - parse.time['req_start_time'])
dbgprint('RequestTime:', parse.time['req_time_header'], v=4)
if (verbose_level >= 3):
dbgprint(r.request.method, 'FinalSentToRemoteRequestUrl:', r.url, '\nRem Resp Stat: ', r.status_code)
dbgprint('RemoteRequestHeaders: ', r.request.headers)
if data:
dbgprint('RemoteRequestRawData: ', r.request.body)
dbgprint('RemoteResponseHeaders: ', r.headers)
return r
| [
"def",
"send_request",
"(",
"url",
",",
"method",
"=",
"'GET'",
",",
"headers",
"=",
"None",
",",
"param_get",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"final_hostname",
"=",
"urlsplit",
"(",
"url",
")",
".",
"netloc",
"dbgprint",
"(",
"'FinalRequestUrl'",
",",
"url",
",",
"'FinalHostname'",
",",
"final_hostname",
")",
"if",
"(",
"(",
"final_hostname",
"not",
"in",
"allowed_domains_set",
")",
"and",
"(",
"not",
"developer_temporary_disable_ssrf_prevention",
")",
")",
":",
"raise",
"ConnectionAbortedError",
"(",
"'Trying to access an OUT-OF-ZONE domain(SSRF Layer 2):'",
",",
"final_hostname",
")",
"if",
"(",
"not",
"data",
")",
":",
"data",
"=",
"None",
"prepped_req",
"=",
"requests",
".",
"Request",
"(",
"method",
",",
"url",
",",
"headers",
"=",
"headers",
",",
"params",
"=",
"param_get",
",",
"data",
"=",
"data",
")",
".",
"prepare",
"(",
")",
"if",
"enable_connection_keep_alive",
":",
"_session",
"=",
"connection_pool",
".",
"get_session",
"(",
"final_hostname",
")",
"else",
":",
"_session",
"=",
"requests",
".",
"Session",
"(",
")",
"parse",
".",
"time",
"[",
"'req_start_time'",
"]",
"=",
"time",
"(",
")",
"r",
"=",
"_session",
".",
"send",
"(",
"prepped_req",
",",
"proxies",
"=",
"requests_proxies",
",",
"allow_redirects",
"=",
"False",
",",
"stream",
"=",
"enable_stream_content_transfer",
",",
"verify",
"=",
"(",
"not",
"developer_do_not_verify_ssl",
")",
")",
"parse",
".",
"time",
"[",
"'req_time_header'",
"]",
"=",
"(",
"time",
"(",
")",
"-",
"parse",
".",
"time",
"[",
"'req_start_time'",
"]",
")",
"dbgprint",
"(",
"'RequestTime:'",
",",
"parse",
".",
"time",
"[",
"'req_time_header'",
"]",
",",
"v",
"=",
"4",
")",
"if",
"(",
"verbose_level",
">=",
"3",
")",
":",
"dbgprint",
"(",
"r",
".",
"request",
".",
"method",
",",
"'FinalSentToRemoteRequestUrl:'",
",",
"r",
".",
"url",
",",
"'\\nRem Resp Stat: '",
",",
"r",
".",
"status_code",
")",
"dbgprint",
"(",
"'RemoteRequestHeaders: '",
",",
"r",
".",
"request",
".",
"headers",
")",
"if",
"data",
":",
"dbgprint",
"(",
"'RemoteRequestRawData: '",
",",
"r",
".",
"request",
".",
"body",
")",
"dbgprint",
"(",
"'RemoteResponseHeaders: '",
",",
"r",
".",
"headers",
")",
"return",
"r"
] | sends a request to notes api with appropriate parameters and headers . | train | false |
17,761 | def force_header_for_response(response, header, value):
force_headers = {}
if hasattr(response, 'force_headers'):
force_headers = response.force_headers
force_headers[header] = value
response.force_headers = force_headers
| [
"def",
"force_header_for_response",
"(",
"response",
",",
"header",
",",
"value",
")",
":",
"force_headers",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"response",
",",
"'force_headers'",
")",
":",
"force_headers",
"=",
"response",
".",
"force_headers",
"force_headers",
"[",
"header",
"]",
"=",
"value",
"response",
".",
"force_headers",
"=",
"force_headers"
] | forces the given header for the given response using the header_control middleware . | train | false |
17,762 | def getComplexByDictionaryListValue(value, valueComplex):
if (value.__class__ == complex):
return value
if (value.__class__ == dict):
return getComplexByDictionary(value, valueComplex)
if (value.__class__ == list):
return getComplexByFloatList(value, valueComplex)
floatFromValue = euclidean.getFloatFromValue(value)
if (floatFromValue == None):
return valueComplex
return complex(floatFromValue, floatFromValue)
| [
"def",
"getComplexByDictionaryListValue",
"(",
"value",
",",
"valueComplex",
")",
":",
"if",
"(",
"value",
".",
"__class__",
"==",
"complex",
")",
":",
"return",
"value",
"if",
"(",
"value",
".",
"__class__",
"==",
"dict",
")",
":",
"return",
"getComplexByDictionary",
"(",
"value",
",",
"valueComplex",
")",
"if",
"(",
"value",
".",
"__class__",
"==",
"list",
")",
":",
"return",
"getComplexByFloatList",
"(",
"value",
",",
"valueComplex",
")",
"floatFromValue",
"=",
"euclidean",
".",
"getFloatFromValue",
"(",
"value",
")",
"if",
"(",
"floatFromValue",
"==",
"None",
")",
":",
"return",
"valueComplex",
"return",
"complex",
"(",
"floatFromValue",
",",
"floatFromValue",
")"
] | get complex by dictionary . | train | false |
17,763 | def _GetKeyKind(key):
return key.path().element_list()[(-1)].type()
| [
"def",
"_GetKeyKind",
"(",
"key",
")",
":",
"return",
"key",
".",
"path",
"(",
")",
".",
"element_list",
"(",
")",
"[",
"(",
"-",
"1",
")",
"]",
".",
"type",
"(",
")"
] | return the kind of the given key . | train | false |
17,765 | def set_stubs(test):
test.stub_out('nova.virt.vmwareapi.network_util.get_network_with_the_name', fake.fake_get_network)
test.stub_out('nova.virt.vmwareapi.images.upload_image_stream_optimized', fake.fake_upload_image)
test.stub_out('nova.virt.vmwareapi.images.fetch_image', fake.fake_fetch_image)
test.stub_out('nova.virt.vmwareapi.driver.VMwareAPISession.vim', fake_vim_prop)
test.stub_out('nova.virt.vmwareapi.driver.VMwareAPISession._is_vim_object', fake_is_vim_object)
if CONF.use_neutron:
test.stub_out('nova.network.neutronv2.api.API.update_instance_vnic_index', (lambda *args, **kwargs: None))
| [
"def",
"set_stubs",
"(",
"test",
")",
":",
"test",
".",
"stub_out",
"(",
"'nova.virt.vmwareapi.network_util.get_network_with_the_name'",
",",
"fake",
".",
"fake_get_network",
")",
"test",
".",
"stub_out",
"(",
"'nova.virt.vmwareapi.images.upload_image_stream_optimized'",
",",
"fake",
".",
"fake_upload_image",
")",
"test",
".",
"stub_out",
"(",
"'nova.virt.vmwareapi.images.fetch_image'",
",",
"fake",
".",
"fake_fetch_image",
")",
"test",
".",
"stub_out",
"(",
"'nova.virt.vmwareapi.driver.VMwareAPISession.vim'",
",",
"fake_vim_prop",
")",
"test",
".",
"stub_out",
"(",
"'nova.virt.vmwareapi.driver.VMwareAPISession._is_vim_object'",
",",
"fake_is_vim_object",
")",
"if",
"CONF",
".",
"use_neutron",
":",
"test",
".",
"stub_out",
"(",
"'nova.network.neutronv2.api.API.update_instance_vnic_index'",
",",
"(",
"lambda",
"*",
"args",
",",
"**",
"kwargs",
":",
"None",
")",
")"
] | set the stubs . | train | false |
17,766 | def _write_mri_config(fname, subject_from, subject_to, scale):
scale = np.asarray(scale)
if (np.isscalar(scale) or (scale.shape == ())):
n_params = 1
else:
n_params = 3
config = configparser.RawConfigParser()
config.add_section('MRI Scaling')
config.set('MRI Scaling', 'subject_from', subject_from)
config.set('MRI Scaling', 'subject_to', subject_to)
config.set('MRI Scaling', 'n_params', str(n_params))
if (n_params == 1):
config.set('MRI Scaling', 'scale', str(scale))
else:
config.set('MRI Scaling', 'scale', ' '.join([str(s) for s in scale]))
config.set('MRI Scaling', 'version', '1')
with open(fname, 'w') as fid:
config.write(fid)
| [
"def",
"_write_mri_config",
"(",
"fname",
",",
"subject_from",
",",
"subject_to",
",",
"scale",
")",
":",
"scale",
"=",
"np",
".",
"asarray",
"(",
"scale",
")",
"if",
"(",
"np",
".",
"isscalar",
"(",
"scale",
")",
"or",
"(",
"scale",
".",
"shape",
"==",
"(",
")",
")",
")",
":",
"n_params",
"=",
"1",
"else",
":",
"n_params",
"=",
"3",
"config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"config",
".",
"add_section",
"(",
"'MRI Scaling'",
")",
"config",
".",
"set",
"(",
"'MRI Scaling'",
",",
"'subject_from'",
",",
"subject_from",
")",
"config",
".",
"set",
"(",
"'MRI Scaling'",
",",
"'subject_to'",
",",
"subject_to",
")",
"config",
".",
"set",
"(",
"'MRI Scaling'",
",",
"'n_params'",
",",
"str",
"(",
"n_params",
")",
")",
"if",
"(",
"n_params",
"==",
"1",
")",
":",
"config",
".",
"set",
"(",
"'MRI Scaling'",
",",
"'scale'",
",",
"str",
"(",
"scale",
")",
")",
"else",
":",
"config",
".",
"set",
"(",
"'MRI Scaling'",
",",
"'scale'",
",",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"scale",
"]",
")",
")",
"config",
".",
"set",
"(",
"'MRI Scaling'",
",",
"'version'",
",",
"'1'",
")",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"fid",
":",
"config",
".",
"write",
"(",
"fid",
")"
] | write the cfg file describing a scaled mri subject . | train | false |
17,767 | @needs('pavelib.prereqs.install_prereqs', 'pavelib.utils.test.utils.clean_reports_dir')
@cmdopts([('failed', 'f', 'Run only failed tests'), ('fail-fast', 'x', 'Run only failed tests'), make_option('-c', '--cov-args', default='', help='adds as args to coverage for the test run'), make_option('--verbose', action='store_const', const=2, dest='verbosity'), make_option('-q', '--quiet', action='store_const', const=0, dest='verbosity'), make_option('-v', '--verbosity', action='count', dest='verbosity', default=1), make_option('--disable-migrations', action='store_true', dest='disable_migrations', help="Create tables directly from apps' models. Can also be used by exporting DISABLE_MIGRATIONS=1."), ('cov_args=', None, 'deprecated in favor of cov-args'), make_option('-e', '--extra_args', default='', help='deprecated, pass extra options directly in the paver commandline'), ('fail_fast', None, 'deprecated in favor of fail-fast')])
@PassthroughTask
@timed
def test_python(options, passthrough_options):
python_suite = suites.PythonTestSuite('Python Tests', passthrough_options=passthrough_options, **options.test_python)
python_suite.run()
| [
"@",
"needs",
"(",
"'pavelib.prereqs.install_prereqs'",
",",
"'pavelib.utils.test.utils.clean_reports_dir'",
")",
"@",
"cmdopts",
"(",
"[",
"(",
"'failed'",
",",
"'f'",
",",
"'Run only failed tests'",
")",
",",
"(",
"'fail-fast'",
",",
"'x'",
",",
"'Run only failed tests'",
")",
",",
"make_option",
"(",
"'-c'",
",",
"'--cov-args'",
",",
"default",
"=",
"''",
",",
"help",
"=",
"'adds as args to coverage for the test run'",
")",
",",
"make_option",
"(",
"'--verbose'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"2",
",",
"dest",
"=",
"'verbosity'",
")",
",",
"make_option",
"(",
"'-q'",
",",
"'--quiet'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"0",
",",
"dest",
"=",
"'verbosity'",
")",
",",
"make_option",
"(",
"'-v'",
",",
"'--verbosity'",
",",
"action",
"=",
"'count'",
",",
"dest",
"=",
"'verbosity'",
",",
"default",
"=",
"1",
")",
",",
"make_option",
"(",
"'--disable-migrations'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'disable_migrations'",
",",
"help",
"=",
"\"Create tables directly from apps' models. Can also be used by exporting DISABLE_MIGRATIONS=1.\"",
")",
",",
"(",
"'cov_args='",
",",
"None",
",",
"'deprecated in favor of cov-args'",
")",
",",
"make_option",
"(",
"'-e'",
",",
"'--extra_args'",
",",
"default",
"=",
"''",
",",
"help",
"=",
"'deprecated, pass extra options directly in the paver commandline'",
")",
",",
"(",
"'fail_fast'",
",",
"None",
",",
"'deprecated in favor of fail-fast'",
")",
"]",
")",
"@",
"PassthroughTask",
"@",
"timed",
"def",
"test_python",
"(",
"options",
",",
"passthrough_options",
")",
":",
"python_suite",
"=",
"suites",
".",
"PythonTestSuite",
"(",
"'Python Tests'",
",",
"passthrough_options",
"=",
"passthrough_options",
",",
"**",
"options",
".",
"test_python",
")",
"python_suite",
".",
"run",
"(",
")"
] | run all python tests . | train | false |
17,768 | def test_write_noformat_arbitrary():
_identifiers.update(_IDENTIFIERS_ORIGINAL)
with pytest.raises(io_registry.IORegistryError) as exc:
TestData().write(object())
assert str(exc.value).startswith(u'Format could not be identified.')
| [
"def",
"test_write_noformat_arbitrary",
"(",
")",
":",
"_identifiers",
".",
"update",
"(",
"_IDENTIFIERS_ORIGINAL",
")",
"with",
"pytest",
".",
"raises",
"(",
"io_registry",
".",
"IORegistryError",
")",
"as",
"exc",
":",
"TestData",
"(",
")",
".",
"write",
"(",
"object",
"(",
")",
")",
"assert",
"str",
"(",
"exc",
".",
"value",
")",
".",
"startswith",
"(",
"u'Format could not be identified.'",
")"
] | test that all identifier functions can accept arbitrary input . | train | false |
17,769 | def extras_msg(extras):
if (len(extras) == 1):
verb = 'was'
else:
verb = 'were'
return (', '.join((repr(extra) for extra in extras)), verb)
| [
"def",
"extras_msg",
"(",
"extras",
")",
":",
"if",
"(",
"len",
"(",
"extras",
")",
"==",
"1",
")",
":",
"verb",
"=",
"'was'",
"else",
":",
"verb",
"=",
"'were'",
"return",
"(",
"', '",
".",
"join",
"(",
"(",
"repr",
"(",
"extra",
")",
"for",
"extra",
"in",
"extras",
")",
")",
",",
"verb",
")"
] | create an error message for extra items or properties . | train | true |
17,771 | def urepr(value):
if isinstance(value, list):
return (('[' + ', '.join(map(urepr, value))) + ']')
if isinstance(value, unicode):
return (('u"' + value.encode('utf-8').replace('"', '\\"').replace('\\', '\\\\')) + '"')
return repr(value)
| [
"def",
"urepr",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"(",
"(",
"'['",
"+",
"', '",
".",
"join",
"(",
"map",
"(",
"urepr",
",",
"value",
")",
")",
")",
"+",
"']'",
")",
"if",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"return",
"(",
"(",
"'u\"'",
"+",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
")",
"+",
"'\"'",
")",
"return",
"repr",
"(",
"value",
")"
] | like repr() . | train | false |
17,772 | def _ListIndexesResponsePbToGetResponse(response, include_schema):
return GetResponse(results=[_NewIndexFromPb(index, include_schema) for index in response.index_metadata_list()])
| [
"def",
"_ListIndexesResponsePbToGetResponse",
"(",
"response",
",",
"include_schema",
")",
":",
"return",
"GetResponse",
"(",
"results",
"=",
"[",
"_NewIndexFromPb",
"(",
"index",
",",
"include_schema",
")",
"for",
"index",
"in",
"response",
".",
"index_metadata_list",
"(",
")",
"]",
")"
] | returns a getresponse constructed from get_indexes response pb . | train | false |
17,773 | @csrf_exempt
def default_render_failure(request, message, status=403, template_name='extauth_failure.html', exception=None):
log.debug(('In openid_failure ' + message))
data = render_to_string(template_name, dict(message=message, exception=exception))
return HttpResponse(data, status=status)
| [
"@",
"csrf_exempt",
"def",
"default_render_failure",
"(",
"request",
",",
"message",
",",
"status",
"=",
"403",
",",
"template_name",
"=",
"'extauth_failure.html'",
",",
"exception",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"(",
"'In openid_failure '",
"+",
"message",
")",
")",
"data",
"=",
"render_to_string",
"(",
"template_name",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"exception",
"=",
"exception",
")",
")",
"return",
"HttpResponse",
"(",
"data",
",",
"status",
"=",
"status",
")"
] | render an error page to the user . | train | false |
17,774 | def append_features(value):
return append_var('FEATURES', value)
| [
"def",
"append_features",
"(",
"value",
")",
":",
"return",
"append_var",
"(",
"'FEATURES'",
",",
"value",
")"
] | add to or create a new features in the make . | train | false |
17,775 | def set_dataset_root(path):
global _dataset_root
_dataset_root = path
| [
"def",
"set_dataset_root",
"(",
"path",
")",
":",
"global",
"_dataset_root",
"_dataset_root",
"=",
"path"
] | sets the root directory to download and cache datasets . | train | false |
17,777 | def decrypt_keyfile():
print('Running in Travis during merge, decrypting stored key file.')
encrypted_key = os.getenv(ENCRYPTED_KEY_ENV)
encrypted_iv = os.getenv(ENCRYPTED_INIT_VECTOR_ENV)
out_file = os.getenv(CREDENTIALS)
subprocess.call(['openssl', 'aes-256-cbc', '-K', encrypted_key, '-iv', encrypted_iv, '-in', ENCRYPTED_KEYFILE, '-out', out_file, '-d'])
| [
"def",
"decrypt_keyfile",
"(",
")",
":",
"print",
"(",
"'Running in Travis during merge, decrypting stored key file.'",
")",
"encrypted_key",
"=",
"os",
".",
"getenv",
"(",
"ENCRYPTED_KEY_ENV",
")",
"encrypted_iv",
"=",
"os",
".",
"getenv",
"(",
"ENCRYPTED_INIT_VECTOR_ENV",
")",
"out_file",
"=",
"os",
".",
"getenv",
"(",
"CREDENTIALS",
")",
"subprocess",
".",
"call",
"(",
"[",
"'openssl'",
",",
"'aes-256-cbc'",
",",
"'-K'",
",",
"encrypted_key",
",",
"'-iv'",
",",
"encrypted_iv",
",",
"'-in'",
",",
"ENCRYPTED_KEYFILE",
",",
"'-out'",
",",
"out_file",
",",
"'-d'",
"]",
")"
] | decrypt a keyfile . | train | false |
17,778 | def naf(n):
while n:
z = ((2 - (n % 4)) if (n & 1) else 0)
n = ((n - z) // 2)
(yield z)
| [
"def",
"naf",
"(",
"n",
")",
":",
"while",
"n",
":",
"z",
"=",
"(",
"(",
"2",
"-",
"(",
"n",
"%",
"4",
")",
")",
"if",
"(",
"n",
"&",
"1",
")",
"else",
"0",
")",
"n",
"=",
"(",
"(",
"n",
"-",
"z",
")",
"//",
"2",
")",
"(",
"yield",
"z",
")"
] | naf -> int generator returns a generator for the non-adjacent form of a number . | train | false |
17,779 | def _get_connection():
global COUCHBASE_CONN
if (COUCHBASE_CONN is None):
opts = _get_options()
if opts['password']:
COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'], password=opts['password'])
else:
COUCHBASE_CONN = couchbase.Couchbase.connect(host=opts['host'], port=opts['port'], bucket=opts['bucket'])
return COUCHBASE_CONN
| [
"def",
"_get_connection",
"(",
")",
":",
"global",
"COUCHBASE_CONN",
"if",
"(",
"COUCHBASE_CONN",
"is",
"None",
")",
":",
"opts",
"=",
"_get_options",
"(",
")",
"if",
"opts",
"[",
"'password'",
"]",
":",
"COUCHBASE_CONN",
"=",
"couchbase",
".",
"Couchbase",
".",
"connect",
"(",
"host",
"=",
"opts",
"[",
"'host'",
"]",
",",
"port",
"=",
"opts",
"[",
"'port'",
"]",
",",
"bucket",
"=",
"opts",
"[",
"'bucket'",
"]",
",",
"password",
"=",
"opts",
"[",
"'password'",
"]",
")",
"else",
":",
"COUCHBASE_CONN",
"=",
"couchbase",
".",
"Couchbase",
".",
"connect",
"(",
"host",
"=",
"opts",
"[",
"'host'",
"]",
",",
"port",
"=",
"opts",
"[",
"'port'",
"]",
",",
"bucket",
"=",
"opts",
"[",
"'bucket'",
"]",
")",
"return",
"COUCHBASE_CONN"
] | global function to access the couchbase connection . | train | true |
17,780 | def _compute_host(host, instance):
if host:
return host
if (not instance):
raise exception.NovaException(_('No compute host specified'))
if (not instance.host):
raise exception.NovaException((_('Unable to find host for Instance %s') % instance.uuid))
return instance.host
| [
"def",
"_compute_host",
"(",
"host",
",",
"instance",
")",
":",
"if",
"host",
":",
"return",
"host",
"if",
"(",
"not",
"instance",
")",
":",
"raise",
"exception",
".",
"NovaException",
"(",
"_",
"(",
"'No compute host specified'",
")",
")",
"if",
"(",
"not",
"instance",
".",
"host",
")",
":",
"raise",
"exception",
".",
"NovaException",
"(",
"(",
"_",
"(",
"'Unable to find host for Instance %s'",
")",
"%",
"instance",
".",
"uuid",
")",
")",
"return",
"instance",
".",
"host"
] | get the destination host for a message . | train | false |
17,782 | def Win32Input(prompt=None):
return eval(input(prompt))
| [
"def",
"Win32Input",
"(",
"prompt",
"=",
"None",
")",
":",
"return",
"eval",
"(",
"input",
"(",
"prompt",
")",
")"
] | provide input() for gui apps . | train | false |
17,783 | def utf8_keys(dictionary):
return dict([(key.encode('utf8'), val) for (key, val) in dictionary.items()])
| [
"def",
"utf8_keys",
"(",
"dictionary",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"key",
".",
"encode",
"(",
"'utf8'",
")",
",",
"val",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"dictionary",
".",
"items",
"(",
")",
"]",
")"
] | convert dictionary keys to utf8-encoded strings for mapnik . | train | false |
17,784 | def filter_users_by_email(email):
from .models import EmailAddress
User = get_user_model()
mails = EmailAddress.objects.filter(email__iexact=email)
users = [e.user for e in mails.prefetch_related('user')]
if app_settings.USER_MODEL_EMAIL_FIELD:
q_dict = {(app_settings.USER_MODEL_EMAIL_FIELD + '__iexact'): email}
users += list(User.objects.filter(**q_dict))
return list(set(users))
| [
"def",
"filter_users_by_email",
"(",
"email",
")",
":",
"from",
".",
"models",
"import",
"EmailAddress",
"User",
"=",
"get_user_model",
"(",
")",
"mails",
"=",
"EmailAddress",
".",
"objects",
".",
"filter",
"(",
"email__iexact",
"=",
"email",
")",
"users",
"=",
"[",
"e",
".",
"user",
"for",
"e",
"in",
"mails",
".",
"prefetch_related",
"(",
"'user'",
")",
"]",
"if",
"app_settings",
".",
"USER_MODEL_EMAIL_FIELD",
":",
"q_dict",
"=",
"{",
"(",
"app_settings",
".",
"USER_MODEL_EMAIL_FIELD",
"+",
"'__iexact'",
")",
":",
"email",
"}",
"users",
"+=",
"list",
"(",
"User",
".",
"objects",
".",
"filter",
"(",
"**",
"q_dict",
")",
")",
"return",
"list",
"(",
"set",
"(",
"users",
")",
")"
] | return list of users by email address typically one . | train | true |
17,787 | def _param_from_config(key, data):
param = {}
if isinstance(data, dict):
for (k, v) in six.iteritems(data):
param.update(_param_from_config('{0}.{1}'.format(key, k), v))
elif (isinstance(data, list) or isinstance(data, tuple)):
for (idx, conf_item) in enumerate(data):
prefix = '{0}.{1}'.format(key, idx)
param.update(_param_from_config(prefix, conf_item))
elif isinstance(data, bool):
param.update({key: str(data).lower()})
else:
param.update({key: data})
return param
| [
"def",
"_param_from_config",
"(",
"key",
",",
"data",
")",
":",
"param",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"data",
")",
":",
"param",
".",
"update",
"(",
"_param_from_config",
"(",
"'{0}.{1}'",
".",
"format",
"(",
"key",
",",
"k",
")",
",",
"v",
")",
")",
"elif",
"(",
"isinstance",
"(",
"data",
",",
"list",
")",
"or",
"isinstance",
"(",
"data",
",",
"tuple",
")",
")",
":",
"for",
"(",
"idx",
",",
"conf_item",
")",
"in",
"enumerate",
"(",
"data",
")",
":",
"prefix",
"=",
"'{0}.{1}'",
".",
"format",
"(",
"key",
",",
"idx",
")",
"param",
".",
"update",
"(",
"_param_from_config",
"(",
"prefix",
",",
"conf_item",
")",
")",
"elif",
"isinstance",
"(",
"data",
",",
"bool",
")",
":",
"param",
".",
"update",
"(",
"{",
"key",
":",
"str",
"(",
"data",
")",
".",
"lower",
"(",
")",
"}",
")",
"else",
":",
"param",
".",
"update",
"(",
"{",
"key",
":",
"data",
"}",
")",
"return",
"param"
] | return ec2 api parameters based on the given config data . | train | true |
17,788 | def test_singleton():
AreEqual((frozenset([]) is frozenset([])), True)
x = frozenset([1, 2, 3])
AreEqual((x is frozenset(x)), True)
| [
"def",
"test_singleton",
"(",
")",
":",
"AreEqual",
"(",
"(",
"frozenset",
"(",
"[",
"]",
")",
"is",
"frozenset",
"(",
"[",
"]",
")",
")",
",",
"True",
")",
"x",
"=",
"frozenset",
"(",
"[",
"1",
",",
"2",
",",
"3",
"]",
")",
"AreEqual",
"(",
"(",
"x",
"is",
"frozenset",
"(",
"x",
")",
")",
",",
"True",
")"
] | verify that an empty frozenset is a singleton . | train | false |
17,789 | def getFirstChildElementByTagName(self, tagName):
for child in self.childNodes:
if isinstance(child, Element):
if (child.tagName == tagName):
return child
return None
| [
"def",
"getFirstChildElementByTagName",
"(",
"self",
",",
"tagName",
")",
":",
"for",
"child",
"in",
"self",
".",
"childNodes",
":",
"if",
"isinstance",
"(",
"child",
",",
"Element",
")",
":",
"if",
"(",
"child",
".",
"tagName",
"==",
"tagName",
")",
":",
"return",
"child",
"return",
"None"
] | return the first element of type tagname if found . | train | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.