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 |
|---|---|---|---|---|---|
22,422 | def _service_disco_configs(agentConfig):
if (agentConfig.get('service_discovery') and (agentConfig.get('service_discovery_backend') in SD_BACKENDS)):
try:
log.info('Fetching service discovery check configurations.')
sd_backend = get_sd_backend(agentConfig=agentConfig)
service_disco_configs = sd_backend.get_configs()
except Exception:
log.exception('Loading service discovery configurations failed.')
return {}
else:
service_disco_configs = {}
return service_disco_configs
| [
"def",
"_service_disco_configs",
"(",
"agentConfig",
")",
":",
"if",
"(",
"agentConfig",
".",
"get",
"(",
"'service_discovery'",
")",
"and",
"(",
"agentConfig",
".",
"get",
"(",
"'service_discovery_backend'",
")",
"in",
"SD_BACKENDS",
")",
")",
":",
"try",
":",
"log",
".",
"info",
"(",
"'Fetching service discovery check configurations.'",
")",
"sd_backend",
"=",
"get_sd_backend",
"(",
"agentConfig",
"=",
"agentConfig",
")",
"service_disco_configs",
"=",
"sd_backend",
".",
"get_configs",
"(",
")",
"except",
"Exception",
":",
"log",
".",
"exception",
"(",
"'Loading service discovery configurations failed.'",
")",
"return",
"{",
"}",
"else",
":",
"service_disco_configs",
"=",
"{",
"}",
"return",
"service_disco_configs"
] | retrieve all the service disco configs and return their conf dicts . | train | false |
22,423 | def expanduser(path):
return path
| [
"def",
"expanduser",
"(",
"path",
")",
":",
"return",
"path"
] | expand ~ and ~user constructions . | train | false |
22,424 | @decorators.memoize
def _check_fmadm():
return salt.utils.which('fmadm')
| [
"@",
"decorators",
".",
"memoize",
"def",
"_check_fmadm",
"(",
")",
":",
"return",
"salt",
".",
"utils",
".",
"which",
"(",
"'fmadm'",
")"
] | looks to see if fmadm is present on the system . | train | false |
22,425 | def check_basic_auth(user, passwd):
auth = request.authorization
return (auth and (auth.username == user) and (auth.password == passwd))
| [
"def",
"check_basic_auth",
"(",
"user",
",",
"passwd",
")",
":",
"auth",
"=",
"request",
".",
"authorization",
"return",
"(",
"auth",
"and",
"(",
"auth",
".",
"username",
"==",
"user",
")",
"and",
"(",
"auth",
".",
"password",
"==",
"passwd",
")",
")"
] | checks user authentication using http basic auth . | train | true |
22,426 | def get_matroska_specs(webm_only=False):
specs = {}
with resource_stream(__name__, 'specs/matroska.xml') as resource:
xmldoc = minidom.parse(resource)
for element in xmldoc.getElementsByTagName('element'):
if ((not webm_only) or (element.hasAttribute('webm') and (element.getAttribute('webm') == '1'))):
specs[int(element.getAttribute('id'), 16)] = (SPEC_TYPES[element.getAttribute('type')], element.getAttribute('name'), int(element.getAttribute('level')))
return specs
| [
"def",
"get_matroska_specs",
"(",
"webm_only",
"=",
"False",
")",
":",
"specs",
"=",
"{",
"}",
"with",
"resource_stream",
"(",
"__name__",
",",
"'specs/matroska.xml'",
")",
"as",
"resource",
":",
"xmldoc",
"=",
"minidom",
".",
"parse",
"(",
"resource",
")",
"for",
"element",
"in",
"xmldoc",
".",
"getElementsByTagName",
"(",
"'element'",
")",
":",
"if",
"(",
"(",
"not",
"webm_only",
")",
"or",
"(",
"element",
".",
"hasAttribute",
"(",
"'webm'",
")",
"and",
"(",
"element",
".",
"getAttribute",
"(",
"'webm'",
")",
"==",
"'1'",
")",
")",
")",
":",
"specs",
"[",
"int",
"(",
"element",
".",
"getAttribute",
"(",
"'id'",
")",
",",
"16",
")",
"]",
"=",
"(",
"SPEC_TYPES",
"[",
"element",
".",
"getAttribute",
"(",
"'type'",
")",
"]",
",",
"element",
".",
"getAttribute",
"(",
"'name'",
")",
",",
"int",
"(",
"element",
".",
"getAttribute",
"(",
"'level'",
")",
")",
")",
"return",
"specs"
] | get the matroska specs . | train | false |
22,428 | def _deserialize_dependencies(artifact_type, deps_from_db, artifact_properties, plugins):
for (dep_name, dep_value) in six.iteritems(deps_from_db):
if (not dep_value):
continue
if isinstance(artifact_type.metadata.attributes.dependencies.get(dep_name), declarative.ListAttributeDefinition):
val = []
for v in dep_value:
val.append(deserialize_from_db(v, plugins))
elif (len(dep_value) == 1):
val = deserialize_from_db(dep_value[0], plugins)
else:
raise exception.InvalidArtifactPropertyValue(message=_('Relation %(name)s may not have multiple values'), name=dep_name)
artifact_properties[dep_name] = val
| [
"def",
"_deserialize_dependencies",
"(",
"artifact_type",
",",
"deps_from_db",
",",
"artifact_properties",
",",
"plugins",
")",
":",
"for",
"(",
"dep_name",
",",
"dep_value",
")",
"in",
"six",
".",
"iteritems",
"(",
"deps_from_db",
")",
":",
"if",
"(",
"not",
"dep_value",
")",
":",
"continue",
"if",
"isinstance",
"(",
"artifact_type",
".",
"metadata",
".",
"attributes",
".",
"dependencies",
".",
"get",
"(",
"dep_name",
")",
",",
"declarative",
".",
"ListAttributeDefinition",
")",
":",
"val",
"=",
"[",
"]",
"for",
"v",
"in",
"dep_value",
":",
"val",
".",
"append",
"(",
"deserialize_from_db",
"(",
"v",
",",
"plugins",
")",
")",
"elif",
"(",
"len",
"(",
"dep_value",
")",
"==",
"1",
")",
":",
"val",
"=",
"deserialize_from_db",
"(",
"dep_value",
"[",
"0",
"]",
",",
"plugins",
")",
"else",
":",
"raise",
"exception",
".",
"InvalidArtifactPropertyValue",
"(",
"message",
"=",
"_",
"(",
"'Relation %(name)s may not have multiple values'",
")",
",",
"name",
"=",
"dep_name",
")",
"artifact_properties",
"[",
"dep_name",
"]",
"=",
"val"
] | retrieves dependencies from database . | train | false |
22,429 | def regexp_span_tokenize(s, regexp):
left = 0
for m in finditer(regexp, s):
(right, next) = m.span()
if (right != left):
(yield (left, right))
left = next
(yield (left, len(s)))
| [
"def",
"regexp_span_tokenize",
"(",
"s",
",",
"regexp",
")",
":",
"left",
"=",
"0",
"for",
"m",
"in",
"finditer",
"(",
"regexp",
",",
"s",
")",
":",
"(",
"right",
",",
"next",
")",
"=",
"m",
".",
"span",
"(",
")",
"if",
"(",
"right",
"!=",
"left",
")",
":",
"(",
"yield",
"(",
"left",
",",
"right",
")",
")",
"left",
"=",
"next",
"(",
"yield",
"(",
"left",
",",
"len",
"(",
"s",
")",
")",
")"
] | return the offsets of the tokens in *s* . | train | false |
22,430 | def qmf(hk):
N = (len(hk) - 1)
asgn = [{0: 1, 1: (-1)}[(k % 2)] for k in range((N + 1))]
return (hk[::(-1)] * np.array(asgn))
| [
"def",
"qmf",
"(",
"hk",
")",
":",
"N",
"=",
"(",
"len",
"(",
"hk",
")",
"-",
"1",
")",
"asgn",
"=",
"[",
"{",
"0",
":",
"1",
",",
"1",
":",
"(",
"-",
"1",
")",
"}",
"[",
"(",
"k",
"%",
"2",
")",
"]",
"for",
"k",
"in",
"range",
"(",
"(",
"N",
"+",
"1",
")",
")",
"]",
"return",
"(",
"hk",
"[",
":",
":",
"(",
"-",
"1",
")",
"]",
"*",
"np",
".",
"array",
"(",
"asgn",
")",
")"
] | return high-pass qmf filter from low-pass parameters hk : array_like coefficients of high-pass filter . | train | false |
22,431 | def get_cache():
return requests.Session().cache
| [
"def",
"get_cache",
"(",
")",
":",
"return",
"requests",
".",
"Session",
"(",
")",
".",
"cache"
] | returns the storage for caching block structures . | train | false |
22,432 | def test_solve_args():
with nose.tools.assert_raises(ValueError):
(t0, k0) = (0, np.array([5.0]))
model.solve(t0, k0, g=_termination_condition)
| [
"def",
"test_solve_args",
"(",
")",
":",
"with",
"nose",
".",
"tools",
".",
"assert_raises",
"(",
"ValueError",
")",
":",
"(",
"t0",
",",
"k0",
")",
"=",
"(",
"0",
",",
"np",
".",
"array",
"(",
"[",
"5.0",
"]",
")",
")",
"model",
".",
"solve",
"(",
"t0",
",",
"k0",
",",
"g",
"=",
"_termination_condition",
")"
] | testing arguments passed to the ivp . | train | false |
22,434 | def sortedJSONDumpS(obj):
itemStrs = []
if isinstance(obj, dict):
items = obj.items()
items.sort()
for (key, value) in items:
itemStrs.append(('%s: %s' % (json.dumps(key), sortedJSONDumpS(value))))
return ('{%s}' % ', '.join(itemStrs))
elif hasattr(obj, '__iter__'):
for val in obj:
itemStrs.append(sortedJSONDumpS(val))
return ('[%s]' % ', '.join(itemStrs))
else:
return json.dumps(obj)
| [
"def",
"sortedJSONDumpS",
"(",
"obj",
")",
":",
"itemStrs",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"items",
"=",
"obj",
".",
"items",
"(",
")",
"items",
".",
"sort",
"(",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"items",
":",
"itemStrs",
".",
"append",
"(",
"(",
"'%s: %s'",
"%",
"(",
"json",
".",
"dumps",
"(",
"key",
")",
",",
"sortedJSONDumpS",
"(",
"value",
")",
")",
")",
")",
"return",
"(",
"'{%s}'",
"%",
"', '",
".",
"join",
"(",
"itemStrs",
")",
")",
"elif",
"hasattr",
"(",
"obj",
",",
"'__iter__'",
")",
":",
"for",
"val",
"in",
"obj",
":",
"itemStrs",
".",
"append",
"(",
"sortedJSONDumpS",
"(",
"val",
")",
")",
"return",
"(",
"'[%s]'",
"%",
"', '",
".",
"join",
"(",
"itemStrs",
")",
")",
"else",
":",
"return",
"json",
".",
"dumps",
"(",
"obj",
")"
] | return a json representation of obj with sorted keys on any embedded dicts . | train | true |
22,437 | def expand_pattern(string):
(lead, pattern, remnant) = re.split(EXPANSION_PATTERN, string, maxsplit=1)
(x, y) = pattern.split('-')
for i in range(int(x), (int(y) + 1)):
if remnant:
for string in expand_pattern(remnant):
(yield '{0}{1}{2}'.format(lead, i, string))
else:
(yield '{0}{1}'.format(lead, i))
| [
"def",
"expand_pattern",
"(",
"string",
")",
":",
"(",
"lead",
",",
"pattern",
",",
"remnant",
")",
"=",
"re",
".",
"split",
"(",
"EXPANSION_PATTERN",
",",
"string",
",",
"maxsplit",
"=",
"1",
")",
"(",
"x",
",",
"y",
")",
"=",
"pattern",
".",
"split",
"(",
"'-'",
")",
"for",
"i",
"in",
"range",
"(",
"int",
"(",
"x",
")",
",",
"(",
"int",
"(",
"y",
")",
"+",
"1",
")",
")",
":",
"if",
"remnant",
":",
"for",
"string",
"in",
"expand_pattern",
"(",
"remnant",
")",
":",
"(",
"yield",
"'{0}{1}{2}'",
".",
"format",
"(",
"lead",
",",
"i",
",",
"string",
")",
")",
"else",
":",
"(",
"yield",
"'{0}{1}'",
".",
"format",
"(",
"lead",
",",
"i",
")",
")"
] | expand a numeric pattern into a list of strings . | train | false |
22,438 | def _scan_sr(session, sr_ref=None):
if sr_ref:
LOG.debug(_('Re-scanning SR %s'), sr_ref)
session.call_xenapi('SR.scan', sr_ref)
| [
"def",
"_scan_sr",
"(",
"session",
",",
"sr_ref",
"=",
"None",
")",
":",
"if",
"sr_ref",
":",
"LOG",
".",
"debug",
"(",
"_",
"(",
"'Re-scanning SR %s'",
")",
",",
"sr_ref",
")",
"session",
".",
"call_xenapi",
"(",
"'SR.scan'",
",",
"sr_ref",
")"
] | scans the sr specified by sr_ref . | train | false |
22,439 | def is_valid_ipv4_address(address):
if (not isinstance(address, (bytes, str_type))):
return False
if (address.count('.') != 3):
return False
for entry in address.split('.'):
if ((not entry.isdigit()) or (int(entry) < 0) or (int(entry) > 255)):
return False
elif ((entry[0] == '0') and (len(entry) > 1)):
return False
return True
| [
"def",
"is_valid_ipv4_address",
"(",
"address",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"address",
",",
"(",
"bytes",
",",
"str_type",
")",
")",
")",
":",
"return",
"False",
"if",
"(",
"address",
".",
"count",
"(",
"'.'",
")",
"!=",
"3",
")",
":",
"return",
"False",
"for",
"entry",
"in",
"address",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"(",
"(",
"not",
"entry",
".",
"isdigit",
"(",
")",
")",
"or",
"(",
"int",
"(",
"entry",
")",
"<",
"0",
")",
"or",
"(",
"int",
"(",
"entry",
")",
">",
"255",
")",
")",
":",
"return",
"False",
"elif",
"(",
"(",
"entry",
"[",
"0",
"]",
"==",
"'0'",
")",
"and",
"(",
"len",
"(",
"entry",
")",
">",
"1",
")",
")",
":",
"return",
"False",
"return",
"True"
] | checks if a string is a valid ipv4 address . | train | false |
22,440 | @cli.command('resize')
@click.option('-w', '--width', type=int, help='The new width of the image.')
@click.option('-h', '--height', type=int, help='The new height of the image.')
@processor
def resize_cmd(images, width, height):
for image in images:
(w, h) = ((width or image.size[0]), (height or image.size[1]))
click.echo(('Resizing "%s" to %dx%d' % (image.filename, w, h)))
image.thumbnail((w, h))
(yield image)
| [
"@",
"cli",
".",
"command",
"(",
"'resize'",
")",
"@",
"click",
".",
"option",
"(",
"'-w'",
",",
"'--width'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'The new width of the image.'",
")",
"@",
"click",
".",
"option",
"(",
"'-h'",
",",
"'--height'",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'The new height of the image.'",
")",
"@",
"processor",
"def",
"resize_cmd",
"(",
"images",
",",
"width",
",",
"height",
")",
":",
"for",
"image",
"in",
"images",
":",
"(",
"w",
",",
"h",
")",
"=",
"(",
"(",
"width",
"or",
"image",
".",
"size",
"[",
"0",
"]",
")",
",",
"(",
"height",
"or",
"image",
".",
"size",
"[",
"1",
"]",
")",
")",
"click",
".",
"echo",
"(",
"(",
"'Resizing \"%s\" to %dx%d'",
"%",
"(",
"image",
".",
"filename",
",",
"w",
",",
"h",
")",
")",
")",
"image",
".",
"thumbnail",
"(",
"(",
"w",
",",
"h",
")",
")",
"(",
"yield",
"image",
")"
] | resizes an image by fitting it into the box without changing the aspect ratio . | train | false |
22,441 | def splitdrive(p):
return ('', p)
| [
"def",
"splitdrive",
"(",
"p",
")",
":",
"return",
"(",
"''",
",",
"p",
")"
] | split a pathname into a drive specification and the rest of the path . | train | false |
22,442 | def quadrature(func, a, b, args=(), tol=1.49e-08, rtol=1.49e-08, maxiter=50, vec_func=True, miniter=1):
if (not isinstance(args, tuple)):
args = (args,)
vfunc = vectorize1(func, args, vec_func=vec_func)
val = np.inf
err = np.inf
maxiter = max((miniter + 1), maxiter)
for n in xrange(miniter, (maxiter + 1)):
newval = fixed_quad(vfunc, a, b, (), n)[0]
err = abs((newval - val))
val = newval
if ((err < tol) or (err < (rtol * abs(val)))):
break
else:
warnings.warn(('maxiter (%d) exceeded. Latest difference = %e' % (maxiter, err)), AccuracyWarning)
return (val, err)
| [
"def",
"quadrature",
"(",
"func",
",",
"a",
",",
"b",
",",
"args",
"=",
"(",
")",
",",
"tol",
"=",
"1.49e-08",
",",
"rtol",
"=",
"1.49e-08",
",",
"maxiter",
"=",
"50",
",",
"vec_func",
"=",
"True",
",",
"miniter",
"=",
"1",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"args",
",",
"tuple",
")",
")",
":",
"args",
"=",
"(",
"args",
",",
")",
"vfunc",
"=",
"vectorize1",
"(",
"func",
",",
"args",
",",
"vec_func",
"=",
"vec_func",
")",
"val",
"=",
"np",
".",
"inf",
"err",
"=",
"np",
".",
"inf",
"maxiter",
"=",
"max",
"(",
"(",
"miniter",
"+",
"1",
")",
",",
"maxiter",
")",
"for",
"n",
"in",
"xrange",
"(",
"miniter",
",",
"(",
"maxiter",
"+",
"1",
")",
")",
":",
"newval",
"=",
"fixed_quad",
"(",
"vfunc",
",",
"a",
",",
"b",
",",
"(",
")",
",",
"n",
")",
"[",
"0",
"]",
"err",
"=",
"abs",
"(",
"(",
"newval",
"-",
"val",
")",
")",
"val",
"=",
"newval",
"if",
"(",
"(",
"err",
"<",
"tol",
")",
"or",
"(",
"err",
"<",
"(",
"rtol",
"*",
"abs",
"(",
"val",
")",
")",
")",
")",
":",
"break",
"else",
":",
"warnings",
".",
"warn",
"(",
"(",
"'maxiter (%d) exceeded. Latest difference = %e'",
"%",
"(",
"maxiter",
",",
"err",
")",
")",
",",
"AccuracyWarning",
")",
"return",
"(",
"val",
",",
"err",
")"
] | compute a definite integral using fixed-tolerance gaussian quadrature . | train | false |
22,443 | def _square_image(img):
width = img.size[0]
return _crop_image_vertically(img, width)
| [
"def",
"_square_image",
"(",
"img",
")",
":",
"width",
"=",
"img",
".",
"size",
"[",
"0",
"]",
"return",
"_crop_image_vertically",
"(",
"img",
",",
"width",
")"
] | if the image is taller than it is wide . | train | false |
22,446 | def update_to_dict_cache(changed_messages):
items_for_remote_cache = {}
message_ids = []
for changed_message in changed_messages:
message_ids.append(changed_message.id)
items_for_remote_cache[to_dict_cache_key(changed_message, True)] = (MessageDict.to_dict_uncached(changed_message, apply_markdown=True),)
items_for_remote_cache[to_dict_cache_key(changed_message, False)] = (MessageDict.to_dict_uncached(changed_message, apply_markdown=False),)
cache_set_many(items_for_remote_cache)
return message_ids
| [
"def",
"update_to_dict_cache",
"(",
"changed_messages",
")",
":",
"items_for_remote_cache",
"=",
"{",
"}",
"message_ids",
"=",
"[",
"]",
"for",
"changed_message",
"in",
"changed_messages",
":",
"message_ids",
".",
"append",
"(",
"changed_message",
".",
"id",
")",
"items_for_remote_cache",
"[",
"to_dict_cache_key",
"(",
"changed_message",
",",
"True",
")",
"]",
"=",
"(",
"MessageDict",
".",
"to_dict_uncached",
"(",
"changed_message",
",",
"apply_markdown",
"=",
"True",
")",
",",
")",
"items_for_remote_cache",
"[",
"to_dict_cache_key",
"(",
"changed_message",
",",
"False",
")",
"]",
"=",
"(",
"MessageDict",
".",
"to_dict_uncached",
"(",
"changed_message",
",",
"apply_markdown",
"=",
"False",
")",
",",
")",
"cache_set_many",
"(",
"items_for_remote_cache",
")",
"return",
"message_ids"
] | updates the message as stored in the to_dict cache . | train | false |
22,448 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get the repository constructor . | train | false |
22,451 | @magic_arguments()
@argument('-f', '--foo', help='an argument')
def magic_foo1(self, args):
return parse_argstring(magic_foo1, args)
| [
"@",
"magic_arguments",
"(",
")",
"@",
"argument",
"(",
"'-f'",
",",
"'--foo'",
",",
"help",
"=",
"'an argument'",
")",
"def",
"magic_foo1",
"(",
"self",
",",
"args",
")",
":",
"return",
"parse_argstring",
"(",
"magic_foo1",
",",
"args",
")"
] | a docstring . | train | false |
22,452 | def set_disk_timeout(timeout, power='ac', scheme=None):
return _set_powercfg_value(scheme, 'SUB_DISK', 'DISKIDLE', power, timeout)
| [
"def",
"set_disk_timeout",
"(",
"timeout",
",",
"power",
"=",
"'ac'",
",",
"scheme",
"=",
"None",
")",
":",
"return",
"_set_powercfg_value",
"(",
"scheme",
",",
"'SUB_DISK'",
",",
"'DISKIDLE'",
",",
"power",
",",
"timeout",
")"
] | set the disk timeout in minutes for the given power scheme cli example: . | train | false |
22,453 | def test_camera():
cameraman = data.camera()
assert_equal(cameraman.ndim, 2)
| [
"def",
"test_camera",
"(",
")",
":",
"cameraman",
"=",
"data",
".",
"camera",
"(",
")",
"assert_equal",
"(",
"cameraman",
".",
"ndim",
",",
"2",
")"
] | test that "camera" image can be loaded . | train | false |
22,454 | def dashboard_absent(name, hosts=None, profile='grafana'):
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
(hosts, index) = _parse_profile(profile)
if (not index):
raise SaltInvocationError('index is a required key in the profile.')
exists = __salt__['elasticsearch.exists'](index=index, id=name, doc_type='dashboard', hosts=hosts)
if exists:
if __opts__['test']:
ret['comment'] = 'Dashboard {0} is set to be removed.'.format(name)
return ret
deleted = __salt__['elasticsearch.delete'](index=index, doc_type='dashboard', id=name, hosts=hosts)
if deleted:
ret['result'] = True
ret['changes']['old'] = name
ret['changes']['new'] = None
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} dashboard.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Dashboard {0} does not exist.'.format(name)
return ret
| [
"def",
"dashboard_absent",
"(",
"name",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"'grafana'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"(",
"hosts",
",",
"index",
")",
"=",
"_parse_profile",
"(",
"profile",
")",
"if",
"(",
"not",
"index",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'index is a required key in the profile.'",
")",
"exists",
"=",
"__salt__",
"[",
"'elasticsearch.exists'",
"]",
"(",
"index",
"=",
"index",
",",
"id",
"=",
"name",
",",
"doc_type",
"=",
"'dashboard'",
",",
"hosts",
"=",
"hosts",
")",
"if",
"exists",
":",
"if",
"__opts__",
"[",
"'test'",
"]",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Dashboard {0} is set to be removed.'",
".",
"format",
"(",
"name",
")",
"return",
"ret",
"deleted",
"=",
"__salt__",
"[",
"'elasticsearch.delete'",
"]",
"(",
"index",
"=",
"index",
",",
"doc_type",
"=",
"'dashboard'",
",",
"id",
"=",
"name",
",",
"hosts",
"=",
"hosts",
")",
"if",
"deleted",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'changes'",
"]",
"[",
"'old'",
"]",
"=",
"name",
"ret",
"[",
"'changes'",
"]",
"[",
"'new'",
"]",
"=",
"None",
"else",
":",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"ret",
"[",
"'comment'",
"]",
"=",
"'Failed to delete {0} dashboard.'",
".",
"format",
"(",
"name",
")",
"else",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"'Dashboard {0} does not exist.'",
".",
"format",
"(",
"name",
")",
"return",
"ret"
] | ensure the named grafana dashboard is deleted . | train | true |
22,455 | def test_distance_in_coordinates():
ra = Longitude(u'4:08:15.162342', unit=u.hour)
dec = Latitude(u'-41:08:15.162342', unit=u.degree)
coo = ICRS(ra, dec, distance=(2 * u.kpc))
cart = coo.cartesian
assert isinstance(cart.xyz, u.Quantity)
| [
"def",
"test_distance_in_coordinates",
"(",
")",
":",
"ra",
"=",
"Longitude",
"(",
"u'4:08:15.162342'",
",",
"unit",
"=",
"u",
".",
"hour",
")",
"dec",
"=",
"Latitude",
"(",
"u'-41:08:15.162342'",
",",
"unit",
"=",
"u",
".",
"degree",
")",
"coo",
"=",
"ICRS",
"(",
"ra",
",",
"dec",
",",
"distance",
"=",
"(",
"2",
"*",
"u",
".",
"kpc",
")",
")",
"cart",
"=",
"coo",
".",
"cartesian",
"assert",
"isinstance",
"(",
"cart",
".",
"xyz",
",",
"u",
".",
"Quantity",
")"
] | test that distances can be created from quantities and that cartesian representations come out right . | train | false |
22,457 | @pytest.mark.parametrize('parallel', [True, False])
def test_include_exclude_names(parallel, read_basic):
text = '\nA B C D E F G H\n1 2 3 4 5 6 7 8\n9 10 11 12 13 14 15 16\n'
table = read_basic(text, include_names=['A', 'B', 'D', 'F', 'H'], exclude_names=['B', 'F'], parallel=parallel)
expected = Table([[1, 9], [4, 12], [8, 16]], names=('A', 'D', 'H'))
assert_table_equal(table, expected)
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'parallel'",
",",
"[",
"True",
",",
"False",
"]",
")",
"def",
"test_include_exclude_names",
"(",
"parallel",
",",
"read_basic",
")",
":",
"text",
"=",
"'\\nA B C D E F G H\\n1 2 3 4 5 6 7 8\\n9 10 11 12 13 14 15 16\\n'",
"table",
"=",
"read_basic",
"(",
"text",
",",
"include_names",
"=",
"[",
"'A'",
",",
"'B'",
",",
"'D'",
",",
"'F'",
",",
"'H'",
"]",
",",
"exclude_names",
"=",
"[",
"'B'",
",",
"'F'",
"]",
",",
"parallel",
"=",
"parallel",
")",
"expected",
"=",
"Table",
"(",
"[",
"[",
"1",
",",
"9",
"]",
",",
"[",
"4",
",",
"12",
"]",
",",
"[",
"8",
",",
"16",
"]",
"]",
",",
"names",
"=",
"(",
"'A'",
",",
"'D'",
",",
"'H'",
")",
")",
"assert_table_equal",
"(",
"table",
",",
"expected",
")"
] | make sure that include_names is applied before exclude_names if both are specified . | train | false |
22,459 | def reset():
_runtime.reset()
| [
"def",
"reset",
"(",
")",
":",
"_runtime",
".",
"reset",
"(",
")"
] | clear root modules database . | train | false |
22,460 | def _compute_singular_values(a):
raise NotImplementedError
| [
"def",
"_compute_singular_values",
"(",
"a",
")",
":",
"raise",
"NotImplementedError"
] | compute singular values of *a* . | train | false |
22,461 | def api_exists(name, description=None, region=None, key=None, keyid=None, profile=None):
apis = _find_apis_by_name(name, description=description, region=region, key=key, keyid=keyid, profile=profile)
return {'exists': bool(apis.get('restapi'))}
| [
"def",
"api_exists",
"(",
"name",
",",
"description",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"apis",
"=",
"_find_apis_by_name",
"(",
"name",
",",
"description",
"=",
"description",
",",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"return",
"{",
"'exists'",
":",
"bool",
"(",
"apis",
".",
"get",
"(",
"'restapi'",
")",
")",
"}"
] | check to see if the given rest api name and optionlly description exists . | train | true |
22,462 | def check_pack_content_directory_exists(pack, content_type):
packs_base_paths = get_packs_base_paths()
for base_dir in packs_base_paths:
pack_content_pack = os.path.join(base_dir, pack, content_type)
if os.path.exists(pack_content_pack):
return True
return False
| [
"def",
"check_pack_content_directory_exists",
"(",
"pack",
",",
"content_type",
")",
":",
"packs_base_paths",
"=",
"get_packs_base_paths",
"(",
")",
"for",
"base_dir",
"in",
"packs_base_paths",
":",
"pack_content_pack",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_dir",
",",
"pack",
",",
"content_type",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"pack_content_pack",
")",
":",
"return",
"True",
"return",
"False"
] | check if a provided pack exists in one of the pack paths . | train | false |
22,466 | def PiVersion():
with open('/proc/cpuinfo', 'r') as f:
cpu_count = sum([1 for x in f.readlines() if x.startswith('processor')])
if (cpu_count == 1):
return 'PiB'
else:
return 'Pi2'
| [
"def",
"PiVersion",
"(",
")",
":",
"with",
"open",
"(",
"'/proc/cpuinfo'",
",",
"'r'",
")",
"as",
"f",
":",
"cpu_count",
"=",
"sum",
"(",
"[",
"1",
"for",
"x",
"in",
"f",
".",
"readlines",
"(",
")",
"if",
"x",
".",
"startswith",
"(",
"'processor'",
")",
"]",
")",
"if",
"(",
"cpu_count",
"==",
"1",
")",
":",
"return",
"'PiB'",
"else",
":",
"return",
"'Pi2'"
] | determines the version of pi currently being used . | train | false |
22,467 | def _get_vm_ref_from_name(session, vm_name):
vms = session._call_method(vim_util, 'get_objects', 'VirtualMachine', ['name'])
return _get_object_from_results(session, vms, vm_name, _get_object_for_value)
| [
"def",
"_get_vm_ref_from_name",
"(",
"session",
",",
"vm_name",
")",
":",
"vms",
"=",
"session",
".",
"_call_method",
"(",
"vim_util",
",",
"'get_objects'",
",",
"'VirtualMachine'",
",",
"[",
"'name'",
"]",
")",
"return",
"_get_object_from_results",
"(",
"session",
",",
"vms",
",",
"vm_name",
",",
"_get_object_for_value",
")"
] | get reference to the vm with the name specified . | train | false |
22,468 | def text_clean(text):
retval = text
retval = retval.replace('\xe2\x80\x98', "'")
retval = retval.replace('\xe2\x80\x99', "'")
retval = retval.replace('\xe2', '')
return retval
| [
"def",
"text_clean",
"(",
"text",
")",
":",
"retval",
"=",
"text",
"retval",
"=",
"retval",
".",
"replace",
"(",
"'\\xe2\\x80\\x98'",
",",
"\"'\"",
")",
"retval",
"=",
"retval",
".",
"replace",
"(",
"'\\xe2\\x80\\x99'",
",",
"\"'\"",
")",
"retval",
"=",
"retval",
".",
"replace",
"(",
"'\\xe2'",
",",
"''",
")",
"return",
"retval"
] | this always seems like such a hack . | train | false |
22,469 | def drop_bad_flags(flags):
if (not flags):
return flags
return ' '.join((x for x in flags.split() if (not (x.startswith('-Werror') or (x in ('-pedantic-errors',))))))
| [
"def",
"drop_bad_flags",
"(",
"flags",
")",
":",
"if",
"(",
"not",
"flags",
")",
":",
"return",
"flags",
"return",
"' '",
".",
"join",
"(",
"(",
"x",
"for",
"x",
"in",
"flags",
".",
"split",
"(",
")",
"if",
"(",
"not",
"(",
"x",
".",
"startswith",
"(",
"'-Werror'",
")",
"or",
"(",
"x",
"in",
"(",
"'-pedantic-errors'",
",",
")",
")",
")",
")",
")",
")"
] | drop flags that are problematic for compiling old scipy versions . | train | false |
22,470 | @collect_auth
def add_pointer(auth):
to_node_id = request.json.get('toNodeID')
pointer_to_move = request.json.get('pointerID')
if (not (to_node_id and pointer_to_move)):
raise HTTPError(http.BAD_REQUEST)
pointer = Node.load(pointer_to_move)
to_node = Node.load(to_node_id)
try:
_add_pointers(to_node, [pointer], auth)
except ValueError:
raise HTTPError(http.BAD_REQUEST)
| [
"@",
"collect_auth",
"def",
"add_pointer",
"(",
"auth",
")",
":",
"to_node_id",
"=",
"request",
".",
"json",
".",
"get",
"(",
"'toNodeID'",
")",
"pointer_to_move",
"=",
"request",
".",
"json",
".",
"get",
"(",
"'pointerID'",
")",
"if",
"(",
"not",
"(",
"to_node_id",
"and",
"pointer_to_move",
")",
")",
":",
"raise",
"HTTPError",
"(",
"http",
".",
"BAD_REQUEST",
")",
"pointer",
"=",
"Node",
".",
"load",
"(",
"pointer_to_move",
")",
"to_node",
"=",
"Node",
".",
"load",
"(",
"to_node_id",
")",
"try",
":",
"_add_pointers",
"(",
"to_node",
",",
"[",
"pointer",
"]",
",",
"auth",
")",
"except",
"ValueError",
":",
"raise",
"HTTPError",
"(",
"http",
".",
"BAD_REQUEST",
")"
] | add a single pointer to a node using only json parameters . | train | false |
22,471 | def test_color():
x = Color('white')
assert_array_equal(x.rgba, ([1.0] * 4))
assert_array_equal(x.rgb, ([1.0] * 3))
assert_array_equal(x.RGBA, ([255] * 4))
assert_array_equal(x.RGB, ([255] * 3))
assert_equal(x.value, 1.0)
assert_equal(x.alpha, 1.0)
x.rgb = [0, 0, 1]
assert_array_equal(x.hsv, [240, 1, 1])
assert_equal(x.hex, '#0000ff')
x.hex = '#00000000'
assert_array_equal(x.rgba, ([0.0] * 4))
| [
"def",
"test_color",
"(",
")",
":",
"x",
"=",
"Color",
"(",
"'white'",
")",
"assert_array_equal",
"(",
"x",
".",
"rgba",
",",
"(",
"[",
"1.0",
"]",
"*",
"4",
")",
")",
"assert_array_equal",
"(",
"x",
".",
"rgb",
",",
"(",
"[",
"1.0",
"]",
"*",
"3",
")",
")",
"assert_array_equal",
"(",
"x",
".",
"RGBA",
",",
"(",
"[",
"255",
"]",
"*",
"4",
")",
")",
"assert_array_equal",
"(",
"x",
".",
"RGB",
",",
"(",
"[",
"255",
"]",
"*",
"3",
")",
")",
"assert_equal",
"(",
"x",
".",
"value",
",",
"1.0",
")",
"assert_equal",
"(",
"x",
".",
"alpha",
",",
"1.0",
")",
"x",
".",
"rgb",
"=",
"[",
"0",
",",
"0",
",",
"1",
"]",
"assert_array_equal",
"(",
"x",
".",
"hsv",
",",
"[",
"240",
",",
"1",
",",
"1",
"]",
")",
"assert_equal",
"(",
"x",
".",
"hex",
",",
"'#0000ff'",
")",
"x",
".",
"hex",
"=",
"'#00000000'",
"assert_array_equal",
"(",
"x",
".",
"rgba",
",",
"(",
"[",
"0.0",
"]",
"*",
"4",
")",
")"
] | basic tests for color class . | train | false |
22,472 | def backup_get_all_active_by_window(context, begin, end=None, project_id=None):
return IMPL.backup_get_all_active_by_window(context, begin, end, project_id)
| [
"def",
"backup_get_all_active_by_window",
"(",
"context",
",",
"begin",
",",
"end",
"=",
"None",
",",
"project_id",
"=",
"None",
")",
":",
"return",
"IMPL",
".",
"backup_get_all_active_by_window",
"(",
"context",
",",
"begin",
",",
"end",
",",
"project_id",
")"
] | get all the backups inside the window . | train | false |
22,473 | def _percent(x, total, default=0.0):
if total:
return ((100.0 * x) / total)
else:
return default
| [
"def",
"_percent",
"(",
"x",
",",
"total",
",",
"default",
"=",
"0.0",
")",
":",
"if",
"total",
":",
"return",
"(",
"(",
"100.0",
"*",
"x",
")",
"/",
"total",
")",
"else",
":",
"return",
"default"
] | return what percentage *x* is of *total* . | train | false |
22,476 | def _likelihood_func(t, k, w, pi, codon_cnt, codon_lst, codon_table):
from scipy.linalg import expm
Q = _get_Q(pi, k, w, codon_lst, codon_table)
P = expm((Q * t))
l = 0
for (i, c1) in enumerate(codon_lst):
for (j, c2) in enumerate(codon_lst):
if ((c1, c2) in codon_cnt):
if ((P[(i, j)] * pi[c1]) <= 0):
l += (codon_cnt[(c1, c2)] * 0)
else:
l += (codon_cnt[(c1, c2)] * log((pi[c1] * P[(i, j)])))
return l
| [
"def",
"_likelihood_func",
"(",
"t",
",",
"k",
",",
"w",
",",
"pi",
",",
"codon_cnt",
",",
"codon_lst",
",",
"codon_table",
")",
":",
"from",
"scipy",
".",
"linalg",
"import",
"expm",
"Q",
"=",
"_get_Q",
"(",
"pi",
",",
"k",
",",
"w",
",",
"codon_lst",
",",
"codon_table",
")",
"P",
"=",
"expm",
"(",
"(",
"Q",
"*",
"t",
")",
")",
"l",
"=",
"0",
"for",
"(",
"i",
",",
"c1",
")",
"in",
"enumerate",
"(",
"codon_lst",
")",
":",
"for",
"(",
"j",
",",
"c2",
")",
"in",
"enumerate",
"(",
"codon_lst",
")",
":",
"if",
"(",
"(",
"c1",
",",
"c2",
")",
"in",
"codon_cnt",
")",
":",
"if",
"(",
"(",
"P",
"[",
"(",
"i",
",",
"j",
")",
"]",
"*",
"pi",
"[",
"c1",
"]",
")",
"<=",
"0",
")",
":",
"l",
"+=",
"(",
"codon_cnt",
"[",
"(",
"c1",
",",
"c2",
")",
"]",
"*",
"0",
")",
"else",
":",
"l",
"+=",
"(",
"codon_cnt",
"[",
"(",
"c1",
",",
"c2",
")",
"]",
"*",
"log",
"(",
"(",
"pi",
"[",
"c1",
"]",
"*",
"P",
"[",
"(",
"i",
",",
"j",
")",
"]",
")",
")",
")",
"return",
"l"
] | likelihood function for ml method . | train | false |
22,478 | def _remap_vbd_dev(dev):
should_remap = CONF.xenserver.remap_vbd_dev
if (not should_remap):
return dev
old_prefix = 'xvd'
new_prefix = CONF.xenserver.remap_vbd_dev_prefix
remapped_dev = dev.replace(old_prefix, new_prefix)
return remapped_dev
| [
"def",
"_remap_vbd_dev",
"(",
"dev",
")",
":",
"should_remap",
"=",
"CONF",
".",
"xenserver",
".",
"remap_vbd_dev",
"if",
"(",
"not",
"should_remap",
")",
":",
"return",
"dev",
"old_prefix",
"=",
"'xvd'",
"new_prefix",
"=",
"CONF",
".",
"xenserver",
".",
"remap_vbd_dev_prefix",
"remapped_dev",
"=",
"dev",
".",
"replace",
"(",
"old_prefix",
",",
"new_prefix",
")",
"return",
"remapped_dev"
] | return the appropriate location for a plugged-in vbd device ubuntu maverick moved xvd? -> sd? . | train | false |
22,479 | def get_edit_and_list_urls(url_prefix, view_template, name_template, permissions=()):
return [admin_url((u'%s/(?P<pk>\\d+)/$' % url_prefix), (view_template % u'Edit'), name=(name_template % u'edit'), permissions=permissions), admin_url((u'%s/new/$' % url_prefix), (view_template % u'Edit'), name=(name_template % u'new'), kwargs={u'pk': None}, permissions=permissions), admin_url((u'%s/$' % url_prefix), (view_template % u'List'), name=(name_template % u'list'), permissions=permissions), admin_url((u'%s/list-settings/' % url_prefix), u'shuup.admin.modules.settings.views.ListSettingsView', name=(name_template % u'list_settings'), permissions=permissions)]
| [
"def",
"get_edit_and_list_urls",
"(",
"url_prefix",
",",
"view_template",
",",
"name_template",
",",
"permissions",
"=",
"(",
")",
")",
":",
"return",
"[",
"admin_url",
"(",
"(",
"u'%s/(?P<pk>\\\\d+)/$'",
"%",
"url_prefix",
")",
",",
"(",
"view_template",
"%",
"u'Edit'",
")",
",",
"name",
"=",
"(",
"name_template",
"%",
"u'edit'",
")",
",",
"permissions",
"=",
"permissions",
")",
",",
"admin_url",
"(",
"(",
"u'%s/new/$'",
"%",
"url_prefix",
")",
",",
"(",
"view_template",
"%",
"u'Edit'",
")",
",",
"name",
"=",
"(",
"name_template",
"%",
"u'new'",
")",
",",
"kwargs",
"=",
"{",
"u'pk'",
":",
"None",
"}",
",",
"permissions",
"=",
"permissions",
")",
",",
"admin_url",
"(",
"(",
"u'%s/$'",
"%",
"url_prefix",
")",
",",
"(",
"view_template",
"%",
"u'List'",
")",
",",
"name",
"=",
"(",
"name_template",
"%",
"u'list'",
")",
",",
"permissions",
"=",
"permissions",
")",
",",
"admin_url",
"(",
"(",
"u'%s/list-settings/'",
"%",
"url_prefix",
")",
",",
"u'shuup.admin.modules.settings.views.ListSettingsView'",
",",
"name",
"=",
"(",
"name_template",
"%",
"u'list_settings'",
")",
",",
"permissions",
"=",
"permissions",
")",
"]"
] | get a list of edit/new/list urls for an object type with standardized urls and names . | train | false |
22,480 | def addValueToEvaluatedDictionary(elementNode, evaluatedDictionary, key):
value = getEvaluatedValueObliviously(elementNode, key)
if (value == None):
valueString = str(elementNode.attributes[key])
print 'Warning, addValueToEvaluatedDictionary in evaluate can not get a value for:'
print valueString
evaluatedDictionary[(key + '__Warning__')] = ('Can not evaluate: ' + valueString.replace('"', ' ').replace("'", ' '))
else:
evaluatedDictionary[key] = value
| [
"def",
"addValueToEvaluatedDictionary",
"(",
"elementNode",
",",
"evaluatedDictionary",
",",
"key",
")",
":",
"value",
"=",
"getEvaluatedValueObliviously",
"(",
"elementNode",
",",
"key",
")",
"if",
"(",
"value",
"==",
"None",
")",
":",
"valueString",
"=",
"str",
"(",
"elementNode",
".",
"attributes",
"[",
"key",
"]",
")",
"print",
"'Warning, addValueToEvaluatedDictionary in evaluate can not get a value for:'",
"print",
"valueString",
"evaluatedDictionary",
"[",
"(",
"key",
"+",
"'__Warning__'",
")",
"]",
"=",
"(",
"'Can not evaluate: '",
"+",
"valueString",
".",
"replace",
"(",
"'\"'",
",",
"' '",
")",
".",
"replace",
"(",
"\"'\"",
",",
"' '",
")",
")",
"else",
":",
"evaluatedDictionary",
"[",
"key",
"]",
"=",
"value"
] | get the evaluated dictionary . | train | false |
22,481 | def expand_user(path):
tilde_expand = False
tilde_val = ''
newpath = path
if path.startswith('~'):
tilde_expand = True
rest = (len(path) - 1)
newpath = os.path.expanduser(path)
if rest:
tilde_val = newpath[:(- rest)]
else:
tilde_val = newpath
return (newpath, tilde_expand, tilde_val)
| [
"def",
"expand_user",
"(",
"path",
")",
":",
"tilde_expand",
"=",
"False",
"tilde_val",
"=",
"''",
"newpath",
"=",
"path",
"if",
"path",
".",
"startswith",
"(",
"'~'",
")",
":",
"tilde_expand",
"=",
"True",
"rest",
"=",
"(",
"len",
"(",
"path",
")",
"-",
"1",
")",
"newpath",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"rest",
":",
"tilde_val",
"=",
"newpath",
"[",
":",
"(",
"-",
"rest",
")",
"]",
"else",
":",
"tilde_val",
"=",
"newpath",
"return",
"(",
"newpath",
",",
"tilde_expand",
",",
"tilde_val",
")"
] | expand ~-style usernames in strings . | train | true |
22,482 | def _is_numeric(x):
try:
float(str(x))
return True
except ValueError:
return False
| [
"def",
"_is_numeric",
"(",
"x",
")",
":",
"try",
":",
"float",
"(",
"str",
"(",
"x",
")",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | test whether the argument can be serialized as a number . | train | false |
22,484 | def _HandleCommonSuffix(first_handler, second_handler, common_suffix):
stripped_first_handler = SimpleHandler(first_handler.pattern[:(- len(common_suffix))], first_handler.properties)
stripped_second_handler = SimpleHandler(second_handler.pattern[:(- len(common_suffix))], second_handler.properties)
stripped_handlers = _IntersectTwoHandlers(stripped_first_handler, stripped_second_handler)
handlers = set()
for stripped_handler in stripped_handlers:
handlers.add(SimpleHandler((stripped_handler.pattern + common_suffix), stripped_handler.properties))
return handlers
| [
"def",
"_HandleCommonSuffix",
"(",
"first_handler",
",",
"second_handler",
",",
"common_suffix",
")",
":",
"stripped_first_handler",
"=",
"SimpleHandler",
"(",
"first_handler",
".",
"pattern",
"[",
":",
"(",
"-",
"len",
"(",
"common_suffix",
")",
")",
"]",
",",
"first_handler",
".",
"properties",
")",
"stripped_second_handler",
"=",
"SimpleHandler",
"(",
"second_handler",
".",
"pattern",
"[",
":",
"(",
"-",
"len",
"(",
"common_suffix",
")",
")",
"]",
",",
"second_handler",
".",
"properties",
")",
"stripped_handlers",
"=",
"_IntersectTwoHandlers",
"(",
"stripped_first_handler",
",",
"stripped_second_handler",
")",
"handlers",
"=",
"set",
"(",
")",
"for",
"stripped_handler",
"in",
"stripped_handlers",
":",
"handlers",
".",
"add",
"(",
"SimpleHandler",
"(",
"(",
"stripped_handler",
".",
"pattern",
"+",
"common_suffix",
")",
",",
"stripped_handler",
".",
"properties",
")",
")",
"return",
"handlers"
] | strips matching suffix from handlers and intersects the substrings . | train | false |
22,485 | @register.inclusion_tag(get_template('inclusion.html'))
def inclusion_only_unlimited_args_from_template(*args):
return {'result': ('inclusion_only_unlimited_args_from_template - Expected result: %s' % ', '.join([six.text_type(arg) for arg in args]))}
| [
"@",
"register",
".",
"inclusion_tag",
"(",
"get_template",
"(",
"'inclusion.html'",
")",
")",
"def",
"inclusion_only_unlimited_args_from_template",
"(",
"*",
"args",
")",
":",
"return",
"{",
"'result'",
":",
"(",
"'inclusion_only_unlimited_args_from_template - Expected result: %s'",
"%",
"', '",
".",
"join",
"(",
"[",
"six",
".",
"text_type",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
")",
")",
"}"
] | expected inclusion_only_unlimited_args_from_template __doc__ . | train | false |
22,486 | def matrix_dagger(e):
if isinstance(e, Matrix):
return e.H
elif isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
return e.conjugate().transpose()
raise TypeError(('Expected sympy/numpy/scipy.sparse matrix, got: %r' % e))
| [
"def",
"matrix_dagger",
"(",
"e",
")",
":",
"if",
"isinstance",
"(",
"e",
",",
"Matrix",
")",
":",
"return",
"e",
".",
"H",
"elif",
"isinstance",
"(",
"e",
",",
"(",
"numpy_ndarray",
",",
"scipy_sparse_matrix",
")",
")",
":",
"return",
"e",
".",
"conjugate",
"(",
")",
".",
"transpose",
"(",
")",
"raise",
"TypeError",
"(",
"(",
"'Expected sympy/numpy/scipy.sparse matrix, got: %r'",
"%",
"e",
")",
")"
] | return the dagger of a sympy/numpy/scipy . | train | false |
22,487 | def error_page_401(status, message, traceback, version):
title = T('Access denied')
body = (T('Error %s: You need to provide a valid username and password.') % status)
return ('\n<html>\n <head>\n <title>%s</title>\n </head>\n <body>\n <br/><br/>\n <font color="#0000FF">%s</font>\n </body>\n</html>\n' % (title, body))
| [
"def",
"error_page_401",
"(",
"status",
",",
"message",
",",
"traceback",
",",
"version",
")",
":",
"title",
"=",
"T",
"(",
"'Access denied'",
")",
"body",
"=",
"(",
"T",
"(",
"'Error %s: You need to provide a valid username and password.'",
")",
"%",
"status",
")",
"return",
"(",
"'\\n<html>\\n <head>\\n <title>%s</title>\\n </head>\\n <body>\\n <br/><br/>\\n <font color=\"#0000FF\">%s</font>\\n </body>\\n</html>\\n'",
"%",
"(",
"title",
",",
"body",
")",
")"
] | custom handler for 401 error . | train | false |
22,488 | def galois_multiply(a, b):
p = 0
while b:
if (b & 1):
p ^= a
a <<= 1
if (a & 256):
a ^= 27
b >>= 1
return (p & 255)
| [
"def",
"galois_multiply",
"(",
"a",
",",
"b",
")",
":",
"p",
"=",
"0",
"while",
"b",
":",
"if",
"(",
"b",
"&",
"1",
")",
":",
"p",
"^=",
"a",
"a",
"<<=",
"1",
"if",
"(",
"a",
"&",
"256",
")",
":",
"a",
"^=",
"27",
"b",
">>=",
"1",
"return",
"(",
"p",
"&",
"255",
")"
] | galois field multiplicaiton for aes . | train | false |
22,489 | def starred_by(username, number=(-1), etag=None):
return gh.starred_by(username, number, etag)
| [
"def",
"starred_by",
"(",
"username",
",",
"number",
"=",
"(",
"-",
"1",
")",
",",
"etag",
"=",
"None",
")",
":",
"return",
"gh",
".",
"starred_by",
"(",
"username",
",",
"number",
",",
"etag",
")"
] | iterate over repositories starred by username . | train | false |
22,490 | def add_progress(kwargs, git, progress):
if (progress is not None):
v = git.version_info[:2]
if (v >= (1, 7)):
kwargs['progress'] = True
return kwargs
| [
"def",
"add_progress",
"(",
"kwargs",
",",
"git",
",",
"progress",
")",
":",
"if",
"(",
"progress",
"is",
"not",
"None",
")",
":",
"v",
"=",
"git",
".",
"version_info",
"[",
":",
"2",
"]",
"if",
"(",
"v",
">=",
"(",
"1",
",",
"7",
")",
")",
":",
"kwargs",
"[",
"'progress'",
"]",
"=",
"True",
"return",
"kwargs"
] | add the --progress flag to the given kwargs dict if supported by the git command . | train | true |
22,491 | def _get_last_updated_by_human_ms(exp_id):
last_human_update_ms = 0
snapshots_metadata = get_exploration_snapshots_metadata(exp_id)
for snapshot_metadata in reversed(snapshots_metadata):
if (snapshot_metadata['committer_id'] != feconf.MIGRATION_BOT_USER_ID):
last_human_update_ms = snapshot_metadata['created_on_ms']
break
return last_human_update_ms
| [
"def",
"_get_last_updated_by_human_ms",
"(",
"exp_id",
")",
":",
"last_human_update_ms",
"=",
"0",
"snapshots_metadata",
"=",
"get_exploration_snapshots_metadata",
"(",
"exp_id",
")",
"for",
"snapshot_metadata",
"in",
"reversed",
"(",
"snapshots_metadata",
")",
":",
"if",
"(",
"snapshot_metadata",
"[",
"'committer_id'",
"]",
"!=",
"feconf",
".",
"MIGRATION_BOT_USER_ID",
")",
":",
"last_human_update_ms",
"=",
"snapshot_metadata",
"[",
"'created_on_ms'",
"]",
"break",
"return",
"last_human_update_ms"
] | return the last time . | train | false |
22,492 | def getSquareIsOccupied(pixelDictionary, x, y):
squareValues = []
for xStep in xrange((x - 1), (x + 2)):
for yStep in xrange((y - 1), (y + 2)):
stepKey = getStepKey(xStep, yStep)
if (stepKey in pixelDictionary):
return True
return False
| [
"def",
"getSquareIsOccupied",
"(",
"pixelDictionary",
",",
"x",
",",
"y",
")",
":",
"squareValues",
"=",
"[",
"]",
"for",
"xStep",
"in",
"xrange",
"(",
"(",
"x",
"-",
"1",
")",
",",
"(",
"x",
"+",
"2",
")",
")",
":",
"for",
"yStep",
"in",
"xrange",
"(",
"(",
"y",
"-",
"1",
")",
",",
"(",
"y",
"+",
"2",
")",
")",
":",
"stepKey",
"=",
"getStepKey",
"(",
"xStep",
",",
"yStep",
")",
"if",
"(",
"stepKey",
"in",
"pixelDictionary",
")",
":",
"return",
"True",
"return",
"False"
] | determine if a square around the x and y pixel coordinates is occupied . | train | false |
22,493 | def action_handler(verb, **kwargs):
kwargs.pop('signal', None)
actor = kwargs.pop('sender')
if hasattr(verb, '_proxy____args'):
verb = verb._proxy____args[0]
newaction = get_model('actstream', 'action')(actor_content_type=ContentType.objects.get_for_model(actor), actor_object_id=actor.pk, verb=text_type(verb), public=bool(kwargs.pop('public', True)), description=kwargs.pop('description', None), timestamp=kwargs.pop('timestamp', now()))
for opt in ('target', 'action_object'):
obj = kwargs.pop(opt, None)
if (obj is not None):
check(obj)
setattr(newaction, ('%s_object_id' % opt), obj.pk)
setattr(newaction, ('%s_content_type' % opt), ContentType.objects.get_for_model(obj))
if (settings.USE_JSONFIELD and len(kwargs)):
newaction.data = kwargs
newaction.save(force_insert=True)
return newaction
| [
"def",
"action_handler",
"(",
"verb",
",",
"**",
"kwargs",
")",
":",
"kwargs",
".",
"pop",
"(",
"'signal'",
",",
"None",
")",
"actor",
"=",
"kwargs",
".",
"pop",
"(",
"'sender'",
")",
"if",
"hasattr",
"(",
"verb",
",",
"'_proxy____args'",
")",
":",
"verb",
"=",
"verb",
".",
"_proxy____args",
"[",
"0",
"]",
"newaction",
"=",
"get_model",
"(",
"'actstream'",
",",
"'action'",
")",
"(",
"actor_content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"actor",
")",
",",
"actor_object_id",
"=",
"actor",
".",
"pk",
",",
"verb",
"=",
"text_type",
"(",
"verb",
")",
",",
"public",
"=",
"bool",
"(",
"kwargs",
".",
"pop",
"(",
"'public'",
",",
"True",
")",
")",
",",
"description",
"=",
"kwargs",
".",
"pop",
"(",
"'description'",
",",
"None",
")",
",",
"timestamp",
"=",
"kwargs",
".",
"pop",
"(",
"'timestamp'",
",",
"now",
"(",
")",
")",
")",
"for",
"opt",
"in",
"(",
"'target'",
",",
"'action_object'",
")",
":",
"obj",
"=",
"kwargs",
".",
"pop",
"(",
"opt",
",",
"None",
")",
"if",
"(",
"obj",
"is",
"not",
"None",
")",
":",
"check",
"(",
"obj",
")",
"setattr",
"(",
"newaction",
",",
"(",
"'%s_object_id'",
"%",
"opt",
")",
",",
"obj",
".",
"pk",
")",
"setattr",
"(",
"newaction",
",",
"(",
"'%s_content_type'",
"%",
"opt",
")",
",",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
")",
"if",
"(",
"settings",
".",
"USE_JSONFIELD",
"and",
"len",
"(",
"kwargs",
")",
")",
":",
"newaction",
".",
"data",
"=",
"kwargs",
"newaction",
".",
"save",
"(",
"force_insert",
"=",
"True",
")",
"return",
"newaction"
] | function to wrap calls to make actions on firewalld in try/except logic and emit useful error messages . | train | true |
22,494 | def get_network_domain_by_name(driver, name, location):
networks = driver.ex_list_network_domains(location=location)
found_networks = [network for network in networks if (network.name == name)]
if (not found_networks):
raise UnknownNetworkError(("Network '%s' could not be found" % name))
return found_networks[0]
| [
"def",
"get_network_domain_by_name",
"(",
"driver",
",",
"name",
",",
"location",
")",
":",
"networks",
"=",
"driver",
".",
"ex_list_network_domains",
"(",
"location",
"=",
"location",
")",
"found_networks",
"=",
"[",
"network",
"for",
"network",
"in",
"networks",
"if",
"(",
"network",
".",
"name",
"==",
"name",
")",
"]",
"if",
"(",
"not",
"found_networks",
")",
":",
"raise",
"UnknownNetworkError",
"(",
"(",
"\"Network '%s' could not be found\"",
"%",
"name",
")",
")",
"return",
"found_networks",
"[",
"0",
"]"
] | get a network domain object by its name . | train | false |
22,495 | def pread_console(fd, buffersize, offset, buf=None):
(cols, rows) = os.get_terminal_size(fd=fd)
x = (offset % cols)
y = (offset // cols)
return read_console_output_character(x=x, y=y, fd=fd, buf=buf, bufsize=buffersize, raw=True)
| [
"def",
"pread_console",
"(",
"fd",
",",
"buffersize",
",",
"offset",
",",
"buf",
"=",
"None",
")",
":",
"(",
"cols",
",",
"rows",
")",
"=",
"os",
".",
"get_terminal_size",
"(",
"fd",
"=",
"fd",
")",
"x",
"=",
"(",
"offset",
"%",
"cols",
")",
"y",
"=",
"(",
"offset",
"//",
"cols",
")",
"return",
"read_console_output_character",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"fd",
"=",
"fd",
",",
"buf",
"=",
"buf",
",",
"bufsize",
"=",
"buffersize",
",",
"raw",
"=",
"True",
")"
] | this is a console-based implementation of os . | train | false |
22,496 | def make_type_to_unpacker_table():
top = max(of._message_type_to_class)
r = [of._message_type_to_class[i].unpack_new for i in range(0, top)]
return r
| [
"def",
"make_type_to_unpacker_table",
"(",
")",
":",
"top",
"=",
"max",
"(",
"of",
".",
"_message_type_to_class",
")",
"r",
"=",
"[",
"of",
".",
"_message_type_to_class",
"[",
"i",
"]",
".",
"unpack_new",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"top",
")",
"]",
"return",
"r"
] | returns a list of unpack methods . | train | false |
22,498 | def search_section(request, query, project_slug=None, version_slug=LATEST, path=None):
kwargs = {}
body = {'query': {'bool': {'should': [{'match_phrase': {'title': {'query': query, 'boost': 10, 'slop': 2}}}, {'match_phrase': {'content': {'query': query, 'slop': 5}}}]}}, 'facets': {'project': {'terms': {'field': 'project'}, 'facet_filter': {'term': {'version': version_slug}}}}, 'highlight': {'fields': {'title': {}, 'content': {}}}, 'fields': ['title', 'project', 'version', 'path', 'page_id', 'content'], 'size': 10}
if project_slug:
body['filter'] = {'and': [{'term': {'project': project_slug}}, {'term': {'version': version_slug}}]}
body['facets']['path'] = ({'terms': {'field': 'path'}, 'facet_filter': {'term': {'project': project_slug}}},)
kwargs['routing'] = project_slug
if path:
body['filter'] = {'and': [{'term': {'path': path}}]}
if (path and (not project_slug)):
body['facets']['path'] = {'terms': {'field': 'path'}}
before_section_search.send(request=request, sender=PageIndex, body=body)
return SectionIndex().search(body, **kwargs)
| [
"def",
"search_section",
"(",
"request",
",",
"query",
",",
"project_slug",
"=",
"None",
",",
"version_slug",
"=",
"LATEST",
",",
"path",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"body",
"=",
"{",
"'query'",
":",
"{",
"'bool'",
":",
"{",
"'should'",
":",
"[",
"{",
"'match_phrase'",
":",
"{",
"'title'",
":",
"{",
"'query'",
":",
"query",
",",
"'boost'",
":",
"10",
",",
"'slop'",
":",
"2",
"}",
"}",
"}",
",",
"{",
"'match_phrase'",
":",
"{",
"'content'",
":",
"{",
"'query'",
":",
"query",
",",
"'slop'",
":",
"5",
"}",
"}",
"}",
"]",
"}",
"}",
",",
"'facets'",
":",
"{",
"'project'",
":",
"{",
"'terms'",
":",
"{",
"'field'",
":",
"'project'",
"}",
",",
"'facet_filter'",
":",
"{",
"'term'",
":",
"{",
"'version'",
":",
"version_slug",
"}",
"}",
"}",
"}",
",",
"'highlight'",
":",
"{",
"'fields'",
":",
"{",
"'title'",
":",
"{",
"}",
",",
"'content'",
":",
"{",
"}",
"}",
"}",
",",
"'fields'",
":",
"[",
"'title'",
",",
"'project'",
",",
"'version'",
",",
"'path'",
",",
"'page_id'",
",",
"'content'",
"]",
",",
"'size'",
":",
"10",
"}",
"if",
"project_slug",
":",
"body",
"[",
"'filter'",
"]",
"=",
"{",
"'and'",
":",
"[",
"{",
"'term'",
":",
"{",
"'project'",
":",
"project_slug",
"}",
"}",
",",
"{",
"'term'",
":",
"{",
"'version'",
":",
"version_slug",
"}",
"}",
"]",
"}",
"body",
"[",
"'facets'",
"]",
"[",
"'path'",
"]",
"=",
"(",
"{",
"'terms'",
":",
"{",
"'field'",
":",
"'path'",
"}",
",",
"'facet_filter'",
":",
"{",
"'term'",
":",
"{",
"'project'",
":",
"project_slug",
"}",
"}",
"}",
",",
")",
"kwargs",
"[",
"'routing'",
"]",
"=",
"project_slug",
"if",
"path",
":",
"body",
"[",
"'filter'",
"]",
"=",
"{",
"'and'",
":",
"[",
"{",
"'term'",
":",
"{",
"'path'",
":",
"path",
"}",
"}",
"]",
"}",
"if",
"(",
"path",
"and",
"(",
"not",
"project_slug",
")",
")",
":",
"body",
"[",
"'facets'",
"]",
"[",
"'path'",
"]",
"=",
"{",
"'terms'",
":",
"{",
"'field'",
":",
"'path'",
"}",
"}",
"before_section_search",
".",
"send",
"(",
"request",
"=",
"request",
",",
"sender",
"=",
"PageIndex",
",",
"body",
"=",
"body",
")",
"return",
"SectionIndex",
"(",
")",
".",
"search",
"(",
"body",
",",
"**",
"kwargs",
")"
] | search for a section of content when you search . | train | false |
22,499 | def _pylong_join(count, digits_ptr='digits', join_type='unsigned long'):
def shift(n):
return ((' << (%d * PyLong_SHIFT < 8 * sizeof(%s) ? %d * PyLong_SHIFT : 0)' % (n, join_type, n)) if n else '')
return ('(%s)' % ' | '.join((('(((%s)%s[%d])%s)' % (join_type, digits_ptr, i, shift(i))) for i in range((count - 1), (-1), (-1)))))
| [
"def",
"_pylong_join",
"(",
"count",
",",
"digits_ptr",
"=",
"'digits'",
",",
"join_type",
"=",
"'unsigned long'",
")",
":",
"def",
"shift",
"(",
"n",
")",
":",
"return",
"(",
"(",
"' << (%d * PyLong_SHIFT < 8 * sizeof(%s) ? %d * PyLong_SHIFT : 0)'",
"%",
"(",
"n",
",",
"join_type",
",",
"n",
")",
")",
"if",
"n",
"else",
"''",
")",
"return",
"(",
"'(%s)'",
"%",
"' | '",
".",
"join",
"(",
"(",
"(",
"'(((%s)%s[%d])%s)'",
"%",
"(",
"join_type",
",",
"digits_ptr",
",",
"i",
",",
"shift",
"(",
"i",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"(",
"count",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
")",
")",
")",
")"
] | generate an or-ed series of shifts for the first count digits . | train | false |
22,500 | def test_rgb_to_hsl_part_5():
assert (rgb_to_hsl(0, 255, 0) == (120, 100, 50))
assert (rgb_to_hsl(0, 255, 51) == (132, 100, 50))
assert (rgb_to_hsl(0, 255, 102) == (144, 100, 50))
assert (rgb_to_hsl(0, 255, 153) == (156, 100, 50))
assert (rgb_to_hsl(0, 255, 204) == (168, 100, 50))
assert (rgb_to_hsl(0, 255, 255) == (180, 100, 50))
assert (rgb_to_hsl(0, 204, 255) == (192, 100, 50))
assert (rgb_to_hsl(0, 153, 255) == (204, 100, 50))
assert (rgb_to_hsl(0, 102, 255) == (216, 100, 50))
assert (rgb_to_hsl(0, 51, 255) == (228, 100, 50))
assert (rgb_to_hsl(0, 0, 255) == (240, 100, 50))
| [
"def",
"test_rgb_to_hsl_part_5",
"(",
")",
":",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"255",
",",
"0",
")",
"==",
"(",
"120",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"255",
",",
"51",
")",
"==",
"(",
"132",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"255",
",",
"102",
")",
"==",
"(",
"144",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"255",
",",
"153",
")",
"==",
"(",
"156",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"255",
",",
"204",
")",
"==",
"(",
"168",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"255",
",",
"255",
")",
"==",
"(",
"180",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"204",
",",
"255",
")",
"==",
"(",
"192",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"153",
",",
"255",
")",
"==",
"(",
"204",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"102",
",",
"255",
")",
"==",
"(",
"216",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"51",
",",
"255",
")",
"==",
"(",
"228",
",",
"100",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"0",
",",
"0",
",",
"255",
")",
"==",
"(",
"240",
",",
"100",
",",
"50",
")",
")"
] | test rgb to hsl color function . | train | false |
22,502 | @cronjobs.register
def escalate_questions():
if settings.STAGE:
return
qs = Question.objects.needs_attention().exclude(tags__slug__in=[config.ESCALATE_TAG_NAME])
qs = qs.filter(locale=settings.WIKI_DEFAULT_LANGUAGE)
qs = qs.exclude(product__slug__in=config.ESCALATE_EXCLUDE_PRODUCTS)
qs = qs.exclude(creator__is_active=False)
start = (datetime.now() - timedelta(hours=24))
end = (datetime.now() - timedelta(hours=25))
qs_no_replies_yet = qs.filter(last_answer__isnull=True, created__lt=start, created__gt=end)
for question in qs_no_replies_yet:
escalate_question.delay(question.id)
return len(qs_no_replies_yet)
| [
"@",
"cronjobs",
".",
"register",
"def",
"escalate_questions",
"(",
")",
":",
"if",
"settings",
".",
"STAGE",
":",
"return",
"qs",
"=",
"Question",
".",
"objects",
".",
"needs_attention",
"(",
")",
".",
"exclude",
"(",
"tags__slug__in",
"=",
"[",
"config",
".",
"ESCALATE_TAG_NAME",
"]",
")",
"qs",
"=",
"qs",
".",
"filter",
"(",
"locale",
"=",
"settings",
".",
"WIKI_DEFAULT_LANGUAGE",
")",
"qs",
"=",
"qs",
".",
"exclude",
"(",
"product__slug__in",
"=",
"config",
".",
"ESCALATE_EXCLUDE_PRODUCTS",
")",
"qs",
"=",
"qs",
".",
"exclude",
"(",
"creator__is_active",
"=",
"False",
")",
"start",
"=",
"(",
"datetime",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"hours",
"=",
"24",
")",
")",
"end",
"=",
"(",
"datetime",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"hours",
"=",
"25",
")",
")",
"qs_no_replies_yet",
"=",
"qs",
".",
"filter",
"(",
"last_answer__isnull",
"=",
"True",
",",
"created__lt",
"=",
"start",
",",
"created__gt",
"=",
"end",
")",
"for",
"question",
"in",
"qs_no_replies_yet",
":",
"escalate_question",
".",
"delay",
"(",
"question",
".",
"id",
")",
"return",
"len",
"(",
"qs_no_replies_yet",
")"
] | escalate questions needing attention . | train | false |
22,503 | @app_view
@require_POST
@permission_required([('Admin', '%'), ('Apps', 'Configure')])
def blocklist(request, addon):
if (addon.status != mkt.STATUS_BLOCKED):
addon.create_blocklisted_version()
messages.success(request, _('Created blocklisted version.'))
else:
messages.info(request, _('App already blocklisted.'))
return redirect(addon.get_dev_url('versions'))
| [
"@",
"app_view",
"@",
"require_POST",
"@",
"permission_required",
"(",
"[",
"(",
"'Admin'",
",",
"'%'",
")",
",",
"(",
"'Apps'",
",",
"'Configure'",
")",
"]",
")",
"def",
"blocklist",
"(",
"request",
",",
"addon",
")",
":",
"if",
"(",
"addon",
".",
"status",
"!=",
"mkt",
".",
"STATUS_BLOCKED",
")",
":",
"addon",
".",
"create_blocklisted_version",
"(",
")",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"'Created blocklisted version.'",
")",
")",
"else",
":",
"messages",
".",
"info",
"(",
"request",
",",
"_",
"(",
"'App already blocklisted.'",
")",
")",
"return",
"redirect",
"(",
"addon",
".",
"get_dev_url",
"(",
"'versions'",
")",
")"
] | blocklists the app by creating a new version/file . | train | false |
22,504 | @core_helper
def dict_list_reduce(list_, key, unique=True):
new_list = []
for item in list_:
value = item.get(key)
if ((not value) or (unique and (value in new_list))):
continue
new_list.append(value)
return new_list
| [
"@",
"core_helper",
"def",
"dict_list_reduce",
"(",
"list_",
",",
"key",
",",
"unique",
"=",
"True",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"item",
"in",
"list_",
":",
"value",
"=",
"item",
".",
"get",
"(",
"key",
")",
"if",
"(",
"(",
"not",
"value",
")",
"or",
"(",
"unique",
"and",
"(",
"value",
"in",
"new_list",
")",
")",
")",
":",
"continue",
"new_list",
".",
"append",
"(",
"value",
")",
"return",
"new_list"
] | take a list of dicts and create a new one containing just the values for the key with unique values if requested . | train | false |
22,505 | def secure_hash_s(data, hash_func=sha1):
digest = hash_func()
data = to_bytes(data, errors='surrogate_or_strict')
digest.update(data)
return digest.hexdigest()
| [
"def",
"secure_hash_s",
"(",
"data",
",",
"hash_func",
"=",
"sha1",
")",
":",
"digest",
"=",
"hash_func",
"(",
")",
"data",
"=",
"to_bytes",
"(",
"data",
",",
"errors",
"=",
"'surrogate_or_strict'",
")",
"digest",
".",
"update",
"(",
"data",
")",
"return",
"digest",
".",
"hexdigest",
"(",
")"
] | return a secure hash hex digest of data . | train | false |
22,506 | def dedent_strip_nodetext_formatter(nodetext, has_options, caller=None):
return dedent(nodetext).strip()
| [
"def",
"dedent_strip_nodetext_formatter",
"(",
"nodetext",
",",
"has_options",
",",
"caller",
"=",
"None",
")",
":",
"return",
"dedent",
"(",
"nodetext",
")",
".",
"strip",
"(",
")"
] | simple dedent formatter that also strips text . | train | false |
22,511 | def make_cmd_fn(cmd):
def do_cmd(rest_of_line, cmd=cmd):
(global_dict, local_dict) = namespaces.get_twill_glocals()
args = []
if (rest_of_line.strip() != ''):
try:
args = parse.arguments.parseString(rest_of_line)[0]
args = parse.process_args(args, global_dict, local_dict)
except Exception as e:
print ('\nINPUT ERROR: %s\n' % (str(e),))
return
try:
parse.execute_command(cmd, args, global_dict, local_dict, '<shell>')
except SystemExit:
raise
except Exception as e:
print ('\nERROR: %s\n' % (str(e),))
return do_cmd
| [
"def",
"make_cmd_fn",
"(",
"cmd",
")",
":",
"def",
"do_cmd",
"(",
"rest_of_line",
",",
"cmd",
"=",
"cmd",
")",
":",
"(",
"global_dict",
",",
"local_dict",
")",
"=",
"namespaces",
".",
"get_twill_glocals",
"(",
")",
"args",
"=",
"[",
"]",
"if",
"(",
"rest_of_line",
".",
"strip",
"(",
")",
"!=",
"''",
")",
":",
"try",
":",
"args",
"=",
"parse",
".",
"arguments",
".",
"parseString",
"(",
"rest_of_line",
")",
"[",
"0",
"]",
"args",
"=",
"parse",
".",
"process_args",
"(",
"args",
",",
"global_dict",
",",
"local_dict",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"'\\nINPUT ERROR: %s\\n'",
"%",
"(",
"str",
"(",
"e",
")",
",",
")",
")",
"return",
"try",
":",
"parse",
".",
"execute_command",
"(",
"cmd",
",",
"args",
",",
"global_dict",
",",
"local_dict",
",",
"'<shell>'",
")",
"except",
"SystemExit",
":",
"raise",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"'\\nERROR: %s\\n'",
"%",
"(",
"str",
"(",
"e",
")",
",",
")",
")",
"return",
"do_cmd"
] | dynamically define a twill shell command function based on an imported function name . | train | false |
22,512 | @click.command('fonts')
def setup_fonts():
from bench.utils import setup_fonts
setup_fonts()
| [
"@",
"click",
".",
"command",
"(",
"'fonts'",
")",
"def",
"setup_fonts",
"(",
")",
":",
"from",
"bench",
".",
"utils",
"import",
"setup_fonts",
"setup_fonts",
"(",
")"
] | add frappe fonts to system . | train | false |
22,513 | def html_to_text(html):
htmlstripper = MLStripper()
htmlstripper.feed(html)
return htmlstripper.get_data()
| [
"def",
"html_to_text",
"(",
"html",
")",
":",
"htmlstripper",
"=",
"MLStripper",
"(",
")",
"htmlstripper",
".",
"feed",
"(",
"html",
")",
"return",
"htmlstripper",
".",
"get_data",
"(",
")"
] | strips the html tags off of the text to return plaintext . | train | false |
22,514 | def f_accel_decel(t, old_d, new_d, abruptness=1, soonness=1.0):
a = (1.0 + abruptness)
def _f(t):
f1 = (lambda t: ((0.5 ** (1 - a)) * (t ** a)))
f2 = (lambda t: (1 - f1((1 - t))))
return (((t < 0.5) * f1(t)) + ((t >= 0.5) * f2(t)))
return (old_d * _f(((t / new_d) ** soonness)))
| [
"def",
"f_accel_decel",
"(",
"t",
",",
"old_d",
",",
"new_d",
",",
"abruptness",
"=",
"1",
",",
"soonness",
"=",
"1.0",
")",
":",
"a",
"=",
"(",
"1.0",
"+",
"abruptness",
")",
"def",
"_f",
"(",
"t",
")",
":",
"f1",
"=",
"(",
"lambda",
"t",
":",
"(",
"(",
"0.5",
"**",
"(",
"1",
"-",
"a",
")",
")",
"*",
"(",
"t",
"**",
"a",
")",
")",
")",
"f2",
"=",
"(",
"lambda",
"t",
":",
"(",
"1",
"-",
"f1",
"(",
"(",
"1",
"-",
"t",
")",
")",
")",
")",
"return",
"(",
"(",
"(",
"t",
"<",
"0.5",
")",
"*",
"f1",
"(",
"t",
")",
")",
"+",
"(",
"(",
"t",
">=",
"0.5",
")",
"*",
"f2",
"(",
"t",
")",
")",
")",
"return",
"(",
"old_d",
"*",
"_f",
"(",
"(",
"(",
"t",
"/",
"new_d",
")",
"**",
"soonness",
")",
")",
")"
] | abruptness negative abruptness : speed up down up zero abruptness : no effect positive abruptness: speed down up down soonness for positive abruptness . | train | false |
22,515 | def prepare_for_display(npy_img):
if (npy_img.ndim < 2):
raise ValueError('Image must be 2D or 3D array')
height = npy_img.shape[0]
width = npy_img.shape[1]
out = np.empty((height, width, 3), dtype=np.uint8)
npy_img = img_as_ubyte(npy_img)
if ((npy_img.ndim == 2) or ((npy_img.ndim == 3) and (npy_img.shape[2] == 1))):
npy_plane = npy_img.reshape((height, width))
out[:, :, 0] = npy_plane
out[:, :, 1] = npy_plane
out[:, :, 2] = npy_plane
elif (npy_img.ndim == 3):
if ((npy_img.shape[2] == 3) or (npy_img.shape[2] == 4)):
out[:, :, :3] = npy_img[:, :, :3]
else:
raise ValueError('Image must have 1, 3, or 4 channels')
else:
raise ValueError('Image must have 2 or 3 dimensions')
return out
| [
"def",
"prepare_for_display",
"(",
"npy_img",
")",
":",
"if",
"(",
"npy_img",
".",
"ndim",
"<",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'Image must be 2D or 3D array'",
")",
"height",
"=",
"npy_img",
".",
"shape",
"[",
"0",
"]",
"width",
"=",
"npy_img",
".",
"shape",
"[",
"1",
"]",
"out",
"=",
"np",
".",
"empty",
"(",
"(",
"height",
",",
"width",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"npy_img",
"=",
"img_as_ubyte",
"(",
"npy_img",
")",
"if",
"(",
"(",
"npy_img",
".",
"ndim",
"==",
"2",
")",
"or",
"(",
"(",
"npy_img",
".",
"ndim",
"==",
"3",
")",
"and",
"(",
"npy_img",
".",
"shape",
"[",
"2",
"]",
"==",
"1",
")",
")",
")",
":",
"npy_plane",
"=",
"npy_img",
".",
"reshape",
"(",
"(",
"height",
",",
"width",
")",
")",
"out",
"[",
":",
",",
":",
",",
"0",
"]",
"=",
"npy_plane",
"out",
"[",
":",
",",
":",
",",
"1",
"]",
"=",
"npy_plane",
"out",
"[",
":",
",",
":",
",",
"2",
"]",
"=",
"npy_plane",
"elif",
"(",
"npy_img",
".",
"ndim",
"==",
"3",
")",
":",
"if",
"(",
"(",
"npy_img",
".",
"shape",
"[",
"2",
"]",
"==",
"3",
")",
"or",
"(",
"npy_img",
".",
"shape",
"[",
"2",
"]",
"==",
"4",
")",
")",
":",
"out",
"[",
":",
",",
":",
",",
":",
"3",
"]",
"=",
"npy_img",
"[",
":",
",",
":",
",",
":",
"3",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Image must have 1, 3, or 4 channels'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Image must have 2 or 3 dimensions'",
")",
"return",
"out"
] | convert a 2d or 3d numpy array of any dtype into a 3d numpy array with dtype uint8 . | train | false |
22,516 | def signal_parse_name(detailed_signal, itype, force_detail_quark):
(res, signal_id, detail) = GObjectModule.signal_parse_name(detailed_signal, itype, force_detail_quark)
if res:
return (signal_id, detail)
else:
raise ValueError(('%s: unknown signal name: %s' % (itype, detailed_signal)))
| [
"def",
"signal_parse_name",
"(",
"detailed_signal",
",",
"itype",
",",
"force_detail_quark",
")",
":",
"(",
"res",
",",
"signal_id",
",",
"detail",
")",
"=",
"GObjectModule",
".",
"signal_parse_name",
"(",
"detailed_signal",
",",
"itype",
",",
"force_detail_quark",
")",
"if",
"res",
":",
"return",
"(",
"signal_id",
",",
"detail",
")",
"else",
":",
"raise",
"ValueError",
"(",
"(",
"'%s: unknown signal name: %s'",
"%",
"(",
"itype",
",",
"detailed_signal",
")",
")",
")"
] | parse a detailed signal name into . | train | true |
22,517 | def setup_save_failure(set_many):
field_data = MagicMock(spec=FieldData)
field_data.get = (lambda block, name, default=None: 99)
field_data.set_many = set_many
class FieldTester(XBlock, ):
'\n Test XBlock with three fields\n '
field_a = Integer(scope=Scope.settings)
field_b = Integer(scope=Scope.content, default=10)
field_c = Integer(scope=Scope.user_state, default=42)
field_tester = FieldTester(TestRuntime(services={'field-data': field_data}), scope_ids=Mock(spec=ScopeIds))
return field_tester
| [
"def",
"setup_save_failure",
"(",
"set_many",
")",
":",
"field_data",
"=",
"MagicMock",
"(",
"spec",
"=",
"FieldData",
")",
"field_data",
".",
"get",
"=",
"(",
"lambda",
"block",
",",
"name",
",",
"default",
"=",
"None",
":",
"99",
")",
"field_data",
".",
"set_many",
"=",
"set_many",
"class",
"FieldTester",
"(",
"XBlock",
",",
")",
":",
"field_a",
"=",
"Integer",
"(",
"scope",
"=",
"Scope",
".",
"settings",
")",
"field_b",
"=",
"Integer",
"(",
"scope",
"=",
"Scope",
".",
"content",
",",
"default",
"=",
"10",
")",
"field_c",
"=",
"Integer",
"(",
"scope",
"=",
"Scope",
".",
"user_state",
",",
"default",
"=",
"42",
")",
"field_tester",
"=",
"FieldTester",
"(",
"TestRuntime",
"(",
"services",
"=",
"{",
"'field-data'",
":",
"field_data",
"}",
")",
",",
"scope_ids",
"=",
"Mock",
"(",
"spec",
"=",
"ScopeIds",
")",
")",
"return",
"field_tester"
] | set up tests for when theres a save error in the underlying keyvaluestore . | train | false |
22,519 | def whereIsYadis(resp):
content_type = resp.headers.get('content-type')
if (content_type and (content_type.split(';', 1)[0].lower() == YADIS_CONTENT_TYPE)):
return resp.final_url
else:
yadis_loc = resp.headers.get(YADIS_HEADER_NAME.lower())
if (not yadis_loc):
try:
yadis_loc = findHTMLMeta(StringIO(resp.body))
except MetaNotFound:
pass
return yadis_loc
| [
"def",
"whereIsYadis",
"(",
"resp",
")",
":",
"content_type",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"if",
"(",
"content_type",
"and",
"(",
"content_type",
".",
"split",
"(",
"';'",
",",
"1",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"YADIS_CONTENT_TYPE",
")",
")",
":",
"return",
"resp",
".",
"final_url",
"else",
":",
"yadis_loc",
"=",
"resp",
".",
"headers",
".",
"get",
"(",
"YADIS_HEADER_NAME",
".",
"lower",
"(",
")",
")",
"if",
"(",
"not",
"yadis_loc",
")",
":",
"try",
":",
"yadis_loc",
"=",
"findHTMLMeta",
"(",
"StringIO",
"(",
"resp",
".",
"body",
")",
")",
"except",
"MetaNotFound",
":",
"pass",
"return",
"yadis_loc"
] | given a httpresponse . | train | false |
22,522 | def utc_timestamp_to_datetime(timestamp):
if (timestamp is not None):
return datetime.fromtimestamp(timestamp, utc)
| [
"def",
"utc_timestamp_to_datetime",
"(",
"timestamp",
")",
":",
"if",
"(",
"timestamp",
"is",
"not",
"None",
")",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
",",
"utc",
")"
] | converts the given timestamp to a datetime instance . | train | false |
22,523 | def hypercube_graph(n):
dim = (n * [2])
G = grid_graph(dim)
G.name = ('hypercube_graph_(%d)' % n)
return G
| [
"def",
"hypercube_graph",
"(",
"n",
")",
":",
"dim",
"=",
"(",
"n",
"*",
"[",
"2",
"]",
")",
"G",
"=",
"grid_graph",
"(",
"dim",
")",
"G",
".",
"name",
"=",
"(",
"'hypercube_graph_(%d)'",
"%",
"n",
")",
"return",
"G"
] | return the n-dimensional hypercube . | train | false |
22,524 | def repeatfunc(func, times=None, *args):
if (times is None):
return starmap(func, repeat(args))
return starmap(func, repeat(args, times))
| [
"def",
"repeatfunc",
"(",
"func",
",",
"times",
"=",
"None",
",",
"*",
"args",
")",
":",
"if",
"(",
"times",
"is",
"None",
")",
":",
"return",
"starmap",
"(",
"func",
",",
"repeat",
"(",
"args",
")",
")",
"return",
"starmap",
"(",
"func",
",",
"repeat",
"(",
"args",
",",
"times",
")",
")"
] | repeat calls to func with specified arguments . | train | true |
22,525 | @command(usage='concurrently download tasks in aria2')
@command_line_parser()
@with_parser(parse_login)
@command_line_value('max-concurrent-downloads', alias='j', default=get_config('aria2-j', '5'))
def download_aria2(args):
aria2_conf = export_aria2_conf(args)
import platform
if (platform.system() == 'Windows'):
download_aria2_temp(aria2_conf, args.max_concurrent_downloads)
else:
download_aria2_stdin(aria2_conf, args.max_concurrent_downloads)
| [
"@",
"command",
"(",
"usage",
"=",
"'concurrently download tasks in aria2'",
")",
"@",
"command_line_parser",
"(",
")",
"@",
"with_parser",
"(",
"parse_login",
")",
"@",
"command_line_value",
"(",
"'max-concurrent-downloads'",
",",
"alias",
"=",
"'j'",
",",
"default",
"=",
"get_config",
"(",
"'aria2-j'",
",",
"'5'",
")",
")",
"def",
"download_aria2",
"(",
"args",
")",
":",
"aria2_conf",
"=",
"export_aria2_conf",
"(",
"args",
")",
"import",
"platform",
"if",
"(",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
")",
":",
"download_aria2_temp",
"(",
"aria2_conf",
",",
"args",
".",
"max_concurrent_downloads",
")",
"else",
":",
"download_aria2_stdin",
"(",
"aria2_conf",
",",
"args",
".",
"max_concurrent_downloads",
")"
] | usage: lx download-aria2 -j 5 [id|name] . | train | false |
22,526 | def oo_hostname_from_url(url):
if (not isinstance(url, string_types)):
raise errors.AnsibleFilterError('|failed expects a string or unicode')
parse_result = urlparse(url)
if (parse_result.netloc != ''):
return parse_result.netloc
else:
return parse_result.path
| [
"def",
"oo_hostname_from_url",
"(",
"url",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"url",
",",
"string_types",
")",
")",
":",
"raise",
"errors",
".",
"AnsibleFilterError",
"(",
"'|failed expects a string or unicode'",
")",
"parse_result",
"=",
"urlparse",
"(",
"url",
")",
"if",
"(",
"parse_result",
".",
"netloc",
"!=",
"''",
")",
":",
"return",
"parse_result",
".",
"netloc",
"else",
":",
"return",
"parse_result",
".",
"path"
] | returns the hostname contained in a url ex: URL -> ose3-master . | train | false |
22,527 | def bytesEnviron():
if (not _PY3):
return dict(os.environ)
target = dict()
for (x, y) in os.environ.items():
target[os.environ.encodekey(x)] = os.environ.encodevalue(y)
return target
| [
"def",
"bytesEnviron",
"(",
")",
":",
"if",
"(",
"not",
"_PY3",
")",
":",
"return",
"dict",
"(",
"os",
".",
"environ",
")",
"target",
"=",
"dict",
"(",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"target",
"[",
"os",
".",
"environ",
".",
"encodekey",
"(",
"x",
")",
"]",
"=",
"os",
".",
"environ",
".",
"encodevalue",
"(",
"y",
")",
"return",
"target"
] | return a l{dict} of l{os . | train | false |
22,528 | def remove_invalid_options(context, search_options, allowed_search_options):
if context.is_admin:
for key in ('sort_key', 'sort_dir', 'limit', 'marker'):
search_options.pop(key, None)
return
unknown_options = [opt for opt in search_options if (opt not in allowed_search_options)]
if unknown_options:
LOG.debug("Removing options '%s' from query", ', '.join(unknown_options))
for opt in unknown_options:
search_options.pop(opt, None)
| [
"def",
"remove_invalid_options",
"(",
"context",
",",
"search_options",
",",
"allowed_search_options",
")",
":",
"if",
"context",
".",
"is_admin",
":",
"for",
"key",
"in",
"(",
"'sort_key'",
",",
"'sort_dir'",
",",
"'limit'",
",",
"'marker'",
")",
":",
"search_options",
".",
"pop",
"(",
"key",
",",
"None",
")",
"return",
"unknown_options",
"=",
"[",
"opt",
"for",
"opt",
"in",
"search_options",
"if",
"(",
"opt",
"not",
"in",
"allowed_search_options",
")",
"]",
"if",
"unknown_options",
":",
"LOG",
".",
"debug",
"(",
"\"Removing options '%s' from query\"",
",",
"', '",
".",
"join",
"(",
"unknown_options",
")",
")",
"for",
"opt",
"in",
"unknown_options",
":",
"search_options",
".",
"pop",
"(",
"opt",
",",
"None",
")"
] | remove search options that are not valid for non-admin api/context . | train | false |
22,530 | @shared_constructor
def sparse_constructor(value, name=None, strict=False, allow_downcast=None, borrow=False, format=None):
if (not isinstance(value, scipy.sparse.spmatrix)):
raise TypeError('Expected a sparse matrix in the sparse shared variable constructor. Received: ', value.__class__)
if (format is None):
format = value.format
type = SparseType(format=format, dtype=value.dtype)
if (not borrow):
value = copy.deepcopy(value)
return SparseTensorSharedVariable(type=type, value=value, name=name, strict=strict, allow_downcast=allow_downcast)
| [
"@",
"shared_constructor",
"def",
"sparse_constructor",
"(",
"value",
",",
"name",
"=",
"None",
",",
"strict",
"=",
"False",
",",
"allow_downcast",
"=",
"None",
",",
"borrow",
"=",
"False",
",",
"format",
"=",
"None",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"value",
",",
"scipy",
".",
"sparse",
".",
"spmatrix",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Expected a sparse matrix in the sparse shared variable constructor. Received: '",
",",
"value",
".",
"__class__",
")",
"if",
"(",
"format",
"is",
"None",
")",
":",
"format",
"=",
"value",
".",
"format",
"type",
"=",
"SparseType",
"(",
"format",
"=",
"format",
",",
"dtype",
"=",
"value",
".",
"dtype",
")",
"if",
"(",
"not",
"borrow",
")",
":",
"value",
"=",
"copy",
".",
"deepcopy",
"(",
"value",
")",
"return",
"SparseTensorSharedVariable",
"(",
"type",
"=",
"type",
",",
"value",
"=",
"value",
",",
"name",
"=",
"name",
",",
"strict",
"=",
"strict",
",",
"allow_downcast",
"=",
"allow_downcast",
")"
] | sharedvariable constructor for sparsetype . | train | false |
22,532 | def make_filter_tuple(doctype, key, value):
if isinstance(value, (list, tuple)):
return [doctype, key, value[0], value[1]]
else:
return [doctype, key, u'=', value]
| [
"def",
"make_filter_tuple",
"(",
"doctype",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"doctype",
",",
"key",
",",
"value",
"[",
"0",
"]",
",",
"value",
"[",
"1",
"]",
"]",
"else",
":",
"return",
"[",
"doctype",
",",
"key",
",",
"u'='",
",",
"value",
"]"
] | return a filter tuple like [doctype . | train | false |
22,535 | def python_format(catalog, message):
if ('python-format' not in message.flags):
return
msgids = message.id
if (not isinstance(msgids, (list, tuple))):
msgids = (msgids,)
msgstrs = message.string
if (not isinstance(msgstrs, (list, tuple))):
msgstrs = (msgstrs,)
for (msgid, msgstr) in izip(msgids, msgstrs):
if msgstr:
_validate_format(msgid, msgstr)
| [
"def",
"python_format",
"(",
"catalog",
",",
"message",
")",
":",
"if",
"(",
"'python-format'",
"not",
"in",
"message",
".",
"flags",
")",
":",
"return",
"msgids",
"=",
"message",
".",
"id",
"if",
"(",
"not",
"isinstance",
"(",
"msgids",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
":",
"msgids",
"=",
"(",
"msgids",
",",
")",
"msgstrs",
"=",
"message",
".",
"string",
"if",
"(",
"not",
"isinstance",
"(",
"msgstrs",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
":",
"msgstrs",
"=",
"(",
"msgstrs",
",",
")",
"for",
"(",
"msgid",
",",
"msgstr",
")",
"in",
"izip",
"(",
"msgids",
",",
"msgstrs",
")",
":",
"if",
"msgstr",
":",
"_validate_format",
"(",
"msgid",
",",
"msgstr",
")"
] | verify the format string placeholders in the translation . | train | false |
22,536 | def update_leases(transform, persistence_service):
config = persistence_service.get()
new_leases = transform(config.leases)
if (new_leases != config.leases):
new_config = config.set('leases', new_leases)
d = persistence_service.save(new_config)
d.addCallback((lambda _: new_config.leases))
return d
return succeed(new_leases)
| [
"def",
"update_leases",
"(",
"transform",
",",
"persistence_service",
")",
":",
"config",
"=",
"persistence_service",
".",
"get",
"(",
")",
"new_leases",
"=",
"transform",
"(",
"config",
".",
"leases",
")",
"if",
"(",
"new_leases",
"!=",
"config",
".",
"leases",
")",
":",
"new_config",
"=",
"config",
".",
"set",
"(",
"'leases'",
",",
"new_leases",
")",
"d",
"=",
"persistence_service",
".",
"save",
"(",
"new_config",
")",
"d",
".",
"addCallback",
"(",
"(",
"lambda",
"_",
":",
"new_config",
".",
"leases",
")",
")",
"return",
"d",
"return",
"succeed",
"(",
"new_leases",
")"
] | update the leases configuration in the persistence service . | train | false |
22,537 | def _exponent(dval):
bb = _double_as_bytes(dval)
return (((bb[0] << 4) | (bb[1] >> 4)) & 2047)
| [
"def",
"_exponent",
"(",
"dval",
")",
":",
"bb",
"=",
"_double_as_bytes",
"(",
"dval",
")",
"return",
"(",
"(",
"(",
"bb",
"[",
"0",
"]",
"<<",
"4",
")",
"|",
"(",
"bb",
"[",
"1",
"]",
">>",
"4",
")",
")",
"&",
"2047",
")"
] | extract the exponentent bits from a double-precision floating point value . | train | false |
22,538 | def _set_ntp_peers(peers):
return __salt__['ntp.set_peers'](commit=False, *peers)
| [
"def",
"_set_ntp_peers",
"(",
"peers",
")",
":",
"return",
"__salt__",
"[",
"'ntp.set_peers'",
"]",
"(",
"commit",
"=",
"False",
",",
"*",
"peers",
")"
] | calls ntp . | train | false |
22,539 | def FormatAsHexString(num, width=None, prefix='0x'):
hex_str = hex(num)[2:]
hex_str = hex_str.replace('L', '')
if width:
hex_str = hex_str.rjust(width, '0')
return ('%s%s' % (prefix, hex_str))
| [
"def",
"FormatAsHexString",
"(",
"num",
",",
"width",
"=",
"None",
",",
"prefix",
"=",
"'0x'",
")",
":",
"hex_str",
"=",
"hex",
"(",
"num",
")",
"[",
"2",
":",
"]",
"hex_str",
"=",
"hex_str",
".",
"replace",
"(",
"'L'",
",",
"''",
")",
"if",
"width",
":",
"hex_str",
"=",
"hex_str",
".",
"rjust",
"(",
"width",
",",
"'0'",
")",
"return",
"(",
"'%s%s'",
"%",
"(",
"prefix",
",",
"hex_str",
")",
")"
] | takes an int and returns the number formatted as a hex string . | train | true |
22,540 | def is_expand():
return (flask.request.args.get('expand') is not None)
| [
"def",
"is_expand",
"(",
")",
":",
"return",
"(",
"flask",
".",
"request",
".",
"args",
".",
"get",
"(",
"'expand'",
")",
"is",
"not",
"None",
")"
] | returns whether the current request is for an expanded response . | train | false |
22,541 | def _get_widgets():
widgets = QApplication.instance().allWidgets()
widgets.sort(key=repr)
return [repr(w) for w in widgets]
| [
"def",
"_get_widgets",
"(",
")",
":",
"widgets",
"=",
"QApplication",
".",
"instance",
"(",
")",
".",
"allWidgets",
"(",
")",
"widgets",
".",
"sort",
"(",
"key",
"=",
"repr",
")",
"return",
"[",
"repr",
"(",
"w",
")",
"for",
"w",
"in",
"widgets",
"]"
] | get a string list of all widgets . | train | false |
22,543 | def parse_duration(value):
match = standard_duration_re.match(value)
if (not match):
match = iso8601_duration_re.match(value)
if match:
kw = match.groupdict()
sign = ((-1) if (kw.pop('sign', '+') == '-') else 1)
if kw.get('microseconds'):
kw['microseconds'] = kw['microseconds'].ljust(6, '0')
if (kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-')):
kw['microseconds'] = ('-' + kw['microseconds'])
kw = {k: float(v) for (k, v) in kw.items() if (v is not None)}
return (sign * datetime.timedelta(**kw))
| [
"def",
"parse_duration",
"(",
"value",
")",
":",
"match",
"=",
"standard_duration_re",
".",
"match",
"(",
"value",
")",
"if",
"(",
"not",
"match",
")",
":",
"match",
"=",
"iso8601_duration_re",
".",
"match",
"(",
"value",
")",
"if",
"match",
":",
"kw",
"=",
"match",
".",
"groupdict",
"(",
")",
"sign",
"=",
"(",
"(",
"-",
"1",
")",
"if",
"(",
"kw",
".",
"pop",
"(",
"'sign'",
",",
"'+'",
")",
"==",
"'-'",
")",
"else",
"1",
")",
"if",
"kw",
".",
"get",
"(",
"'microseconds'",
")",
":",
"kw",
"[",
"'microseconds'",
"]",
"=",
"kw",
"[",
"'microseconds'",
"]",
".",
"ljust",
"(",
"6",
",",
"'0'",
")",
"if",
"(",
"kw",
".",
"get",
"(",
"'seconds'",
")",
"and",
"kw",
".",
"get",
"(",
"'microseconds'",
")",
"and",
"kw",
"[",
"'seconds'",
"]",
".",
"startswith",
"(",
"'-'",
")",
")",
":",
"kw",
"[",
"'microseconds'",
"]",
"=",
"(",
"'-'",
"+",
"kw",
"[",
"'microseconds'",
"]",
")",
"kw",
"=",
"{",
"k",
":",
"float",
"(",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"kw",
".",
"items",
"(",
")",
"if",
"(",
"v",
"is",
"not",
"None",
")",
"}",
"return",
"(",
"sign",
"*",
"datetime",
".",
"timedelta",
"(",
"**",
"kw",
")",
")"
] | parses a duration string and returns a datetime . | train | false |
22,545 | def dvr_case_default_status():
s3db = current.s3db
ctable = s3db.dvr_case
field = ctable.status_id
default = field.default
if default:
return default
stable = s3db.dvr_case_status
query = ((stable.is_default == True) & (stable.deleted != True))
row = current.db(query).select(stable.id, limitby=(0, 1)).first()
if row:
ctable = s3db.dvr_case
default = field.default = row.id
return default
| [
"def",
"dvr_case_default_status",
"(",
")",
":",
"s3db",
"=",
"current",
".",
"s3db",
"ctable",
"=",
"s3db",
".",
"dvr_case",
"field",
"=",
"ctable",
".",
"status_id",
"default",
"=",
"field",
".",
"default",
"if",
"default",
":",
"return",
"default",
"stable",
"=",
"s3db",
".",
"dvr_case_status",
"query",
"=",
"(",
"(",
"stable",
".",
"is_default",
"==",
"True",
")",
"&",
"(",
"stable",
".",
"deleted",
"!=",
"True",
")",
")",
"row",
"=",
"current",
".",
"db",
"(",
"query",
")",
".",
"select",
"(",
"stable",
".",
"id",
",",
"limitby",
"=",
"(",
"0",
",",
"1",
")",
")",
".",
"first",
"(",
")",
"if",
"row",
":",
"ctable",
"=",
"s3db",
".",
"dvr_case",
"default",
"=",
"field",
".",
"default",
"=",
"row",
".",
"id",
"return",
"default"
] | helper to get/set the default status for case records @return: the default status_id . | train | false |
22,547 | def install_requires():
if JYTHON:
return (reqs('default.txt') + reqs('jython.txt'))
return reqs('default.txt')
| [
"def",
"install_requires",
"(",
")",
":",
"if",
"JYTHON",
":",
"return",
"(",
"reqs",
"(",
"'default.txt'",
")",
"+",
"reqs",
"(",
"'jython.txt'",
")",
")",
"return",
"reqs",
"(",
"'default.txt'",
")"
] | get list of requirements required for installation . | train | false |
22,548 | def test_category_delete_with_user(topic):
user = topic.user
forum = topic.forum
category = topic.forum.category
assert (user.post_count == 1)
assert (forum.post_count == 1)
assert (forum.topic_count == 1)
category.delete([user])
assert (user.post_count == 0)
category = Category.query.filter_by(id=category.id).first()
topic = Topic.query.filter_by(id=topic.id).first()
assert (category is None)
assert (topic is None)
| [
"def",
"test_category_delete_with_user",
"(",
"topic",
")",
":",
"user",
"=",
"topic",
".",
"user",
"forum",
"=",
"topic",
".",
"forum",
"category",
"=",
"topic",
".",
"forum",
".",
"category",
"assert",
"(",
"user",
".",
"post_count",
"==",
"1",
")",
"assert",
"(",
"forum",
".",
"post_count",
"==",
"1",
")",
"assert",
"(",
"forum",
".",
"topic_count",
"==",
"1",
")",
"category",
".",
"delete",
"(",
"[",
"user",
"]",
")",
"assert",
"(",
"user",
".",
"post_count",
"==",
"0",
")",
"category",
"=",
"Category",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"category",
".",
"id",
")",
".",
"first",
"(",
")",
"topic",
"=",
"Topic",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"topic",
".",
"id",
")",
".",
"first",
"(",
")",
"assert",
"(",
"category",
"is",
"None",
")",
"assert",
"(",
"topic",
"is",
"None",
")"
] | test the delete category method with recounting the users post counts . | train | false |
22,549 | def ErrorExit(msg):
print >>sys.stderr, msg
sys.exit(1)
| [
"def",
"ErrorExit",
"(",
"msg",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"msg",
"sys",
".",
"exit",
"(",
"1",
")"
] | print an error message to stderr and exit . | train | false |
22,550 | def rackconnectv3(vm_):
return config.get_cloud_config_value('rackconnectv3', vm_, __opts__, default=False, search_global=False)
| [
"def",
"rackconnectv3",
"(",
"vm_",
")",
":",
"return",
"config",
".",
"get_cloud_config_value",
"(",
"'rackconnectv3'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"False",
",",
"search_global",
"=",
"False",
")"
] | determine if server is using rackconnectv3 or not return the rackconnect network name or false . | train | true |
22,551 | def local_cache(namespace, key, generator, regenerate_if_none=False):
if (namespace not in local.cache):
local.cache[namespace] = {}
if (key not in local.cache[namespace]):
local.cache[namespace][key] = generator()
elif ((local.cache[namespace][key] == None) and regenerate_if_none):
local.cache[namespace][key] = generator()
return local.cache[namespace][key]
| [
"def",
"local_cache",
"(",
"namespace",
",",
"key",
",",
"generator",
",",
"regenerate_if_none",
"=",
"False",
")",
":",
"if",
"(",
"namespace",
"not",
"in",
"local",
".",
"cache",
")",
":",
"local",
".",
"cache",
"[",
"namespace",
"]",
"=",
"{",
"}",
"if",
"(",
"key",
"not",
"in",
"local",
".",
"cache",
"[",
"namespace",
"]",
")",
":",
"local",
".",
"cache",
"[",
"namespace",
"]",
"[",
"key",
"]",
"=",
"generator",
"(",
")",
"elif",
"(",
"(",
"local",
".",
"cache",
"[",
"namespace",
"]",
"[",
"key",
"]",
"==",
"None",
")",
"and",
"regenerate_if_none",
")",
":",
"local",
".",
"cache",
"[",
"namespace",
"]",
"[",
"key",
"]",
"=",
"generator",
"(",
")",
"return",
"local",
".",
"cache",
"[",
"namespace",
"]",
"[",
"key",
"]"
] | a key value store for caching within a request . | train | false |
22,552 | def CDLINVERTEDHAMMER(barDs, count):
return call_talib_with_ohlc(barDs, count, talib.CDLINVERTEDHAMMER)
| [
"def",
"CDLINVERTEDHAMMER",
"(",
"barDs",
",",
"count",
")",
":",
"return",
"call_talib_with_ohlc",
"(",
"barDs",
",",
"count",
",",
"talib",
".",
"CDLINVERTEDHAMMER",
")"
] | inverted hammer . | train | false |
22,553 | def test_bc_fit_invalid_ratio():
ratio = (1.0 / 10000.0)
bc = BalanceCascade(ratio=ratio, random_state=RND_SEED)
assert_raises(RuntimeError, bc.fit_sample, X, Y)
| [
"def",
"test_bc_fit_invalid_ratio",
"(",
")",
":",
"ratio",
"=",
"(",
"1.0",
"/",
"10000.0",
")",
"bc",
"=",
"BalanceCascade",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"assert_raises",
"(",
"RuntimeError",
",",
"bc",
".",
"fit_sample",
",",
"X",
",",
"Y",
")"
] | test either if an error is raised when the balancing ratio to fit is smaller than the one of the data . | train | false |
22,554 | def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args):
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
| [
"def",
"DEFINE_multistring",
"(",
"name",
",",
"default",
",",
"help",
",",
"flag_values",
"=",
"FLAGS",
",",
"**",
"args",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
")",
"serializer",
"=",
"ArgumentSerializer",
"(",
")",
"DEFINE_multi",
"(",
"parser",
",",
"serializer",
",",
"name",
",",
"default",
",",
"help",
",",
"flag_values",
",",
"**",
"args",
")"
] | registers a flag whose value can be a list of any strings . | train | true |
22,555 | def unfollow_group(context, data_dict):
schema = context.get('schema', ckan.logic.schema.default_follow_group_schema())
_unfollow(context, data_dict, schema, context['model'].UserFollowingGroup)
| [
"def",
"unfollow_group",
"(",
"context",
",",
"data_dict",
")",
":",
"schema",
"=",
"context",
".",
"get",
"(",
"'schema'",
",",
"ckan",
".",
"logic",
".",
"schema",
".",
"default_follow_group_schema",
"(",
")",
")",
"_unfollow",
"(",
"context",
",",
"data_dict",
",",
"schema",
",",
"context",
"[",
"'model'",
"]",
".",
"UserFollowingGroup",
")"
] | stop following a group . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.