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 |
|---|---|---|---|---|---|
45,556 | def _parse_ddwrt_response(data_str):
return {key: val for (key, val) in _DDWRT_DATA_REGEX.findall(data_str)}
| [
"def",
"_parse_ddwrt_response",
"(",
"data_str",
")",
":",
"return",
"{",
"key",
":",
"val",
"for",
"(",
"key",
",",
"val",
")",
"in",
"_DDWRT_DATA_REGEX",
".",
"findall",
"(",
"data_str",
")",
"}"
] | parse the dd-wrt data format . | train | false |
45,557 | def rotate_right(x, y):
if (len(x) == 0):
return []
y = (len(x) - (y % len(x)))
return (x[y:] + x[:y])
| [
"def",
"rotate_right",
"(",
"x",
",",
"y",
")",
":",
"if",
"(",
"len",
"(",
"x",
")",
"==",
"0",
")",
":",
"return",
"[",
"]",
"y",
"=",
"(",
"len",
"(",
"x",
")",
"-",
"(",
"y",
"%",
"len",
"(",
"x",
")",
")",
")",
"return",
"(",
"x",
"[",
"y",
":",
"]",
"+",
"x",
"[",
":",
"y",
"]",
")"
] | right rotates a list x by the number of steps specified in y . | train | false |
45,558 | def deterministicResolvingReactor(reactor, expectedAddresses=(), hostMap=None):
if (hostMap is None):
hostMap = {}
hostMap = hostMap.copy()
@provider(IHostnameResolver)
class SimpleNameResolver(object, ):
@staticmethod
def resolveHostName(resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics='TCP'):
resolutionReceiver.resolutionBegan(None)
for expectedAddress in hostMap.get(hostName, expectedAddresses):
if isinstance(expectedAddress, str):
expectedAddress = [IPv4Address, IPv6Address][isIPv6Address(expectedAddress)]('TCP', expectedAddress, portNumber)
resolutionReceiver.addressResolved(expectedAddress)
resolutionReceiver.resolutionComplete()
@provider(IReactorPluggableNameResolver)
class WithResolver(proxyForInterface(InterfaceClass('*', tuple(providedBy(reactor)))), ):
nameResolver = SimpleNameResolver()
return WithResolver(reactor)
| [
"def",
"deterministicResolvingReactor",
"(",
"reactor",
",",
"expectedAddresses",
"=",
"(",
")",
",",
"hostMap",
"=",
"None",
")",
":",
"if",
"(",
"hostMap",
"is",
"None",
")",
":",
"hostMap",
"=",
"{",
"}",
"hostMap",
"=",
"hostMap",
".",
"copy",
"(",
")",
"@",
"provider",
"(",
"IHostnameResolver",
")",
"class",
"SimpleNameResolver",
"(",
"object",
",",
")",
":",
"@",
"staticmethod",
"def",
"resolveHostName",
"(",
"resolutionReceiver",
",",
"hostName",
",",
"portNumber",
"=",
"0",
",",
"addressTypes",
"=",
"None",
",",
"transportSemantics",
"=",
"'TCP'",
")",
":",
"resolutionReceiver",
".",
"resolutionBegan",
"(",
"None",
")",
"for",
"expectedAddress",
"in",
"hostMap",
".",
"get",
"(",
"hostName",
",",
"expectedAddresses",
")",
":",
"if",
"isinstance",
"(",
"expectedAddress",
",",
"str",
")",
":",
"expectedAddress",
"=",
"[",
"IPv4Address",
",",
"IPv6Address",
"]",
"[",
"isIPv6Address",
"(",
"expectedAddress",
")",
"]",
"(",
"'TCP'",
",",
"expectedAddress",
",",
"portNumber",
")",
"resolutionReceiver",
".",
"addressResolved",
"(",
"expectedAddress",
")",
"resolutionReceiver",
".",
"resolutionComplete",
"(",
")",
"@",
"provider",
"(",
"IReactorPluggableNameResolver",
")",
"class",
"WithResolver",
"(",
"proxyForInterface",
"(",
"InterfaceClass",
"(",
"'*'",
",",
"tuple",
"(",
"providedBy",
"(",
"reactor",
")",
")",
")",
")",
",",
")",
":",
"nameResolver",
"=",
"SimpleNameResolver",
"(",
")",
"return",
"WithResolver",
"(",
"reactor",
")"
] | create a reactor that will deterministically resolve all hostnames it is passed to the list of addresses given . | train | false |
45,561 | def sin(x):
return Sin()(x)
| [
"def",
"sin",
"(",
"x",
")",
":",
"return",
"Sin",
"(",
")",
"(",
"x",
")"
] | apply sin to each element of the matrix mat . | train | false |
45,562 | def volume_type_get_all_by_group(context, group_id):
return IMPL.volume_type_get_all_by_group(context, group_id)
| [
"def",
"volume_type_get_all_by_group",
"(",
"context",
",",
"group_id",
")",
":",
"return",
"IMPL",
".",
"volume_type_get_all_by_group",
"(",
"context",
",",
"group_id",
")"
] | get all volumes in a group . | train | false |
45,564 | def commit():
connection._commit()
set_clean()
| [
"def",
"commit",
"(",
")",
":",
"connection",
".",
"_commit",
"(",
")",
"set_clean",
"(",
")"
] | commits pending changes . | train | false |
45,565 | def parallel(iterable, count, callable, *args, **named):
coop = task.Cooperator()
work = (callable(elem, *args, **named) for elem in iterable)
return defer.DeferredList([coop.coiterate(work) for _ in range(count)])
| [
"def",
"parallel",
"(",
"iterable",
",",
"count",
",",
"callable",
",",
"*",
"args",
",",
"**",
"named",
")",
":",
"coop",
"=",
"task",
".",
"Cooperator",
"(",
")",
"work",
"=",
"(",
"callable",
"(",
"elem",
",",
"*",
"args",
",",
"**",
"named",
")",
"for",
"elem",
"in",
"iterable",
")",
"return",
"defer",
".",
"DeferredList",
"(",
"[",
"coop",
".",
"coiterate",
"(",
"work",
")",
"for",
"_",
"in",
"range",
"(",
"count",
")",
"]",
")"
] | execute a callable over the objects in the given iterable . | train | false |
45,566 | def unpack_chunks(hg_unbundle10_obj):
while True:
(length,) = struct.unpack('>l', readexactly(hg_unbundle10_obj, 4))
if (length <= 4):
break
if (length < 84):
raise Exception('negative data length')
(node, p1, p2, cs) = struct.unpack('20s20s20s20s', readexactly(hg_unbundle10_obj, 80))
(yield {'node': node.encode('hex'), 'p1': p1.encode('hex'), 'p2': p2.encode('hex'), 'cs': cs.encode('hex'), 'data': [patch for patch in unpack_patches(hg_unbundle10_obj, (length - 84))]})
| [
"def",
"unpack_chunks",
"(",
"hg_unbundle10_obj",
")",
":",
"while",
"True",
":",
"(",
"length",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"'>l'",
",",
"readexactly",
"(",
"hg_unbundle10_obj",
",",
"4",
")",
")",
"if",
"(",
"length",
"<=",
"4",
")",
":",
"break",
"if",
"(",
"length",
"<",
"84",
")",
":",
"raise",
"Exception",
"(",
"'negative data length'",
")",
"(",
"node",
",",
"p1",
",",
"p2",
",",
"cs",
")",
"=",
"struct",
".",
"unpack",
"(",
"'20s20s20s20s'",
",",
"readexactly",
"(",
"hg_unbundle10_obj",
",",
"80",
")",
")",
"(",
"yield",
"{",
"'node'",
":",
"node",
".",
"encode",
"(",
"'hex'",
")",
",",
"'p1'",
":",
"p1",
".",
"encode",
"(",
"'hex'",
")",
",",
"'p2'",
":",
"p2",
".",
"encode",
"(",
"'hex'",
")",
",",
"'cs'",
":",
"cs",
".",
"encode",
"(",
"'hex'",
")",
",",
"'data'",
":",
"[",
"patch",
"for",
"patch",
"in",
"unpack_patches",
"(",
"hg_unbundle10_obj",
",",
"(",
"length",
"-",
"84",
")",
")",
"]",
"}",
")"
] | this method provides a generator of parsed chunks of a "group" in a mercurial unbundle10 object which is created when a changeset that is pushed to a tool shed repository using hg push from the command line is read using readbundle . | train | false |
45,567 | @subscriber(ResourceChanged, for_resources=('group',), for_actions=(ACTIONS.DELETE,))
def on_groups_deleted(event):
permission_backend = event.request.registry.permission
for change in event.impacted_records:
group = change['old']
bucket_id = event.payload['bucket_id']
group_uri = utils.instance_uri(event.request, 'group', bucket_id=bucket_id, id=group['id'])
permission_backend.remove_principal(group_uri)
| [
"@",
"subscriber",
"(",
"ResourceChanged",
",",
"for_resources",
"=",
"(",
"'group'",
",",
")",
",",
"for_actions",
"=",
"(",
"ACTIONS",
".",
"DELETE",
",",
")",
")",
"def",
"on_groups_deleted",
"(",
"event",
")",
":",
"permission_backend",
"=",
"event",
".",
"request",
".",
"registry",
".",
"permission",
"for",
"change",
"in",
"event",
".",
"impacted_records",
":",
"group",
"=",
"change",
"[",
"'old'",
"]",
"bucket_id",
"=",
"event",
".",
"payload",
"[",
"'bucket_id'",
"]",
"group_uri",
"=",
"utils",
".",
"instance_uri",
"(",
"event",
".",
"request",
",",
"'group'",
",",
"bucket_id",
"=",
"bucket_id",
",",
"id",
"=",
"group",
"[",
"'id'",
"]",
")",
"permission_backend",
".",
"remove_principal",
"(",
"group_uri",
")"
] | some groups were deleted . | train | false |
45,568 | def quota_destroy_all_by_project_and_user(context, project_id, user_id):
return IMPL.quota_destroy_all_by_project_and_user(context, project_id, user_id)
| [
"def",
"quota_destroy_all_by_project_and_user",
"(",
"context",
",",
"project_id",
",",
"user_id",
")",
":",
"return",
"IMPL",
".",
"quota_destroy_all_by_project_and_user",
"(",
"context",
",",
"project_id",
",",
"user_id",
")"
] | destroy all quotas associated with a given project and user . | train | false |
45,569 | def windows_get_size(path):
import win32file
if isbytestring(path):
path = path.decode(filesystem_encoding)
h = win32file.CreateFileW(path, 0, ((win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE) | win32file.FILE_SHARE_DELETE), None, win32file.OPEN_EXISTING, 0, None)
try:
return win32file.GetFileSize(h)
finally:
win32file.CloseHandle(h)
| [
"def",
"windows_get_size",
"(",
"path",
")",
":",
"import",
"win32file",
"if",
"isbytestring",
"(",
"path",
")",
":",
"path",
"=",
"path",
".",
"decode",
"(",
"filesystem_encoding",
")",
"h",
"=",
"win32file",
".",
"CreateFileW",
"(",
"path",
",",
"0",
",",
"(",
"(",
"win32file",
".",
"FILE_SHARE_READ",
"|",
"win32file",
".",
"FILE_SHARE_WRITE",
")",
"|",
"win32file",
".",
"FILE_SHARE_DELETE",
")",
",",
"None",
",",
"win32file",
".",
"OPEN_EXISTING",
",",
"0",
",",
"None",
")",
"try",
":",
"return",
"win32file",
".",
"GetFileSize",
"(",
"h",
")",
"finally",
":",
"win32file",
".",
"CloseHandle",
"(",
"h",
")"
] | on windows file sizes are only accurately stored in the actual file . | train | false |
45,570 | def _compute_type_url(klass, prefix=_GOOGLE_APIS_PREFIX):
name = klass.DESCRIPTOR.full_name
return ('%s/%s' % (prefix, name))
| [
"def",
"_compute_type_url",
"(",
"klass",
",",
"prefix",
"=",
"_GOOGLE_APIS_PREFIX",
")",
":",
"name",
"=",
"klass",
".",
"DESCRIPTOR",
".",
"full_name",
"return",
"(",
"'%s/%s'",
"%",
"(",
"prefix",
",",
"name",
")",
")"
] | compute a type url for a klass . | train | true |
45,571 | def teardown_environment():
(oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff
os.chdir(old_wd)
reload(path)
for key in list(env):
if (key not in oldenv):
del env[key]
env.update(oldenv)
if hasattr(sys, 'frozen'):
del sys.frozen
| [
"def",
"teardown_environment",
"(",
")",
":",
"(",
"oldenv",
",",
"os",
".",
"name",
",",
"sys",
".",
"platform",
",",
"path",
".",
"get_home_dir",
",",
"IPython",
".",
"__file__",
",",
"old_wd",
")",
"=",
"oldstuff",
"os",
".",
"chdir",
"(",
"old_wd",
")",
"reload",
"(",
"path",
")",
"for",
"key",
"in",
"list",
"(",
"env",
")",
":",
"if",
"(",
"key",
"not",
"in",
"oldenv",
")",
":",
"del",
"env",
"[",
"key",
"]",
"env",
".",
"update",
"(",
"oldenv",
")",
"if",
"hasattr",
"(",
"sys",
",",
"'frozen'",
")",
":",
"del",
"sys",
".",
"frozen"
] | restore things that were remembered by the setup_environment function . | train | false |
45,572 | @register.filter
def is_locked(model):
return (model.current_revision and model.current_revision.locked)
| [
"@",
"register",
".",
"filter",
"def",
"is_locked",
"(",
"model",
")",
":",
"return",
"(",
"model",
".",
"current_revision",
"and",
"model",
".",
"current_revision",
".",
"locked",
")"
] | check if article is locked . | train | false |
45,574 | @post_required
@user_view
def remove_locale(request, user):
POST = request.POST
if (('locale' in POST) and (POST['locale'] != settings.LANGUAGE_CODE)):
user.remove_locale(POST['locale'])
return http.HttpResponse()
return http.HttpResponseBadRequest()
| [
"@",
"post_required",
"@",
"user_view",
"def",
"remove_locale",
"(",
"request",
",",
"user",
")",
":",
"POST",
"=",
"request",
".",
"POST",
"if",
"(",
"(",
"'locale'",
"in",
"POST",
")",
"and",
"(",
"POST",
"[",
"'locale'",
"]",
"!=",
"settings",
".",
"LANGUAGE_CODE",
")",
")",
":",
"user",
".",
"remove_locale",
"(",
"POST",
"[",
"'locale'",
"]",
")",
"return",
"http",
".",
"HttpResponse",
"(",
")",
"return",
"http",
".",
"HttpResponseBadRequest",
"(",
")"
] | remove a locale from the users translations . | train | false |
45,575 | def _DefaultNamespace():
return namespace_manager.get_namespace()
| [
"def",
"_DefaultNamespace",
"(",
")",
":",
"return",
"namespace_manager",
".",
"get_namespace",
"(",
")"
] | return the default namespace . | train | false |
45,578 | @command('mix\\s*(\\d{1,4})')
def mix(num):
g.content = (g.content or content.generate_songlist_display())
if (g.browse_mode != 'normal'):
g.message = util.F('mix only videos')
else:
item = g.model[(int(num) - 1)]
if (item is None):
g.message = util.F('invalid item')
return
item = util.get_pafy(item)
try:
plist(('RD' + item.videoid))
except OSError:
g.message = util.F('no mix')
| [
"@",
"command",
"(",
"'mix\\\\s*(\\\\d{1,4})'",
")",
"def",
"mix",
"(",
"num",
")",
":",
"g",
".",
"content",
"=",
"(",
"g",
".",
"content",
"or",
"content",
".",
"generate_songlist_display",
"(",
")",
")",
"if",
"(",
"g",
".",
"browse_mode",
"!=",
"'normal'",
")",
":",
"g",
".",
"message",
"=",
"util",
".",
"F",
"(",
"'mix only videos'",
")",
"else",
":",
"item",
"=",
"g",
".",
"model",
"[",
"(",
"int",
"(",
"num",
")",
"-",
"1",
")",
"]",
"if",
"(",
"item",
"is",
"None",
")",
":",
"g",
".",
"message",
"=",
"util",
".",
"F",
"(",
"'invalid item'",
")",
"return",
"item",
"=",
"util",
".",
"get_pafy",
"(",
"item",
")",
"try",
":",
"plist",
"(",
"(",
"'RD'",
"+",
"item",
".",
"videoid",
")",
")",
"except",
"OSError",
":",
"g",
".",
"message",
"=",
"util",
".",
"F",
"(",
"'no mix'",
")"
] | returns an iterator that alternates the given lists . | train | false |
45,580 | def removeGeneratedFiles():
gcodeFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['gcode'])
for gcodeFilePath in gcodeFilePaths:
if ('alterations' not in gcodeFilePath):
os.remove(gcodeFilePath)
print ('removeGeneratedFiles deleted ' + gcodeFilePath)
svgFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['svg'])
for svgFilePath in svgFilePaths:
if archive.getEndsWithList(svgFilePath, ['_bottom.svg', '_carve.svg', '_chop.svg', '_cleave.svg']):
os.remove(svgFilePath)
print ('removeGeneratedFiles deleted ' + svgFilePath)
xmlFilePaths = archive.getFilesWithFileTypesWithoutWordsRecursively(['xml'])
for xmlFilePath in xmlFilePaths:
if archive.getEndsWithList(xmlFilePath, ['_interpret.xml']):
os.remove(xmlFilePath)
print ('removeGeneratedFiles deleted ' + xmlFilePath)
archive.removeBackupFilesByTypes(['gcode', 'svg', 'xml'])
| [
"def",
"removeGeneratedFiles",
"(",
")",
":",
"gcodeFilePaths",
"=",
"archive",
".",
"getFilesWithFileTypesWithoutWordsRecursively",
"(",
"[",
"'gcode'",
"]",
")",
"for",
"gcodeFilePath",
"in",
"gcodeFilePaths",
":",
"if",
"(",
"'alterations'",
"not",
"in",
"gcodeFilePath",
")",
":",
"os",
".",
"remove",
"(",
"gcodeFilePath",
")",
"print",
"(",
"'removeGeneratedFiles deleted '",
"+",
"gcodeFilePath",
")",
"svgFilePaths",
"=",
"archive",
".",
"getFilesWithFileTypesWithoutWordsRecursively",
"(",
"[",
"'svg'",
"]",
")",
"for",
"svgFilePath",
"in",
"svgFilePaths",
":",
"if",
"archive",
".",
"getEndsWithList",
"(",
"svgFilePath",
",",
"[",
"'_bottom.svg'",
",",
"'_carve.svg'",
",",
"'_chop.svg'",
",",
"'_cleave.svg'",
"]",
")",
":",
"os",
".",
"remove",
"(",
"svgFilePath",
")",
"print",
"(",
"'removeGeneratedFiles deleted '",
"+",
"svgFilePath",
")",
"xmlFilePaths",
"=",
"archive",
".",
"getFilesWithFileTypesWithoutWordsRecursively",
"(",
"[",
"'xml'",
"]",
")",
"for",
"xmlFilePath",
"in",
"xmlFilePaths",
":",
"if",
"archive",
".",
"getEndsWithList",
"(",
"xmlFilePath",
",",
"[",
"'_interpret.xml'",
"]",
")",
":",
"os",
".",
"remove",
"(",
"xmlFilePath",
")",
"print",
"(",
"'removeGeneratedFiles deleted '",
"+",
"xmlFilePath",
")",
"archive",
".",
"removeBackupFilesByTypes",
"(",
"[",
"'gcode'",
",",
"'svg'",
",",
"'xml'",
"]",
")"
] | remove generated files . | train | false |
45,582 | def _fetch_secret(pass_path):
cmd = 'pass show {0}'.format(pass_path.strip())
log.debug('Fetching secret: {0}'.format(cmd))
proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
(pass_data, pass_error) = proc.communicate()
if (proc.returncode or (not pass_data)):
msg = 'Could not fetch secret: {0} {1}'.format(pass_data, pass_error)
log.warn(msg)
pass_data = pass_path
return pass_data.strip()
| [
"def",
"_fetch_secret",
"(",
"pass_path",
")",
":",
"cmd",
"=",
"'pass show {0}'",
".",
"format",
"(",
"pass_path",
".",
"strip",
"(",
")",
")",
"log",
".",
"debug",
"(",
"'Fetching secret: {0}'",
".",
"format",
"(",
"cmd",
")",
")",
"proc",
"=",
"Popen",
"(",
"cmd",
".",
"split",
"(",
"' '",
")",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"(",
"pass_data",
",",
"pass_error",
")",
"=",
"proc",
".",
"communicate",
"(",
")",
"if",
"(",
"proc",
".",
"returncode",
"or",
"(",
"not",
"pass_data",
")",
")",
":",
"msg",
"=",
"'Could not fetch secret: {0} {1}'",
".",
"format",
"(",
"pass_data",
",",
"pass_error",
")",
"log",
".",
"warn",
"(",
"msg",
")",
"pass_data",
"=",
"pass_path",
"return",
"pass_data",
".",
"strip",
"(",
")"
] | fetch secret from pass based on pass_path . | train | true |
45,583 | def SetOutputFile(file=None, needclose=0):
global _File, _NeedClose
if _NeedClose:
tmp = _File
_NeedClose = 0
_File = None
tmp.close()
if (file is None):
import sys
file = sys.stdout
_File = file
_NeedClose = (file and needclose)
| [
"def",
"SetOutputFile",
"(",
"file",
"=",
"None",
",",
"needclose",
"=",
"0",
")",
":",
"global",
"_File",
",",
"_NeedClose",
"if",
"_NeedClose",
":",
"tmp",
"=",
"_File",
"_NeedClose",
"=",
"0",
"_File",
"=",
"None",
"tmp",
".",
"close",
"(",
")",
"if",
"(",
"file",
"is",
"None",
")",
":",
"import",
"sys",
"file",
"=",
"sys",
".",
"stdout",
"_File",
"=",
"file",
"_NeedClose",
"=",
"(",
"file",
"and",
"needclose",
")"
] | call this with an open file object to make it the output file . | train | false |
45,584 | def read_timit_block(stream):
line = stream.readline()
if (not line):
return []
(n, sent) = line.split(u' ', 1)
return [sent]
| [
"def",
"read_timit_block",
"(",
"stream",
")",
":",
"line",
"=",
"stream",
".",
"readline",
"(",
")",
"if",
"(",
"not",
"line",
")",
":",
"return",
"[",
"]",
"(",
"n",
",",
"sent",
")",
"=",
"line",
".",
"split",
"(",
"u' '",
",",
"1",
")",
"return",
"[",
"sent",
"]"
] | block reader for timit tagged sentences . | train | false |
45,586 | @requires_sklearn
def test_gat_plot_matrix():
gat = _get_data()
gat.plot()
del gat.scores_
assert_raises(RuntimeError, gat.plot)
| [
"@",
"requires_sklearn",
"def",
"test_gat_plot_matrix",
"(",
")",
":",
"gat",
"=",
"_get_data",
"(",
")",
"gat",
".",
"plot",
"(",
")",
"del",
"gat",
".",
"scores_",
"assert_raises",
"(",
"RuntimeError",
",",
"gat",
".",
"plot",
")"
] | test gat matrix plot . | train | false |
45,588 | def date(*args, **kwargs):
d = None
f = None
if ((len(args) == 0) and (kwargs.get('year') is not None) and kwargs.get('month') and kwargs.get('day')):
d = Date(**kwargs)
elif kwargs.get('week'):
f = kwargs.pop('format', None)
d = Date(*_yyyywwd2yyyymmdd(kwargs.pop('year', ((args and args[0]) or Date.now().year)), kwargs.pop('week'), kwargs.pop('weekday', kwargs.pop('day', 1))), **kwargs)
elif ((len(args) == 0) or (args[0] == NOW)):
d = Date.now()
elif ((len(args) == 1) and isinstance(args[0], (Date, datetime))):
d = Date.fromtimestamp(int(mktime(args[0].timetuple())))
d += time(microseconds=args[0].microsecond)
elif ((len(args) == 1) and (isinstance(args[0], int) or (isinstance(args[0], basestring) and args[0].isdigit()))):
d = Date.fromtimestamp(int(args[0]))
elif ((len(args) == 1) and isinstance(args[0], basestring)):
try:
d = Date.fromtimestamp(mktime_tz(parsedate_tz(args[0])))
except:
for format in (((('format' in kwargs) and [kwargs['format']]) or []) + date_formats):
try:
d = Date.strptime(args[0], format)
break
except:
pass
if (d is None):
raise DateError(('unknown date format for %s' % repr(args[0])))
elif ((len(args) == 2) and isinstance(args[0], basestring)):
d = Date.strptime(args[0], args[1])
elif (len(args) >= 3):
f = kwargs.pop('format', None)
d = Date(*args[:7], **kwargs)
else:
raise DateError('unknown date format')
d.format = (kwargs.get('format') or ((len(args) > 7) and args[7]) or f or Date.format)
return d
| [
"def",
"date",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"d",
"=",
"None",
"f",
"=",
"None",
"if",
"(",
"(",
"len",
"(",
"args",
")",
"==",
"0",
")",
"and",
"(",
"kwargs",
".",
"get",
"(",
"'year'",
")",
"is",
"not",
"None",
")",
"and",
"kwargs",
".",
"get",
"(",
"'month'",
")",
"and",
"kwargs",
".",
"get",
"(",
"'day'",
")",
")",
":",
"d",
"=",
"Date",
"(",
"**",
"kwargs",
")",
"elif",
"kwargs",
".",
"get",
"(",
"'week'",
")",
":",
"f",
"=",
"kwargs",
".",
"pop",
"(",
"'format'",
",",
"None",
")",
"d",
"=",
"Date",
"(",
"*",
"_yyyywwd2yyyymmdd",
"(",
"kwargs",
".",
"pop",
"(",
"'year'",
",",
"(",
"(",
"args",
"and",
"args",
"[",
"0",
"]",
")",
"or",
"Date",
".",
"now",
"(",
")",
".",
"year",
")",
")",
",",
"kwargs",
".",
"pop",
"(",
"'week'",
")",
",",
"kwargs",
".",
"pop",
"(",
"'weekday'",
",",
"kwargs",
".",
"pop",
"(",
"'day'",
",",
"1",
")",
")",
")",
",",
"**",
"kwargs",
")",
"elif",
"(",
"(",
"len",
"(",
"args",
")",
"==",
"0",
")",
"or",
"(",
"args",
"[",
"0",
"]",
"==",
"NOW",
")",
")",
":",
"d",
"=",
"Date",
".",
"now",
"(",
")",
"elif",
"(",
"(",
"len",
"(",
"args",
")",
"==",
"1",
")",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"(",
"Date",
",",
"datetime",
")",
")",
")",
":",
"d",
"=",
"Date",
".",
"fromtimestamp",
"(",
"int",
"(",
"mktime",
"(",
"args",
"[",
"0",
"]",
".",
"timetuple",
"(",
")",
")",
")",
")",
"d",
"+=",
"time",
"(",
"microseconds",
"=",
"args",
"[",
"0",
"]",
".",
"microsecond",
")",
"elif",
"(",
"(",
"len",
"(",
"args",
")",
"==",
"1",
")",
"and",
"(",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"int",
")",
"or",
"(",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"basestring",
")",
"and",
"args",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
")",
")",
")",
":",
"d",
"=",
"Date",
".",
"fromtimestamp",
"(",
"int",
"(",
"args",
"[",
"0",
"]",
")",
")",
"elif",
"(",
"(",
"len",
"(",
"args",
")",
"==",
"1",
")",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"basestring",
")",
")",
":",
"try",
":",
"d",
"=",
"Date",
".",
"fromtimestamp",
"(",
"mktime_tz",
"(",
"parsedate_tz",
"(",
"args",
"[",
"0",
"]",
")",
")",
")",
"except",
":",
"for",
"format",
"in",
"(",
"(",
"(",
"(",
"'format'",
"in",
"kwargs",
")",
"and",
"[",
"kwargs",
"[",
"'format'",
"]",
"]",
")",
"or",
"[",
"]",
")",
"+",
"date_formats",
")",
":",
"try",
":",
"d",
"=",
"Date",
".",
"strptime",
"(",
"args",
"[",
"0",
"]",
",",
"format",
")",
"break",
"except",
":",
"pass",
"if",
"(",
"d",
"is",
"None",
")",
":",
"raise",
"DateError",
"(",
"(",
"'unknown date format for %s'",
"%",
"repr",
"(",
"args",
"[",
"0",
"]",
")",
")",
")",
"elif",
"(",
"(",
"len",
"(",
"args",
")",
"==",
"2",
")",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"basestring",
")",
")",
":",
"d",
"=",
"Date",
".",
"strptime",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
")",
"elif",
"(",
"len",
"(",
"args",
")",
">=",
"3",
")",
":",
"f",
"=",
"kwargs",
".",
"pop",
"(",
"'format'",
",",
"None",
")",
"d",
"=",
"Date",
"(",
"*",
"args",
"[",
":",
"7",
"]",
",",
"**",
"kwargs",
")",
"else",
":",
"raise",
"DateError",
"(",
"'unknown date format'",
")",
"d",
".",
"format",
"=",
"(",
"kwargs",
".",
"get",
"(",
"'format'",
")",
"or",
"(",
"(",
"len",
"(",
"args",
")",
">",
"7",
")",
"and",
"args",
"[",
"7",
"]",
")",
"or",
"f",
"or",
"Date",
".",
"format",
")",
"return",
"d"
] | return the current date . | train | false |
45,589 | def register_run_keyword(library, keyword, args_to_process=None, deprecation_warning=True):
RUN_KW_REGISTER.register_run_keyword(library, keyword, args_to_process, deprecation_warning)
| [
"def",
"register_run_keyword",
"(",
"library",
",",
"keyword",
",",
"args_to_process",
"=",
"None",
",",
"deprecation_warning",
"=",
"True",
")",
":",
"RUN_KW_REGISTER",
".",
"register_run_keyword",
"(",
"library",
",",
"keyword",
",",
"args_to_process",
",",
"deprecation_warning",
")"
] | registers run keyword so that its arguments can be handled correctly . | train | false |
45,590 | def _create_cadf_payload(operation, resource_type, resource_id, outcome, initiator, reason=None):
if (resource_type not in CADF_TYPE_MAP):
target_uri = taxonomy.UNKNOWN
else:
target_uri = CADF_TYPE_MAP.get(resource_type)
target = resource.Resource(typeURI=target_uri, id=resource_id)
audit_kwargs = {'resource_info': resource_id}
cadf_action = ('%s.%s' % (operation, resource_type))
event_type = ('%s.%s.%s' % (SERVICE, resource_type, operation))
_send_audit_notification(cadf_action, initiator, outcome, target, event_type, reason=reason, **audit_kwargs)
| [
"def",
"_create_cadf_payload",
"(",
"operation",
",",
"resource_type",
",",
"resource_id",
",",
"outcome",
",",
"initiator",
",",
"reason",
"=",
"None",
")",
":",
"if",
"(",
"resource_type",
"not",
"in",
"CADF_TYPE_MAP",
")",
":",
"target_uri",
"=",
"taxonomy",
".",
"UNKNOWN",
"else",
":",
"target_uri",
"=",
"CADF_TYPE_MAP",
".",
"get",
"(",
"resource_type",
")",
"target",
"=",
"resource",
".",
"Resource",
"(",
"typeURI",
"=",
"target_uri",
",",
"id",
"=",
"resource_id",
")",
"audit_kwargs",
"=",
"{",
"'resource_info'",
":",
"resource_id",
"}",
"cadf_action",
"=",
"(",
"'%s.%s'",
"%",
"(",
"operation",
",",
"resource_type",
")",
")",
"event_type",
"=",
"(",
"'%s.%s.%s'",
"%",
"(",
"SERVICE",
",",
"resource_type",
",",
"operation",
")",
")",
"_send_audit_notification",
"(",
"cadf_action",
",",
"initiator",
",",
"outcome",
",",
"target",
",",
"event_type",
",",
"reason",
"=",
"reason",
",",
"**",
"audit_kwargs",
")"
] | prepare data for cadf audit notifier . | train | false |
45,591 | @require_context
@require_volume_exists
def volume_glance_metadata_copy_from_volume_to_volume(context, src_volume_id, volume_id):
session = get_session()
with session.begin():
metadata = _volume_glance_metadata_get(context, src_volume_id, session=session)
for meta in metadata:
vol_glance_metadata = models.VolumeGlanceMetadata()
vol_glance_metadata.volume_id = volume_id
vol_glance_metadata.key = meta['key']
vol_glance_metadata.value = meta['value']
vol_glance_metadata.save(session=session)
| [
"@",
"require_context",
"@",
"require_volume_exists",
"def",
"volume_glance_metadata_copy_from_volume_to_volume",
"(",
"context",
",",
"src_volume_id",
",",
"volume_id",
")",
":",
"session",
"=",
"get_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"metadata",
"=",
"_volume_glance_metadata_get",
"(",
"context",
",",
"src_volume_id",
",",
"session",
"=",
"session",
")",
"for",
"meta",
"in",
"metadata",
":",
"vol_glance_metadata",
"=",
"models",
".",
"VolumeGlanceMetadata",
"(",
")",
"vol_glance_metadata",
".",
"volume_id",
"=",
"volume_id",
"vol_glance_metadata",
".",
"key",
"=",
"meta",
"[",
"'key'",
"]",
"vol_glance_metadata",
".",
"value",
"=",
"meta",
"[",
"'value'",
"]",
"vol_glance_metadata",
".",
"save",
"(",
"session",
"=",
"session",
")"
] | update the glance metadata for a volume . | train | false |
45,592 | def _is_dev_environment():
return os.environ.get('SERVER_SOFTWARE', '').startswith('Development')
| [
"def",
"_is_dev_environment",
"(",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"'SERVER_SOFTWARE'",
",",
"''",
")",
".",
"startswith",
"(",
"'Development'",
")"
] | indicates whether this code is being run in the development environment . | train | false |
45,593 | def set_audio_mode(new_mode):
if (new_mode in ('voice and sound', 'silent', 'voice only', 'sound only')):
global audio_mode
audio_mode = new_mode
| [
"def",
"set_audio_mode",
"(",
"new_mode",
")",
":",
"if",
"(",
"new_mode",
"in",
"(",
"'voice and sound'",
",",
"'silent'",
",",
"'voice only'",
",",
"'sound only'",
")",
")",
":",
"global",
"audio_mode",
"audio_mode",
"=",
"new_mode"
] | a save way to set the audio mode . | train | false |
45,594 | def export_host_info(inventory):
export_info = {'hosts': {}}
host_info = export_info['hosts']
export_info['all'] = inventory['all']['vars']
for (host, hostvars) in inventory['_meta']['hostvars'].items():
host_info[host] = {}
host_info[host]['hostvars'] = hostvars
for (group_name, group_info) in inventory.items():
if (group_name in ('_meta', 'all')):
continue
for host in group_info['hosts']:
if ('groups' not in host_info[host]):
host_info[host]['groups'] = []
host_info[host]['groups'].append(group_name)
return export_info
| [
"def",
"export_host_info",
"(",
"inventory",
")",
":",
"export_info",
"=",
"{",
"'hosts'",
":",
"{",
"}",
"}",
"host_info",
"=",
"export_info",
"[",
"'hosts'",
"]",
"export_info",
"[",
"'all'",
"]",
"=",
"inventory",
"[",
"'all'",
"]",
"[",
"'vars'",
"]",
"for",
"(",
"host",
",",
"hostvars",
")",
"in",
"inventory",
"[",
"'_meta'",
"]",
"[",
"'hostvars'",
"]",
".",
"items",
"(",
")",
":",
"host_info",
"[",
"host",
"]",
"=",
"{",
"}",
"host_info",
"[",
"host",
"]",
"[",
"'hostvars'",
"]",
"=",
"hostvars",
"for",
"(",
"group_name",
",",
"group_info",
")",
"in",
"inventory",
".",
"items",
"(",
")",
":",
"if",
"(",
"group_name",
"in",
"(",
"'_meta'",
",",
"'all'",
")",
")",
":",
"continue",
"for",
"host",
"in",
"group_info",
"[",
"'hosts'",
"]",
":",
"if",
"(",
"'groups'",
"not",
"in",
"host_info",
"[",
"host",
"]",
")",
":",
"host_info",
"[",
"host",
"]",
"[",
"'groups'",
"]",
"=",
"[",
"]",
"host_info",
"[",
"host",
"]",
"[",
"'groups'",
"]",
".",
"append",
"(",
"group_name",
")",
"return",
"export_info"
] | pivot variable information to be a per-host dict this command is meant for exporting an existing inventorys information . | train | false |
45,595 | def tokenize_string(source):
line_reader = StringIO(source).readline
for (toknum, tokval, _, _, _) in tokenize.generate_tokens(line_reader):
(yield (toknum, tokval))
| [
"def",
"tokenize_string",
"(",
"source",
")",
":",
"line_reader",
"=",
"StringIO",
"(",
"source",
")",
".",
"readline",
"for",
"(",
"toknum",
",",
"tokval",
",",
"_",
",",
"_",
",",
"_",
")",
"in",
"tokenize",
".",
"generate_tokens",
"(",
"line_reader",
")",
":",
"(",
"yield",
"(",
"toknum",
",",
"tokval",
")",
")"
] | tokenize a python source code string . | train | false |
45,596 | def printError(failure, hostname):
failure.trap(error.DNSNameError)
sys.stderr.write(('ERROR: hostname not found %r\n' % (hostname,)))
| [
"def",
"printError",
"(",
"failure",
",",
"hostname",
")",
":",
"failure",
".",
"trap",
"(",
"error",
".",
"DNSNameError",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"(",
"'ERROR: hostname not found %r\\n'",
"%",
"(",
"hostname",
",",
")",
")",
")"
] | print a friendly error message if the hostname could not be resolved . | train | false |
45,597 | def resource_absent(resource, identifier_fields, profile='pagerduty', subdomain=None, api_key=None, **kwargs):
ret = {'name': kwargs['name'], 'changes': {}, 'result': None, 'comment': ''}
for (k, v) in kwargs.items():
if (k not in identifier_fields):
continue
result = delete_resource(resource, v, identifier_fields, profile=profile, subdomain=subdomain, api_key=api_key)
if (result is None):
ret['result'] = True
ret['comment'] = '{0} deleted'.format(v)
return ret
elif (result is True):
continue
elif __opts__['test']:
ret['comment'] = result
return ret
elif ('error' in result):
ret['result'] = False
ret['comment'] = result
return ret
return ret
| [
"def",
"resource_absent",
"(",
"resource",
",",
"identifier_fields",
",",
"profile",
"=",
"'pagerduty'",
",",
"subdomain",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"kwargs",
"[",
"'name'",
"]",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"(",
"k",
"not",
"in",
"identifier_fields",
")",
":",
"continue",
"result",
"=",
"delete_resource",
"(",
"resource",
",",
"v",
",",
"identifier_fields",
",",
"profile",
"=",
"profile",
",",
"subdomain",
"=",
"subdomain",
",",
"api_key",
"=",
"api_key",
")",
"if",
"(",
"result",
"is",
"None",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"'{0} deleted'",
".",
"format",
"(",
"v",
")",
"return",
"ret",
"elif",
"(",
"result",
"is",
"True",
")",
":",
"continue",
"elif",
"__opts__",
"[",
"'test'",
"]",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"result",
"return",
"ret",
"elif",
"(",
"'error'",
"in",
"result",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"ret",
"[",
"'comment'",
"]",
"=",
"result",
"return",
"ret",
"return",
"ret"
] | generic resource . | train | true |
45,598 | def rotate_key(bucket, obj, current_encryption_key, current_key_hash, new_encryption_key, new_key_hash):
service = create_service()
request = service.objects().rewrite(sourceBucket=bucket, sourceObject=obj, destinationBucket=bucket, destinationObject=obj, body={})
while True:
request.headers.update({'x-goog-copy-source-encryption-algorithm': 'AES256', 'x-goog-copy-source-encryption-key': current_encryption_key, 'x-goog-copy-source-encryption-key-sha256': current_key_hash, 'x-goog-encryption-algorithm': 'AES256', 'x-goog-encryption-key': new_encryption_key, 'x-goog-encryption-key-sha256': new_key_hash})
rewrite_response = request.execute()
if rewrite_response['done']:
break
print 'Continuing rewrite call...'
request = service.objects().rewrite(source_bucket=bucket, source_object=obj, destination_bucket=bucket, destination_object=obj, rewriteToken=rewrite_response['rewriteToken'])
rewrite_response.execute()
| [
"def",
"rotate_key",
"(",
"bucket",
",",
"obj",
",",
"current_encryption_key",
",",
"current_key_hash",
",",
"new_encryption_key",
",",
"new_key_hash",
")",
":",
"service",
"=",
"create_service",
"(",
")",
"request",
"=",
"service",
".",
"objects",
"(",
")",
".",
"rewrite",
"(",
"sourceBucket",
"=",
"bucket",
",",
"sourceObject",
"=",
"obj",
",",
"destinationBucket",
"=",
"bucket",
",",
"destinationObject",
"=",
"obj",
",",
"body",
"=",
"{",
"}",
")",
"while",
"True",
":",
"request",
".",
"headers",
".",
"update",
"(",
"{",
"'x-goog-copy-source-encryption-algorithm'",
":",
"'AES256'",
",",
"'x-goog-copy-source-encryption-key'",
":",
"current_encryption_key",
",",
"'x-goog-copy-source-encryption-key-sha256'",
":",
"current_key_hash",
",",
"'x-goog-encryption-algorithm'",
":",
"'AES256'",
",",
"'x-goog-encryption-key'",
":",
"new_encryption_key",
",",
"'x-goog-encryption-key-sha256'",
":",
"new_key_hash",
"}",
")",
"rewrite_response",
"=",
"request",
".",
"execute",
"(",
")",
"if",
"rewrite_response",
"[",
"'done'",
"]",
":",
"break",
"print",
"'Continuing rewrite call...'",
"request",
"=",
"service",
".",
"objects",
"(",
")",
".",
"rewrite",
"(",
"source_bucket",
"=",
"bucket",
",",
"source_object",
"=",
"obj",
",",
"destination_bucket",
"=",
"bucket",
",",
"destination_object",
"=",
"obj",
",",
"rewriteToken",
"=",
"rewrite_response",
"[",
"'rewriteToken'",
"]",
")",
"rewrite_response",
".",
"execute",
"(",
")"
] | changes the encryption key used to store an existing object . | train | false |
45,599 | def printUsage():
format = 'Usage: %s <opts1> [<opts2>] <root> [<resources>]'
print (format % basename(sys.argv[0]))
print
print ' with arguments:'
print ' (mandatory) root: the package root folder'
print ' (optional) resources: the package resources folder'
print
print ' and options:'
print ' (mandatory) opts1:'
mandatoryKeys = string.split('Title Version Description', ' ')
for k in mandatoryKeys:
print (' --%s' % k)
print ' (optional) opts2: (with default values)'
pmDefaults = PackageMaker.packageInfoDefaults
optionalKeys = pmDefaults.keys()
for k in mandatoryKeys:
optionalKeys.remove(k)
optionalKeys.sort()
maxKeyLen = max(map(len, optionalKeys))
for k in optionalKeys:
format = ' --%%s:%s %%s'
format = (format % (' ' * (maxKeyLen - len(k))))
print (format % (k, repr(pmDefaults[k])))
| [
"def",
"printUsage",
"(",
")",
":",
"format",
"=",
"'Usage: %s <opts1> [<opts2>] <root> [<resources>]'",
"print",
"(",
"format",
"%",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"print",
"print",
"' with arguments:'",
"print",
"' (mandatory) root: the package root folder'",
"print",
"' (optional) resources: the package resources folder'",
"print",
"print",
"' and options:'",
"print",
"' (mandatory) opts1:'",
"mandatoryKeys",
"=",
"string",
".",
"split",
"(",
"'Title Version Description'",
",",
"' '",
")",
"for",
"k",
"in",
"mandatoryKeys",
":",
"print",
"(",
"' --%s'",
"%",
"k",
")",
"print",
"' (optional) opts2: (with default values)'",
"pmDefaults",
"=",
"PackageMaker",
".",
"packageInfoDefaults",
"optionalKeys",
"=",
"pmDefaults",
".",
"keys",
"(",
")",
"for",
"k",
"in",
"mandatoryKeys",
":",
"optionalKeys",
".",
"remove",
"(",
"k",
")",
"optionalKeys",
".",
"sort",
"(",
")",
"maxKeyLen",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"optionalKeys",
")",
")",
"for",
"k",
"in",
"optionalKeys",
":",
"format",
"=",
"' --%%s:%s %%s'",
"format",
"=",
"(",
"format",
"%",
"(",
"' '",
"*",
"(",
"maxKeyLen",
"-",
"len",
"(",
"k",
")",
")",
")",
")",
"print",
"(",
"format",
"%",
"(",
"k",
",",
"repr",
"(",
"pmDefaults",
"[",
"k",
"]",
")",
")",
")"
] | print usage message . | train | false |
45,601 | def validate_templates_configuration():
for template_engine in django.conf.settings.TEMPLATES:
backend = template_engine[u'BACKEND']
if (u'DjangoTemplates' in backend):
raise ImproperlyConfigured(u'The DjangoTemplates engine was encountered in your template configuration before Django-Jinja. This configuration will not work correctly with Shuup.')
if (backend == u'django_jinja.backend.Jinja2'):
if (not template_engine.get(u'APP_DIRS')):
raise ImproperlyConfigured(u'You have the django_jinja backend configured, but it is not configured to take application template directories into account. Set APP_DIRS = True.')
options = (template_engine.get(u'OPTIONS') or {})
if (options.get(u'match_extension') != u'.jinja'):
raise ImproperlyConfigured(u'You have the django_jinja backend configured, but it is not configured to render `.jinja` templates. Set OPTIONS.match_extension to ".jinja".')
return True
raise ImproperlyConfigured(u'The `django_jinja` template backend was not encountered in your TEMPLATES configuration. See the Shuup or Django-Jinja documentation on more information how to configure things correctly.')
| [
"def",
"validate_templates_configuration",
"(",
")",
":",
"for",
"template_engine",
"in",
"django",
".",
"conf",
".",
"settings",
".",
"TEMPLATES",
":",
"backend",
"=",
"template_engine",
"[",
"u'BACKEND'",
"]",
"if",
"(",
"u'DjangoTemplates'",
"in",
"backend",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"u'The DjangoTemplates engine was encountered in your template configuration before Django-Jinja. This configuration will not work correctly with Shuup.'",
")",
"if",
"(",
"backend",
"==",
"u'django_jinja.backend.Jinja2'",
")",
":",
"if",
"(",
"not",
"template_engine",
".",
"get",
"(",
"u'APP_DIRS'",
")",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"u'You have the django_jinja backend configured, but it is not configured to take application template directories into account. Set APP_DIRS = True.'",
")",
"options",
"=",
"(",
"template_engine",
".",
"get",
"(",
"u'OPTIONS'",
")",
"or",
"{",
"}",
")",
"if",
"(",
"options",
".",
"get",
"(",
"u'match_extension'",
")",
"!=",
"u'.jinja'",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"u'You have the django_jinja backend configured, but it is not configured to render `.jinja` templates. Set OPTIONS.match_extension to \".jinja\".'",
")",
"return",
"True",
"raise",
"ImproperlyConfigured",
"(",
"u'The `django_jinja` template backend was not encountered in your TEMPLATES configuration. See the Shuup or Django-Jinja documentation on more information how to configure things correctly.'",
")"
] | validate the templates configuration in the django settings . | train | false |
45,602 | def backend_setting(backend, name, default=None):
backend_name = get_backend_name(backend)
setting_name = ('%s_%s' % (backend_name.upper().replace('-', '_'), name))
if hasattr(settings, setting_name):
return setting(setting_name)
elif hasattr(settings, name):
return setting(name)
else:
return default
| [
"def",
"backend_setting",
"(",
"backend",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"backend_name",
"=",
"get_backend_name",
"(",
"backend",
")",
"setting_name",
"=",
"(",
"'%s_%s'",
"%",
"(",
"backend_name",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
",",
"name",
")",
")",
"if",
"hasattr",
"(",
"settings",
",",
"setting_name",
")",
":",
"return",
"setting",
"(",
"setting_name",
")",
"elif",
"hasattr",
"(",
"settings",
",",
"name",
")",
":",
"return",
"setting",
"(",
"name",
")",
"else",
":",
"return",
"default"
] | looks for setting value following these rules: 1 . | train | false |
45,603 | def _read_dipole_fixed(fname):
logger.info(('Reading %s ...' % fname))
_check_fname(fname, overwrite=True, must_exist=True)
(info, nave, aspect_kind, first, last, comment, times, data) = _read_evoked(fname)
return DipoleFixed(info, data, times, nave, aspect_kind, first, last, comment)
| [
"def",
"_read_dipole_fixed",
"(",
"fname",
")",
":",
"logger",
".",
"info",
"(",
"(",
"'Reading %s ...'",
"%",
"fname",
")",
")",
"_check_fname",
"(",
"fname",
",",
"overwrite",
"=",
"True",
",",
"must_exist",
"=",
"True",
")",
"(",
"info",
",",
"nave",
",",
"aspect_kind",
",",
"first",
",",
"last",
",",
"comment",
",",
"times",
",",
"data",
")",
"=",
"_read_evoked",
"(",
"fname",
")",
"return",
"DipoleFixed",
"(",
"info",
",",
"data",
",",
"times",
",",
"nave",
",",
"aspect_kind",
",",
"first",
",",
"last",
",",
"comment",
")"
] | helper to read a fixed dipole fif file . | train | false |
45,605 | def tools_binscope():
mobsf_subdir_tools = CONFIG['MobSF']['tools']
binscope_path = (mobsf_subdir_tools + 'BinScope')
if platform.machine().endswith('64'):
binscope_url = CONFIG['binscope']['url_x64']
binscope_installer_path = (binscope_path + '\\BinScope_x64.msi')
else:
binscope_url = CONFIG['binscope']['url_x86']
binscope_installer_path = (binscope_path + '\\BinScope_x86.msi')
if (not os.path.exists(binscope_path)):
os.makedirs(binscope_path)
binscope_installer_file = open(binscope_installer_path, 'wb')
print '[*] Downloading BinScope..'
binscope_installer = urlrequest.urlopen(binscope_url)
print '[*] Saving to File {}'.format(binscope_installer_path)
binscope_installer_file.write(bytes(binscope_installer.read()))
binscope_installer_file.close()
print '[*] Installing BinScope to {}'.format(binscope_path)
os.system(((((((('msiexec' + ' INSTALLLOCATION="') + binscope_path) + '" ') + '/i "') + binscope_installer_path) + '" ') + '/passive'))
CONFIG['binscope']['file'] = (binscope_path + '\\Binscope.exe')
with open(os.path.join(CONFIG_PATH, CONFIG_FILE), 'w') as configfile:
CONFIG.write(configfile)
| [
"def",
"tools_binscope",
"(",
")",
":",
"mobsf_subdir_tools",
"=",
"CONFIG",
"[",
"'MobSF'",
"]",
"[",
"'tools'",
"]",
"binscope_path",
"=",
"(",
"mobsf_subdir_tools",
"+",
"'BinScope'",
")",
"if",
"platform",
".",
"machine",
"(",
")",
".",
"endswith",
"(",
"'64'",
")",
":",
"binscope_url",
"=",
"CONFIG",
"[",
"'binscope'",
"]",
"[",
"'url_x64'",
"]",
"binscope_installer_path",
"=",
"(",
"binscope_path",
"+",
"'\\\\BinScope_x64.msi'",
")",
"else",
":",
"binscope_url",
"=",
"CONFIG",
"[",
"'binscope'",
"]",
"[",
"'url_x86'",
"]",
"binscope_installer_path",
"=",
"(",
"binscope_path",
"+",
"'\\\\BinScope_x86.msi'",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"binscope_path",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"binscope_path",
")",
"binscope_installer_file",
"=",
"open",
"(",
"binscope_installer_path",
",",
"'wb'",
")",
"print",
"'[*] Downloading BinScope..'",
"binscope_installer",
"=",
"urlrequest",
".",
"urlopen",
"(",
"binscope_url",
")",
"print",
"'[*] Saving to File {}'",
".",
"format",
"(",
"binscope_installer_path",
")",
"binscope_installer_file",
".",
"write",
"(",
"bytes",
"(",
"binscope_installer",
".",
"read",
"(",
")",
")",
")",
"binscope_installer_file",
".",
"close",
"(",
")",
"print",
"'[*] Installing BinScope to {}'",
".",
"format",
"(",
"binscope_path",
")",
"os",
".",
"system",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"'msiexec'",
"+",
"' INSTALLLOCATION=\"'",
")",
"+",
"binscope_path",
")",
"+",
"'\" '",
")",
"+",
"'/i \"'",
")",
"+",
"binscope_installer_path",
")",
"+",
"'\" '",
")",
"+",
"'/passive'",
")",
")",
"CONFIG",
"[",
"'binscope'",
"]",
"[",
"'file'",
"]",
"=",
"(",
"binscope_path",
"+",
"'\\\\Binscope.exe'",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CONFIG_PATH",
",",
"CONFIG_FILE",
")",
",",
"'w'",
")",
"as",
"configfile",
":",
"CONFIG",
".",
"write",
"(",
"configfile",
")"
] | download and install binscope for mobsf . | train | false |
45,606 | def vb_xpcom_to_attribute_dict(xpcom, interface_name=None, attributes=None, excluded_attributes=None, extra_attributes=None):
if interface_name:
m = re.search('XPCOM.+implementing {0}'.format(interface_name), str(xpcom))
if (not m):
log.warning('Interface %s is unknown and cannot be converted to dict', interface_name)
return dict()
interface_attributes = set((attributes or XPCOM_ATTRIBUTES.get(interface_name, [])))
if extra_attributes:
interface_attributes = interface_attributes.union(extra_attributes)
if excluded_attributes:
interface_attributes = interface_attributes.difference(excluded_attributes)
attribute_tuples = []
for attribute in interface_attributes:
if isinstance(attribute, tuple):
attribute_name = attribute[0]
attribute_class = attribute[1]
value = (attribute_name, getattr(xpcom, attribute_name, attribute_class()))
else:
value = (attribute, getattr(xpcom, attribute, ''))
attribute_tuples.append(value)
return dict(attribute_tuples)
| [
"def",
"vb_xpcom_to_attribute_dict",
"(",
"xpcom",
",",
"interface_name",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"excluded_attributes",
"=",
"None",
",",
"extra_attributes",
"=",
"None",
")",
":",
"if",
"interface_name",
":",
"m",
"=",
"re",
".",
"search",
"(",
"'XPCOM.+implementing {0}'",
".",
"format",
"(",
"interface_name",
")",
",",
"str",
"(",
"xpcom",
")",
")",
"if",
"(",
"not",
"m",
")",
":",
"log",
".",
"warning",
"(",
"'Interface %s is unknown and cannot be converted to dict'",
",",
"interface_name",
")",
"return",
"dict",
"(",
")",
"interface_attributes",
"=",
"set",
"(",
"(",
"attributes",
"or",
"XPCOM_ATTRIBUTES",
".",
"get",
"(",
"interface_name",
",",
"[",
"]",
")",
")",
")",
"if",
"extra_attributes",
":",
"interface_attributes",
"=",
"interface_attributes",
".",
"union",
"(",
"extra_attributes",
")",
"if",
"excluded_attributes",
":",
"interface_attributes",
"=",
"interface_attributes",
".",
"difference",
"(",
"excluded_attributes",
")",
"attribute_tuples",
"=",
"[",
"]",
"for",
"attribute",
"in",
"interface_attributes",
":",
"if",
"isinstance",
"(",
"attribute",
",",
"tuple",
")",
":",
"attribute_name",
"=",
"attribute",
"[",
"0",
"]",
"attribute_class",
"=",
"attribute",
"[",
"1",
"]",
"value",
"=",
"(",
"attribute_name",
",",
"getattr",
"(",
"xpcom",
",",
"attribute_name",
",",
"attribute_class",
"(",
")",
")",
")",
"else",
":",
"value",
"=",
"(",
"attribute",
",",
"getattr",
"(",
"xpcom",
",",
"attribute",
",",
"''",
")",
")",
"attribute_tuples",
".",
"append",
"(",
"value",
")",
"return",
"dict",
"(",
"attribute_tuples",
")"
] | attempts to build a dict from an xpcom object . | train | true |
45,607 | def _enhook(klass, name):
if hasattr(klass, ORIG(klass, name)):
return
def newfunc(*args, **kw):
for preMethod in getattr(klass, PRE(klass, name)):
preMethod(*args, **kw)
try:
return getattr(klass, ORIG(klass, name))(*args, **kw)
finally:
for postMethod in getattr(klass, POST(klass, name)):
postMethod(*args, **kw)
try:
newfunc.func_name = name
except TypeError:
pass
oldfunc = getattr(klass, name).im_func
setattr(klass, ORIG(klass, name), oldfunc)
setattr(klass, PRE(klass, name), [])
setattr(klass, POST(klass, name), [])
setattr(klass, name, newfunc)
| [
"def",
"_enhook",
"(",
"klass",
",",
"name",
")",
":",
"if",
"hasattr",
"(",
"klass",
",",
"ORIG",
"(",
"klass",
",",
"name",
")",
")",
":",
"return",
"def",
"newfunc",
"(",
"*",
"args",
",",
"**",
"kw",
")",
":",
"for",
"preMethod",
"in",
"getattr",
"(",
"klass",
",",
"PRE",
"(",
"klass",
",",
"name",
")",
")",
":",
"preMethod",
"(",
"*",
"args",
",",
"**",
"kw",
")",
"try",
":",
"return",
"getattr",
"(",
"klass",
",",
"ORIG",
"(",
"klass",
",",
"name",
")",
")",
"(",
"*",
"args",
",",
"**",
"kw",
")",
"finally",
":",
"for",
"postMethod",
"in",
"getattr",
"(",
"klass",
",",
"POST",
"(",
"klass",
",",
"name",
")",
")",
":",
"postMethod",
"(",
"*",
"args",
",",
"**",
"kw",
")",
"try",
":",
"newfunc",
".",
"func_name",
"=",
"name",
"except",
"TypeError",
":",
"pass",
"oldfunc",
"=",
"getattr",
"(",
"klass",
",",
"name",
")",
".",
"im_func",
"setattr",
"(",
"klass",
",",
"ORIG",
"(",
"klass",
",",
"name",
")",
",",
"oldfunc",
")",
"setattr",
"(",
"klass",
",",
"PRE",
"(",
"klass",
",",
"name",
")",
",",
"[",
"]",
")",
"setattr",
"(",
"klass",
",",
"POST",
"(",
"klass",
",",
"name",
")",
",",
"[",
"]",
")",
"setattr",
"(",
"klass",
",",
"name",
",",
"newfunc",
")"
] | causes a certain method name to be hooked on a class . | train | false |
45,611 | def irc_raw(triggers_param, **kwargs):
def _raw_hook(func):
hook = _get_hook(func, 'irc_raw')
if (hook is None):
hook = _RawHook(func)
_add_hook(func, hook)
hook.add_hook(triggers_param, kwargs)
return func
if callable(triggers_param):
raise TypeError('@irc_raw() must be used as a function that returns a decorator')
else:
return (lambda func: _raw_hook(func))
| [
"def",
"irc_raw",
"(",
"triggers_param",
",",
"**",
"kwargs",
")",
":",
"def",
"_raw_hook",
"(",
"func",
")",
":",
"hook",
"=",
"_get_hook",
"(",
"func",
",",
"'irc_raw'",
")",
"if",
"(",
"hook",
"is",
"None",
")",
":",
"hook",
"=",
"_RawHook",
"(",
"func",
")",
"_add_hook",
"(",
"func",
",",
"hook",
")",
"hook",
".",
"add_hook",
"(",
"triggers_param",
",",
"kwargs",
")",
"return",
"func",
"if",
"callable",
"(",
"triggers_param",
")",
":",
"raise",
"TypeError",
"(",
"'@irc_raw() must be used as a function that returns a decorator'",
")",
"else",
":",
"return",
"(",
"lambda",
"func",
":",
"_raw_hook",
"(",
"func",
")",
")"
] | external raw decorator . | train | false |
45,613 | def pportDataStrobe(state):
global ctrlReg
if (state == 0):
ctrlReg = (ctrlReg | 1)
else:
ctrlReg = (ctrlReg & (~ 1))
port.DlPortWritePortUchar(ctrlRegAdrs, ctrlReg)
| [
"def",
"pportDataStrobe",
"(",
"state",
")",
":",
"global",
"ctrlReg",
"if",
"(",
"state",
"==",
"0",
")",
":",
"ctrlReg",
"=",
"(",
"ctrlReg",
"|",
"1",
")",
"else",
":",
"ctrlReg",
"=",
"(",
"ctrlReg",
"&",
"(",
"~",
"1",
")",
")",
"port",
".",
"DlPortWritePortUchar",
"(",
"ctrlRegAdrs",
",",
"ctrlReg",
")"
] | toggle control register data strobe bit . | train | false |
45,614 | def filesharing():
status = (-1)
finder = _getfinder()
args = {}
attrs = {}
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', seld=aetypes.Type('fshr'), fr=None)
(_reply, args, attrs) = finder.send('core', 'getd', args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
if (args['----'] == 0):
status = (-1)
else:
status = 1
args = {}
attrs = {}
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', seld=aetypes.Type('fsup'), fr=None)
(_reply, args, attrs) = finder.send('core', 'getd', args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
if (args['----'] == 1):
status = 0
return status
| [
"def",
"filesharing",
"(",
")",
":",
"status",
"=",
"(",
"-",
"1",
")",
"finder",
"=",
"_getfinder",
"(",
")",
"args",
"=",
"{",
"}",
"attrs",
"=",
"{",
"}",
"args",
"[",
"'----'",
"]",
"=",
"aetypes",
".",
"ObjectSpecifier",
"(",
"want",
"=",
"aetypes",
".",
"Type",
"(",
"'prop'",
")",
",",
"form",
"=",
"'prop'",
",",
"seld",
"=",
"aetypes",
".",
"Type",
"(",
"'fshr'",
")",
",",
"fr",
"=",
"None",
")",
"(",
"_reply",
",",
"args",
",",
"attrs",
")",
"=",
"finder",
".",
"send",
"(",
"'core'",
",",
"'getd'",
",",
"args",
",",
"attrs",
")",
"if",
"args",
".",
"has_key",
"(",
"'errn'",
")",
":",
"raise",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"args",
")",
"if",
"args",
".",
"has_key",
"(",
"'----'",
")",
":",
"if",
"(",
"args",
"[",
"'----'",
"]",
"==",
"0",
")",
":",
"status",
"=",
"(",
"-",
"1",
")",
"else",
":",
"status",
"=",
"1",
"args",
"=",
"{",
"}",
"attrs",
"=",
"{",
"}",
"args",
"[",
"'----'",
"]",
"=",
"aetypes",
".",
"ObjectSpecifier",
"(",
"want",
"=",
"aetypes",
".",
"Type",
"(",
"'prop'",
")",
",",
"form",
"=",
"'prop'",
",",
"seld",
"=",
"aetypes",
".",
"Type",
"(",
"'fsup'",
")",
",",
"fr",
"=",
"None",
")",
"(",
"_reply",
",",
"args",
",",
"attrs",
")",
"=",
"finder",
".",
"send",
"(",
"'core'",
",",
"'getd'",
",",
"args",
",",
"attrs",
")",
"if",
"args",
".",
"has_key",
"(",
"'errn'",
")",
":",
"raise",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"args",
")",
"if",
"args",
".",
"has_key",
"(",
"'----'",
")",
":",
"if",
"(",
"args",
"[",
"'----'",
"]",
"==",
"1",
")",
":",
"status",
"=",
"0",
"return",
"status"
] | return the current status of filesharing and whether it is starting up or not: -1 file sharing is off and not starting up 0 file sharing is off and starting up 1 file sharing is on . | train | false |
45,615 | def _key_id_or_name_n(key, index):
if (not key):
return None
path = key.to_path()
if (not path):
return None
path_index = ((index * 2) + 1)
return path[path_index]
| [
"def",
"_key_id_or_name_n",
"(",
"key",
",",
"index",
")",
":",
"if",
"(",
"not",
"key",
")",
":",
"return",
"None",
"path",
"=",
"key",
".",
"to_path",
"(",
")",
"if",
"(",
"not",
"path",
")",
":",
"return",
"None",
"path_index",
"=",
"(",
"(",
"index",
"*",
"2",
")",
"+",
"1",
")",
"return",
"path",
"[",
"path_index",
"]"
] | internal helper function for key id and name transforms . | train | false |
45,617 | def selectables_overlap(left, right):
return bool(set(surface_selectables(left)).intersection(surface_selectables(right)))
| [
"def",
"selectables_overlap",
"(",
"left",
",",
"right",
")",
":",
"return",
"bool",
"(",
"set",
"(",
"surface_selectables",
"(",
"left",
")",
")",
".",
"intersection",
"(",
"surface_selectables",
"(",
"right",
")",
")",
")"
] | return true if left/right have some overlapping selectable . | train | false |
45,619 | def ellipk(m):
return ellipkm1((1 - asarray(m)))
| [
"def",
"ellipk",
"(",
"m",
")",
":",
"return",
"ellipkm1",
"(",
"(",
"1",
"-",
"asarray",
"(",
"m",
")",
")",
")"
] | complete elliptic integral of the first kind . | train | false |
45,620 | def get_mako(factory=Mako, key=_registry_key, app=None):
app = (app or webapp2.get_app())
mako = app.registry.get(key)
if (not mako):
mako = app.registry[key] = factory(app)
return mako
| [
"def",
"get_mako",
"(",
"factory",
"=",
"Mako",
",",
"key",
"=",
"_registry_key",
",",
"app",
"=",
"None",
")",
":",
"app",
"=",
"(",
"app",
"or",
"webapp2",
".",
"get_app",
"(",
")",
")",
"mako",
"=",
"app",
".",
"registry",
".",
"get",
"(",
"key",
")",
"if",
"(",
"not",
"mako",
")",
":",
"mako",
"=",
"app",
".",
"registry",
"[",
"key",
"]",
"=",
"factory",
"(",
"app",
")",
"return",
"mako"
] | returns an instance of :class:mako from the app registry . | train | false |
45,621 | def sleep(at_time=None):
cmd = 'shutdown -s now'
return _execute_command(cmd, at_time)
| [
"def",
"sleep",
"(",
"at_time",
"=",
"None",
")",
":",
"cmd",
"=",
"'shutdown -s now'",
"return",
"_execute_command",
"(",
"cmd",
",",
"at_time",
")"
] | sleep t seconds . | train | false |
45,622 | def _log_dirichlet_norm(dirichlet_concentration):
return (gammaln(np.sum(dirichlet_concentration)) - np.sum(gammaln(dirichlet_concentration)))
| [
"def",
"_log_dirichlet_norm",
"(",
"dirichlet_concentration",
")",
":",
"return",
"(",
"gammaln",
"(",
"np",
".",
"sum",
"(",
"dirichlet_concentration",
")",
")",
"-",
"np",
".",
"sum",
"(",
"gammaln",
"(",
"dirichlet_concentration",
")",
")",
")"
] | compute the log of the dirichlet distribution normalization term . | train | false |
45,624 | def show_instance(name, call=None):
if (call != 'action'):
raise SaltCloudSystemExit('The show_instance action must be called with -a or --action.')
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
| [
"def",
"show_instance",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'action'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_instance action must be called with -a or --action.'",
")",
"node",
"=",
"_get_node",
"(",
"name",
")",
"__utils__",
"[",
"'cloud.cache_node'",
"]",
"(",
"node",
",",
"__active_provider_name__",
",",
"__opts__",
")",
"return",
"node"
] | show the details from opennebula concerning a named vm . | train | true |
45,625 | def _poll_until_success_returning_result(should_retry, steps, sleep, function, args, kwargs):
saved_result = [None]
def pollable():
Message.new(message_type=_TRY_RETRYING).write()
try:
result = function(*args, **kwargs)
except Exception as e:
saved_result[0] = exc_info()
should_retry(*saved_result[0])
Message.new(message_type=_TRY_FAILURE, exception=str(e)).write()
return False
else:
Message.new(message_type=_TRY_SUCCESS, result=result).write()
saved_result[0] = result
return True
try:
poll_until(pollable, (step.total_seconds() for step in steps), sleep=sleep)
except LoopExceeded:
thing = saved_result.pop()
try:
raise thing[0], thing[1], thing[2]
finally:
del thing
else:
return saved_result[0]
| [
"def",
"_poll_until_success_returning_result",
"(",
"should_retry",
",",
"steps",
",",
"sleep",
",",
"function",
",",
"args",
",",
"kwargs",
")",
":",
"saved_result",
"=",
"[",
"None",
"]",
"def",
"pollable",
"(",
")",
":",
"Message",
".",
"new",
"(",
"message_type",
"=",
"_TRY_RETRYING",
")",
".",
"write",
"(",
")",
"try",
":",
"result",
"=",
"function",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"saved_result",
"[",
"0",
"]",
"=",
"exc_info",
"(",
")",
"should_retry",
"(",
"*",
"saved_result",
"[",
"0",
"]",
")",
"Message",
".",
"new",
"(",
"message_type",
"=",
"_TRY_FAILURE",
",",
"exception",
"=",
"str",
"(",
"e",
")",
")",
".",
"write",
"(",
")",
"return",
"False",
"else",
":",
"Message",
".",
"new",
"(",
"message_type",
"=",
"_TRY_SUCCESS",
",",
"result",
"=",
"result",
")",
".",
"write",
"(",
")",
"saved_result",
"[",
"0",
"]",
"=",
"result",
"return",
"True",
"try",
":",
"poll_until",
"(",
"pollable",
",",
"(",
"step",
".",
"total_seconds",
"(",
")",
"for",
"step",
"in",
"steps",
")",
",",
"sleep",
"=",
"sleep",
")",
"except",
"LoopExceeded",
":",
"thing",
"=",
"saved_result",
".",
"pop",
"(",
")",
"try",
":",
"raise",
"thing",
"[",
"0",
"]",
",",
"thing",
"[",
"1",
"]",
",",
"thing",
"[",
"2",
"]",
"finally",
":",
"del",
"thing",
"else",
":",
"return",
"saved_result",
"[",
"0",
"]"
] | call a function until it does not raise an exception or should_retry says it shouldnt be tried anymore . | train | false |
45,626 | def write_t2b(t2bfile, coverdata=None):
from PIL import Image
if (coverdata is not None):
coverdata = StringIO.StringIO(coverdata)
cover = Image.open(coverdata).convert('L')
cover.thumbnail((96, 144), Image.ANTIALIAS)
t2bcover = Image.new('L', (96, 144), 'white')
(x, y) = cover.size
t2bcover.paste(cover, (((96 - x) / 2), ((144 - y) / 2)))
px = []
pxs = t2bcover.getdata()
for i in range(len(pxs)):
px.append(pxs[i])
if (len(px) >= 4):
binstr = (((i2b(reduce_color(px[0])) + i2b(reduce_color(px[1]))) + i2b(reduce_color(px[2]))) + i2b(reduce_color(px[3])))
t2bfile.write(chr(int(binstr, 2)))
px = []
else:
t2bfile.write(DEFAULT_T2B_DATA)
| [
"def",
"write_t2b",
"(",
"t2bfile",
",",
"coverdata",
"=",
"None",
")",
":",
"from",
"PIL",
"import",
"Image",
"if",
"(",
"coverdata",
"is",
"not",
"None",
")",
":",
"coverdata",
"=",
"StringIO",
".",
"StringIO",
"(",
"coverdata",
")",
"cover",
"=",
"Image",
".",
"open",
"(",
"coverdata",
")",
".",
"convert",
"(",
"'L'",
")",
"cover",
".",
"thumbnail",
"(",
"(",
"96",
",",
"144",
")",
",",
"Image",
".",
"ANTIALIAS",
")",
"t2bcover",
"=",
"Image",
".",
"new",
"(",
"'L'",
",",
"(",
"96",
",",
"144",
")",
",",
"'white'",
")",
"(",
"x",
",",
"y",
")",
"=",
"cover",
".",
"size",
"t2bcover",
".",
"paste",
"(",
"cover",
",",
"(",
"(",
"(",
"96",
"-",
"x",
")",
"/",
"2",
")",
",",
"(",
"(",
"144",
"-",
"y",
")",
"/",
"2",
")",
")",
")",
"px",
"=",
"[",
"]",
"pxs",
"=",
"t2bcover",
".",
"getdata",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"pxs",
")",
")",
":",
"px",
".",
"append",
"(",
"pxs",
"[",
"i",
"]",
")",
"if",
"(",
"len",
"(",
"px",
")",
">=",
"4",
")",
":",
"binstr",
"=",
"(",
"(",
"(",
"i2b",
"(",
"reduce_color",
"(",
"px",
"[",
"0",
"]",
")",
")",
"+",
"i2b",
"(",
"reduce_color",
"(",
"px",
"[",
"1",
"]",
")",
")",
")",
"+",
"i2b",
"(",
"reduce_color",
"(",
"px",
"[",
"2",
"]",
")",
")",
")",
"+",
"i2b",
"(",
"reduce_color",
"(",
"px",
"[",
"3",
"]",
")",
")",
")",
"t2bfile",
".",
"write",
"(",
"chr",
"(",
"int",
"(",
"binstr",
",",
"2",
")",
")",
")",
"px",
"=",
"[",
"]",
"else",
":",
"t2bfile",
".",
"write",
"(",
"DEFAULT_T2B_DATA",
")"
] | t2bfile is a file handle ready to write binary data to disk . | train | false |
45,627 | @cronjobs.register
def process_exit_surveys():
_process_exit_survey_results()
if settings.STAGE:
return
startdate = (date.today() - timedelta(days=2))
enddate = (date.today() - timedelta(days=1))
for survey in SURVEYS.keys():
if ('email_collection_survey_id' not in SURVEYS[survey]):
continue
emails = get_email_addresses(survey, startdate, enddate)
for email in emails:
add_email_to_campaign(survey, email)
statsd.gauge('survey.{0}'.format(survey), len(emails))
| [
"@",
"cronjobs",
".",
"register",
"def",
"process_exit_surveys",
"(",
")",
":",
"_process_exit_survey_results",
"(",
")",
"if",
"settings",
".",
"STAGE",
":",
"return",
"startdate",
"=",
"(",
"date",
".",
"today",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"2",
")",
")",
"enddate",
"=",
"(",
"date",
".",
"today",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"1",
")",
")",
"for",
"survey",
"in",
"SURVEYS",
".",
"keys",
"(",
")",
":",
"if",
"(",
"'email_collection_survey_id'",
"not",
"in",
"SURVEYS",
"[",
"survey",
"]",
")",
":",
"continue",
"emails",
"=",
"get_email_addresses",
"(",
"survey",
",",
"startdate",
",",
"enddate",
")",
"for",
"email",
"in",
"emails",
":",
"add_email_to_campaign",
"(",
"survey",
",",
"email",
")",
"statsd",
".",
"gauge",
"(",
"'survey.{0}'",
".",
"format",
"(",
"survey",
")",
",",
"len",
"(",
"emails",
")",
")"
] | exit survey handling . | train | false |
45,628 | def render_form(form, **kwargs):
renderer_cls = get_form_renderer(**kwargs)
return renderer_cls(form, **kwargs).render()
| [
"def",
"render_form",
"(",
"form",
",",
"**",
"kwargs",
")",
":",
"renderer_cls",
"=",
"get_form_renderer",
"(",
"**",
"kwargs",
")",
"return",
"renderer_cls",
"(",
"form",
",",
"**",
"kwargs",
")",
".",
"render",
"(",
")"
] | render a form to a bootstrap layout . | train | true |
45,629 | def hash_thesubdb(video_path):
readsize = (64 * 1024)
if (os.path.getsize(video_path) < readsize):
return
with open(video_path, 'rb') as f:
data = f.read(readsize)
f.seek((- readsize), os.SEEK_END)
data += f.read(readsize)
return hashlib.md5(data).hexdigest()
| [
"def",
"hash_thesubdb",
"(",
"video_path",
")",
":",
"readsize",
"=",
"(",
"64",
"*",
"1024",
")",
"if",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"video_path",
")",
"<",
"readsize",
")",
":",
"return",
"with",
"open",
"(",
"video_path",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
"readsize",
")",
"f",
".",
"seek",
"(",
"(",
"-",
"readsize",
")",
",",
"os",
".",
"SEEK_END",
")",
"data",
"+=",
"f",
".",
"read",
"(",
"readsize",
")",
"return",
"hashlib",
".",
"md5",
"(",
"data",
")",
".",
"hexdigest",
"(",
")"
] | compute a hash using thesubdbs algorithm . | train | true |
45,630 | def require_docker_version(minimum_docker_version, message):
minimum_docker_version = LooseVersion(minimum_docker_version)
def decorator(wrapped):
@wraps(wrapped)
def wrapper(*args, **kwargs):
client = DockerClient()
docker_version = LooseVersion(client._client.version()['Version'])
if (docker_version < minimum_docker_version):
raise SkipTest('Minimum required Docker version: {}. Actual Docker version: {}. Details: {}'.format(minimum_docker_version, docker_version, message))
return wrapped(*args, **kwargs)
return wrapper
return decorator
| [
"def",
"require_docker_version",
"(",
"minimum_docker_version",
",",
"message",
")",
":",
"minimum_docker_version",
"=",
"LooseVersion",
"(",
"minimum_docker_version",
")",
"def",
"decorator",
"(",
"wrapped",
")",
":",
"@",
"wraps",
"(",
"wrapped",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"client",
"=",
"DockerClient",
"(",
")",
"docker_version",
"=",
"LooseVersion",
"(",
"client",
".",
"_client",
".",
"version",
"(",
")",
"[",
"'Version'",
"]",
")",
"if",
"(",
"docker_version",
"<",
"minimum_docker_version",
")",
":",
"raise",
"SkipTest",
"(",
"'Minimum required Docker version: {}. Actual Docker version: {}. Details: {}'",
".",
"format",
"(",
"minimum_docker_version",
",",
"docker_version",
",",
"message",
")",
")",
"return",
"wrapped",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"wrapper",
"return",
"decorator"
] | skip the wrapped test if the actual docker version is less than minimum_docker_version . | train | false |
45,631 | def dmp_one_p(f, u, K):
return dmp_ground_p(f, K.one, u)
| [
"def",
"dmp_one_p",
"(",
"f",
",",
"u",
",",
"K",
")",
":",
"return",
"dmp_ground_p",
"(",
"f",
",",
"K",
".",
"one",
",",
"u",
")"
] | return true if f is one in k[x] . | train | false |
45,634 | def test_exp_schedule(backend_default):
lr_init = 0.1
decay = 0.01
sch = ExpSchedule(decay)
for epoch in range(10):
lr = sch.get_learning_rate(learning_rate=lr_init, epoch=epoch)
assert np.allclose(lr, (lr_init / (1.0 + (decay * epoch))))
| [
"def",
"test_exp_schedule",
"(",
"backend_default",
")",
":",
"lr_init",
"=",
"0.1",
"decay",
"=",
"0.01",
"sch",
"=",
"ExpSchedule",
"(",
"decay",
")",
"for",
"epoch",
"in",
"range",
"(",
"10",
")",
":",
"lr",
"=",
"sch",
".",
"get_learning_rate",
"(",
"learning_rate",
"=",
"lr_init",
",",
"epoch",
"=",
"epoch",
")",
"assert",
"np",
".",
"allclose",
"(",
"lr",
",",
"(",
"lr_init",
"/",
"(",
"1.0",
"+",
"(",
"decay",
"*",
"epoch",
")",
")",
")",
")"
] | test exponential learning rate schedule . | train | false |
45,635 | def check_master(client, master_only=False):
if (master_only and (not is_master_node(client))):
logger.info('Master-only flag detected. Connected to non-master node. Aborting.')
sys.exit(0)
| [
"def",
"check_master",
"(",
"client",
",",
"master_only",
"=",
"False",
")",
":",
"if",
"(",
"master_only",
"and",
"(",
"not",
"is_master_node",
"(",
"client",
")",
")",
")",
":",
"logger",
".",
"info",
"(",
"'Master-only flag detected. Connected to non-master node. Aborting.'",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | check if connected client is the elected master node of the cluster . | train | false |
45,636 | def _get_all_files():
jscsrc_path = os.path.join(os.getcwd(), '.jscsrc')
parsed_args = _PARSER.parse_args()
if parsed_args.path:
input_path = os.path.join(os.getcwd(), parsed_args.path)
if (not os.path.exists(input_path)):
print ('Could not locate file or directory %s. Exiting.' % input_path)
print '----------------------------------------'
sys.exit(1)
if os.path.isfile(input_path):
all_files = [input_path]
else:
excluded_glob_patterns = _get_glob_patterns_excluded_from_jscsrc(jscsrc_path)
all_files = _get_all_files_in_directory(input_path, excluded_glob_patterns)
elif parsed_args.files:
valid_filepaths = []
invalid_filepaths = []
for f in parsed_args.files:
if os.path.isfile(f):
valid_filepaths.append(f)
else:
invalid_filepaths.append(f)
if invalid_filepaths:
print ('The following file(s) do not exist: %s\nExiting.' % invalid_filepaths)
sys.exit(1)
all_files = valid_filepaths
else:
all_files = _get_changed_filenames()
return all_files
| [
"def",
"_get_all_files",
"(",
")",
":",
"jscsrc_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'.jscsrc'",
")",
"parsed_args",
"=",
"_PARSER",
".",
"parse_args",
"(",
")",
"if",
"parsed_args",
".",
"path",
":",
"input_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"parsed_args",
".",
"path",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"input_path",
")",
")",
":",
"print",
"(",
"'Could not locate file or directory %s. Exiting.'",
"%",
"input_path",
")",
"print",
"'----------------------------------------'",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"input_path",
")",
":",
"all_files",
"=",
"[",
"input_path",
"]",
"else",
":",
"excluded_glob_patterns",
"=",
"_get_glob_patterns_excluded_from_jscsrc",
"(",
"jscsrc_path",
")",
"all_files",
"=",
"_get_all_files_in_directory",
"(",
"input_path",
",",
"excluded_glob_patterns",
")",
"elif",
"parsed_args",
".",
"files",
":",
"valid_filepaths",
"=",
"[",
"]",
"invalid_filepaths",
"=",
"[",
"]",
"for",
"f",
"in",
"parsed_args",
".",
"files",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
":",
"valid_filepaths",
".",
"append",
"(",
"f",
")",
"else",
":",
"invalid_filepaths",
".",
"append",
"(",
"f",
")",
"if",
"invalid_filepaths",
":",
"print",
"(",
"'The following file(s) do not exist: %s\\nExiting.'",
"%",
"invalid_filepaths",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"all_files",
"=",
"valid_filepaths",
"else",
":",
"all_files",
"=",
"_get_changed_filenames",
"(",
")",
"return",
"all_files"
] | this function is used to check if this script is ran from root directory and to return a list of all the files for linting and pattern checks . | train | false |
45,637 | def get_event_differences(expected, actual, tolerate=None):
tolerate = EventMatchTolerates.default_if_not_defined(tolerate)
if (EventMatchTolerates.STRING_PAYLOAD in tolerate):
expected = parse_event_payload(expected)
actual = parse_event_payload(actual)
def should_strict_compare(path):
'\n We want to be able to vary the degree of strictness we apply depending on the testing context.\n\n Some tests will want to assert that the entire event matches exactly, others will tolerate some variance in the\n context or root fields, but not in the payload (for example).\n '
if ((path == []) and (EventMatchTolerates.ROOT_EXTRA_FIELDS in tolerate)):
return False
elif ((path == ['event']) and (EventMatchTolerates.PAYLOAD_EXTRA_FIELDS in tolerate)):
return False
elif ((path == ['context']) and (EventMatchTolerates.CONTEXT_EXTRA_FIELDS in tolerate)):
return False
else:
return True
return compare_structs(expected, actual, should_strict_compare=should_strict_compare)
| [
"def",
"get_event_differences",
"(",
"expected",
",",
"actual",
",",
"tolerate",
"=",
"None",
")",
":",
"tolerate",
"=",
"EventMatchTolerates",
".",
"default_if_not_defined",
"(",
"tolerate",
")",
"if",
"(",
"EventMatchTolerates",
".",
"STRING_PAYLOAD",
"in",
"tolerate",
")",
":",
"expected",
"=",
"parse_event_payload",
"(",
"expected",
")",
"actual",
"=",
"parse_event_payload",
"(",
"actual",
")",
"def",
"should_strict_compare",
"(",
"path",
")",
":",
"if",
"(",
"(",
"path",
"==",
"[",
"]",
")",
"and",
"(",
"EventMatchTolerates",
".",
"ROOT_EXTRA_FIELDS",
"in",
"tolerate",
")",
")",
":",
"return",
"False",
"elif",
"(",
"(",
"path",
"==",
"[",
"'event'",
"]",
")",
"and",
"(",
"EventMatchTolerates",
".",
"PAYLOAD_EXTRA_FIELDS",
"in",
"tolerate",
")",
")",
":",
"return",
"False",
"elif",
"(",
"(",
"path",
"==",
"[",
"'context'",
"]",
")",
"and",
"(",
"EventMatchTolerates",
".",
"CONTEXT_EXTRA_FIELDS",
"in",
"tolerate",
")",
")",
":",
"return",
"False",
"else",
":",
"return",
"True",
"return",
"compare_structs",
"(",
"expected",
",",
"actual",
",",
"should_strict_compare",
"=",
"should_strict_compare",
")"
] | given two events . | train | false |
45,638 | def test_invalid_service_provider_type(rf, admin_user):
get_default_shop()
view = ServiceProviderEditView.as_view()
url = '/?type=SomethingThatIsNotProvided'
soup = get_bs_object_for_view(rf.get(url), view, admin_user)
provider_form = soup.find('form', attrs={'id': 'service_provider_form'})
type_select = provider_form.find('select', attrs={'id': 'id_type'})
options = []
for option in type_select.findAll('option'):
options.append({'selected': bool(option.get('selected')), 'value': option['value']})
assert (options[0]['selected'] is True)
assert ([x['selected'] for x in options[1:]] == [False, False])
| [
"def",
"test_invalid_service_provider_type",
"(",
"rf",
",",
"admin_user",
")",
":",
"get_default_shop",
"(",
")",
"view",
"=",
"ServiceProviderEditView",
".",
"as_view",
"(",
")",
"url",
"=",
"'/?type=SomethingThatIsNotProvided'",
"soup",
"=",
"get_bs_object_for_view",
"(",
"rf",
".",
"get",
"(",
"url",
")",
",",
"view",
",",
"admin_user",
")",
"provider_form",
"=",
"soup",
".",
"find",
"(",
"'form'",
",",
"attrs",
"=",
"{",
"'id'",
":",
"'service_provider_form'",
"}",
")",
"type_select",
"=",
"provider_form",
".",
"find",
"(",
"'select'",
",",
"attrs",
"=",
"{",
"'id'",
":",
"'id_type'",
"}",
")",
"options",
"=",
"[",
"]",
"for",
"option",
"in",
"type_select",
".",
"findAll",
"(",
"'option'",
")",
":",
"options",
".",
"append",
"(",
"{",
"'selected'",
":",
"bool",
"(",
"option",
".",
"get",
"(",
"'selected'",
")",
")",
",",
"'value'",
":",
"option",
"[",
"'value'",
"]",
"}",
")",
"assert",
"(",
"options",
"[",
"0",
"]",
"[",
"'selected'",
"]",
"is",
"True",
")",
"assert",
"(",
"[",
"x",
"[",
"'selected'",
"]",
"for",
"x",
"in",
"options",
"[",
"1",
":",
"]",
"]",
"==",
"[",
"False",
",",
"False",
"]",
")"
] | test serviceprovideeditview with invalid type parameter . | train | false |
45,639 | def get_cohort_by_id(course_key, cohort_id):
return CourseUserGroup.objects.get(course_id=course_key, group_type=CourseUserGroup.COHORT, id=cohort_id)
| [
"def",
"get_cohort_by_id",
"(",
"course_key",
",",
"cohort_id",
")",
":",
"return",
"CourseUserGroup",
".",
"objects",
".",
"get",
"(",
"course_id",
"=",
"course_key",
",",
"group_type",
"=",
"CourseUserGroup",
".",
"COHORT",
",",
"id",
"=",
"cohort_id",
")"
] | return the courseusergroup object for the given cohort . | train | false |
45,640 | def change_ls(table):
if ('total' in table):
for field in ['files', 'bytes']:
if ((field in table['total']) and table['total'][field].isdigit()):
table['total'][field] = int(table['total'][field])
for volume in table.get('volumes', []):
for fileentry in volume.get('files', []):
if (('size' in fileentry) and fileentry['size'].isdigit()):
fileentry['size'] = int(fileentry['size'])
return table
| [
"def",
"change_ls",
"(",
"table",
")",
":",
"if",
"(",
"'total'",
"in",
"table",
")",
":",
"for",
"field",
"in",
"[",
"'files'",
",",
"'bytes'",
"]",
":",
"if",
"(",
"(",
"field",
"in",
"table",
"[",
"'total'",
"]",
")",
"and",
"table",
"[",
"'total'",
"]",
"[",
"field",
"]",
".",
"isdigit",
"(",
")",
")",
":",
"table",
"[",
"'total'",
"]",
"[",
"field",
"]",
"=",
"int",
"(",
"table",
"[",
"'total'",
"]",
"[",
"field",
"]",
")",
"for",
"volume",
"in",
"table",
".",
"get",
"(",
"'volumes'",
",",
"[",
"]",
")",
":",
"for",
"fileentry",
"in",
"volume",
".",
"get",
"(",
"'files'",
",",
"[",
"]",
")",
":",
"if",
"(",
"(",
"'size'",
"in",
"fileentry",
")",
"and",
"fileentry",
"[",
"'size'",
"]",
".",
"isdigit",
"(",
")",
")",
":",
"fileentry",
"[",
"'size'",
"]",
"=",
"int",
"(",
"fileentry",
"[",
"'size'",
"]",
")",
"return",
"table"
] | adapt structured data from "ls" nse module to convert some fields to integers . | train | false |
45,642 | @world.absorb
def css_check(css_selector, wait_time=GLOBAL_WAIT_FOR_TIMEOUT):
css_click(css_selector=css_selector, wait_time=wait_time)
wait_for((lambda _: css_find(css_selector).selected))
return True
| [
"@",
"world",
".",
"absorb",
"def",
"css_check",
"(",
"css_selector",
",",
"wait_time",
"=",
"GLOBAL_WAIT_FOR_TIMEOUT",
")",
":",
"css_click",
"(",
"css_selector",
"=",
"css_selector",
",",
"wait_time",
"=",
"wait_time",
")",
"wait_for",
"(",
"(",
"lambda",
"_",
":",
"css_find",
"(",
"css_selector",
")",
".",
"selected",
")",
")",
"return",
"True"
] | checks a check box based on a css selector . | train | false |
45,643 | def Scalar(obj):
return Sequence([obj])
| [
"def",
"Scalar",
"(",
"obj",
")",
":",
"return",
"Sequence",
"(",
"[",
"obj",
"]",
")"
] | shortcut for sequence creation . | train | false |
45,644 | def sync_desktop_icons():
for app in frappe.get_installed_apps():
sync_from_app(app)
| [
"def",
"sync_desktop_icons",
"(",
")",
":",
"for",
"app",
"in",
"frappe",
".",
"get_installed_apps",
"(",
")",
":",
"sync_from_app",
"(",
"app",
")"
] | sync desktop icons from all apps . | train | false |
45,645 | def toTypeURIs(namespace_map, alias_list_s):
uris = []
if alias_list_s:
for alias in alias_list_s.split(','):
type_uri = namespace_map.getNamespaceURI(alias)
if (type_uri is None):
raise KeyError(('No type is defined for attribute name %r' % (alias,)))
else:
uris.append(type_uri)
return uris
| [
"def",
"toTypeURIs",
"(",
"namespace_map",
",",
"alias_list_s",
")",
":",
"uris",
"=",
"[",
"]",
"if",
"alias_list_s",
":",
"for",
"alias",
"in",
"alias_list_s",
".",
"split",
"(",
"','",
")",
":",
"type_uri",
"=",
"namespace_map",
".",
"getNamespaceURI",
"(",
"alias",
")",
"if",
"(",
"type_uri",
"is",
"None",
")",
":",
"raise",
"KeyError",
"(",
"(",
"'No type is defined for attribute name %r'",
"%",
"(",
"alias",
",",
")",
")",
")",
"else",
":",
"uris",
".",
"append",
"(",
"type_uri",
")",
"return",
"uris"
] | given a namespace mapping and a string containing a comma-separated list of namespace aliases . | train | true |
45,646 | def onLoggerAppReady():
INFO_MSG(('onLoggerAppReady: bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s' % (os.getenv('KBE_BOOTIDX_GROUP'), os.getenv('KBE_BOOTIDX_GLOBAL'))))
| [
"def",
"onLoggerAppReady",
"(",
")",
":",
"INFO_MSG",
"(",
"(",
"'onLoggerAppReady: bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s'",
"%",
"(",
"os",
".",
"getenv",
"(",
"'KBE_BOOTIDX_GROUP'",
")",
",",
"os",
".",
"getenv",
"(",
"'KBE_BOOTIDX_GLOBAL'",
")",
")",
")",
")"
] | kbengine method . | train | false |
45,647 | def idd_frmi(m):
return _id.idd_frmi(m)
| [
"def",
"idd_frmi",
"(",
"m",
")",
":",
"return",
"_id",
".",
"idd_frmi",
"(",
"m",
")"
] | initialize data for :func:idd_frm . | train | false |
45,648 | def url_escape(value, plus=True):
quote = (urllib_parse.quote_plus if plus else urllib_parse.quote)
return quote(utf8(value))
| [
"def",
"url_escape",
"(",
"value",
",",
"plus",
"=",
"True",
")",
":",
"quote",
"=",
"(",
"urllib_parse",
".",
"quote_plus",
"if",
"plus",
"else",
"urllib_parse",
".",
"quote",
")",
"return",
"quote",
"(",
"utf8",
"(",
"value",
")",
")"
] | returns a url-encoded version of the given value . | train | true |
45,650 | def read_no_interrupt(p):
import errno
try:
return p.read()
except IOError as err:
if (err.errno != errno.EINTR):
raise
| [
"def",
"read_no_interrupt",
"(",
"p",
")",
":",
"import",
"errno",
"try",
":",
"return",
"p",
".",
"read",
"(",
")",
"except",
"IOError",
"as",
"err",
":",
"if",
"(",
"err",
".",
"errno",
"!=",
"errno",
".",
"EINTR",
")",
":",
"raise"
] | read from a pipe ignoring eintr errors . | train | true |
45,652 | def get_view_config(context, global_type=False):
request = context.get(u'request')
config_key = (u'_xtheme_global_view_config' if global_type else u'_xtheme_view_config')
config = context.vars.get(config_key)
if (config is None):
view_object = context.get(u'view')
if view_object:
view_class = view_object.__class__
view_name = view_class.__name__
else:
view_name = u'UnknownView'
config = ViewConfig(theme=get_current_theme(request), view_name=view_name, draft=is_edit_mode(request), global_type=global_type)
context.vars[config_key] = config
return config
| [
"def",
"get_view_config",
"(",
"context",
",",
"global_type",
"=",
"False",
")",
":",
"request",
"=",
"context",
".",
"get",
"(",
"u'request'",
")",
"config_key",
"=",
"(",
"u'_xtheme_global_view_config'",
"if",
"global_type",
"else",
"u'_xtheme_view_config'",
")",
"config",
"=",
"context",
".",
"vars",
".",
"get",
"(",
"config_key",
")",
"if",
"(",
"config",
"is",
"None",
")",
":",
"view_object",
"=",
"context",
".",
"get",
"(",
"u'view'",
")",
"if",
"view_object",
":",
"view_class",
"=",
"view_object",
".",
"__class__",
"view_name",
"=",
"view_class",
".",
"__name__",
"else",
":",
"view_name",
"=",
"u'UnknownView'",
"config",
"=",
"ViewConfig",
"(",
"theme",
"=",
"get_current_theme",
"(",
"request",
")",
",",
"view_name",
"=",
"view_name",
",",
"draft",
"=",
"is_edit_mode",
"(",
"request",
")",
",",
"global_type",
"=",
"global_type",
")",
"context",
".",
"vars",
"[",
"config_key",
"]",
"=",
"config",
"return",
"config"
] | get a view configuration object for a jinja2 rendering context . | train | false |
45,654 | def nottest(f):
f.__test__ = False
return f
| [
"def",
"nottest",
"(",
"f",
")",
":",
"f",
".",
"__test__",
"=",
"False",
"return",
"f"
] | decorator to mark a function as not a test . | train | false |
45,655 | def get_action_parameters_specs(action_ref):
action_db = get_action_by_ref(ref=action_ref)
parameters = {}
if (not action_db):
return parameters
runner_type_name = action_db.runner_type['name']
runner_type_db = get_runnertype_by_name(runnertype_name=runner_type_name)
parameters.update(runner_type_db['runner_parameters'])
parameters.update(action_db.parameters)
return parameters
| [
"def",
"get_action_parameters_specs",
"(",
"action_ref",
")",
":",
"action_db",
"=",
"get_action_by_ref",
"(",
"ref",
"=",
"action_ref",
")",
"parameters",
"=",
"{",
"}",
"if",
"(",
"not",
"action_db",
")",
":",
"return",
"parameters",
"runner_type_name",
"=",
"action_db",
".",
"runner_type",
"[",
"'name'",
"]",
"runner_type_db",
"=",
"get_runnertype_by_name",
"(",
"runnertype_name",
"=",
"runner_type_name",
")",
"parameters",
".",
"update",
"(",
"runner_type_db",
"[",
"'runner_parameters'",
"]",
")",
"parameters",
".",
"update",
"(",
"action_db",
".",
"parameters",
")",
"return",
"parameters"
] | retrieve parameters specifications schema for the provided action reference . | train | false |
45,656 | def valid_certificate(name, weeks=0, days=0, hours=0, minutes=0, seconds=0):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
now = time.time()
cert_info = __salt__['tls.cert_info'](name)
if (now < cert_info['not_before']):
ret['comment'] = 'Certificate is not yet valid'
return ret
if (now > cert_info['not_after']):
ret['comment'] = 'Certificate is expired'
return ret
delta_remaining = datetime.timedelta(seconds=(cert_info['not_after'] - now))
delta_kind_map = {'weeks': weeks, 'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds}
delta_min = datetime.timedelta(**delta_kind_map)
if (delta_remaining < delta_min):
ret['comment'] = 'Certificate will expire in {0}, which is less than {1}'.format(delta_remaining, delta_min)
return ret
ret['result'] = True
ret['comment'] = 'Certificate is valid for {0}'.format(delta_remaining)
return ret
| [
"def",
"valid_certificate",
"(",
"name",
",",
"weeks",
"=",
"0",
",",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"now",
"=",
"time",
".",
"time",
"(",
")",
"cert_info",
"=",
"__salt__",
"[",
"'tls.cert_info'",
"]",
"(",
"name",
")",
"if",
"(",
"now",
"<",
"cert_info",
"[",
"'not_before'",
"]",
")",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Certificate is not yet valid'",
"return",
"ret",
"if",
"(",
"now",
">",
"cert_info",
"[",
"'not_after'",
"]",
")",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Certificate is expired'",
"return",
"ret",
"delta_remaining",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"(",
"cert_info",
"[",
"'not_after'",
"]",
"-",
"now",
")",
")",
"delta_kind_map",
"=",
"{",
"'weeks'",
":",
"weeks",
",",
"'days'",
":",
"days",
",",
"'hours'",
":",
"hours",
",",
"'minutes'",
":",
"minutes",
",",
"'seconds'",
":",
"seconds",
"}",
"delta_min",
"=",
"datetime",
".",
"timedelta",
"(",
"**",
"delta_kind_map",
")",
"if",
"(",
"delta_remaining",
"<",
"delta_min",
")",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Certificate will expire in {0}, which is less than {1}'",
".",
"format",
"(",
"delta_remaining",
",",
"delta_min",
")",
"return",
"ret",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"'Certificate is valid for {0}'",
".",
"format",
"(",
"delta_remaining",
")",
"return",
"ret"
] | verify that a tls certificate is valid now and will be valid for the time specified through weeks . | train | true |
45,660 | def menu():
return s3_rest_controller()
| [
"def",
"menu",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | restful crud controller . | train | false |
45,662 | def s3_has_foreign_key(field, m2m=True):
try:
ftype = str(field.type)
except:
return False
if ((ftype[:9] == 'reference') or (m2m and (ftype[:14] == 'list:reference')) or current.s3db.virtual_reference(field)):
return True
return False
| [
"def",
"s3_has_foreign_key",
"(",
"field",
",",
"m2m",
"=",
"True",
")",
":",
"try",
":",
"ftype",
"=",
"str",
"(",
"field",
".",
"type",
")",
"except",
":",
"return",
"False",
"if",
"(",
"(",
"ftype",
"[",
":",
"9",
"]",
"==",
"'reference'",
")",
"or",
"(",
"m2m",
"and",
"(",
"ftype",
"[",
":",
"14",
"]",
"==",
"'list:reference'",
")",
")",
"or",
"current",
".",
"s3db",
".",
"virtual_reference",
"(",
"field",
")",
")",
":",
"return",
"True",
"return",
"False"
] | check whether a field contains a foreign key constraint . | train | false |
45,663 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | return a signature scheme object pss_sigscheme that can be used to perform pkcs#1 pss signature or verification . | train | false |
45,665 | def set_restart_mode(restart_file, flag='reload'):
with open(restart_file, 'w') as f:
f.write(str(flag))
| [
"def",
"set_restart_mode",
"(",
"restart_file",
",",
"flag",
"=",
"'reload'",
")",
":",
"with",
"open",
"(",
"restart_file",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"flag",
")",
")"
] | this sets a flag file for the restart mode . | train | false |
45,666 | def test_ast_invalid_let():
cant_compile(u'(let 1)')
cant_compile(u'(let [1])')
cant_compile(u'(let [a 1 2])')
cant_compile(u'(let [a])')
cant_compile(u'(let [1])')
| [
"def",
"test_ast_invalid_let",
"(",
")",
":",
"cant_compile",
"(",
"u'(let 1)'",
")",
"cant_compile",
"(",
"u'(let [1])'",
")",
"cant_compile",
"(",
"u'(let [a 1 2])'",
")",
"cant_compile",
"(",
"u'(let [a])'",
")",
"cant_compile",
"(",
"u'(let [1])'",
")"
] | make sure ast cant compile invalid let . | train | false |
45,667 | def parse_volgroup(rule):
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
partitions = []
newrules = []
for count in range(0, len(rules)):
if (count == 0):
newrules.append(rules[count])
continue
elif rules[count].startswith('--'):
newrules.append(rules[count])
continue
else:
partitions.append(rules[count])
rules = newrules
parser.add_argument('name')
parser.add_argument('--noformat', dest='noformat', action='store_true')
parser.add_argument('--useexisting', dest='useexisting', action='store_true')
parser.add_argument('--pesize', dest='pesize', action='store')
parser.add_argument('--reserved-space', dest='reserved-space', action='store')
parser.add_argument('--reserved-percent', dest='reserved-percent', action='store')
args = clean_args(vars(parser.parse_args(rules)))
if partitions:
args['partitions'] = partitions
parser = None
return args
| [
"def",
"parse_volgroup",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"partitions",
"=",
"[",
"]",
"newrules",
"=",
"[",
"]",
"for",
"count",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"rules",
")",
")",
":",
"if",
"(",
"count",
"==",
"0",
")",
":",
"newrules",
".",
"append",
"(",
"rules",
"[",
"count",
"]",
")",
"continue",
"elif",
"rules",
"[",
"count",
"]",
".",
"startswith",
"(",
"'--'",
")",
":",
"newrules",
".",
"append",
"(",
"rules",
"[",
"count",
"]",
")",
"continue",
"else",
":",
"partitions",
".",
"append",
"(",
"rules",
"[",
"count",
"]",
")",
"rules",
"=",
"newrules",
"parser",
".",
"add_argument",
"(",
"'name'",
")",
"parser",
".",
"add_argument",
"(",
"'--noformat'",
",",
"dest",
"=",
"'noformat'",
",",
"action",
"=",
"'store_true'",
")",
"parser",
".",
"add_argument",
"(",
"'--useexisting'",
",",
"dest",
"=",
"'useexisting'",
",",
"action",
"=",
"'store_true'",
")",
"parser",
".",
"add_argument",
"(",
"'--pesize'",
",",
"dest",
"=",
"'pesize'",
",",
"action",
"=",
"'store'",
")",
"parser",
".",
"add_argument",
"(",
"'--reserved-space'",
",",
"dest",
"=",
"'reserved-space'",
",",
"action",
"=",
"'store'",
")",
"parser",
".",
"add_argument",
"(",
"'--reserved-percent'",
",",
"dest",
"=",
"'reserved-percent'",
",",
"action",
"=",
"'store'",
")",
"args",
"=",
"clean_args",
"(",
"vars",
"(",
"parser",
".",
"parse_args",
"(",
"rules",
")",
")",
")",
"if",
"partitions",
":",
"args",
"[",
"'partitions'",
"]",
"=",
"partitions",
"parser",
"=",
"None",
"return",
"args"
] | parse the volgroup line . | train | true |
45,668 | def escape_rfc3986(s):
if ((sys.version_info < (3, 0)) and isinstance(s, compat_str)):
s = s.encode(u'utf-8')
return compat_urllib_parse.quote(s, "%/;:@&=+$,!~*'()?#[]")
| [
"def",
"escape_rfc3986",
"(",
"s",
")",
":",
"if",
"(",
"(",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
")",
"and",
"isinstance",
"(",
"s",
",",
"compat_str",
")",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"u'utf-8'",
")",
"return",
"compat_urllib_parse",
".",
"quote",
"(",
"s",
",",
"\"%/;:@&=+$,!~*'()?#[]\"",
")"
] | escape non-ascii characters as suggested by rfc 3986 . | train | false |
45,669 | def komodo(exe=u'komodo'):
install_editor((exe + u' -l {line} {filename}'), wait=True)
| [
"def",
"komodo",
"(",
"exe",
"=",
"u'komodo'",
")",
":",
"install_editor",
"(",
"(",
"exe",
"+",
"u' -l {line} {filename}'",
")",
",",
"wait",
"=",
"True",
")"
] | activestate komodo [edit] . | train | false |
45,671 | def choice_param(registry, xml_parent, data):
pdef = base_param(registry, xml_parent, data, False, 'hudson.model.ChoiceParameterDefinition')
choices = XML.SubElement(pdef, 'choices', {'class': 'java.util.Arrays$ArrayList'})
a = XML.SubElement(choices, 'a', {'class': 'string-array'})
for choice in data['choices']:
XML.SubElement(a, 'string').text = choice
| [
"def",
"choice_param",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"pdef",
"=",
"base_param",
"(",
"registry",
",",
"xml_parent",
",",
"data",
",",
"False",
",",
"'hudson.model.ChoiceParameterDefinition'",
")",
"choices",
"=",
"XML",
".",
"SubElement",
"(",
"pdef",
",",
"'choices'",
",",
"{",
"'class'",
":",
"'java.util.Arrays$ArrayList'",
"}",
")",
"a",
"=",
"XML",
".",
"SubElement",
"(",
"choices",
",",
"'a'",
",",
"{",
"'class'",
":",
"'string-array'",
"}",
")",
"for",
"choice",
"in",
"data",
"[",
"'choices'",
"]",
":",
"XML",
".",
"SubElement",
"(",
"a",
",",
"'string'",
")",
".",
"text",
"=",
"choice"
] | yaml: choice a single selection parameter . | train | false |
45,672 | def set_geofence_all(instance):
resource = instance.get_self_resource()
if hasattr(resource, 'layer'):
try:
'\n curl -X POST -u admin:geoserver -H "Content-Type: text/xml" -d "<Rule><workspace>geonode</workspace><layer>{layer}</layer><access>ALLOW</access></Rule>" http://<host>:<port>/geoserver/geofence/rest/rules\n '
url = settings.OGC_SERVER['default']['PUBLIC_LOCATION']
user = settings.OGC_SERVER['default']['USER']
passwd = settings.OGC_SERVER['default']['PASSWORD']
headers = {'Content-type': 'application/xml'}
payload = '<Rule><workspace>geonode</workspace><layer>'
payload = (payload + resource.layer.name)
payload = (payload + '</layer><access>ALLOW</access></Rule>')
r = requests.post((url + 'geofence/rest/rules'), headers=headers, data=payload, auth=HTTPBasicAuth(user, passwd))
if (r.status_code != 200):
logger.warning(('Could not ADD GeoServer ANONYMOUS Rule for Layer ' + str(resource.layer.name)))
except:
tb = traceback.format_exc()
logger.debug(tb)
| [
"def",
"set_geofence_all",
"(",
"instance",
")",
":",
"resource",
"=",
"instance",
".",
"get_self_resource",
"(",
")",
"if",
"hasattr",
"(",
"resource",
",",
"'layer'",
")",
":",
"try",
":",
"url",
"=",
"settings",
".",
"OGC_SERVER",
"[",
"'default'",
"]",
"[",
"'PUBLIC_LOCATION'",
"]",
"user",
"=",
"settings",
".",
"OGC_SERVER",
"[",
"'default'",
"]",
"[",
"'USER'",
"]",
"passwd",
"=",
"settings",
".",
"OGC_SERVER",
"[",
"'default'",
"]",
"[",
"'PASSWORD'",
"]",
"headers",
"=",
"{",
"'Content-type'",
":",
"'application/xml'",
"}",
"payload",
"=",
"'<Rule><workspace>geonode</workspace><layer>'",
"payload",
"=",
"(",
"payload",
"+",
"resource",
".",
"layer",
".",
"name",
")",
"payload",
"=",
"(",
"payload",
"+",
"'</layer><access>ALLOW</access></Rule>'",
")",
"r",
"=",
"requests",
".",
"post",
"(",
"(",
"url",
"+",
"'geofence/rest/rules'",
")",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"payload",
",",
"auth",
"=",
"HTTPBasicAuth",
"(",
"user",
",",
"passwd",
")",
")",
"if",
"(",
"r",
".",
"status_code",
"!=",
"200",
")",
":",
"logger",
".",
"warning",
"(",
"(",
"'Could not ADD GeoServer ANONYMOUS Rule for Layer '",
"+",
"str",
"(",
"resource",
".",
"layer",
".",
"name",
")",
")",
")",
"except",
":",
"tb",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"logger",
".",
"debug",
"(",
"tb",
")"
] | assign access permissions to all users . | train | false |
45,674 | def count_blocks(A, blocksize):
(r, c) = blocksize
if ((r < 1) or (c < 1)):
raise ValueError('r and c must be positive')
if isspmatrix_csr(A):
(M, N) = A.shape
return csr_count_blocks(M, N, r, c, A.indptr, A.indices)
elif isspmatrix_csc(A):
return count_blocks(A.T, (c, r))
else:
return count_blocks(csr_matrix(A), blocksize)
| [
"def",
"count_blocks",
"(",
"A",
",",
"blocksize",
")",
":",
"(",
"r",
",",
"c",
")",
"=",
"blocksize",
"if",
"(",
"(",
"r",
"<",
"1",
")",
"or",
"(",
"c",
"<",
"1",
")",
")",
":",
"raise",
"ValueError",
"(",
"'r and c must be positive'",
")",
"if",
"isspmatrix_csr",
"(",
"A",
")",
":",
"(",
"M",
",",
"N",
")",
"=",
"A",
".",
"shape",
"return",
"csr_count_blocks",
"(",
"M",
",",
"N",
",",
"r",
",",
"c",
",",
"A",
".",
"indptr",
",",
"A",
".",
"indices",
")",
"elif",
"isspmatrix_csc",
"(",
"A",
")",
":",
"return",
"count_blocks",
"(",
"A",
".",
"T",
",",
"(",
"c",
",",
"r",
")",
")",
"else",
":",
"return",
"count_blocks",
"(",
"csr_matrix",
"(",
"A",
")",
",",
"blocksize",
")"
] | for a given blocksize= count the number of occupied blocks in a sparse matrix a . | train | false |
45,675 | def print_dict(dct, dict_property='Property', wrap=0, dict_value='Value'):
pt = prettytable.PrettyTable([dict_property, dict_value])
pt.align = 'l'
for (k, v) in sorted(dct.items()):
if isinstance(v, dict):
v = six.text_type(v)
if (wrap > 0):
v = textwrap.fill(six.text_type(v), wrap)
if (v and isinstance(v, six.string_types) and ('\\n' in v)):
lines = v.strip().split('\\n')
col1 = k
for line in lines:
pt.add_row([col1, line])
col1 = ''
else:
pt.add_row([k, v])
if six.PY2:
print encodeutils.safe_encode(pt.get_string())
else:
print encodeutils.safe_encode(pt.get_string()).decode()
| [
"def",
"print_dict",
"(",
"dct",
",",
"dict_property",
"=",
"'Property'",
",",
"wrap",
"=",
"0",
",",
"dict_value",
"=",
"'Value'",
")",
":",
"pt",
"=",
"prettytable",
".",
"PrettyTable",
"(",
"[",
"dict_property",
",",
"dict_value",
"]",
")",
"pt",
".",
"align",
"=",
"'l'",
"for",
"(",
"k",
",",
"v",
")",
"in",
"sorted",
"(",
"dct",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"v",
"=",
"six",
".",
"text_type",
"(",
"v",
")",
"if",
"(",
"wrap",
">",
"0",
")",
":",
"v",
"=",
"textwrap",
".",
"fill",
"(",
"six",
".",
"text_type",
"(",
"v",
")",
",",
"wrap",
")",
"if",
"(",
"v",
"and",
"isinstance",
"(",
"v",
",",
"six",
".",
"string_types",
")",
"and",
"(",
"'\\\\n'",
"in",
"v",
")",
")",
":",
"lines",
"=",
"v",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\\\n'",
")",
"col1",
"=",
"k",
"for",
"line",
"in",
"lines",
":",
"pt",
".",
"add_row",
"(",
"[",
"col1",
",",
"line",
"]",
")",
"col1",
"=",
"''",
"else",
":",
"pt",
".",
"add_row",
"(",
"[",
"k",
",",
"v",
"]",
")",
"if",
"six",
".",
"PY2",
":",
"print",
"encodeutils",
".",
"safe_encode",
"(",
"pt",
".",
"get_string",
"(",
")",
")",
"else",
":",
"print",
"encodeutils",
".",
"safe_encode",
"(",
"pt",
".",
"get_string",
"(",
")",
")",
".",
"decode",
"(",
")"
] | print a dict as a table of two columns . | train | false |
45,676 | def ns_join(ns, name):
if (is_private(name) or is_global(name)):
return name
if (ns == PRIV_NAME):
return (PRIV_NAME + name)
if (not ns):
return name
if (ns[(-1)] == SEP):
return (ns + name)
return ((ns + SEP) + name)
| [
"def",
"ns_join",
"(",
"ns",
",",
"name",
")",
":",
"if",
"(",
"is_private",
"(",
"name",
")",
"or",
"is_global",
"(",
"name",
")",
")",
":",
"return",
"name",
"if",
"(",
"ns",
"==",
"PRIV_NAME",
")",
":",
"return",
"(",
"PRIV_NAME",
"+",
"name",
")",
"if",
"(",
"not",
"ns",
")",
":",
"return",
"name",
"if",
"(",
"ns",
"[",
"(",
"-",
"1",
")",
"]",
"==",
"SEP",
")",
":",
"return",
"(",
"ns",
"+",
"name",
")",
"return",
"(",
"(",
"ns",
"+",
"SEP",
")",
"+",
"name",
")"
] | join a namespace and name . | train | false |
45,677 | @cachedmethod
def getConsoleWidth(default=80):
width = None
if os.getenv('COLUMNS', '').isdigit():
width = int(os.getenv('COLUMNS'))
else:
try:
try:
FNULL = open(os.devnull, 'w')
except IOError:
FNULL = None
process = subprocess.Popen('stty size', shell=True, stdout=subprocess.PIPE, stderr=(FNULL or subprocess.PIPE))
(stdout, _) = process.communicate()
items = stdout.split()
if ((len(items) == 2) and items[1].isdigit()):
width = int(items[1])
except (OSError, MemoryError):
pass
if (width is None):
try:
import curses
stdscr = curses.initscr()
(_, width) = stdscr.getmaxyx()
curses.endwin()
except:
pass
return (width or default)
| [
"@",
"cachedmethod",
"def",
"getConsoleWidth",
"(",
"default",
"=",
"80",
")",
":",
"width",
"=",
"None",
"if",
"os",
".",
"getenv",
"(",
"'COLUMNS'",
",",
"''",
")",
".",
"isdigit",
"(",
")",
":",
"width",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"'COLUMNS'",
")",
")",
"else",
":",
"try",
":",
"try",
":",
"FNULL",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"except",
"IOError",
":",
"FNULL",
"=",
"None",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"'stty size'",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"(",
"FNULL",
"or",
"subprocess",
".",
"PIPE",
")",
")",
"(",
"stdout",
",",
"_",
")",
"=",
"process",
".",
"communicate",
"(",
")",
"items",
"=",
"stdout",
".",
"split",
"(",
")",
"if",
"(",
"(",
"len",
"(",
"items",
")",
"==",
"2",
")",
"and",
"items",
"[",
"1",
"]",
".",
"isdigit",
"(",
")",
")",
":",
"width",
"=",
"int",
"(",
"items",
"[",
"1",
"]",
")",
"except",
"(",
"OSError",
",",
"MemoryError",
")",
":",
"pass",
"if",
"(",
"width",
"is",
"None",
")",
":",
"try",
":",
"import",
"curses",
"stdscr",
"=",
"curses",
".",
"initscr",
"(",
")",
"(",
"_",
",",
"width",
")",
"=",
"stdscr",
".",
"getmaxyx",
"(",
")",
"curses",
".",
"endwin",
"(",
")",
"except",
":",
"pass",
"return",
"(",
"width",
"or",
"default",
")"
] | returns console width . | train | false |
45,678 | def fixclasspath():
paths = []
classpaths = []
for path in sys.path:
if ((path == '__classpath__') or path.startswith('__pyclasspath__')):
classpaths.append(path)
else:
paths.append(path)
sys.path = paths
sys.path.extend(classpaths)
| [
"def",
"fixclasspath",
"(",
")",
":",
"paths",
"=",
"[",
"]",
"classpaths",
"=",
"[",
"]",
"for",
"path",
"in",
"sys",
".",
"path",
":",
"if",
"(",
"(",
"path",
"==",
"'__classpath__'",
")",
"or",
"path",
".",
"startswith",
"(",
"'__pyclasspath__'",
")",
")",
":",
"classpaths",
".",
"append",
"(",
"path",
")",
"else",
":",
"paths",
".",
"append",
"(",
"path",
")",
"sys",
".",
"path",
"=",
"paths",
"sys",
".",
"path",
".",
"extend",
"(",
"classpaths",
")"
] | adjust the special classpath sys . | train | true |
45,679 | @register.inclusion_tag(u'wagtailusers/groups/includes/formatted_permissions.html')
def format_permissions(permission_bound_field):
permissions = permission_bound_field.field._queryset
content_type_ids = set(permissions.values_list(u'content_type_id', flat=True))
checkboxes_by_id = {int(checkbox.choice_value): checkbox for checkbox in permission_bound_field}
object_perms = []
other_perms = []
for content_type_id in content_type_ids:
content_perms = permissions.filter(content_type_id=content_type_id)
content_perms_dict = {}
for perm in content_perms:
checkbox = checkboxes_by_id[perm.id]
permission_action = perm.codename.split(u'_')[0]
if (permission_action in [u'add', u'change', u'delete']):
content_perms_dict[u'object'] = perm.content_type.name
content_perms_dict[permission_action] = checkbox
else:
other_perms.append((perm, checkbox))
if content_perms_dict:
object_perms.append(content_perms_dict)
return {u'object_perms': object_perms, u'other_perms': other_perms}
| [
"@",
"register",
".",
"inclusion_tag",
"(",
"u'wagtailusers/groups/includes/formatted_permissions.html'",
")",
"def",
"format_permissions",
"(",
"permission_bound_field",
")",
":",
"permissions",
"=",
"permission_bound_field",
".",
"field",
".",
"_queryset",
"content_type_ids",
"=",
"set",
"(",
"permissions",
".",
"values_list",
"(",
"u'content_type_id'",
",",
"flat",
"=",
"True",
")",
")",
"checkboxes_by_id",
"=",
"{",
"int",
"(",
"checkbox",
".",
"choice_value",
")",
":",
"checkbox",
"for",
"checkbox",
"in",
"permission_bound_field",
"}",
"object_perms",
"=",
"[",
"]",
"other_perms",
"=",
"[",
"]",
"for",
"content_type_id",
"in",
"content_type_ids",
":",
"content_perms",
"=",
"permissions",
".",
"filter",
"(",
"content_type_id",
"=",
"content_type_id",
")",
"content_perms_dict",
"=",
"{",
"}",
"for",
"perm",
"in",
"content_perms",
":",
"checkbox",
"=",
"checkboxes_by_id",
"[",
"perm",
".",
"id",
"]",
"permission_action",
"=",
"perm",
".",
"codename",
".",
"split",
"(",
"u'_'",
")",
"[",
"0",
"]",
"if",
"(",
"permission_action",
"in",
"[",
"u'add'",
",",
"u'change'",
",",
"u'delete'",
"]",
")",
":",
"content_perms_dict",
"[",
"u'object'",
"]",
"=",
"perm",
".",
"content_type",
".",
"name",
"content_perms_dict",
"[",
"permission_action",
"]",
"=",
"checkbox",
"else",
":",
"other_perms",
".",
"append",
"(",
"(",
"perm",
",",
"checkbox",
")",
")",
"if",
"content_perms_dict",
":",
"object_perms",
".",
"append",
"(",
"content_perms_dict",
")",
"return",
"{",
"u'object_perms'",
":",
"object_perms",
",",
"u'other_perms'",
":",
"other_perms",
"}"
] | given a bound field with a queryset of permission objects - which must be using the checkboxselectmultiple widget - construct a list of dictionaries for objects: objects: [ object: name_of_some_content_object . | train | false |
45,680 | def show_backends(socket='/var/run/haproxy.sock'):
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.showBackends()
return ha_conn.sendCmd(ha_cmd)
| [
"def",
"show_backends",
"(",
"socket",
"=",
"'/var/run/haproxy.sock'",
")",
":",
"ha_conn",
"=",
"_get_conn",
"(",
"socket",
")",
"ha_cmd",
"=",
"haproxy",
".",
"cmds",
".",
"showBackends",
"(",
")",
"return",
"ha_conn",
".",
"sendCmd",
"(",
"ha_cmd",
")"
] | show haproxy backends socket haproxy stats socket cli example: . | train | true |
45,681 | def pretty_print_prediction(emissions, real_state, predicted_state, emission_title='Emissions', real_title='Real State', predicted_title='Predicted State', line_width=75):
title_length = (max(len(emission_title), len(real_title), len(predicted_title)) + 1)
seq_length = (line_width - title_length)
emission_title = emission_title.ljust(title_length)
real_title = real_title.ljust(title_length)
predicted_title = predicted_title.ljust(title_length)
cur_position = 0
while True:
if ((cur_position + seq_length) < len(emissions)):
extension = seq_length
else:
extension = (len(emissions) - cur_position)
print(('%s%s' % (emission_title, emissions[cur_position:(cur_position + seq_length)])))
print(('%s%s' % (real_title, real_state[cur_position:(cur_position + seq_length)])))
print(('%s%s\n' % (predicted_title, predicted_state[cur_position:(cur_position + seq_length)])))
if (len(emissions) < (cur_position + seq_length)):
break
cur_position += seq_length
| [
"def",
"pretty_print_prediction",
"(",
"emissions",
",",
"real_state",
",",
"predicted_state",
",",
"emission_title",
"=",
"'Emissions'",
",",
"real_title",
"=",
"'Real State'",
",",
"predicted_title",
"=",
"'Predicted State'",
",",
"line_width",
"=",
"75",
")",
":",
"title_length",
"=",
"(",
"max",
"(",
"len",
"(",
"emission_title",
")",
",",
"len",
"(",
"real_title",
")",
",",
"len",
"(",
"predicted_title",
")",
")",
"+",
"1",
")",
"seq_length",
"=",
"(",
"line_width",
"-",
"title_length",
")",
"emission_title",
"=",
"emission_title",
".",
"ljust",
"(",
"title_length",
")",
"real_title",
"=",
"real_title",
".",
"ljust",
"(",
"title_length",
")",
"predicted_title",
"=",
"predicted_title",
".",
"ljust",
"(",
"title_length",
")",
"cur_position",
"=",
"0",
"while",
"True",
":",
"if",
"(",
"(",
"cur_position",
"+",
"seq_length",
")",
"<",
"len",
"(",
"emissions",
")",
")",
":",
"extension",
"=",
"seq_length",
"else",
":",
"extension",
"=",
"(",
"len",
"(",
"emissions",
")",
"-",
"cur_position",
")",
"print",
"(",
"(",
"'%s%s'",
"%",
"(",
"emission_title",
",",
"emissions",
"[",
"cur_position",
":",
"(",
"cur_position",
"+",
"seq_length",
")",
"]",
")",
")",
")",
"print",
"(",
"(",
"'%s%s'",
"%",
"(",
"real_title",
",",
"real_state",
"[",
"cur_position",
":",
"(",
"cur_position",
"+",
"seq_length",
")",
"]",
")",
")",
")",
"print",
"(",
"(",
"'%s%s\\n'",
"%",
"(",
"predicted_title",
",",
"predicted_state",
"[",
"cur_position",
":",
"(",
"cur_position",
"+",
"seq_length",
")",
"]",
")",
")",
")",
"if",
"(",
"len",
"(",
"emissions",
")",
"<",
"(",
"cur_position",
"+",
"seq_length",
")",
")",
":",
"break",
"cur_position",
"+=",
"seq_length"
] | print out a state sequence prediction in a nice manner . | train | false |
45,682 | def _sqrt_numeric_denest(a, b, r, d2):
from sympy.simplify.simplify import radsimp
depthr = sqrt_depth(r)
d = sqrt(d2)
vad = (a + d)
if ((sqrt_depth(vad) < (depthr + 1)) or (vad ** 2).is_Rational):
vad1 = radsimp((1 / vad))
return (sqrt((vad / 2)) + (sign(b) * sqrt(((((b ** 2) * r) * vad1) / 2).expand()))).expand()
| [
"def",
"_sqrt_numeric_denest",
"(",
"a",
",",
"b",
",",
"r",
",",
"d2",
")",
":",
"from",
"sympy",
".",
"simplify",
".",
"simplify",
"import",
"radsimp",
"depthr",
"=",
"sqrt_depth",
"(",
"r",
")",
"d",
"=",
"sqrt",
"(",
"d2",
")",
"vad",
"=",
"(",
"a",
"+",
"d",
")",
"if",
"(",
"(",
"sqrt_depth",
"(",
"vad",
")",
"<",
"(",
"depthr",
"+",
"1",
")",
")",
"or",
"(",
"vad",
"**",
"2",
")",
".",
"is_Rational",
")",
":",
"vad1",
"=",
"radsimp",
"(",
"(",
"1",
"/",
"vad",
")",
")",
"return",
"(",
"sqrt",
"(",
"(",
"vad",
"/",
"2",
")",
")",
"+",
"(",
"sign",
"(",
"b",
")",
"*",
"sqrt",
"(",
"(",
"(",
"(",
"(",
"b",
"**",
"2",
")",
"*",
"r",
")",
"*",
"vad1",
")",
"/",
"2",
")",
".",
"expand",
"(",
")",
")",
")",
")",
".",
"expand",
"(",
")"
] | helper that denest expr = a + b*sqrt(r) . | train | false |
45,683 | @click.command(name='open')
@click.option('--ignore_empty_list', is_flag=True, help='Do not raise exception if there are no actionable indices')
@click.option('--filter_list', callback=validate_filter_json, help='JSON string representing an array of filters.', required=True)
@click.pass_context
def open_singleton(ctx, ignore_empty_list, filter_list):
action = 'open'
action_class = CLASS_MAP[action]
c_args = ctx.obj['config']['client']
client = get_client(**c_args)
logger = logging.getLogger(__name__)
logger.debug('Validating provided filters: {0}'.format(filter_list))
clean_filters = {'filters': filter_schema_check(action, filter_list)}
ilo = IndexList(client)
_do_filters(ilo, clean_filters, ignore_empty_list)
action_obj = action_class(ilo)
_actionator(action, action_obj, dry_run=ctx.parent.params['dry_run'])
| [
"@",
"click",
".",
"command",
"(",
"name",
"=",
"'open'",
")",
"@",
"click",
".",
"option",
"(",
"'--ignore_empty_list'",
",",
"is_flag",
"=",
"True",
",",
"help",
"=",
"'Do not raise exception if there are no actionable indices'",
")",
"@",
"click",
".",
"option",
"(",
"'--filter_list'",
",",
"callback",
"=",
"validate_filter_json",
",",
"help",
"=",
"'JSON string representing an array of filters.'",
",",
"required",
"=",
"True",
")",
"@",
"click",
".",
"pass_context",
"def",
"open_singleton",
"(",
"ctx",
",",
"ignore_empty_list",
",",
"filter_list",
")",
":",
"action",
"=",
"'open'",
"action_class",
"=",
"CLASS_MAP",
"[",
"action",
"]",
"c_args",
"=",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
"[",
"'client'",
"]",
"client",
"=",
"get_client",
"(",
"**",
"c_args",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'Validating provided filters: {0}'",
".",
"format",
"(",
"filter_list",
")",
")",
"clean_filters",
"=",
"{",
"'filters'",
":",
"filter_schema_check",
"(",
"action",
",",
"filter_list",
")",
"}",
"ilo",
"=",
"IndexList",
"(",
"client",
")",
"_do_filters",
"(",
"ilo",
",",
"clean_filters",
",",
"ignore_empty_list",
")",
"action_obj",
"=",
"action_class",
"(",
"ilo",
")",
"_actionator",
"(",
"action",
",",
"action_obj",
",",
"dry_run",
"=",
"ctx",
".",
"parent",
".",
"params",
"[",
"'dry_run'",
"]",
")"
] | open indices . | train | false |
45,685 | @pytest.mark.parametrize('user_input, output', [('qutebrowser.org', 'http://qutebrowser.org'), ('http://qutebrowser.org', 'http://qutebrowser.org'), ('::1/foo', 'http://[::1]/foo'), ('[::1]/foo', 'http://[::1]/foo'), ('http://[::1]', 'http://[::1]'), ('qutebrowser.org', 'http://qutebrowser.org'), ('http://qutebrowser.org', 'http://qutebrowser.org'), ('::1/foo', 'http://[::1]/foo'), ('[::1]/foo', 'http://[::1]/foo'), ('http://[::1]', 'http://[::1]')])
def test_qurl_from_user_input(user_input, output):
url = urlutils.qurl_from_user_input(user_input)
assert (url.toString() == output)
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'user_input, output'",
",",
"[",
"(",
"'qutebrowser.org'",
",",
"'http://qutebrowser.org'",
")",
",",
"(",
"'http://qutebrowser.org'",
",",
"'http://qutebrowser.org'",
")",
",",
"(",
"'::1/foo'",
",",
"'http://[::1]/foo'",
")",
",",
"(",
"'[::1]/foo'",
",",
"'http://[::1]/foo'",
")",
",",
"(",
"'http://[::1]'",
",",
"'http://[::1]'",
")",
",",
"(",
"'qutebrowser.org'",
",",
"'http://qutebrowser.org'",
")",
",",
"(",
"'http://qutebrowser.org'",
",",
"'http://qutebrowser.org'",
")",
",",
"(",
"'::1/foo'",
",",
"'http://[::1]/foo'",
")",
",",
"(",
"'[::1]/foo'",
",",
"'http://[::1]/foo'",
")",
",",
"(",
"'http://[::1]'",
",",
"'http://[::1]'",
")",
"]",
")",
"def",
"test_qurl_from_user_input",
"(",
"user_input",
",",
"output",
")",
":",
"url",
"=",
"urlutils",
".",
"qurl_from_user_input",
"(",
"user_input",
")",
"assert",
"(",
"url",
".",
"toString",
"(",
")",
"==",
"output",
")"
] | test qurl_from_user_input . | train | false |
45,686 | def decode_pair(s, pos=0):
nameLength = ord(s[pos])
if (nameLength & 128):
nameLength = (struct.unpack('!L', s[pos:(pos + 4)])[0] & 2147483647)
pos += 4
else:
pos += 1
valueLength = ord(s[pos])
if (valueLength & 128):
valueLength = (struct.unpack('!L', s[pos:(pos + 4)])[0] & 2147483647)
pos += 4
else:
pos += 1
name = s[pos:(pos + nameLength)]
pos += nameLength
value = s[pos:(pos + valueLength)]
pos += valueLength
return (pos, (name, value))
| [
"def",
"decode_pair",
"(",
"s",
",",
"pos",
"=",
"0",
")",
":",
"nameLength",
"=",
"ord",
"(",
"s",
"[",
"pos",
"]",
")",
"if",
"(",
"nameLength",
"&",
"128",
")",
":",
"nameLength",
"=",
"(",
"struct",
".",
"unpack",
"(",
"'!L'",
",",
"s",
"[",
"pos",
":",
"(",
"pos",
"+",
"4",
")",
"]",
")",
"[",
"0",
"]",
"&",
"2147483647",
")",
"pos",
"+=",
"4",
"else",
":",
"pos",
"+=",
"1",
"valueLength",
"=",
"ord",
"(",
"s",
"[",
"pos",
"]",
")",
"if",
"(",
"valueLength",
"&",
"128",
")",
":",
"valueLength",
"=",
"(",
"struct",
".",
"unpack",
"(",
"'!L'",
",",
"s",
"[",
"pos",
":",
"(",
"pos",
"+",
"4",
")",
"]",
")",
"[",
"0",
"]",
"&",
"2147483647",
")",
"pos",
"+=",
"4",
"else",
":",
"pos",
"+=",
"1",
"name",
"=",
"s",
"[",
"pos",
":",
"(",
"pos",
"+",
"nameLength",
")",
"]",
"pos",
"+=",
"nameLength",
"value",
"=",
"s",
"[",
"pos",
":",
"(",
"pos",
"+",
"valueLength",
")",
"]",
"pos",
"+=",
"valueLength",
"return",
"(",
"pos",
",",
"(",
"name",
",",
"value",
")",
")"
] | decodes a name/value pair . | train | false |
45,687 | @task
@timed
def install_prereqs():
if no_prereq_install():
print NO_PREREQ_MESSAGE
return
install_node_prereqs()
install_python_prereqs()
log_installed_python_prereqs()
| [
"@",
"task",
"@",
"timed",
"def",
"install_prereqs",
"(",
")",
":",
"if",
"no_prereq_install",
"(",
")",
":",
"print",
"NO_PREREQ_MESSAGE",
"return",
"install_node_prereqs",
"(",
")",
"install_python_prereqs",
"(",
")",
"log_installed_python_prereqs",
"(",
")"
] | installs node and python prerequisites . | train | false |
45,688 | @deprecated_network
def do_floating_ip_list(cs, _args):
_print_floating_ip_list(cs.floating_ips.list())
| [
"@",
"deprecated_network",
"def",
"do_floating_ip_list",
"(",
"cs",
",",
"_args",
")",
":",
"_print_floating_ip_list",
"(",
"cs",
".",
"floating_ips",
".",
"list",
"(",
")",
")"
] | list floating ips . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.