nwo
stringlengths 5
106
| sha
stringlengths 40
40
| path
stringlengths 4
174
| language
stringclasses 1
value | identifier
stringlengths 1
140
| parameters
stringlengths 0
87.7k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
426k
| docstring
stringlengths 0
64.3k
| docstring_summary
stringlengths 0
26.3k
| docstring_tokens
list | function
stringlengths 18
4.83M
| function_tokens
list | url
stringlengths 83
304
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CheckPointSW/Karta
|
b845928487b50a5b41acd532ae0399177a4356aa
|
src/thumbs_up/analyzers/mips.py
|
python
|
MipsAnalyzer.codeTypes
|
(self)
|
return 0, 1
|
Return a tuple of the CPU supported code types.
Return Value:
collection of supported code types
|
Return a tuple of the CPU supported code types.
|
[
"Return",
"a",
"tuple",
"of",
"the",
"CPU",
"supported",
"code",
"types",
"."
] |
def codeTypes(self):
"""Return a tuple of the CPU supported code types.
Return Value:
collection of supported code types
"""
return 0, 1
|
[
"def",
"codeTypes",
"(",
"self",
")",
":",
"return",
"0",
",",
"1"
] |
https://github.com/CheckPointSW/Karta/blob/b845928487b50a5b41acd532ae0399177a4356aa/src/thumbs_up/analyzers/mips.py#L165-L171
|
|
jazzband/tablib
|
94ffe67e50eb5bfd99d73a4f010e463478a98928
|
src/tablib/core.py
|
python
|
Dataset._get_headers
|
(self)
|
return self.__headers
|
An *optional* list of strings to be used for header rows and attribute names.
This must be set manually. The given list length must equal :attr:`Dataset.width`.
|
An *optional* list of strings to be used for header rows and attribute names.
|
[
"An",
"*",
"optional",
"*",
"list",
"of",
"strings",
"to",
"be",
"used",
"for",
"header",
"rows",
"and",
"attribute",
"names",
"."
] |
def _get_headers(self):
"""An *optional* list of strings to be used for header rows and attribute names.
This must be set manually. The given list length must equal :attr:`Dataset.width`.
"""
return self.__headers
|
[
"def",
"_get_headers",
"(",
"self",
")",
":",
"return",
"self",
".",
"__headers"
] |
https://github.com/jazzband/tablib/blob/94ffe67e50eb5bfd99d73a4f010e463478a98928/src/tablib/core.py#L291-L297
|
|
uqfoundation/multiprocess
|
028cc73f02655e6451d92e5147d19d8c10aebe50
|
py3.2/multiprocess/forking.py
|
python
|
prepare
|
(data)
|
Try to get current process ready to unpickle process object
|
Try to get current process ready to unpickle process object
|
[
"Try",
"to",
"get",
"current",
"process",
"ready",
"to",
"unpickle",
"process",
"object"
] |
def prepare(data):
'''
Try to get current process ready to unpickle process object
'''
old_main_modules.append(sys.modules['__main__'])
if 'name' in data:
process.current_process().name = data['name']
if 'authkey' in data:
process.current_process()._authkey = data['authkey']
if 'log_to_stderr' in data and data['log_to_stderr']:
util.log_to_stderr()
if 'log_level' in data:
util.get_logger().setLevel(data['log_level'])
if 'sys_path' in data:
sys.path = data['sys_path']
if 'sys_argv' in data:
sys.argv = data['sys_argv']
if 'dir' in data:
os.chdir(data['dir'])
if 'orig_dir' in data:
process.ORIGINAL_DIR = data['orig_dir']
if 'main_path' in data:
# XXX (ncoghlan): The following code makes several bogus
# assumptions regarding the relationship between __file__
# and a module's real name. See PEP 302 and issue #10845
main_path = data['main_path']
main_name = os.path.splitext(os.path.basename(main_path))[0]
if main_name == '__init__':
main_name = os.path.basename(os.path.dirname(main_path))
if main_name == '__main__':
main_module = sys.modules['__main__']
main_module.__file__ = main_path
elif main_name != 'ipython':
# Main modules not actually called __main__.py may
# contain additional code that should still be executed
import imp
if main_path is None:
dirs = None
elif os.path.basename(main_path).startswith('__init__.py'):
dirs = [os.path.dirname(os.path.dirname(main_path))]
else:
dirs = [os.path.dirname(main_path)]
assert main_name not in sys.modules, main_name
file, path_name, etc = imp.find_module(main_name, dirs)
try:
# We would like to do "imp.load_module('__main__', ...)"
# here. However, that would cause 'if __name__ ==
# "__main__"' clauses to be executed.
main_module = imp.load_module(
'__parents_main__', file, path_name, etc
)
finally:
if file:
file.close()
sys.modules['__main__'] = main_module
main_module.__name__ = '__main__'
# Try to make the potentially picklable objects in
# sys.modules['__main__'] realize they are in the main
# module -- somewhat ugly.
for obj in list(main_module.__dict__.values()):
try:
if obj.__module__ == '__parents_main__':
obj.__module__ = '__main__'
except Exception:
pass
|
[
"def",
"prepare",
"(",
"data",
")",
":",
"old_main_modules",
".",
"append",
"(",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
")",
"if",
"'name'",
"in",
"data",
":",
"process",
".",
"current_process",
"(",
")",
".",
"name",
"=",
"data",
"[",
"'name'",
"]",
"if",
"'authkey'",
"in",
"data",
":",
"process",
".",
"current_process",
"(",
")",
".",
"_authkey",
"=",
"data",
"[",
"'authkey'",
"]",
"if",
"'log_to_stderr'",
"in",
"data",
"and",
"data",
"[",
"'log_to_stderr'",
"]",
":",
"util",
".",
"log_to_stderr",
"(",
")",
"if",
"'log_level'",
"in",
"data",
":",
"util",
".",
"get_logger",
"(",
")",
".",
"setLevel",
"(",
"data",
"[",
"'log_level'",
"]",
")",
"if",
"'sys_path'",
"in",
"data",
":",
"sys",
".",
"path",
"=",
"data",
"[",
"'sys_path'",
"]",
"if",
"'sys_argv'",
"in",
"data",
":",
"sys",
".",
"argv",
"=",
"data",
"[",
"'sys_argv'",
"]",
"if",
"'dir'",
"in",
"data",
":",
"os",
".",
"chdir",
"(",
"data",
"[",
"'dir'",
"]",
")",
"if",
"'orig_dir'",
"in",
"data",
":",
"process",
".",
"ORIGINAL_DIR",
"=",
"data",
"[",
"'orig_dir'",
"]",
"if",
"'main_path'",
"in",
"data",
":",
"# XXX (ncoghlan): The following code makes several bogus",
"# assumptions regarding the relationship between __file__",
"# and a module's real name. See PEP 302 and issue #10845",
"main_path",
"=",
"data",
"[",
"'main_path'",
"]",
"main_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"main_path",
")",
")",
"[",
"0",
"]",
"if",
"main_name",
"==",
"'__init__'",
":",
"main_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"main_path",
")",
")",
"if",
"main_name",
"==",
"'__main__'",
":",
"main_module",
"=",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
"main_module",
".",
"__file__",
"=",
"main_path",
"elif",
"main_name",
"!=",
"'ipython'",
":",
"# Main modules not actually called __main__.py may",
"# contain additional code that should still be executed",
"import",
"imp",
"if",
"main_path",
"is",
"None",
":",
"dirs",
"=",
"None",
"elif",
"os",
".",
"path",
".",
"basename",
"(",
"main_path",
")",
".",
"startswith",
"(",
"'__init__.py'",
")",
":",
"dirs",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"main_path",
")",
")",
"]",
"else",
":",
"dirs",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"main_path",
")",
"]",
"assert",
"main_name",
"not",
"in",
"sys",
".",
"modules",
",",
"main_name",
"file",
",",
"path_name",
",",
"etc",
"=",
"imp",
".",
"find_module",
"(",
"main_name",
",",
"dirs",
")",
"try",
":",
"# We would like to do \"imp.load_module('__main__', ...)\"",
"# here. However, that would cause 'if __name__ ==",
"# \"__main__\"' clauses to be executed.",
"main_module",
"=",
"imp",
".",
"load_module",
"(",
"'__parents_main__'",
",",
"file",
",",
"path_name",
",",
"etc",
")",
"finally",
":",
"if",
"file",
":",
"file",
".",
"close",
"(",
")",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
"=",
"main_module",
"main_module",
".",
"__name__",
"=",
"'__main__'",
"# Try to make the potentially picklable objects in",
"# sys.modules['__main__'] realize they are in the main",
"# module -- somewhat ugly.",
"for",
"obj",
"in",
"list",
"(",
"main_module",
".",
"__dict__",
".",
"values",
"(",
")",
")",
":",
"try",
":",
"if",
"obj",
".",
"__module__",
"==",
"'__parents_main__'",
":",
"obj",
".",
"__module__",
"=",
"'__main__'",
"except",
"Exception",
":",
"pass"
] |
https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.2/multiprocess/forking.py#L449-L527
|
||
facebookresearch/SlowFast
|
39ef35c9a086443209b458cceaec86a02e27b369
|
slowfast/utils/ava_evaluation/label_map_util.py
|
python
|
create_category_index_from_labelmap
|
(label_map_path)
|
return create_category_index(categories)
|
Reads a label map and returns a category index.
Args:
label_map_path: Path to `StringIntLabelMap` proto text file.
Returns:
A category index, which is a dictionary that maps integer ids to dicts
containing categories, e.g.
{1: {'id': 1, 'name': 'dog'}, 2: {'id': 2, 'name': 'cat'}, ...}
|
Reads a label map and returns a category index.
|
[
"Reads",
"a",
"label",
"map",
"and",
"returns",
"a",
"category",
"index",
"."
] |
def create_category_index_from_labelmap(label_map_path):
"""Reads a label map and returns a category index.
Args:
label_map_path: Path to `StringIntLabelMap` proto text file.
Returns:
A category index, which is a dictionary that maps integer ids to dicts
containing categories, e.g.
{1: {'id': 1, 'name': 'dog'}, 2: {'id': 2, 'name': 'cat'}, ...}
"""
label_map = load_labelmap(label_map_path)
max_num_classes = max(item.id for item in label_map.item)
categories = convert_label_map_to_categories(label_map, max_num_classes)
return create_category_index(categories)
|
[
"def",
"create_category_index_from_labelmap",
"(",
"label_map_path",
")",
":",
"label_map",
"=",
"load_labelmap",
"(",
"label_map_path",
")",
"max_num_classes",
"=",
"max",
"(",
"item",
".",
"id",
"for",
"item",
"in",
"label_map",
".",
"item",
")",
"categories",
"=",
"convert_label_map_to_categories",
"(",
"label_map",
",",
"max_num_classes",
")",
"return",
"create_category_index",
"(",
"categories",
")"
] |
https://github.com/facebookresearch/SlowFast/blob/39ef35c9a086443209b458cceaec86a02e27b369/slowfast/utils/ava_evaluation/label_map_util.py#L168-L182
|
|
Chaffelson/nipyapi
|
d3b186fd701ce308c2812746d98af9120955e810
|
nipyapi/nifi/models/controller_service_referencing_component_entity.py
|
python
|
ControllerServiceReferencingComponentEntity.component
|
(self)
|
return self._component
|
Gets the component of this ControllerServiceReferencingComponentEntity.
:return: The component of this ControllerServiceReferencingComponentEntity.
:rtype: ControllerServiceReferencingComponentDTO
|
Gets the component of this ControllerServiceReferencingComponentEntity.
|
[
"Gets",
"the",
"component",
"of",
"this",
"ControllerServiceReferencingComponentEntity",
"."
] |
def component(self):
"""
Gets the component of this ControllerServiceReferencingComponentEntity.
:return: The component of this ControllerServiceReferencingComponentEntity.
:rtype: ControllerServiceReferencingComponentDTO
"""
return self._component
|
[
"def",
"component",
"(",
"self",
")",
":",
"return",
"self",
".",
"_component"
] |
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/controller_service_referencing_component_entity.py#L253-L260
|
|
zhl2008/awd-platform
|
0416b31abea29743387b10b3914581fbe8e7da5e
|
web_flaskbb/Python-2.7.9/Lib/plat-sunos5/STROPTS.py
|
python
|
AS_TYPE_64BIT
|
(as_)
|
return
|
[] |
def AS_TYPE_64BIT(as_): return
|
[
"def",
"AS_TYPE_64BIT",
"(",
"as_",
")",
":",
"return"
] |
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-sunos5/STROPTS.py#L1553-L1553
|
|||
henkelis/sonospy
|
841f52010fd6e1e932d8f1a8896ad4e5a0667b8a
|
web2py/gluon/shell.py
|
python
|
env
|
(
a,
import_models=False,
c=None,
f=None,
dir='',
)
|
return environment
|
Return web2py execution environment for application (a), controller (c),
function (f).
If import_models is True the exec all application models into the
environment.
|
Return web2py execution environment for application (a), controller (c),
function (f).
If import_models is True the exec all application models into the
environment.
|
[
"Return",
"web2py",
"execution",
"environment",
"for",
"application",
"(",
"a",
")",
"controller",
"(",
"c",
")",
"function",
"(",
"f",
")",
".",
"If",
"import_models",
"is",
"True",
"the",
"exec",
"all",
"application",
"models",
"into",
"the",
"environment",
"."
] |
def env(
a,
import_models=False,
c=None,
f=None,
dir='',
):
"""
Return web2py execution environment for application (a), controller (c),
function (f).
If import_models is True the exec all application models into the
environment.
"""
request = Request()
response = Response()
session = Session()
request.application = a
# Populate the dummy environment with sensible defaults.
if not dir:
request.folder = os.path.join('applications', a)
else:
request.folder = dir
request.controller = c or 'default'
request.function = f or 'index'
response.view = '%s/%s.html' % (request.controller,
request.function)
request.env.path_info = '/%s/%s/%s' % (a, c, f)
request.env.http_host = '127.0.0.1:8000'
request.env.remote_addr = '127.0.0.1'
# Monkey patch so credentials checks pass.
def check_credentials(request, other_application='admin'):
return True
fileutils.check_credentials = check_credentials
environment = build_environment(request, response, session)
if import_models:
try:
run_models_in(environment)
except RestrictedError, e:
sys.stderr.write(e.traceback+'\n')
sys.exit(1)
return environment
|
[
"def",
"env",
"(",
"a",
",",
"import_models",
"=",
"False",
",",
"c",
"=",
"None",
",",
"f",
"=",
"None",
",",
"dir",
"=",
"''",
",",
")",
":",
"request",
"=",
"Request",
"(",
")",
"response",
"=",
"Response",
"(",
")",
"session",
"=",
"Session",
"(",
")",
"request",
".",
"application",
"=",
"a",
"# Populate the dummy environment with sensible defaults.",
"if",
"not",
"dir",
":",
"request",
".",
"folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'applications'",
",",
"a",
")",
"else",
":",
"request",
".",
"folder",
"=",
"dir",
"request",
".",
"controller",
"=",
"c",
"or",
"'default'",
"request",
".",
"function",
"=",
"f",
"or",
"'index'",
"response",
".",
"view",
"=",
"'%s/%s.html'",
"%",
"(",
"request",
".",
"controller",
",",
"request",
".",
"function",
")",
"request",
".",
"env",
".",
"path_info",
"=",
"'/%s/%s/%s'",
"%",
"(",
"a",
",",
"c",
",",
"f",
")",
"request",
".",
"env",
".",
"http_host",
"=",
"'127.0.0.1:8000'",
"request",
".",
"env",
".",
"remote_addr",
"=",
"'127.0.0.1'",
"# Monkey patch so credentials checks pass.",
"def",
"check_credentials",
"(",
"request",
",",
"other_application",
"=",
"'admin'",
")",
":",
"return",
"True",
"fileutils",
".",
"check_credentials",
"=",
"check_credentials",
"environment",
"=",
"build_environment",
"(",
"request",
",",
"response",
",",
"session",
")",
"if",
"import_models",
":",
"try",
":",
"run_models_in",
"(",
"environment",
")",
"except",
"RestrictedError",
",",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"e",
".",
"traceback",
"+",
"'\\n'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"environment"
] |
https://github.com/henkelis/sonospy/blob/841f52010fd6e1e932d8f1a8896ad4e5a0667b8a/web2py/gluon/shell.py#L66-L114
|
|
holzschu/Carnets
|
44effb10ddfc6aa5c8b0687582a724ba82c6b547
|
Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/settings.py
|
python
|
PrioritizedSetting.set_value
|
(self, value)
|
Specify a value for this setting programmatically.
A value set this way takes precedence over all other methods except
immediate values.
Args:
value (str or int or float):
A user-set value for this setting
Returns:
None
|
Specify a value for this setting programmatically.
|
[
"Specify",
"a",
"value",
"for",
"this",
"setting",
"programmatically",
"."
] |
def set_value(self, value):
''' Specify a value for this setting programmatically.
A value set this way takes precedence over all other methods except
immediate values.
Args:
value (str or int or float):
A user-set value for this setting
Returns:
None
'''
self._user_value = value
|
[
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_user_value",
"=",
"value"
] |
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/settings.py#L334-L347
|
||
bitprophet/ssh
|
e8bdad4c82a50158a749233dca58c29e47c60b76
|
ssh/client.py
|
python
|
SSHClient._auth
|
(self, username, password, pkey, key_filenames, allow_agent, look_for_keys)
|
Try, in order:
- The key passed in, if one was passed in.
- Any key we can find through an SSH agent (if allowed).
- Any "id_rsa" or "id_dsa" key discoverable in ~/.ssh/ (if allowed).
- Plain username/password auth, if a password was given.
(The password might be needed to unlock a private key.)
The password is required for two-factor authentication.
|
Try, in order:
|
[
"Try",
"in",
"order",
":"
] |
def _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys):
"""
Try, in order:
- The key passed in, if one was passed in.
- Any key we can find through an SSH agent (if allowed).
- Any "id_rsa" or "id_dsa" key discoverable in ~/.ssh/ (if allowed).
- Plain username/password auth, if a password was given.
(The password might be needed to unlock a private key.)
The password is required for two-factor authentication.
"""
saved_exception = None
two_factor = False
allowed_types = []
if pkey is not None:
try:
self._log(DEBUG, 'Trying SSH key %s' % hexlify(pkey.get_fingerprint()))
allowed_types = self._transport.auth_publickey(username, pkey)
two_factor = (allowed_types == ['password'])
if not two_factor:
return
except SSHException, e:
saved_exception = e
if not two_factor:
for key_filename in key_filenames:
for pkey_class in (RSAKey, DSSKey):
try:
key = pkey_class.from_private_key_file(key_filename, password)
self._log(DEBUG, 'Trying key %s from %s' % (hexlify(key.get_fingerprint()), key_filename))
self._transport.auth_publickey(username, key)
two_factor = (allowed_types == ['password'])
if not two_factor:
return
break
except SSHException, e:
saved_exception = e
if not two_factor and allow_agent:
if self._agent == None:
self._agent = Agent()
for key in self._agent.get_keys():
try:
self._log(DEBUG, 'Trying SSH agent key %s' % hexlify(key.get_fingerprint()))
# for 2-factor auth a successfully auth'd key will result in ['password']
allowed_types = self._transport.auth_publickey(username, key)
two_factor = (allowed_types == ['password'])
if not two_factor:
return
break
except SSHException, e:
saved_exception = e
if not two_factor:
keyfiles = []
rsa_key = os.path.expanduser('~/.ssh/id_rsa')
dsa_key = os.path.expanduser('~/.ssh/id_dsa')
if os.path.isfile(rsa_key):
keyfiles.append((RSAKey, rsa_key))
if os.path.isfile(dsa_key):
keyfiles.append((DSSKey, dsa_key))
# look in ~/ssh/ for windows users:
rsa_key = os.path.expanduser('~/ssh/id_rsa')
dsa_key = os.path.expanduser('~/ssh/id_dsa')
if os.path.isfile(rsa_key):
keyfiles.append((RSAKey, rsa_key))
if os.path.isfile(dsa_key):
keyfiles.append((DSSKey, dsa_key))
if not look_for_keys:
keyfiles = []
for pkey_class, filename in keyfiles:
try:
key = pkey_class.from_private_key_file(filename, password)
self._log(DEBUG, 'Trying discovered key %s in %s' % (hexlify(key.get_fingerprint()), filename))
# for 2-factor auth a successfully auth'd key will result in ['password']
allowed_types = self._transport.auth_publickey(username, key)
two_factor = (allowed_types == ['password'])
if not two_factor:
return
break
except SSHException, e:
saved_exception = e
except IOError, e:
saved_exception = e
if password is not None:
try:
self._transport.auth_password(username, password)
return
except SSHException, e:
saved_exception = e
elif two_factor:
raise SSHException('Two-factor authentication requires a password')
# if we got an auth-failed exception earlier, re-raise it
if saved_exception is not None:
raise saved_exception
raise SSHException('No authentication methods available')
|
[
"def",
"_auth",
"(",
"self",
",",
"username",
",",
"password",
",",
"pkey",
",",
"key_filenames",
",",
"allow_agent",
",",
"look_for_keys",
")",
":",
"saved_exception",
"=",
"None",
"two_factor",
"=",
"False",
"allowed_types",
"=",
"[",
"]",
"if",
"pkey",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"'Trying SSH key %s'",
"%",
"hexlify",
"(",
"pkey",
".",
"get_fingerprint",
"(",
")",
")",
")",
"allowed_types",
"=",
"self",
".",
"_transport",
".",
"auth_publickey",
"(",
"username",
",",
"pkey",
")",
"two_factor",
"=",
"(",
"allowed_types",
"==",
"[",
"'password'",
"]",
")",
"if",
"not",
"two_factor",
":",
"return",
"except",
"SSHException",
",",
"e",
":",
"saved_exception",
"=",
"e",
"if",
"not",
"two_factor",
":",
"for",
"key_filename",
"in",
"key_filenames",
":",
"for",
"pkey_class",
"in",
"(",
"RSAKey",
",",
"DSSKey",
")",
":",
"try",
":",
"key",
"=",
"pkey_class",
".",
"from_private_key_file",
"(",
"key_filename",
",",
"password",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"'Trying key %s from %s'",
"%",
"(",
"hexlify",
"(",
"key",
".",
"get_fingerprint",
"(",
")",
")",
",",
"key_filename",
")",
")",
"self",
".",
"_transport",
".",
"auth_publickey",
"(",
"username",
",",
"key",
")",
"two_factor",
"=",
"(",
"allowed_types",
"==",
"[",
"'password'",
"]",
")",
"if",
"not",
"two_factor",
":",
"return",
"break",
"except",
"SSHException",
",",
"e",
":",
"saved_exception",
"=",
"e",
"if",
"not",
"two_factor",
"and",
"allow_agent",
":",
"if",
"self",
".",
"_agent",
"==",
"None",
":",
"self",
".",
"_agent",
"=",
"Agent",
"(",
")",
"for",
"key",
"in",
"self",
".",
"_agent",
".",
"get_keys",
"(",
")",
":",
"try",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"'Trying SSH agent key %s'",
"%",
"hexlify",
"(",
"key",
".",
"get_fingerprint",
"(",
")",
")",
")",
"# for 2-factor auth a successfully auth'd key will result in ['password']",
"allowed_types",
"=",
"self",
".",
"_transport",
".",
"auth_publickey",
"(",
"username",
",",
"key",
")",
"two_factor",
"=",
"(",
"allowed_types",
"==",
"[",
"'password'",
"]",
")",
"if",
"not",
"two_factor",
":",
"return",
"break",
"except",
"SSHException",
",",
"e",
":",
"saved_exception",
"=",
"e",
"if",
"not",
"two_factor",
":",
"keyfiles",
"=",
"[",
"]",
"rsa_key",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.ssh/id_rsa'",
")",
"dsa_key",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.ssh/id_dsa'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"rsa_key",
")",
":",
"keyfiles",
".",
"append",
"(",
"(",
"RSAKey",
",",
"rsa_key",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dsa_key",
")",
":",
"keyfiles",
".",
"append",
"(",
"(",
"DSSKey",
",",
"dsa_key",
")",
")",
"# look in ~/ssh/ for windows users:",
"rsa_key",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/ssh/id_rsa'",
")",
"dsa_key",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/ssh/id_dsa'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"rsa_key",
")",
":",
"keyfiles",
".",
"append",
"(",
"(",
"RSAKey",
",",
"rsa_key",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dsa_key",
")",
":",
"keyfiles",
".",
"append",
"(",
"(",
"DSSKey",
",",
"dsa_key",
")",
")",
"if",
"not",
"look_for_keys",
":",
"keyfiles",
"=",
"[",
"]",
"for",
"pkey_class",
",",
"filename",
"in",
"keyfiles",
":",
"try",
":",
"key",
"=",
"pkey_class",
".",
"from_private_key_file",
"(",
"filename",
",",
"password",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"'Trying discovered key %s in %s'",
"%",
"(",
"hexlify",
"(",
"key",
".",
"get_fingerprint",
"(",
")",
")",
",",
"filename",
")",
")",
"# for 2-factor auth a successfully auth'd key will result in ['password']",
"allowed_types",
"=",
"self",
".",
"_transport",
".",
"auth_publickey",
"(",
"username",
",",
"key",
")",
"two_factor",
"=",
"(",
"allowed_types",
"==",
"[",
"'password'",
"]",
")",
"if",
"not",
"two_factor",
":",
"return",
"break",
"except",
"SSHException",
",",
"e",
":",
"saved_exception",
"=",
"e",
"except",
"IOError",
",",
"e",
":",
"saved_exception",
"=",
"e",
"if",
"password",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"_transport",
".",
"auth_password",
"(",
"username",
",",
"password",
")",
"return",
"except",
"SSHException",
",",
"e",
":",
"saved_exception",
"=",
"e",
"elif",
"two_factor",
":",
"raise",
"SSHException",
"(",
"'Two-factor authentication requires a password'",
")",
"# if we got an auth-failed exception earlier, re-raise it",
"if",
"saved_exception",
"is",
"not",
"None",
":",
"raise",
"saved_exception",
"raise",
"SSHException",
"(",
"'No authentication methods available'",
")"
] |
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/client.py#L413-L516
|
||
kyzhouhzau/NLPGNN
|
b9ecec2c6df1b3e40a54511366dcb6085cf90c34
|
nlpgnn/gnn/utils.py
|
python
|
coalesce
|
(index, value, n, sort=True)
|
return edge_index, value
|
index = [[row,col],[row,col],[row,col]]
value = [v,v,v]
n: num_nodes
|
index = [[row,col],[row,col],[row,col]]
value = [v,v,v]
n: num_nodes
|
[
"index",
"=",
"[[",
"row",
"col",
"]",
"[",
"row",
"col",
"]",
"[",
"row",
"col",
"]]",
"value",
"=",
"[",
"v",
"v",
"v",
"]",
"n",
":",
"num_nodes"
] |
def coalesce(index, value, n, sort=True):
"""
index = [[row,col],[row,col],[row,col]]
value = [v,v,v]
n: num_nodes
"""
# if sort:
# index = index[np.argsort(index[:, 0])]
# index = np.array(sorted(index.tolist()))
row = index[:, 0]
col = index[:, 1]
idx = np.full((col.size + 1,), -1, dtype=col.dtype)
idx[1:] = n * row + col
mask = idx[1:] > idx[:-1]
if mask.all():
return index, value
row = row[mask]
col = col[mask]
if value is not None:
ptr = mask.nonzero()[0]
ptr = np.concatenate([ptr, np.full((1,), value.size)])
ptr = rebuilt(ptr)
value = tf.math.segment_sum(value, ptr)[mask]
value = value[0] if isinstance(value, tuple) else value
edge_index = np.array(list(zip(row, col)))
return edge_index, value
|
[
"def",
"coalesce",
"(",
"index",
",",
"value",
",",
"n",
",",
"sort",
"=",
"True",
")",
":",
"# if sort:",
"# index = index[np.argsort(index[:, 0])]",
"# index = np.array(sorted(index.tolist()))",
"row",
"=",
"index",
"[",
":",
",",
"0",
"]",
"col",
"=",
"index",
"[",
":",
",",
"1",
"]",
"idx",
"=",
"np",
".",
"full",
"(",
"(",
"col",
".",
"size",
"+",
"1",
",",
")",
",",
"-",
"1",
",",
"dtype",
"=",
"col",
".",
"dtype",
")",
"idx",
"[",
"1",
":",
"]",
"=",
"n",
"*",
"row",
"+",
"col",
"mask",
"=",
"idx",
"[",
"1",
":",
"]",
">",
"idx",
"[",
":",
"-",
"1",
"]",
"if",
"mask",
".",
"all",
"(",
")",
":",
"return",
"index",
",",
"value",
"row",
"=",
"row",
"[",
"mask",
"]",
"col",
"=",
"col",
"[",
"mask",
"]",
"if",
"value",
"is",
"not",
"None",
":",
"ptr",
"=",
"mask",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"ptr",
"=",
"np",
".",
"concatenate",
"(",
"[",
"ptr",
",",
"np",
".",
"full",
"(",
"(",
"1",
",",
")",
",",
"value",
".",
"size",
")",
"]",
")",
"ptr",
"=",
"rebuilt",
"(",
"ptr",
")",
"value",
"=",
"tf",
".",
"math",
".",
"segment_sum",
"(",
"value",
",",
"ptr",
")",
"[",
"mask",
"]",
"value",
"=",
"value",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
"else",
"value",
"edge_index",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"zip",
"(",
"row",
",",
"col",
")",
")",
")",
"return",
"edge_index",
",",
"value"
] |
https://github.com/kyzhouhzau/NLPGNN/blob/b9ecec2c6df1b3e40a54511366dcb6085cf90c34/nlpgnn/gnn/utils.py#L64-L89
|
|
SeldonIO/alibi
|
ce961caf995d22648a8338857822c90428af4765
|
alibi/explainers/backends/cfrl_tabular.py
|
python
|
get_numerical_conditional_vector
|
(X: np.ndarray,
condition: Dict[str, List[Union[float, str]]],
preprocessor: Callable[[np.ndarray], np.ndarray],
feature_names: List[str],
category_map: Dict[int, List[str]],
stats: Dict[int, Dict[str, float]],
ranges: Optional[Dict[str, List[float]]] = None,
immutable_features: Optional[List[str]] = None,
diverse=False)
|
return C
|
Generates a conditional vector. The condition is expressed a a delta change of the feature.
For numerical features, if the `Age` feature is allowed to increase up to 10 more years, the delta change is
`[0, 10]`. If the `Hours per week` is allowed to decrease down to `-5` and increases up to `+10`, then the
delta change is `[-5, +10]`. Note that the interval must go include `0`.
Parameters
----------
X
Instances for which to generate the conditional vector in the original input format.
condition
Dictionary of conditions per feature. For numerical features it expects a range that contains the original
value. For categorical features it expects a list of feature values per features that includes the original
value.
preprocessor
Data preprocessor. The preprocessor should standardize the numerical values and convert categorical ones
into one-hot encoding representation. By convention, numerical features should be first, followed by the
rest of categorical ones.
feature_names
List of feature names. This should be provided by the dataset.
category_map
Dictionary of category mapping. The keys are column indexes and the values are lists containing the
possible feature values. This should be provided by the dataset.
stats
Dictionary of statistic of the training data. Contains the minimum and maximum value of each numerical
feature in the training set. Each key is an index of the column and each value is another dictionary
containing `min` and `max` keys.
ranges
Dictionary of ranges for numerical feature. Each value is a list containing two elements, first one
negative and the second one positive.
immutable_features
List of immutable features.
diverse
Whether to generate a diverse set of conditional vectors. A diverse set of conditional vector can generate
a diverse set of counterfactuals for a given input instance.
Returns
-------
List of conditional vectors for each numerical feature.
|
Generates a conditional vector. The condition is expressed a a delta change of the feature.
For numerical features, if the `Age` feature is allowed to increase up to 10 more years, the delta change is
`[0, 10]`. If the `Hours per week` is allowed to decrease down to `-5` and increases up to `+10`, then the
delta change is `[-5, +10]`. Note that the interval must go include `0`.
|
[
"Generates",
"a",
"conditional",
"vector",
".",
"The",
"condition",
"is",
"expressed",
"a",
"a",
"delta",
"change",
"of",
"the",
"feature",
".",
"For",
"numerical",
"features",
"if",
"the",
"Age",
"feature",
"is",
"allowed",
"to",
"increase",
"up",
"to",
"10",
"more",
"years",
"the",
"delta",
"change",
"is",
"[",
"0",
"10",
"]",
".",
"If",
"the",
"Hours",
"per",
"week",
"is",
"allowed",
"to",
"decrease",
"down",
"to",
"-",
"5",
"and",
"increases",
"up",
"to",
"+",
"10",
"then",
"the",
"delta",
"change",
"is",
"[",
"-",
"5",
"+",
"10",
"]",
".",
"Note",
"that",
"the",
"interval",
"must",
"go",
"include",
"0",
"."
] |
def get_numerical_conditional_vector(X: np.ndarray,
condition: Dict[str, List[Union[float, str]]],
preprocessor: Callable[[np.ndarray], np.ndarray],
feature_names: List[str],
category_map: Dict[int, List[str]],
stats: Dict[int, Dict[str, float]],
ranges: Optional[Dict[str, List[float]]] = None,
immutable_features: Optional[List[str]] = None,
diverse=False) -> List[np.ndarray]:
"""
Generates a conditional vector. The condition is expressed a a delta change of the feature.
For numerical features, if the `Age` feature is allowed to increase up to 10 more years, the delta change is
`[0, 10]`. If the `Hours per week` is allowed to decrease down to `-5` and increases up to `+10`, then the
delta change is `[-5, +10]`. Note that the interval must go include `0`.
Parameters
----------
X
Instances for which to generate the conditional vector in the original input format.
condition
Dictionary of conditions per feature. For numerical features it expects a range that contains the original
value. For categorical features it expects a list of feature values per features that includes the original
value.
preprocessor
Data preprocessor. The preprocessor should standardize the numerical values and convert categorical ones
into one-hot encoding representation. By convention, numerical features should be first, followed by the
rest of categorical ones.
feature_names
List of feature names. This should be provided by the dataset.
category_map
Dictionary of category mapping. The keys are column indexes and the values are lists containing the
possible feature values. This should be provided by the dataset.
stats
Dictionary of statistic of the training data. Contains the minimum and maximum value of each numerical
feature in the training set. Each key is an index of the column and each value is another dictionary
containing `min` and `max` keys.
ranges
Dictionary of ranges for numerical feature. Each value is a list containing two elements, first one
negative and the second one positive.
immutable_features
List of immutable features.
diverse
Whether to generate a diverse set of conditional vectors. A diverse set of conditional vector can generate
a diverse set of counterfactuals for a given input instance.
Returns
-------
List of conditional vectors for each numerical feature.
"""
if ranges is None:
ranges = dict()
if immutable_features is None:
immutable_features = list()
# Extract numerical features
num_features_ids = [id for id in range(X.shape[1]) if id not in category_map]
num_features_names = [feature_names[id] for id in num_features_ids]
# Need to standardize numerical features. Thus, we use the preprocessor
X_low, X_high = X.copy(), X.copy()
for feature_id, feature_name in enumerate(feature_names):
if feature_id in category_map:
continue
if feature_name in condition:
if int(condition[feature_name][0]) > 0: # int conversion because of mypy error (the value can be str too)
raise ValueError(f"Lower bound on the conditional vector for {feature_name} should be negative.")
if int(condition[feature_name][1]) < 0: # int conversion because of mypy error (the value can be str too)
raise ValueError(f"Upper bound on the conditional vector for {feature_name} should be positive.")
X_low[:, feature_id] += condition[feature_name][0]
X_high[:, feature_id] += condition[feature_name][1]
# Preprocess the vectors (standardize + one-hot encoding)
X_low_ohe = preprocessor(X_low)
X_high_ohe = preprocessor(X_high)
X_ohe = preprocessor(X)
# Initialize conditional vector buffer.
C = []
# Scale the numerical features in [0, 1] and add them to the conditional vector
for i, (feature_id, feature_name) in enumerate(zip(num_features_ids, num_features_names)):
if feature_name in immutable_features:
range_low, range_high = 0., 0.
elif feature_name in ranges:
range_low, range_high = ranges[feature_name][0], ranges[feature_name][1]
else:
range_low, range_high = -1., 1.
if (feature_name in condition) and (feature_name not in immutable_features):
# Mutable feature with conditioning
min, max = stats[feature_id]["min"], stats[feature_id]["max"]
X_low_ohe[:, i] = (X_low_ohe[:, i] - X_ohe[:, i]) / (max - min)
X_high_ohe[:, i] = (X_high_ohe[:, i] - X_ohe[:, i]) / (max - min)
# Clip in [0, 1]
X_low_ohe[:, i] = np.clip(X_low_ohe[:, i], a_min=range_low, a_max=0)
X_high_ohe[:, i] = np.clip(X_high_ohe[:, i], a_min=0, a_max=range_high)
else:
# This means no conditioning
X_low_ohe[:, i] = range_low
X_high_ohe[:, i] = range_high
if diverse:
# Note that this is still a feasible counterfactual
X_low_ohe[:, i] *= np.random.rand(*X_low_ohe[:, i].shape)
X_high_ohe[:, i] *= np.random.rand(*X_high_ohe[:, i].shape)
# Append feature conditioning
C += [X_low_ohe[:, i].reshape(-1, 1), X_high_ohe[:, i].reshape(-1, 1)]
return C
|
[
"def",
"get_numerical_conditional_vector",
"(",
"X",
":",
"np",
".",
"ndarray",
",",
"condition",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"Union",
"[",
"float",
",",
"str",
"]",
"]",
"]",
",",
"preprocessor",
":",
"Callable",
"[",
"[",
"np",
".",
"ndarray",
"]",
",",
"np",
".",
"ndarray",
"]",
",",
"feature_names",
":",
"List",
"[",
"str",
"]",
",",
"category_map",
":",
"Dict",
"[",
"int",
",",
"List",
"[",
"str",
"]",
"]",
",",
"stats",
":",
"Dict",
"[",
"int",
",",
"Dict",
"[",
"str",
",",
"float",
"]",
"]",
",",
"ranges",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"List",
"[",
"float",
"]",
"]",
"]",
"=",
"None",
",",
"immutable_features",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"diverse",
"=",
"False",
")",
"->",
"List",
"[",
"np",
".",
"ndarray",
"]",
":",
"if",
"ranges",
"is",
"None",
":",
"ranges",
"=",
"dict",
"(",
")",
"if",
"immutable_features",
"is",
"None",
":",
"immutable_features",
"=",
"list",
"(",
")",
"# Extract numerical features",
"num_features_ids",
"=",
"[",
"id",
"for",
"id",
"in",
"range",
"(",
"X",
".",
"shape",
"[",
"1",
"]",
")",
"if",
"id",
"not",
"in",
"category_map",
"]",
"num_features_names",
"=",
"[",
"feature_names",
"[",
"id",
"]",
"for",
"id",
"in",
"num_features_ids",
"]",
"# Need to standardize numerical features. Thus, we use the preprocessor",
"X_low",
",",
"X_high",
"=",
"X",
".",
"copy",
"(",
")",
",",
"X",
".",
"copy",
"(",
")",
"for",
"feature_id",
",",
"feature_name",
"in",
"enumerate",
"(",
"feature_names",
")",
":",
"if",
"feature_id",
"in",
"category_map",
":",
"continue",
"if",
"feature_name",
"in",
"condition",
":",
"if",
"int",
"(",
"condition",
"[",
"feature_name",
"]",
"[",
"0",
"]",
")",
">",
"0",
":",
"# int conversion because of mypy error (the value can be str too)",
"raise",
"ValueError",
"(",
"f\"Lower bound on the conditional vector for {feature_name} should be negative.\"",
")",
"if",
"int",
"(",
"condition",
"[",
"feature_name",
"]",
"[",
"1",
"]",
")",
"<",
"0",
":",
"# int conversion because of mypy error (the value can be str too)",
"raise",
"ValueError",
"(",
"f\"Upper bound on the conditional vector for {feature_name} should be positive.\"",
")",
"X_low",
"[",
":",
",",
"feature_id",
"]",
"+=",
"condition",
"[",
"feature_name",
"]",
"[",
"0",
"]",
"X_high",
"[",
":",
",",
"feature_id",
"]",
"+=",
"condition",
"[",
"feature_name",
"]",
"[",
"1",
"]",
"# Preprocess the vectors (standardize + one-hot encoding)",
"X_low_ohe",
"=",
"preprocessor",
"(",
"X_low",
")",
"X_high_ohe",
"=",
"preprocessor",
"(",
"X_high",
")",
"X_ohe",
"=",
"preprocessor",
"(",
"X",
")",
"# Initialize conditional vector buffer.",
"C",
"=",
"[",
"]",
"# Scale the numerical features in [0, 1] and add them to the conditional vector",
"for",
"i",
",",
"(",
"feature_id",
",",
"feature_name",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"num_features_ids",
",",
"num_features_names",
")",
")",
":",
"if",
"feature_name",
"in",
"immutable_features",
":",
"range_low",
",",
"range_high",
"=",
"0.",
",",
"0.",
"elif",
"feature_name",
"in",
"ranges",
":",
"range_low",
",",
"range_high",
"=",
"ranges",
"[",
"feature_name",
"]",
"[",
"0",
"]",
",",
"ranges",
"[",
"feature_name",
"]",
"[",
"1",
"]",
"else",
":",
"range_low",
",",
"range_high",
"=",
"-",
"1.",
",",
"1.",
"if",
"(",
"feature_name",
"in",
"condition",
")",
"and",
"(",
"feature_name",
"not",
"in",
"immutable_features",
")",
":",
"# Mutable feature with conditioning",
"min",
",",
"max",
"=",
"stats",
"[",
"feature_id",
"]",
"[",
"\"min\"",
"]",
",",
"stats",
"[",
"feature_id",
"]",
"[",
"\"max\"",
"]",
"X_low_ohe",
"[",
":",
",",
"i",
"]",
"=",
"(",
"X_low_ohe",
"[",
":",
",",
"i",
"]",
"-",
"X_ohe",
"[",
":",
",",
"i",
"]",
")",
"/",
"(",
"max",
"-",
"min",
")",
"X_high_ohe",
"[",
":",
",",
"i",
"]",
"=",
"(",
"X_high_ohe",
"[",
":",
",",
"i",
"]",
"-",
"X_ohe",
"[",
":",
",",
"i",
"]",
")",
"/",
"(",
"max",
"-",
"min",
")",
"# Clip in [0, 1]",
"X_low_ohe",
"[",
":",
",",
"i",
"]",
"=",
"np",
".",
"clip",
"(",
"X_low_ohe",
"[",
":",
",",
"i",
"]",
",",
"a_min",
"=",
"range_low",
",",
"a_max",
"=",
"0",
")",
"X_high_ohe",
"[",
":",
",",
"i",
"]",
"=",
"np",
".",
"clip",
"(",
"X_high_ohe",
"[",
":",
",",
"i",
"]",
",",
"a_min",
"=",
"0",
",",
"a_max",
"=",
"range_high",
")",
"else",
":",
"# This means no conditioning",
"X_low_ohe",
"[",
":",
",",
"i",
"]",
"=",
"range_low",
"X_high_ohe",
"[",
":",
",",
"i",
"]",
"=",
"range_high",
"if",
"diverse",
":",
"# Note that this is still a feasible counterfactual",
"X_low_ohe",
"[",
":",
",",
"i",
"]",
"*=",
"np",
".",
"random",
".",
"rand",
"(",
"*",
"X_low_ohe",
"[",
":",
",",
"i",
"]",
".",
"shape",
")",
"X_high_ohe",
"[",
":",
",",
"i",
"]",
"*=",
"np",
".",
"random",
".",
"rand",
"(",
"*",
"X_high_ohe",
"[",
":",
",",
"i",
"]",
".",
"shape",
")",
"# Append feature conditioning",
"C",
"+=",
"[",
"X_low_ohe",
"[",
":",
",",
"i",
"]",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
",",
"X_high_ohe",
"[",
":",
",",
"i",
"]",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"]",
"return",
"C"
] |
https://github.com/SeldonIO/alibi/blob/ce961caf995d22648a8338857822c90428af4765/alibi/explainers/backends/cfrl_tabular.py#L569-L684
|
|
nlloyd/SubliminalCollaborator
|
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
|
libs/twisted/python/constants.py
|
python
|
_flagOp
|
(op, left, right)
|
return result
|
Implement a binary operator for a L{FlagConstant} instance.
@param op: A two-argument callable implementing the binary operation. For
example, C{operator.or_}.
@param left: The left-hand L{FlagConstant} instance.
@param right: The right-hand L{FlagConstant} instance.
@return: A new L{FlagConstant} instance representing the result of the
operation.
|
Implement a binary operator for a L{FlagConstant} instance.
|
[
"Implement",
"a",
"binary",
"operator",
"for",
"a",
"L",
"{",
"FlagConstant",
"}",
"instance",
"."
] |
def _flagOp(op, left, right):
"""
Implement a binary operator for a L{FlagConstant} instance.
@param op: A two-argument callable implementing the binary operation. For
example, C{operator.or_}.
@param left: The left-hand L{FlagConstant} instance.
@param right: The right-hand L{FlagConstant} instance.
@return: A new L{FlagConstant} instance representing the result of the
operation.
"""
value = op(left.value, right.value)
names = op(left.names, right.names)
result = FlagConstant()
result._realize(left._container, names, value)
return result
|
[
"def",
"_flagOp",
"(",
"op",
",",
"left",
",",
"right",
")",
":",
"value",
"=",
"op",
"(",
"left",
".",
"value",
",",
"right",
".",
"value",
")",
"names",
"=",
"op",
"(",
"left",
".",
"names",
",",
"right",
".",
"names",
")",
"result",
"=",
"FlagConstant",
"(",
")",
"result",
".",
"_realize",
"(",
"left",
".",
"_container",
",",
"names",
",",
"value",
")",
"return",
"result"
] |
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/python/constants.py#L252-L269
|
|
realpython/book2-exercises
|
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
|
py2manager/gluon/contrib/pam.py
|
python
|
authenticate
|
(username, password, service='login')
|
return retval == 0
|
Returns True if the given username and password authenticate for the
given service. Returns False otherwise
``username``: the username to authenticate
``password``: the password in plain text
``service``: the PAM service to authenticate against.
Defaults to 'login
|
Returns True if the given username and password authenticate for the
given service. Returns False otherwise
|
[
"Returns",
"True",
"if",
"the",
"given",
"username",
"and",
"password",
"authenticate",
"for",
"the",
"given",
"service",
".",
"Returns",
"False",
"otherwise"
] |
def authenticate(username, password, service='login'):
"""Returns True if the given username and password authenticate for the
given service. Returns False otherwise
``username``: the username to authenticate
``password``: the password in plain text
``service``: the PAM service to authenticate against.
Defaults to 'login'"""
@CONV_FUNC
def my_conv(n_messages, messages, p_response, app_data):
"""Simple conversation function that responds to any
prompt where the echo is off with the supplied password"""
# Create an array of n_messages response objects
addr = CALLOC(n_messages, sizeof(PamResponse))
p_response[0] = cast(addr, POINTER(PamResponse))
for i in range(n_messages):
if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:
pw_copy = STRDUP(str(password))
p_response.contents[i].resp = cast(pw_copy, c_char_p)
p_response.contents[i].resp_retcode = 0
return 0
handle = PamHandle()
conv = PamConv(my_conv, 0)
retval = PAM_START(service, username, pointer(conv), pointer(handle))
if retval != 0:
# TODO: This is not an authentication error, something
# has gone wrong starting up PAM
return False
retval = PAM_AUTHENTICATE(handle, 0)
return retval == 0
|
[
"def",
"authenticate",
"(",
"username",
",",
"password",
",",
"service",
"=",
"'login'",
")",
":",
"@",
"CONV_FUNC",
"def",
"my_conv",
"(",
"n_messages",
",",
"messages",
",",
"p_response",
",",
"app_data",
")",
":",
"\"\"\"Simple conversation function that responds to any\n prompt where the echo is off with the supplied password\"\"\"",
"# Create an array of n_messages response objects",
"addr",
"=",
"CALLOC",
"(",
"n_messages",
",",
"sizeof",
"(",
"PamResponse",
")",
")",
"p_response",
"[",
"0",
"]",
"=",
"cast",
"(",
"addr",
",",
"POINTER",
"(",
"PamResponse",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n_messages",
")",
":",
"if",
"messages",
"[",
"i",
"]",
".",
"contents",
".",
"msg_style",
"==",
"PAM_PROMPT_ECHO_OFF",
":",
"pw_copy",
"=",
"STRDUP",
"(",
"str",
"(",
"password",
")",
")",
"p_response",
".",
"contents",
"[",
"i",
"]",
".",
"resp",
"=",
"cast",
"(",
"pw_copy",
",",
"c_char_p",
")",
"p_response",
".",
"contents",
"[",
"i",
"]",
".",
"resp_retcode",
"=",
"0",
"return",
"0",
"handle",
"=",
"PamHandle",
"(",
")",
"conv",
"=",
"PamConv",
"(",
"my_conv",
",",
"0",
")",
"retval",
"=",
"PAM_START",
"(",
"service",
",",
"username",
",",
"pointer",
"(",
"conv",
")",
",",
"pointer",
"(",
"handle",
")",
")",
"if",
"retval",
"!=",
"0",
":",
"# TODO: This is not an authentication error, something",
"# has gone wrong starting up PAM",
"return",
"False",
"retval",
"=",
"PAM_AUTHENTICATE",
"(",
"handle",
",",
"0",
")",
"return",
"retval",
"==",
"0"
] |
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/py2manager/gluon/contrib/pam.py#L90-L124
|
|
llimllib/limbo
|
2e33a11e73f1ab13f24c06c8a76d1c9bfcf81afb
|
limbo/plugins/github.py
|
python
|
github
|
(server, room, cmd, body, repo)
|
[] |
def github(server, room, cmd, body, repo):
# If repo wasn't passed in explicitly, grab it from the database
if not repo:
repo = get_default_repo(server, room)
# If we still couldn't find one in the database, either it's a command to
# set it or we can instrcut the user how to do so
if not repo:
if cmd == "setdefault":
set_default_repo(server, room, body[0])
return "Default repo for this room set to `{0}`".format(body[0])
else:
return (
"Unable to find default repo for this channel. "
"Run `!hub setdefault <repo_name>`"
)
try:
command_func = COMMANDS[cmd]
return command_func(repo, body)
except KeyError:
return
|
[
"def",
"github",
"(",
"server",
",",
"room",
",",
"cmd",
",",
"body",
",",
"repo",
")",
":",
"# If repo wasn't passed in explicitly, grab it from the database",
"if",
"not",
"repo",
":",
"repo",
"=",
"get_default_repo",
"(",
"server",
",",
"room",
")",
"# If we still couldn't find one in the database, either it's a command to",
"# set it or we can instrcut the user how to do so",
"if",
"not",
"repo",
":",
"if",
"cmd",
"==",
"\"setdefault\"",
":",
"set_default_repo",
"(",
"server",
",",
"room",
",",
"body",
"[",
"0",
"]",
")",
"return",
"\"Default repo for this room set to `{0}`\"",
".",
"format",
"(",
"body",
"[",
"0",
"]",
")",
"else",
":",
"return",
"(",
"\"Unable to find default repo for this channel. \"",
"\"Run `!hub setdefault <repo_name>`\"",
")",
"try",
":",
"command_func",
"=",
"COMMANDS",
"[",
"cmd",
"]",
"return",
"command_func",
"(",
"repo",
",",
"body",
")",
"except",
"KeyError",
":",
"return"
] |
https://github.com/llimllib/limbo/blob/2e33a11e73f1ab13f24c06c8a76d1c9bfcf81afb/limbo/plugins/github.py#L283-L304
|
||||
huggingface/transformers
|
623b4f7c63f60cce917677ee704d6c93ee960b4b
|
src/transformers/utils/dummy_pt_objects.py
|
python
|
ImageGPTModel.forward
|
(self, *args, **kwargs)
|
[] |
def forward(self, *args, **kwargs):
requires_backends(self, ["torch"])
|
[
"def",
"forward",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"requires_backends",
"(",
"self",
",",
"[",
"\"torch\"",
"]",
")"
] |
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L2740-L2741
|
||||
Qirky/FoxDot
|
76318f9630bede48ff3994146ed644affa27bfa4
|
FoxDot/lib/SCLang/SCLang.py
|
python
|
cls.__init__
|
(self, name, **kwargs)
|
[] |
def __init__(self, name, **kwargs):
self.name = name
self.ref = kwargs.get("ref", "")
|
[
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"ref",
"=",
"kwargs",
".",
"get",
"(",
"\"ref\"",
",",
"\"\"",
")"
] |
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/SCLang/SCLang.py#L17-L19
|
||||
oracle/graalpython
|
577e02da9755d916056184ec441c26e00b70145c
|
graalpython/lib-graalpython/python_cext.py
|
python
|
instancemethod.__repr__
|
(self)
|
return "<instancemethod {} at ?>".format(self.__func__.__name__)
|
[] |
def __repr__(self):
return "<instancemethod {} at ?>".format(self.__func__.__name__)
|
[
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"<instancemethod {} at ?>\"",
".",
"format",
"(",
"self",
".",
"__func__",
".",
"__name__",
")"
] |
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-graalpython/python_cext.py#L137-L138
|
|||
demisto/content
|
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
|
Packs/MicrosoftGraphGroups/Integrations/MicrosoftGraphGroups/MicrosoftGraphGroups.py
|
python
|
MsGraphClient.add_member
|
(self, group_id: str, properties: Dict[str, str])
|
Add a single member to a group by sending a POST request.
Args:
group_id: the group id to add the member to.
properties: the member properties.
|
Add a single member to a group by sending a POST request.
Args:
group_id: the group id to add the member to.
properties: the member properties.
|
[
"Add",
"a",
"single",
"member",
"to",
"a",
"group",
"by",
"sending",
"a",
"POST",
"request",
".",
"Args",
":",
"group_id",
":",
"the",
"group",
"id",
"to",
"add",
"the",
"member",
"to",
".",
"properties",
":",
"the",
"member",
"properties",
"."
] |
def add_member(self, group_id: str, properties: Dict[str, str]):
"""Add a single member to a group by sending a POST request.
Args:
group_id: the group id to add the member to.
properties: the member properties.
"""
# If successful, this method returns 204 No Content response code.
# It does not return anything in the response body.
# Using resp_type="text" to avoid parsing error in the calling method.
self.ms_client.http_request(
method='POST',
url_suffix=f'groups/{group_id}/members/$ref',
json_data=properties,
resp_type="text")
|
[
"def",
"add_member",
"(",
"self",
",",
"group_id",
":",
"str",
",",
"properties",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
":",
"# If successful, this method returns 204 No Content response code.",
"# It does not return anything in the response body.",
"# Using resp_type=\"text\" to avoid parsing error in the calling method.",
"self",
".",
"ms_client",
".",
"http_request",
"(",
"method",
"=",
"'POST'",
",",
"url_suffix",
"=",
"f'groups/{group_id}/members/$ref'",
",",
"json_data",
"=",
"properties",
",",
"resp_type",
"=",
"\"text\"",
")"
] |
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/MicrosoftGraphGroups/Integrations/MicrosoftGraphGroups/MicrosoftGraphGroups.py#L165-L178
|
||
LeapBeyond/scrubadub
|
ab199f0b3cc3ca11f646aabb05ebe124d2757ea5
|
scrubadub/filth/phone.py
|
python
|
PhoneFilth.generate
|
(faker: Faker)
|
return phone_number
|
Generates an example of this ``Filth`` type, usually using the faker python library.
:param faker: The ``Faker`` class from the ``faker`` library
:type faker: Faker
:return: An example of this ``Filth``
:rtype: str
|
Generates an example of this ``Filth`` type, usually using the faker python library.
|
[
"Generates",
"an",
"example",
"of",
"this",
"Filth",
"type",
"usually",
"using",
"the",
"faker",
"python",
"library",
"."
] |
def generate(faker: Faker) -> str:
"""Generates an example of this ``Filth`` type, usually using the faker python library.
:param faker: The ``Faker`` class from the ``faker`` library
:type faker: Faker
:return: An example of this ``Filth``
:rtype: str
"""
phone_number = ''
language, region = utils.locale_split(faker._locales[0])
results = [] # type: List[phonenumbers.PhoneNumberMatch]
# Here I'm filtering for numbers that pass validation by the phonenumbers package
while len(results) < 1:
# Faker generates random numbers of the right format eg (###)###-####
phone_number = re.sub(r'x.*$', '', faker.phone_number())
# phonenumbers checks that they follow the rules around area codes and that they are possibly valid
results = list(phonenumbers.PhoneNumberMatcher(phone_number, region))
return phone_number
|
[
"def",
"generate",
"(",
"faker",
":",
"Faker",
")",
"->",
"str",
":",
"phone_number",
"=",
"''",
"language",
",",
"region",
"=",
"utils",
".",
"locale_split",
"(",
"faker",
".",
"_locales",
"[",
"0",
"]",
")",
"results",
"=",
"[",
"]",
"# type: List[phonenumbers.PhoneNumberMatch]",
"# Here I'm filtering for numbers that pass validation by the phonenumbers package",
"while",
"len",
"(",
"results",
")",
"<",
"1",
":",
"# Faker generates random numbers of the right format eg (###)###-####",
"phone_number",
"=",
"re",
".",
"sub",
"(",
"r'x.*$'",
",",
"''",
",",
"faker",
".",
"phone_number",
"(",
")",
")",
"# phonenumbers checks that they follow the rules around area codes and that they are possibly valid",
"results",
"=",
"list",
"(",
"phonenumbers",
".",
"PhoneNumberMatcher",
"(",
"phone_number",
",",
"region",
")",
")",
"return",
"phone_number"
] |
https://github.com/LeapBeyond/scrubadub/blob/ab199f0b3cc3ca11f646aabb05ebe124d2757ea5/scrubadub/filth/phone.py#L15-L32
|
|
hatRiot/zarp
|
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
|
src/lib/scapy/supersocket.py
|
python
|
SuperSocket.close
|
(self)
|
[] |
def close(self):
if self.closed:
return
self.closed=1
if self.ins != self.outs:
if self.outs and self.outs.fileno() != -1:
self.outs.close()
if self.ins and self.ins.fileno() != -1:
self.ins.close()
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"return",
"self",
".",
"closed",
"=",
"1",
"if",
"self",
".",
"ins",
"!=",
"self",
".",
"outs",
":",
"if",
"self",
".",
"outs",
"and",
"self",
".",
"outs",
".",
"fileno",
"(",
")",
"!=",
"-",
"1",
":",
"self",
".",
"outs",
".",
"close",
"(",
")",
"if",
"self",
".",
"ins",
"and",
"self",
".",
"ins",
".",
"fileno",
"(",
")",
"!=",
"-",
"1",
":",
"self",
".",
"ins",
".",
"close",
"(",
")"
] |
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/supersocket.py#L34-L42
|
||||
zhufz/nlp_research
|
b435319858520edcca7c0320dca3e0013087c276
|
language_model/bert/run_classifier.py
|
python
|
DataProcessor.get_train_examples
|
(self, data_dir)
|
Gets a collection of `InputExample`s for the train set.
|
Gets a collection of `InputExample`s for the train set.
|
[
"Gets",
"a",
"collection",
"of",
"InputExample",
"s",
"for",
"the",
"train",
"set",
"."
] |
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
|
[
"def",
"get_train_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] |
https://github.com/zhufz/nlp_research/blob/b435319858520edcca7c0320dca3e0013087c276/language_model/bert/run_classifier.py#L180-L182
|
||
omz/PythonistaAppTemplate
|
f560f93f8876d82a21d108977f90583df08d55af
|
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/markdown/extensions/fenced_code.py
|
python
|
FencedCodeExtension.extendMarkdown
|
(self, md, md_globals)
|
Add FencedBlockPreprocessor to the Markdown instance.
|
Add FencedBlockPreprocessor to the Markdown instance.
|
[
"Add",
"FencedBlockPreprocessor",
"to",
"the",
"Markdown",
"instance",
"."
] |
def extendMarkdown(self, md, md_globals):
""" Add FencedBlockPreprocessor to the Markdown instance. """
md.registerExtension(self)
md.preprocessors.add('fenced_code_block',
FencedBlockPreprocessor(md),
"_begin")
|
[
"def",
"extendMarkdown",
"(",
"self",
",",
"md",
",",
"md_globals",
")",
":",
"md",
".",
"registerExtension",
"(",
"self",
")",
"md",
".",
"preprocessors",
".",
"add",
"(",
"'fenced_code_block'",
",",
"FencedBlockPreprocessor",
"(",
"md",
")",
",",
"\"_begin\"",
")"
] |
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/markdown/extensions/fenced_code.py#L91-L97
|
||
lovelylain/pyctp
|
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
|
example/ctp/stock/ApiStruct.py
|
python
|
QryBrokerUserFunction.__init__
|
(self, BrokerID='', UserID='')
|
[] |
def __init__(self, BrokerID='', UserID=''):
self.BrokerID = '' #经纪公司代码, char[11]
self.UserID = ''
|
[
"def",
"__init__",
"(",
"self",
",",
"BrokerID",
"=",
"''",
",",
"UserID",
"=",
"''",
")",
":",
"self",
".",
"BrokerID",
"=",
"''",
"#经纪公司代码, char[11]",
"self",
".",
"UserID",
"=",
"''"
] |
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/ctp/stock/ApiStruct.py#L2622-L2624
|
||||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
|
cb692f527e4e819b6c228187c5702d990a180043
|
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/mailbox.py
|
python
|
_mboxMMDF.get_file
|
(self, key, from_=False)
|
return _PartialFile(self._file, self._file.tell(), stop)
|
Return a file-like representation or raise a KeyError.
|
Return a file-like representation or raise a KeyError.
|
[
"Return",
"a",
"file",
"-",
"like",
"representation",
"or",
"raise",
"a",
"KeyError",
"."
] |
def get_file(self, key, from_=False):
"""Return a file-like representation or raise a KeyError."""
start, stop = self._lookup(key)
self._file.seek(start)
if not from_:
self._file.readline()
return _PartialFile(self._file, self._file.tell(), stop)
|
[
"def",
"get_file",
"(",
"self",
",",
"key",
",",
"from_",
"=",
"False",
")",
":",
"start",
",",
"stop",
"=",
"self",
".",
"_lookup",
"(",
"key",
")",
"self",
".",
"_file",
".",
"seek",
"(",
"start",
")",
"if",
"not",
"from_",
":",
"self",
".",
"_file",
".",
"readline",
"(",
")",
"return",
"_PartialFile",
"(",
"self",
".",
"_file",
",",
"self",
".",
"_file",
".",
"tell",
"(",
")",
",",
"stop",
")"
] |
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/mailbox.py#L746-L752
|
|
amimo/dcc
|
114326ab5a082a42c7728a375726489e4709ca29
|
androguard/core/bytecodes/dvm.py
|
python
|
TypeItem.get_type_idx
|
(self)
|
return self.type_idx
|
Return the index into the type_ids list
:rtype: int
|
Return the index into the type_ids list
|
[
"Return",
"the",
"index",
"into",
"the",
"type_ids",
"list"
] |
def get_type_idx(self):
"""
Return the index into the type_ids list
:rtype: int
"""
return self.type_idx
|
[
"def",
"get_type_idx",
"(",
"self",
")",
":",
"return",
"self",
".",
"type_idx"
] |
https://github.com/amimo/dcc/blob/114326ab5a082a42c7728a375726489e4709ca29/androguard/core/bytecodes/dvm.py#L1098-L1104
|
|
phonopy/phonopy
|
816586d0ba8177482ecf40e52f20cbdee2260d51
|
phonopy/structure/tetrahedron_method.py
|
python
|
TetrahedronMethod._J_32
|
(self)
|
return (
(1.0 - self._f(0, 3) * self._f(1, 3) * self._f(2, 3) ** 2) / 4 / self._n_3()
)
|
[] |
def _J_32(self):
return (
(1.0 - self._f(0, 3) * self._f(1, 3) * self._f(2, 3) ** 2) / 4 / self._n_3()
)
|
[
"def",
"_J_32",
"(",
"self",
")",
":",
"return",
"(",
"(",
"1.0",
"-",
"self",
".",
"_f",
"(",
"0",
",",
"3",
")",
"*",
"self",
".",
"_f",
"(",
"1",
",",
"3",
")",
"*",
"self",
".",
"_f",
"(",
"2",
",",
"3",
")",
"**",
"2",
")",
"/",
"4",
"/",
"self",
".",
"_n_3",
"(",
")",
")"
] |
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/structure/tetrahedron_method.py#L606-L609
|
|||
meiqua/6DPose
|
619be5790448b4cd13290cf7727b35f1265e69e0
|
pysixd/renderer.py
|
python
|
render
|
(model, im_size, K, R, t, clip_near=100, clip_far=2000,
texture=None, surf_color=None, bg_color=(0.0, 0.0, 0.0, 0.0),
ambient_weight=0.5, shading='flat', mode='rgb+depth')
|
[] |
def render(model, im_size, K, R, t, clip_near=100, clip_far=2000,
texture=None, surf_color=None, bg_color=(0.0, 0.0, 0.0, 0.0),
ambient_weight=0.5, shading='flat', mode='rgb+depth'):
# Process input data
#---------------------------------------------------------------------------
# Make sure vertices and faces are provided in the model
assert({'pts', 'faces'}.issubset(set(model.keys())))
# Set texture / color of vertices
if texture is not None:
if texture.max() > 1.0:
texture = texture.astype(np.float32) / 255.0
texture = np.flipud(texture)
texture_uv = model['texture_uv']
colors = np.zeros((model['pts'].shape[0], 3), np.float32)
else:
texture_uv = np.zeros((model['pts'].shape[0], 2), np.float32)
if not surf_color:
if 'colors' in model.keys():
assert(model['pts'].shape[0] == model['colors'].shape[0])
colors = model['colors']
if colors.max() > 1.0:
colors /= 255.0 # Color values are expected in range [0, 1]
else:
colors = np.ones((model['pts'].shape[0], 3), np.float32) * 0.5
else:
colors = np.tile(list(surf_color) + [1.0], [model['pts'].shape[0], 1])
# Set the vertex data
if mode == 'depth':
vertices_type = [('a_position', np.float32, 3),
('a_color', np.float32, colors.shape[1])]
vertices = np.array(list(zip(model['pts'], colors)), vertices_type)
else:
if shading == 'flat':
vertices_type = [('a_position', np.float32, 3),
('a_color', np.float32, colors.shape[1]),
('a_texcoord', np.float32, 2)]
vertices = np.array(list(zip(model['pts'], colors, texture_uv)),
vertices_type)
else: # shading == 'phong'
vertices_type = [('a_position', np.float32, 3),
('a_normal', np.float32, 3),
('a_color', np.float32, colors.shape[1]),
('a_texcoord', np.float32, 2)]
vertices = np.array(list(zip(model['pts'], model['normals'],
colors, texture_uv)), vertices_type)
# Rendering
#---------------------------------------------------------------------------
render_rgb = mode in ['rgb', 'rgb+depth']
render_depth = mode in ['depth', 'rgb+depth']
# Model matrix
mat_model = np.eye(4, dtype=np.float32) # From object space to world space
# View matrix (transforming also the coordinate system from OpenCV to
# OpenGL camera space)
mat_view = np.eye(4, dtype=np.float32) # From world space to eye space
mat_view[:3, :3], mat_view[:3, 3] = R, t.squeeze()
yz_flip = np.eye(4, dtype=np.float32)
yz_flip[1, 1], yz_flip[2, 2] = -1, -1
mat_view = yz_flip.dot(mat_view) # OpenCV to OpenGL camera system
mat_view = mat_view.T # OpenGL expects column-wise matrix format
# Projection matrix
mat_proj = _compute_calib_proj(K, 0, 0, im_size[0], im_size[1], clip_near, clip_far)
# Create buffers
vertex_buffer = vertices.view(gloo.VertexBuffer)
index_buffer = model['faces'].flatten().astype(np.uint32).view(gloo.IndexBuffer)
# Create window
# config = app.configuration.Configuration()
# Number of samples used around the current pixel for multisample
# anti-aliasing (max is 8)
# config.samples = 8
# config.profile = "core"
# window = app.Window(config=config, visible=False)
window = app.Window(visible=False)
global rgb, depth
rgb = None
depth = None
@window.event
def on_draw(dt):
window.clear()
shape = (im_size[1], im_size[0])
if render_rgb:
# Render color image
global rgb
rgb = draw_color(shape, vertex_buffer, index_buffer, texture, mat_model,
mat_view, mat_proj, ambient_weight, bg_color, shading)
if render_depth:
# Render depth image
global depth
depth = draw_depth(shape, vertex_buffer, index_buffer, mat_model,
mat_view, mat_proj)
app.run(framecount=0) # The on_draw function is called framecount+1 times
window.close()
# Set output
#---------------------------------------------------------------------------
if mode == 'rgb':
return rgb
elif mode == 'depth':
return depth
elif mode == 'rgb+depth':
return rgb, depth
else:
print('Error: Unknown rendering mode.')
exit(-1)
|
[
"def",
"render",
"(",
"model",
",",
"im_size",
",",
"K",
",",
"R",
",",
"t",
",",
"clip_near",
"=",
"100",
",",
"clip_far",
"=",
"2000",
",",
"texture",
"=",
"None",
",",
"surf_color",
"=",
"None",
",",
"bg_color",
"=",
"(",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
")",
",",
"ambient_weight",
"=",
"0.5",
",",
"shading",
"=",
"'flat'",
",",
"mode",
"=",
"'rgb+depth'",
")",
":",
"# Process input data",
"#---------------------------------------------------------------------------",
"# Make sure vertices and faces are provided in the model",
"assert",
"(",
"{",
"'pts'",
",",
"'faces'",
"}",
".",
"issubset",
"(",
"set",
"(",
"model",
".",
"keys",
"(",
")",
")",
")",
")",
"# Set texture / color of vertices",
"if",
"texture",
"is",
"not",
"None",
":",
"if",
"texture",
".",
"max",
"(",
")",
">",
"1.0",
":",
"texture",
"=",
"texture",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"/",
"255.0",
"texture",
"=",
"np",
".",
"flipud",
"(",
"texture",
")",
"texture_uv",
"=",
"model",
"[",
"'texture_uv'",
"]",
"colors",
"=",
"np",
".",
"zeros",
"(",
"(",
"model",
"[",
"'pts'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"3",
")",
",",
"np",
".",
"float32",
")",
"else",
":",
"texture_uv",
"=",
"np",
".",
"zeros",
"(",
"(",
"model",
"[",
"'pts'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"2",
")",
",",
"np",
".",
"float32",
")",
"if",
"not",
"surf_color",
":",
"if",
"'colors'",
"in",
"model",
".",
"keys",
"(",
")",
":",
"assert",
"(",
"model",
"[",
"'pts'",
"]",
".",
"shape",
"[",
"0",
"]",
"==",
"model",
"[",
"'colors'",
"]",
".",
"shape",
"[",
"0",
"]",
")",
"colors",
"=",
"model",
"[",
"'colors'",
"]",
"if",
"colors",
".",
"max",
"(",
")",
">",
"1.0",
":",
"colors",
"/=",
"255.0",
"# Color values are expected in range [0, 1]",
"else",
":",
"colors",
"=",
"np",
".",
"ones",
"(",
"(",
"model",
"[",
"'pts'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"3",
")",
",",
"np",
".",
"float32",
")",
"*",
"0.5",
"else",
":",
"colors",
"=",
"np",
".",
"tile",
"(",
"list",
"(",
"surf_color",
")",
"+",
"[",
"1.0",
"]",
",",
"[",
"model",
"[",
"'pts'",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"1",
"]",
")",
"# Set the vertex data",
"if",
"mode",
"==",
"'depth'",
":",
"vertices_type",
"=",
"[",
"(",
"'a_position'",
",",
"np",
".",
"float32",
",",
"3",
")",
",",
"(",
"'a_color'",
",",
"np",
".",
"float32",
",",
"colors",
".",
"shape",
"[",
"1",
"]",
")",
"]",
"vertices",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"zip",
"(",
"model",
"[",
"'pts'",
"]",
",",
"colors",
")",
")",
",",
"vertices_type",
")",
"else",
":",
"if",
"shading",
"==",
"'flat'",
":",
"vertices_type",
"=",
"[",
"(",
"'a_position'",
",",
"np",
".",
"float32",
",",
"3",
")",
",",
"(",
"'a_color'",
",",
"np",
".",
"float32",
",",
"colors",
".",
"shape",
"[",
"1",
"]",
")",
",",
"(",
"'a_texcoord'",
",",
"np",
".",
"float32",
",",
"2",
")",
"]",
"vertices",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"zip",
"(",
"model",
"[",
"'pts'",
"]",
",",
"colors",
",",
"texture_uv",
")",
")",
",",
"vertices_type",
")",
"else",
":",
"# shading == 'phong'",
"vertices_type",
"=",
"[",
"(",
"'a_position'",
",",
"np",
".",
"float32",
",",
"3",
")",
",",
"(",
"'a_normal'",
",",
"np",
".",
"float32",
",",
"3",
")",
",",
"(",
"'a_color'",
",",
"np",
".",
"float32",
",",
"colors",
".",
"shape",
"[",
"1",
"]",
")",
",",
"(",
"'a_texcoord'",
",",
"np",
".",
"float32",
",",
"2",
")",
"]",
"vertices",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"zip",
"(",
"model",
"[",
"'pts'",
"]",
",",
"model",
"[",
"'normals'",
"]",
",",
"colors",
",",
"texture_uv",
")",
")",
",",
"vertices_type",
")",
"# Rendering",
"#---------------------------------------------------------------------------",
"render_rgb",
"=",
"mode",
"in",
"[",
"'rgb'",
",",
"'rgb+depth'",
"]",
"render_depth",
"=",
"mode",
"in",
"[",
"'depth'",
",",
"'rgb+depth'",
"]",
"# Model matrix",
"mat_model",
"=",
"np",
".",
"eye",
"(",
"4",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# From object space to world space",
"# View matrix (transforming also the coordinate system from OpenCV to",
"# OpenGL camera space)",
"mat_view",
"=",
"np",
".",
"eye",
"(",
"4",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# From world space to eye space",
"mat_view",
"[",
":",
"3",
",",
":",
"3",
"]",
",",
"mat_view",
"[",
":",
"3",
",",
"3",
"]",
"=",
"R",
",",
"t",
".",
"squeeze",
"(",
")",
"yz_flip",
"=",
"np",
".",
"eye",
"(",
"4",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"yz_flip",
"[",
"1",
",",
"1",
"]",
",",
"yz_flip",
"[",
"2",
",",
"2",
"]",
"=",
"-",
"1",
",",
"-",
"1",
"mat_view",
"=",
"yz_flip",
".",
"dot",
"(",
"mat_view",
")",
"# OpenCV to OpenGL camera system",
"mat_view",
"=",
"mat_view",
".",
"T",
"# OpenGL expects column-wise matrix format",
"# Projection matrix",
"mat_proj",
"=",
"_compute_calib_proj",
"(",
"K",
",",
"0",
",",
"0",
",",
"im_size",
"[",
"0",
"]",
",",
"im_size",
"[",
"1",
"]",
",",
"clip_near",
",",
"clip_far",
")",
"# Create buffers",
"vertex_buffer",
"=",
"vertices",
".",
"view",
"(",
"gloo",
".",
"VertexBuffer",
")",
"index_buffer",
"=",
"model",
"[",
"'faces'",
"]",
".",
"flatten",
"(",
")",
".",
"astype",
"(",
"np",
".",
"uint32",
")",
".",
"view",
"(",
"gloo",
".",
"IndexBuffer",
")",
"# Create window",
"# config = app.configuration.Configuration()",
"# Number of samples used around the current pixel for multisample",
"# anti-aliasing (max is 8)",
"# config.samples = 8",
"# config.profile = \"core\"",
"# window = app.Window(config=config, visible=False)",
"window",
"=",
"app",
".",
"Window",
"(",
"visible",
"=",
"False",
")",
"global",
"rgb",
",",
"depth",
"rgb",
"=",
"None",
"depth",
"=",
"None",
"@",
"window",
".",
"event",
"def",
"on_draw",
"(",
"dt",
")",
":",
"window",
".",
"clear",
"(",
")",
"shape",
"=",
"(",
"im_size",
"[",
"1",
"]",
",",
"im_size",
"[",
"0",
"]",
")",
"if",
"render_rgb",
":",
"# Render color image",
"global",
"rgb",
"rgb",
"=",
"draw_color",
"(",
"shape",
",",
"vertex_buffer",
",",
"index_buffer",
",",
"texture",
",",
"mat_model",
",",
"mat_view",
",",
"mat_proj",
",",
"ambient_weight",
",",
"bg_color",
",",
"shading",
")",
"if",
"render_depth",
":",
"# Render depth image",
"global",
"depth",
"depth",
"=",
"draw_depth",
"(",
"shape",
",",
"vertex_buffer",
",",
"index_buffer",
",",
"mat_model",
",",
"mat_view",
",",
"mat_proj",
")",
"app",
".",
"run",
"(",
"framecount",
"=",
"0",
")",
"# The on_draw function is called framecount+1 times",
"window",
".",
"close",
"(",
")",
"# Set output",
"#---------------------------------------------------------------------------",
"if",
"mode",
"==",
"'rgb'",
":",
"return",
"rgb",
"elif",
"mode",
"==",
"'depth'",
":",
"return",
"depth",
"elif",
"mode",
"==",
"'rgb+depth'",
":",
"return",
"rgb",
",",
"depth",
"else",
":",
"print",
"(",
"'Error: Unknown rendering mode.'",
")",
"exit",
"(",
"-",
"1",
")"
] |
https://github.com/meiqua/6DPose/blob/619be5790448b4cd13290cf7727b35f1265e69e0/pysixd/renderer.py#L306-L420
|
||||
Chaffelson/nipyapi
|
d3b186fd701ce308c2812746d98af9120955e810
|
nipyapi/nifi/models/remote_process_group_dto.py
|
python
|
RemoteProcessGroupDTO.authorization_issues
|
(self, authorization_issues)
|
Sets the authorization_issues of this RemoteProcessGroupDTO.
Any remote authorization issues for the remote process group.
:param authorization_issues: The authorization_issues of this RemoteProcessGroupDTO.
:type: list[str]
|
Sets the authorization_issues of this RemoteProcessGroupDTO.
Any remote authorization issues for the remote process group.
|
[
"Sets",
"the",
"authorization_issues",
"of",
"this",
"RemoteProcessGroupDTO",
".",
"Any",
"remote",
"authorization",
"issues",
"for",
"the",
"remote",
"process",
"group",
"."
] |
def authorization_issues(self, authorization_issues):
"""
Sets the authorization_issues of this RemoteProcessGroupDTO.
Any remote authorization issues for the remote process group.
:param authorization_issues: The authorization_issues of this RemoteProcessGroupDTO.
:type: list[str]
"""
self._authorization_issues = authorization_issues
|
[
"def",
"authorization_issues",
"(",
"self",
",",
"authorization_issues",
")",
":",
"self",
".",
"_authorization_issues",
"=",
"authorization_issues"
] |
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/remote_process_group_dto.py#L579-L588
|
||
freewym/espresso
|
6671c507350295269e38add57dbe601dcb8e6ecf
|
fairseq/modules/rotary_positional_embedding.py
|
python
|
RotaryPositionalEmbedding.__init__
|
(self, dim, base=10000, precision=torch.half)
|
Rotary positional embedding
Reference : https://blog.eleuther.ai/rotary-embeddings/
Paper: https://arxiv.org/pdf/2104.09864.pdf
Args:
dim: Dimension of embedding
base: Base value for exponential
precision: precision to use for numerical values
|
Rotary positional embedding
Reference : https://blog.eleuther.ai/rotary-embeddings/
Paper: https://arxiv.org/pdf/2104.09864.pdf
Args:
dim: Dimension of embedding
base: Base value for exponential
precision: precision to use for numerical values
|
[
"Rotary",
"positional",
"embedding",
"Reference",
":",
"https",
":",
"//",
"blog",
".",
"eleuther",
".",
"ai",
"/",
"rotary",
"-",
"embeddings",
"/",
"Paper",
":",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"2104",
".",
"09864",
".",
"pdf",
"Args",
":",
"dim",
":",
"Dimension",
"of",
"embedding",
"base",
":",
"Base",
"value",
"for",
"exponential",
"precision",
":",
"precision",
"to",
"use",
"for",
"numerical",
"values"
] |
def __init__(self, dim, base=10000, precision=torch.half):
"""Rotary positional embedding
Reference : https://blog.eleuther.ai/rotary-embeddings/
Paper: https://arxiv.org/pdf/2104.09864.pdf
Args:
dim: Dimension of embedding
base: Base value for exponential
precision: precision to use for numerical values
"""
super().__init__()
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer("inv_freq", inv_freq)
self.seq_len_cached = None
self.cos_cached = None
self.sin_cached = None
self.precision = precision
|
[
"def",
"__init__",
"(",
"self",
",",
"dim",
",",
"base",
"=",
"10000",
",",
"precision",
"=",
"torch",
".",
"half",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"inv_freq",
"=",
"1.0",
"/",
"(",
"base",
"**",
"(",
"torch",
".",
"arange",
"(",
"0",
",",
"dim",
",",
"2",
")",
".",
"float",
"(",
")",
"/",
"dim",
")",
")",
"self",
".",
"register_buffer",
"(",
"\"inv_freq\"",
",",
"inv_freq",
")",
"self",
".",
"seq_len_cached",
"=",
"None",
"self",
".",
"cos_cached",
"=",
"None",
"self",
".",
"sin_cached",
"=",
"None",
"self",
".",
"precision",
"=",
"precision"
] |
https://github.com/freewym/espresso/blob/6671c507350295269e38add57dbe601dcb8e6ecf/fairseq/modules/rotary_positional_embedding.py#L5-L20
|
||
tobegit3hub/deep_image_model
|
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
|
java_predict_client/src/main/proto/tensorflow/python/ops/data_flow_ops.py
|
python
|
ConditionalAccumulatorBase.num_accumulated
|
(self, name=None)
|
return gen_data_flow_ops.accumulator_num_accumulated(
self._accumulator_ref, name=name)
|
Number of gradients that have currently been aggregated in accumulator.
Args:
name: Optional name for the operation.
Returns:
Number of accumulated gradients currently in accumulator.
|
Number of gradients that have currently been aggregated in accumulator.
|
[
"Number",
"of",
"gradients",
"that",
"have",
"currently",
"been",
"aggregated",
"in",
"accumulator",
"."
] |
def num_accumulated(self, name=None):
"""Number of gradients that have currently been aggregated in accumulator.
Args:
name: Optional name for the operation.
Returns:
Number of accumulated gradients currently in accumulator.
"""
if name is None:
name = "%s_NumAccumulated" % self._name
return gen_data_flow_ops.accumulator_num_accumulated(
self._accumulator_ref, name=name)
|
[
"def",
"num_accumulated",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"\"%s_NumAccumulated\"",
"%",
"self",
".",
"_name",
"return",
"gen_data_flow_ops",
".",
"accumulator_num_accumulated",
"(",
"self",
".",
"_accumulator_ref",
",",
"name",
"=",
"name",
")"
] |
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/python/ops/data_flow_ops.py#L1195-L1207
|
|
ambakick/Person-Detection-and-Tracking
|
f925394ac29b5cf321f1ce89a71b193381519a0b
|
core/preprocessor.py
|
python
|
random_jitter_boxes
|
(boxes, ratio=0.05, seed=None)
|
Randomly jitter boxes in image.
Args:
boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
Each row is in the form of [ymin, xmin, ymax, xmax].
ratio: The ratio of the box width and height that the corners can jitter.
For example if the width is 100 pixels and ratio is 0.05,
the corners can jitter up to 5 pixels in the x direction.
seed: random seed.
Returns:
boxes: boxes which is the same shape as input boxes.
|
Randomly jitter boxes in image.
|
[
"Randomly",
"jitter",
"boxes",
"in",
"image",
"."
] |
def random_jitter_boxes(boxes, ratio=0.05, seed=None):
"""Randomly jitter boxes in image.
Args:
boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
Each row is in the form of [ymin, xmin, ymax, xmax].
ratio: The ratio of the box width and height that the corners can jitter.
For example if the width is 100 pixels and ratio is 0.05,
the corners can jitter up to 5 pixels in the x direction.
seed: random seed.
Returns:
boxes: boxes which is the same shape as input boxes.
"""
def random_jitter_box(box, ratio, seed):
"""Randomly jitter box.
Args:
box: bounding box [1, 1, 4].
ratio: max ratio between jittered box and original box,
a number between [0, 0.5].
seed: random seed.
Returns:
jittered_box: jittered box.
"""
rand_numbers = tf.random_uniform(
[1, 1, 4], minval=-ratio, maxval=ratio, dtype=tf.float32, seed=seed)
box_width = tf.subtract(box[0, 0, 3], box[0, 0, 1])
box_height = tf.subtract(box[0, 0, 2], box[0, 0, 0])
hw_coefs = tf.stack([box_height, box_width, box_height, box_width])
hw_rand_coefs = tf.multiply(hw_coefs, rand_numbers)
jittered_box = tf.add(box, hw_rand_coefs)
jittered_box = tf.clip_by_value(jittered_box, 0.0, 1.0)
return jittered_box
with tf.name_scope('RandomJitterBoxes', values=[boxes]):
# boxes are [N, 4]. Lets first make them [N, 1, 1, 4]
boxes_shape = tf.shape(boxes)
boxes = tf.expand_dims(boxes, 1)
boxes = tf.expand_dims(boxes, 2)
distorted_boxes = tf.map_fn(
lambda x: random_jitter_box(x, ratio, seed), boxes, dtype=tf.float32)
distorted_boxes = tf.reshape(distorted_boxes, boxes_shape)
return distorted_boxes
|
[
"def",
"random_jitter_boxes",
"(",
"boxes",
",",
"ratio",
"=",
"0.05",
",",
"seed",
"=",
"None",
")",
":",
"def",
"random_jitter_box",
"(",
"box",
",",
"ratio",
",",
"seed",
")",
":",
"\"\"\"Randomly jitter box.\n\n Args:\n box: bounding box [1, 1, 4].\n ratio: max ratio between jittered box and original box,\n a number between [0, 0.5].\n seed: random seed.\n\n Returns:\n jittered_box: jittered box.\n \"\"\"",
"rand_numbers",
"=",
"tf",
".",
"random_uniform",
"(",
"[",
"1",
",",
"1",
",",
"4",
"]",
",",
"minval",
"=",
"-",
"ratio",
",",
"maxval",
"=",
"ratio",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"seed",
"=",
"seed",
")",
"box_width",
"=",
"tf",
".",
"subtract",
"(",
"box",
"[",
"0",
",",
"0",
",",
"3",
"]",
",",
"box",
"[",
"0",
",",
"0",
",",
"1",
"]",
")",
"box_height",
"=",
"tf",
".",
"subtract",
"(",
"box",
"[",
"0",
",",
"0",
",",
"2",
"]",
",",
"box",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
"hw_coefs",
"=",
"tf",
".",
"stack",
"(",
"[",
"box_height",
",",
"box_width",
",",
"box_height",
",",
"box_width",
"]",
")",
"hw_rand_coefs",
"=",
"tf",
".",
"multiply",
"(",
"hw_coefs",
",",
"rand_numbers",
")",
"jittered_box",
"=",
"tf",
".",
"add",
"(",
"box",
",",
"hw_rand_coefs",
")",
"jittered_box",
"=",
"tf",
".",
"clip_by_value",
"(",
"jittered_box",
",",
"0.0",
",",
"1.0",
")",
"return",
"jittered_box",
"with",
"tf",
".",
"name_scope",
"(",
"'RandomJitterBoxes'",
",",
"values",
"=",
"[",
"boxes",
"]",
")",
":",
"# boxes are [N, 4]. Lets first make them [N, 1, 1, 4]",
"boxes_shape",
"=",
"tf",
".",
"shape",
"(",
"boxes",
")",
"boxes",
"=",
"tf",
".",
"expand_dims",
"(",
"boxes",
",",
"1",
")",
"boxes",
"=",
"tf",
".",
"expand_dims",
"(",
"boxes",
",",
"2",
")",
"distorted_boxes",
"=",
"tf",
".",
"map_fn",
"(",
"lambda",
"x",
":",
"random_jitter_box",
"(",
"x",
",",
"ratio",
",",
"seed",
")",
",",
"boxes",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"distorted_boxes",
"=",
"tf",
".",
"reshape",
"(",
"distorted_boxes",
",",
"boxes_shape",
")",
"return",
"distorted_boxes"
] |
https://github.com/ambakick/Person-Detection-and-Tracking/blob/f925394ac29b5cf321f1ce89a71b193381519a0b/core/preprocessor.py#L1054-L1103
|
||
openstack/swift
|
b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100
|
swift/common/constraints.py
|
python
|
valid_api_version
|
(version)
|
return version in VALID_API_VERSIONS
|
Checks if the requested version is valid.
Currently Swift only supports "v1" and "v1.0".
|
Checks if the requested version is valid.
|
[
"Checks",
"if",
"the",
"requested",
"version",
"is",
"valid",
"."
] |
def valid_api_version(version):
"""
Checks if the requested version is valid.
Currently Swift only supports "v1" and "v1.0".
"""
global VALID_API_VERSIONS
if not isinstance(VALID_API_VERSIONS, list):
VALID_API_VERSIONS = [str(VALID_API_VERSIONS)]
return version in VALID_API_VERSIONS
|
[
"def",
"valid_api_version",
"(",
"version",
")",
":",
"global",
"VALID_API_VERSIONS",
"if",
"not",
"isinstance",
"(",
"VALID_API_VERSIONS",
",",
"list",
")",
":",
"VALID_API_VERSIONS",
"=",
"[",
"str",
"(",
"VALID_API_VERSIONS",
")",
"]",
"return",
"version",
"in",
"VALID_API_VERSIONS"
] |
https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/common/constraints.py#L431-L440
|
|
ytdl-org/youtube-dl
|
5014bd67c22b421207b2650d4dc874b95b36dda1
|
youtube_dl/extractor/openload.py
|
python
|
PhantomJSwrapper.get
|
(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();')
|
return (html, encodeArgument(out))
|
Downloads webpage (if needed) and executes JS
Params:
url: website url
html: optional, html code of website
video_id: video id
note: optional, displayed when downloading webpage
note2: optional, displayed when executing JS
headers: custom http headers
jscode: code to be executed when page is loaded
Returns tuple with:
* downloaded website (after JS execution)
* anything you print with `console.log` (but not inside `page.execute`!)
In most cases you don't need to add any `jscode`.
It is executed in `page.onLoadFinished`.
`saveAndExit();` is mandatory, use it instead of `phantom.exit()`
It is possible to wait for some element on the webpage, for example:
var check = function() {
var elementFound = page.evaluate(function() {
return document.querySelector('#b.done') !== null;
});
if(elementFound)
saveAndExit();
else
window.setTimeout(check, 500);
}
page.evaluate(function(){
document.querySelector('#a').click();
});
check();
|
Downloads webpage (if needed) and executes JS
|
[
"Downloads",
"webpage",
"(",
"if",
"needed",
")",
"and",
"executes",
"JS"
] |
def get(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();'):
"""
Downloads webpage (if needed) and executes JS
Params:
url: website url
html: optional, html code of website
video_id: video id
note: optional, displayed when downloading webpage
note2: optional, displayed when executing JS
headers: custom http headers
jscode: code to be executed when page is loaded
Returns tuple with:
* downloaded website (after JS execution)
* anything you print with `console.log` (but not inside `page.execute`!)
In most cases you don't need to add any `jscode`.
It is executed in `page.onLoadFinished`.
`saveAndExit();` is mandatory, use it instead of `phantom.exit()`
It is possible to wait for some element on the webpage, for example:
var check = function() {
var elementFound = page.evaluate(function() {
return document.querySelector('#b.done') !== null;
});
if(elementFound)
saveAndExit();
else
window.setTimeout(check, 500);
}
page.evaluate(function(){
document.querySelector('#a').click();
});
check();
"""
if 'saveAndExit();' not in jscode:
raise ExtractorError('`saveAndExit();` not found in `jscode`')
if not html:
html = self.extractor._download_webpage(url, video_id, note=note, headers=headers)
with open(self._TMP_FILES['html'].name, 'wb') as f:
f.write(html.encode('utf-8'))
self._save_cookies(url)
replaces = self.options
replaces['url'] = url
user_agent = headers.get('User-Agent') or std_headers['User-Agent']
replaces['ua'] = user_agent.replace('"', '\\"')
replaces['jscode'] = jscode
for x in self._TMP_FILE_NAMES:
replaces[x] = self._TMP_FILES[x].name.replace('\\', '\\\\').replace('"', '\\"')
with open(self._TMP_FILES['script'].name, 'wb') as f:
f.write(self._TEMPLATE.format(**replaces).encode('utf-8'))
if video_id is None:
self.extractor.to_screen('%s' % (note2,))
else:
self.extractor.to_screen('%s: %s' % (video_id, note2))
p = subprocess.Popen([
self.exe, '--ssl-protocol=any',
self._TMP_FILES['script'].name
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
raise ExtractorError(
'Executing JS failed\n:' + encodeArgument(err))
with open(self._TMP_FILES['html'].name, 'rb') as f:
html = f.read().decode('utf-8')
self._load_cookies()
return (html, encodeArgument(out))
|
[
"def",
"get",
"(",
"self",
",",
"url",
",",
"html",
"=",
"None",
",",
"video_id",
"=",
"None",
",",
"note",
"=",
"None",
",",
"note2",
"=",
"'Executing JS on webpage'",
",",
"headers",
"=",
"{",
"}",
",",
"jscode",
"=",
"'saveAndExit();'",
")",
":",
"if",
"'saveAndExit();'",
"not",
"in",
"jscode",
":",
"raise",
"ExtractorError",
"(",
"'`saveAndExit();` not found in `jscode`'",
")",
"if",
"not",
"html",
":",
"html",
"=",
"self",
".",
"extractor",
".",
"_download_webpage",
"(",
"url",
",",
"video_id",
",",
"note",
"=",
"note",
",",
"headers",
"=",
"headers",
")",
"with",
"open",
"(",
"self",
".",
"_TMP_FILES",
"[",
"'html'",
"]",
".",
"name",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"html",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"self",
".",
"_save_cookies",
"(",
"url",
")",
"replaces",
"=",
"self",
".",
"options",
"replaces",
"[",
"'url'",
"]",
"=",
"url",
"user_agent",
"=",
"headers",
".",
"get",
"(",
"'User-Agent'",
")",
"or",
"std_headers",
"[",
"'User-Agent'",
"]",
"replaces",
"[",
"'ua'",
"]",
"=",
"user_agent",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
"replaces",
"[",
"'jscode'",
"]",
"=",
"jscode",
"for",
"x",
"in",
"self",
".",
"_TMP_FILE_NAMES",
":",
"replaces",
"[",
"x",
"]",
"=",
"self",
".",
"_TMP_FILES",
"[",
"x",
"]",
".",
"name",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
"with",
"open",
"(",
"self",
".",
"_TMP_FILES",
"[",
"'script'",
"]",
".",
"name",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"_TEMPLATE",
".",
"format",
"(",
"*",
"*",
"replaces",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"video_id",
"is",
"None",
":",
"self",
".",
"extractor",
".",
"to_screen",
"(",
"'%s'",
"%",
"(",
"note2",
",",
")",
")",
"else",
":",
"self",
".",
"extractor",
".",
"to_screen",
"(",
"'%s: %s'",
"%",
"(",
"video_id",
",",
"note2",
")",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"self",
".",
"exe",
",",
"'--ssl-protocol=any'",
",",
"self",
".",
"_TMP_FILES",
"[",
"'script'",
"]",
".",
"name",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
"!=",
"0",
":",
"raise",
"ExtractorError",
"(",
"'Executing JS failed\\n:'",
"+",
"encodeArgument",
"(",
"err",
")",
")",
"with",
"open",
"(",
"self",
".",
"_TMP_FILES",
"[",
"'html'",
"]",
".",
"name",
",",
"'rb'",
")",
"as",
"f",
":",
"html",
"=",
"f",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"self",
".",
"_load_cookies",
"(",
")",
"return",
"(",
"html",
",",
"encodeArgument",
"(",
"out",
")",
")"
] |
https://github.com/ytdl-org/youtube-dl/blob/5014bd67c22b421207b2650d4dc874b95b36dda1/youtube_dl/extractor/openload.py#L163-L238
|
|
OpenMDAO/OpenMDAO-Framework
|
f2e37b7de3edeaaeb2d251b375917adec059db9b
|
openmdao.main/src/openmdao/main/systems.py
|
python
|
AssemblySystem.set_complex_step
|
(self, complex_step=False)
|
Toggles complex_step plumbing for this system and all
subsystems. Assemblies must prepare their inner system.
|
Toggles complex_step plumbing for this system and all
subsystems. Assemblies must prepare their inner system.
|
[
"Toggles",
"complex_step",
"plumbing",
"for",
"this",
"system",
"and",
"all",
"subsystems",
".",
"Assemblies",
"must",
"prepare",
"their",
"inner",
"system",
"."
] |
def set_complex_step(self, complex_step=False):
""" Toggles complex_step plumbing for this system and all
subsystems. Assemblies must prepare their inner system."""
self.complex_step = complex_step
self._comp._system.set_complex_step(complex_step)
|
[
"def",
"set_complex_step",
"(",
"self",
",",
"complex_step",
"=",
"False",
")",
":",
"self",
".",
"complex_step",
"=",
"complex_step",
"self",
".",
"_comp",
".",
"_system",
".",
"set_complex_step",
"(",
"complex_step",
")"
] |
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.main/src/openmdao/main/systems.py#L1557-L1562
|
||
WikidPad/WikidPad
|
558109638807bc76b4672922686e416ab2d5f79c
|
WikidPad/lib/pwiki/Exporters.py
|
python
|
MultiPageTextExporter.export
|
(self, wikiDocument, wordList, exportType, exportDest,
compatFilenames, addOpt, progressHandler)
|
Run export operation.
wikiDocument -- WikiDocument object
wordList -- Sequence of wiki words to export
exportType -- string tag to identify how to export
exportDest -- Path to destination directory or file to export to
compatFilenames -- Should the filenames be encoded to be lowest
level compatible
addOpt -- additional options returned by getAddOpt()
|
Run export operation.
wikiDocument -- WikiDocument object
wordList -- Sequence of wiki words to export
exportType -- string tag to identify how to export
exportDest -- Path to destination directory or file to export to
compatFilenames -- Should the filenames be encoded to be lowest
level compatible
addOpt -- additional options returned by getAddOpt()
|
[
"Run",
"export",
"operation",
".",
"wikiDocument",
"--",
"WikiDocument",
"object",
"wordList",
"--",
"Sequence",
"of",
"wiki",
"words",
"to",
"export",
"exportType",
"--",
"string",
"tag",
"to",
"identify",
"how",
"to",
"export",
"exportDest",
"--",
"Path",
"to",
"destination",
"directory",
"or",
"file",
"to",
"export",
"to",
"compatFilenames",
"--",
"Should",
"the",
"filenames",
"be",
"encoded",
"to",
"be",
"lowest",
"level",
"compatible",
"addOpt",
"--",
"additional",
"options",
"returned",
"by",
"getAddOpt",
"()"
] |
def export(self, wikiDocument, wordList, exportType, exportDest,
compatFilenames, addOpt, progressHandler):
"""
Run export operation.
wikiDocument -- WikiDocument object
wordList -- Sequence of wiki words to export
exportType -- string tag to identify how to export
exportDest -- Path to destination directory or file to export to
compatFilenames -- Should the filenames be encoded to be lowest
level compatible
addOpt -- additional options returned by getAddOpt()
"""
self.wikiDocument = wikiDocument
self.wordList = wordList
self.exportDest = exportDest
self.addOpt = addOpt
self.exportFile = None
self.rawExportFile = None
self.firstSeparatorCallDone = False
self.formatVer = min(addOpt[0], 1)
self.writeWikiFuncPages = addOpt[1] and (self.formatVer > 0)
self.writeSavedSearches = addOpt[2] and (self.formatVer > 0)
self.writeVersionData = addOpt[3] and (self.formatVer > 0)
try:
for tryNumber in range(35):
self.separator = "-----%s-----" % createRandomString(25)
try:
self.rawExportFile = open(pathEnc(self.exportDest), "wb")
# Only UTF-8 mode currently
self.rawExportFile.write(BOM_UTF8)
self.exportFile = _SeparatorWatchUtf8Writer(
self.rawExportFile, self.separator, "replace")
self.wikiPageWriter = MultiPageTextWikiPageWriter(
self.wikiDocument, self.exportFile,
self.writeVersionData, self.formatVer)
# Identifier line with file format
self.exportFile.write("Multipage text format %i\n" %
self.formatVer)
# Separator line
self.exportFile.write("Separator: %s\n" % self.separator)
# Write wiki-bound functional pages
if self.writeWikiFuncPages:
# Only wiki related functional pages
wikiFuncTags = [ft for ft in DocPages.getFuncTags()
if ft.startswith("wiki/")]
for ft in wikiFuncTags:
self.exportFile.writeSeparator()
self.exportFile.write("funcpage/%s\n" % ft)
page = self.wikiDocument.getFuncPage(ft)
self.exportFile.write(page.getLiveText())
# Write saved searches
if self.writeSavedSearches:
# Wiki-wide searches
wikiData = self.wikiDocument.getWikiData()
unifNames = wikiData.getDataBlockUnifNamesStartingWith(
"savedsearch/")
for un in unifNames:
self.exportFile.writeSeparator()
self.exportFile.write(un + "\n")
datablock = wikiData.retrieveDataBlock(un)
self.exportFile.write(base64BlockEncode(datablock))
# Page searches
unifNames = wikiData.getDataBlockUnifNamesStartingWith(
"savedpagesearch/")
for un in unifNames:
self.exportFile.writeSeparator()
self._writeHintedDatablock(un, False)
# locale.setlocale(locale.LC_ALL, '')
#
# wx.Locale(wx.LANGUAGE_DEFAULT)
Localization.setLocale("")
# Write actual wiki words
for word in self.wordList:
self.wikiPageWriter.exportWikiWord(word)
self.exportFile.checkAndClearBuffer()
break
except _SeparatorFoundException:
if self.exportFile is not None:
self.exportFile.flush()
self.exportFile = None
if self.rawExportFile is not None:
self.rawExportFile.close()
self.rawExportFile = None
continue
except Exception as e:
traceback.print_exc()
raise ExportException(str(e))
else:
raise ExportException(_("No usable separator found"))
finally:
if self.exportFile is not None:
self.exportFile.flush()
self.exportFile = None
if self.rawExportFile is not None:
self.rawExportFile.close()
self.rawExportFile = None
|
[
"def",
"export",
"(",
"self",
",",
"wikiDocument",
",",
"wordList",
",",
"exportType",
",",
"exportDest",
",",
"compatFilenames",
",",
"addOpt",
",",
"progressHandler",
")",
":",
"self",
".",
"wikiDocument",
"=",
"wikiDocument",
"self",
".",
"wordList",
"=",
"wordList",
"self",
".",
"exportDest",
"=",
"exportDest",
"self",
".",
"addOpt",
"=",
"addOpt",
"self",
".",
"exportFile",
"=",
"None",
"self",
".",
"rawExportFile",
"=",
"None",
"self",
".",
"firstSeparatorCallDone",
"=",
"False",
"self",
".",
"formatVer",
"=",
"min",
"(",
"addOpt",
"[",
"0",
"]",
",",
"1",
")",
"self",
".",
"writeWikiFuncPages",
"=",
"addOpt",
"[",
"1",
"]",
"and",
"(",
"self",
".",
"formatVer",
">",
"0",
")",
"self",
".",
"writeSavedSearches",
"=",
"addOpt",
"[",
"2",
"]",
"and",
"(",
"self",
".",
"formatVer",
">",
"0",
")",
"self",
".",
"writeVersionData",
"=",
"addOpt",
"[",
"3",
"]",
"and",
"(",
"self",
".",
"formatVer",
">",
"0",
")",
"try",
":",
"for",
"tryNumber",
"in",
"range",
"(",
"35",
")",
":",
"self",
".",
"separator",
"=",
"\"-----%s-----\"",
"%",
"createRandomString",
"(",
"25",
")",
"try",
":",
"self",
".",
"rawExportFile",
"=",
"open",
"(",
"pathEnc",
"(",
"self",
".",
"exportDest",
")",
",",
"\"wb\"",
")",
"# Only UTF-8 mode currently",
"self",
".",
"rawExportFile",
".",
"write",
"(",
"BOM_UTF8",
")",
"self",
".",
"exportFile",
"=",
"_SeparatorWatchUtf8Writer",
"(",
"self",
".",
"rawExportFile",
",",
"self",
".",
"separator",
",",
"\"replace\"",
")",
"self",
".",
"wikiPageWriter",
"=",
"MultiPageTextWikiPageWriter",
"(",
"self",
".",
"wikiDocument",
",",
"self",
".",
"exportFile",
",",
"self",
".",
"writeVersionData",
",",
"self",
".",
"formatVer",
")",
"# Identifier line with file format",
"self",
".",
"exportFile",
".",
"write",
"(",
"\"Multipage text format %i\\n\"",
"%",
"self",
".",
"formatVer",
")",
"# Separator line",
"self",
".",
"exportFile",
".",
"write",
"(",
"\"Separator: %s\\n\"",
"%",
"self",
".",
"separator",
")",
"# Write wiki-bound functional pages",
"if",
"self",
".",
"writeWikiFuncPages",
":",
"# Only wiki related functional pages",
"wikiFuncTags",
"=",
"[",
"ft",
"for",
"ft",
"in",
"DocPages",
".",
"getFuncTags",
"(",
")",
"if",
"ft",
".",
"startswith",
"(",
"\"wiki/\"",
")",
"]",
"for",
"ft",
"in",
"wikiFuncTags",
":",
"self",
".",
"exportFile",
".",
"writeSeparator",
"(",
")",
"self",
".",
"exportFile",
".",
"write",
"(",
"\"funcpage/%s\\n\"",
"%",
"ft",
")",
"page",
"=",
"self",
".",
"wikiDocument",
".",
"getFuncPage",
"(",
"ft",
")",
"self",
".",
"exportFile",
".",
"write",
"(",
"page",
".",
"getLiveText",
"(",
")",
")",
"# Write saved searches",
"if",
"self",
".",
"writeSavedSearches",
":",
"# Wiki-wide searches",
"wikiData",
"=",
"self",
".",
"wikiDocument",
".",
"getWikiData",
"(",
")",
"unifNames",
"=",
"wikiData",
".",
"getDataBlockUnifNamesStartingWith",
"(",
"\"savedsearch/\"",
")",
"for",
"un",
"in",
"unifNames",
":",
"self",
".",
"exportFile",
".",
"writeSeparator",
"(",
")",
"self",
".",
"exportFile",
".",
"write",
"(",
"un",
"+",
"\"\\n\"",
")",
"datablock",
"=",
"wikiData",
".",
"retrieveDataBlock",
"(",
"un",
")",
"self",
".",
"exportFile",
".",
"write",
"(",
"base64BlockEncode",
"(",
"datablock",
")",
")",
"# Page searches",
"unifNames",
"=",
"wikiData",
".",
"getDataBlockUnifNamesStartingWith",
"(",
"\"savedpagesearch/\"",
")",
"for",
"un",
"in",
"unifNames",
":",
"self",
".",
"exportFile",
".",
"writeSeparator",
"(",
")",
"self",
".",
"_writeHintedDatablock",
"(",
"un",
",",
"False",
")",
"# locale.setlocale(locale.LC_ALL, '')",
"# ",
"# wx.Locale(wx.LANGUAGE_DEFAULT)",
"Localization",
".",
"setLocale",
"(",
"\"\"",
")",
"# Write actual wiki words",
"for",
"word",
"in",
"self",
".",
"wordList",
":",
"self",
".",
"wikiPageWriter",
".",
"exportWikiWord",
"(",
"word",
")",
"self",
".",
"exportFile",
".",
"checkAndClearBuffer",
"(",
")",
"break",
"except",
"_SeparatorFoundException",
":",
"if",
"self",
".",
"exportFile",
"is",
"not",
"None",
":",
"self",
".",
"exportFile",
".",
"flush",
"(",
")",
"self",
".",
"exportFile",
"=",
"None",
"if",
"self",
".",
"rawExportFile",
"is",
"not",
"None",
":",
"self",
".",
"rawExportFile",
".",
"close",
"(",
")",
"self",
".",
"rawExportFile",
"=",
"None",
"continue",
"except",
"Exception",
"as",
"e",
":",
"traceback",
".",
"print_exc",
"(",
")",
"raise",
"ExportException",
"(",
"str",
"(",
"e",
")",
")",
"else",
":",
"raise",
"ExportException",
"(",
"_",
"(",
"\"No usable separator found\"",
")",
")",
"finally",
":",
"if",
"self",
".",
"exportFile",
"is",
"not",
"None",
":",
"self",
".",
"exportFile",
".",
"flush",
"(",
")",
"self",
".",
"exportFile",
"=",
"None",
"if",
"self",
".",
"rawExportFile",
"is",
"not",
"None",
":",
"self",
".",
"rawExportFile",
".",
"close",
"(",
")",
"self",
".",
"rawExportFile",
"=",
"None"
] |
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/Exporters.py#L762-L878
|
||
PyMVPA/PyMVPA
|
76c476b3de8264b0bb849bf226da5674d659564e
|
mvpa2/misc/fsl/base.py
|
python
|
FslEV3.to_events
|
(self, **kwargs)
|
return \
[Event(onset=self['onsets'][i],
duration=self['durations'][i],
features=[self['intensities'][i]],
**kwargs)
for i in xrange(self.nevs)]
|
Convert into a list of `Event` instances.
Parameters
----------
kwargs
Any keyword arugment provided would be replicated, through all
the entries. Useful to specify label or even a chunk
|
Convert into a list of `Event` instances.
|
[
"Convert",
"into",
"a",
"list",
"of",
"Event",
"instances",
"."
] |
def to_events(self, **kwargs):
"""Convert into a list of `Event` instances.
Parameters
----------
kwargs
Any keyword arugment provided would be replicated, through all
the entries. Useful to specify label or even a chunk
"""
return \
[Event(onset=self['onsets'][i],
duration=self['durations'][i],
features=[self['intensities'][i]],
**kwargs)
for i in xrange(self.nevs)]
|
[
"def",
"to_events",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"Event",
"(",
"onset",
"=",
"self",
"[",
"'onsets'",
"]",
"[",
"i",
"]",
",",
"duration",
"=",
"self",
"[",
"'durations'",
"]",
"[",
"i",
"]",
",",
"features",
"=",
"[",
"self",
"[",
"'intensities'",
"]",
"[",
"i",
"]",
"]",
",",
"*",
"*",
"kwargs",
")",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"nevs",
")",
"]"
] |
https://github.com/PyMVPA/PyMVPA/blob/76c476b3de8264b0bb849bf226da5674d659564e/mvpa2/misc/fsl/base.py#L70-L84
|
|
OpenCobolIDE/OpenCobolIDE
|
c78d0d335378e5fe0a5e74f53c19b68b55e85388
|
open_cobol_ide/extlibs/future/types/newint.py
|
python
|
newint.from_bytes
|
(cls, mybytes, byteorder='big', signed=False)
|
return cls(num)
|
Return the integer represented by the given array of bytes.
The mybytes argument must either support the buffer protocol or be an
iterable object producing bytes. Bytes and bytearray are examples of
built-in objects that support the buffer protocol.
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument indicates whether two's complement is
used to represent the integer.
|
Return the integer represented by the given array of bytes.
|
[
"Return",
"the",
"integer",
"represented",
"by",
"the",
"given",
"array",
"of",
"bytes",
"."
] |
def from_bytes(cls, mybytes, byteorder='big', signed=False):
"""
Return the integer represented by the given array of bytes.
The mybytes argument must either support the buffer protocol or be an
iterable object producing bytes. Bytes and bytearray are examples of
built-in objects that support the buffer protocol.
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument indicates whether two's complement is
used to represent the integer.
"""
if byteorder not in ('little', 'big'):
raise ValueError("byteorder must be either 'little' or 'big'")
if isinstance(mybytes, unicode):
raise TypeError("cannot convert unicode objects to bytes")
# mybytes can also be passed as a sequence of integers on Py3.
# Test for this:
elif isinstance(mybytes, collections.Iterable):
mybytes = newbytes(mybytes)
b = mybytes if byteorder == 'big' else mybytes[::-1]
if len(b) == 0:
b = b'\x00'
# The encode() method has been disabled by newbytes, but Py2's
# str has it:
num = int(native(b).encode('hex'), 16)
if signed and (b[0] & 0x80):
num = num - (2 ** (len(b)*8))
return cls(num)
|
[
"def",
"from_bytes",
"(",
"cls",
",",
"mybytes",
",",
"byteorder",
"=",
"'big'",
",",
"signed",
"=",
"False",
")",
":",
"if",
"byteorder",
"not",
"in",
"(",
"'little'",
",",
"'big'",
")",
":",
"raise",
"ValueError",
"(",
"\"byteorder must be either 'little' or 'big'\"",
")",
"if",
"isinstance",
"(",
"mybytes",
",",
"unicode",
")",
":",
"raise",
"TypeError",
"(",
"\"cannot convert unicode objects to bytes\"",
")",
"# mybytes can also be passed as a sequence of integers on Py3.",
"# Test for this:",
"elif",
"isinstance",
"(",
"mybytes",
",",
"collections",
".",
"Iterable",
")",
":",
"mybytes",
"=",
"newbytes",
"(",
"mybytes",
")",
"b",
"=",
"mybytes",
"if",
"byteorder",
"==",
"'big'",
"else",
"mybytes",
"[",
":",
":",
"-",
"1",
"]",
"if",
"len",
"(",
"b",
")",
"==",
"0",
":",
"b",
"=",
"b'\\x00'",
"# The encode() method has been disabled by newbytes, but Py2's",
"# str has it:",
"num",
"=",
"int",
"(",
"native",
"(",
"b",
")",
".",
"encode",
"(",
"'hex'",
")",
",",
"16",
")",
"if",
"signed",
"and",
"(",
"b",
"[",
"0",
"]",
"&",
"0x80",
")",
":",
"num",
"=",
"num",
"-",
"(",
"2",
"**",
"(",
"len",
"(",
"b",
")",
"*",
"8",
")",
")",
"return",
"cls",
"(",
"num",
")"
] |
https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/future/types/newint.py#L336-L369
|
|
home-assistant/core
|
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
|
homeassistant/components/kef/media_player.py
|
python
|
KefMediaPlayer.source_list
|
(self)
|
return self._sources
|
List of available input sources.
|
List of available input sources.
|
[
"List",
"of",
"available",
"input",
"sources",
"."
] |
def source_list(self):
"""List of available input sources."""
return self._sources
|
[
"def",
"source_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sources"
] |
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/kef/media_player.py#L311-L313
|
|
triaquae/triaquae
|
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
|
TriAquae/models/django/contrib/gis/maps/google/zoom.py
|
python
|
GoogleZoom.get_zoom
|
(self, geom)
|
return self._nzoom-1
|
Returns the optimal Zoom level for the given geometry.
|
Returns the optimal Zoom level for the given geometry.
|
[
"Returns",
"the",
"optimal",
"Zoom",
"level",
"for",
"the",
"given",
"geometry",
"."
] |
def get_zoom(self, geom):
"Returns the optimal Zoom level for the given geometry."
# Checking the input type.
if not isinstance(geom, GEOSGeometry) or geom.srid != 4326:
raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.')
# Getting the envelope for the geometry, and its associated width, height
# and centroid.
env = geom.envelope
env_w, env_h = self.get_width_height(env.extent)
center = env.centroid
for z in xrange(self._nzoom):
# Getting the tile at the zoom level.
tile_w, tile_h = self.get_width_height(self.tile(center, z).extent)
# When we span more than one tile, this is an approximately good
# zoom level.
if (env_w > tile_w) or (env_h > tile_h):
if z == 0:
raise GoogleMapException('Geometry width and height should not exceed that of the Earth.')
return z-1
# Otherwise, we've zoomed in to the max.
return self._nzoom-1
|
[
"def",
"get_zoom",
"(",
"self",
",",
"geom",
")",
":",
"# Checking the input type.",
"if",
"not",
"isinstance",
"(",
"geom",
",",
"GEOSGeometry",
")",
"or",
"geom",
".",
"srid",
"!=",
"4326",
":",
"raise",
"TypeError",
"(",
"'get_zoom() expects a GEOS Geometry with an SRID of 4326.'",
")",
"# Getting the envelope for the geometry, and its associated width, height",
"# and centroid.",
"env",
"=",
"geom",
".",
"envelope",
"env_w",
",",
"env_h",
"=",
"self",
".",
"get_width_height",
"(",
"env",
".",
"extent",
")",
"center",
"=",
"env",
".",
"centroid",
"for",
"z",
"in",
"xrange",
"(",
"self",
".",
"_nzoom",
")",
":",
"# Getting the tile at the zoom level.",
"tile_w",
",",
"tile_h",
"=",
"self",
".",
"get_width_height",
"(",
"self",
".",
"tile",
"(",
"center",
",",
"z",
")",
".",
"extent",
")",
"# When we span more than one tile, this is an approximately good",
"# zoom level.",
"if",
"(",
"env_w",
">",
"tile_w",
")",
"or",
"(",
"env_h",
">",
"tile_h",
")",
":",
"if",
"z",
"==",
"0",
":",
"raise",
"GoogleMapException",
"(",
"'Geometry width and height should not exceed that of the Earth.'",
")",
"return",
"z",
"-",
"1",
"# Otherwise, we've zoomed in to the max.",
"return",
"self",
".",
"_nzoom",
"-",
"1"
] |
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/contrib/gis/maps/google/zoom.py#L124-L148
|
|
maiyao1988/ExAndroidNativeEmu
|
56b592187d744a41191944741e91c66554ae3fb7
|
androidemu/java/jni_env.py
|
python
|
JNIEnv.get_static_field_id
|
(self, mu, env, clazz_idx, name_ptr, sig_ptr)
|
return field.jvm_id
|
Returns the field ID for a static field of a class. The field is specified by its name and signature. The
GetStatic<type>Field and SetStatic<type>Field families of accessor functions use field IDs to retrieve static
fields.
|
Returns the field ID for a static field of a class. The field is specified by its name and signature. The
GetStatic<type>Field and SetStatic<type>Field families of accessor functions use field IDs to retrieve static
fields.
|
[
"Returns",
"the",
"field",
"ID",
"for",
"a",
"static",
"field",
"of",
"a",
"class",
".",
"The",
"field",
"is",
"specified",
"by",
"its",
"name",
"and",
"signature",
".",
"The",
"GetStatic<type",
">",
"Field",
"and",
"SetStatic<type",
">",
"Field",
"families",
"of",
"accessor",
"functions",
"use",
"field",
"IDs",
"to",
"retrieve",
"static",
"fields",
"."
] |
def get_static_field_id(self, mu, env, clazz_idx, name_ptr, sig_ptr):
"""
Returns the field ID for a static field of a class. The field is specified by its name and signature. The
GetStatic<type>Field and SetStatic<type>Field families of accessor functions use field IDs to retrieve static
fields.
"""
name = memory_helpers.read_utf8(mu, name_ptr)
sig = memory_helpers.read_utf8(mu, sig_ptr)
logger.debug("JNIEnv->GetStaticFieldId(%d, %s, %s) was called" % (clazz_idx, name, sig))
clazz = self.get_reference(clazz_idx)
class_obj = clazz.value
pyclazz = class_obj.get_py_clazz()
field = pyclazz.find_field(name, sig, True)
if field is None:
# TODO: Proper Java error?
raise RuntimeError(
"Could not find static field ('%s', '%s') in class %s." % (name, sig, pyclazz.jvm_name))
return field.jvm_id
|
[
"def",
"get_static_field_id",
"(",
"self",
",",
"mu",
",",
"env",
",",
"clazz_idx",
",",
"name_ptr",
",",
"sig_ptr",
")",
":",
"name",
"=",
"memory_helpers",
".",
"read_utf8",
"(",
"mu",
",",
"name_ptr",
")",
"sig",
"=",
"memory_helpers",
".",
"read_utf8",
"(",
"mu",
",",
"sig_ptr",
")",
"logger",
".",
"debug",
"(",
"\"JNIEnv->GetStaticFieldId(%d, %s, %s) was called\"",
"%",
"(",
"clazz_idx",
",",
"name",
",",
"sig",
")",
")",
"clazz",
"=",
"self",
".",
"get_reference",
"(",
"clazz_idx",
")",
"class_obj",
"=",
"clazz",
".",
"value",
"pyclazz",
"=",
"class_obj",
".",
"get_py_clazz",
"(",
")",
"field",
"=",
"pyclazz",
".",
"find_field",
"(",
"name",
",",
"sig",
",",
"True",
")",
"if",
"field",
"is",
"None",
":",
"# TODO: Proper Java error?",
"raise",
"RuntimeError",
"(",
"\"Could not find static field ('%s', '%s') in class %s.\"",
"%",
"(",
"name",
",",
"sig",
",",
"pyclazz",
".",
"jvm_name",
")",
")",
"return",
"field",
".",
"jvm_id"
] |
https://github.com/maiyao1988/ExAndroidNativeEmu/blob/56b592187d744a41191944741e91c66554ae3fb7/androidemu/java/jni_env.py#L1412-L1436
|
|
tendenci/tendenci
|
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
|
tendenci/apps/forums/feeds.py
|
python
|
LastTopics.items
|
(self, user)
|
return perms.filter_topics(user, Topic.objects.all()).select_related('forum').order_by('-created', '-id')[:15]
|
[] |
def items(self, user):
return perms.filter_topics(user, Topic.objects.all()).select_related('forum').order_by('-created', '-id')[:15]
|
[
"def",
"items",
"(",
"self",
",",
"user",
")",
":",
"return",
"perms",
".",
"filter_topics",
"(",
"user",
",",
"Topic",
".",
"objects",
".",
"all",
"(",
")",
")",
".",
"select_related",
"(",
"'forum'",
")",
".",
"order_by",
"(",
"'-created'",
",",
"'-id'",
")",
"[",
":",
"15",
"]"
] |
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/forums/feeds.py#L53-L54
|
|||
rembo10/headphones
|
b3199605be1ebc83a7a8feab6b1e99b64014187c
|
lib/beets/importer.py
|
python
|
ImportTask.chosen_ident
|
(self)
|
Returns identifying metadata about the current choice. For
albums, this is an (artist, album) pair. For items, this is
(artist, title). May only be called when the choice flag is ASIS
or RETAG (in which case the data comes from the files' current
metadata) or APPLY (data comes from the choice).
|
Returns identifying metadata about the current choice. For
albums, this is an (artist, album) pair. For items, this is
(artist, title). May only be called when the choice flag is ASIS
or RETAG (in which case the data comes from the files' current
metadata) or APPLY (data comes from the choice).
|
[
"Returns",
"identifying",
"metadata",
"about",
"the",
"current",
"choice",
".",
"For",
"albums",
"this",
"is",
"an",
"(",
"artist",
"album",
")",
"pair",
".",
"For",
"items",
"this",
"is",
"(",
"artist",
"title",
")",
".",
"May",
"only",
"be",
"called",
"when",
"the",
"choice",
"flag",
"is",
"ASIS",
"or",
"RETAG",
"(",
"in",
"which",
"case",
"the",
"data",
"comes",
"from",
"the",
"files",
"current",
"metadata",
")",
"or",
"APPLY",
"(",
"data",
"comes",
"from",
"the",
"choice",
")",
"."
] |
def chosen_ident(self):
"""Returns identifying metadata about the current choice. For
albums, this is an (artist, album) pair. For items, this is
(artist, title). May only be called when the choice flag is ASIS
or RETAG (in which case the data comes from the files' current
metadata) or APPLY (data comes from the choice).
"""
if self.choice_flag in (action.ASIS, action.RETAG):
return (self.cur_artist, self.cur_album)
elif self.choice_flag is action.APPLY:
return (self.match.info.artist, self.match.info.album)
|
[
"def",
"chosen_ident",
"(",
"self",
")",
":",
"if",
"self",
".",
"choice_flag",
"in",
"(",
"action",
".",
"ASIS",
",",
"action",
".",
"RETAG",
")",
":",
"return",
"(",
"self",
".",
"cur_artist",
",",
"self",
".",
"cur_album",
")",
"elif",
"self",
".",
"choice_flag",
"is",
"action",
".",
"APPLY",
":",
"return",
"(",
"self",
".",
"match",
".",
"info",
".",
"artist",
",",
"self",
".",
"match",
".",
"info",
".",
"album",
")"
] |
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/beets/importer.py#L485-L495
|
||
PaulSonOfLars/tgbot
|
0ece72778b7772725ab214fe0929daaa2fc7d2d1
|
tg_bot/modules/sql/welcome_sql.py
|
python
|
WelcomeButtons.__init__
|
(self, chat_id, name, url, same_line=False)
|
[] |
def __init__(self, chat_id, name, url, same_line=False):
self.chat_id = str(chat_id)
self.name = name
self.url = url
self.same_line = same_line
|
[
"def",
"__init__",
"(",
"self",
",",
"chat_id",
",",
"name",
",",
"url",
",",
"same_line",
"=",
"False",
")",
":",
"self",
".",
"chat_id",
"=",
"str",
"(",
"chat_id",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"url",
"=",
"url",
"self",
".",
"same_line",
"=",
"same_line"
] |
https://github.com/PaulSonOfLars/tgbot/blob/0ece72778b7772725ab214fe0929daaa2fc7d2d1/tg_bot/modules/sql/welcome_sql.py#L43-L47
|
||||
mgear-dev/mgear_dist
|
24477b05a1ea3c615f313dbdfa56710326894fdb
|
drag_n_drop_install.py
|
python
|
InstallUI.on_help_button_clicked
|
(self)
|
Help button command.
|
Help button command.
|
[
"Help",
"button",
"command",
"."
] |
def on_help_button_clicked(self):
"""Help button command."""
QtGui.QDesktopServices.openUrl(QtCore.QUrl(
"http://forum.mgear-framework.com/t/official-installation-support-help"))
|
[
"def",
"on_help_button_clicked",
"(",
"self",
")",
":",
"QtGui",
".",
"QDesktopServices",
".",
"openUrl",
"(",
"QtCore",
".",
"QUrl",
"(",
"\"http://forum.mgear-framework.com/t/official-installation-support-help\"",
")",
")"
] |
https://github.com/mgear-dev/mgear_dist/blob/24477b05a1ea3c615f313dbdfa56710326894fdb/drag_n_drop_install.py#L151-L155
|
||
erevus-cn/pocscan
|
5fef32b1abe22a9f666ad3aacfd1f99d784cb72d
|
pocscan/plugins/pocsuite/packages/requests/adapters.py
|
python
|
HTTPAdapter.build_response
|
(self, req, resp)
|
return response
|
Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
|
Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
|
[
"Builds",
"a",
":",
"class",
":",
"Response",
"<requests",
".",
"Response",
">",
"object",
"from",
"a",
"urllib3",
"response",
".",
"This",
"should",
"not",
"be",
"called",
"from",
"user",
"code",
"and",
"is",
"only",
"exposed",
"for",
"use",
"when",
"subclassing",
"the",
":",
"class",
":",
"HTTPAdapter",
"<requests",
".",
"adapters",
".",
"HTTPAdapter",
">"
] |
def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
"""
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
# Add new cookies from the server.
extract_cookies_to_jar(response.cookies, req, resp)
# Give the Response some context.
response.request = req
response.connection = self
return response
|
[
"def",
"build_response",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"response",
"=",
"Response",
"(",
")",
"# Fallback to None if there's no status_code, for whatever reason.",
"response",
".",
"status_code",
"=",
"getattr",
"(",
"resp",
",",
"'status'",
",",
"None",
")",
"# Make headers case-insensitive.",
"response",
".",
"headers",
"=",
"CaseInsensitiveDict",
"(",
"getattr",
"(",
"resp",
",",
"'headers'",
",",
"{",
"}",
")",
")",
"# Set encoding.",
"response",
".",
"encoding",
"=",
"get_encoding_from_headers",
"(",
"response",
".",
"headers",
")",
"response",
".",
"raw",
"=",
"resp",
"response",
".",
"reason",
"=",
"response",
".",
"raw",
".",
"reason",
"if",
"isinstance",
"(",
"req",
".",
"url",
",",
"bytes",
")",
":",
"response",
".",
"url",
"=",
"req",
".",
"url",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"response",
".",
"url",
"=",
"req",
".",
"url",
"# Add new cookies from the server.",
"extract_cookies_to_jar",
"(",
"response",
".",
"cookies",
",",
"req",
",",
"resp",
")",
"# Give the Response some context.",
"response",
".",
"request",
"=",
"req",
"response",
".",
"connection",
"=",
"self",
"return",
"response"
] |
https://github.com/erevus-cn/pocscan/blob/5fef32b1abe22a9f666ad3aacfd1f99d784cb72d/pocscan/plugins/pocsuite/packages/requests/adapters.py#L158-L192
|
|
diefenbach/django-lfs
|
3bbcb3453d324c181ec68d11d5d35115a60a2fd5
|
lfs/catalog/models.py
|
python
|
DeliveryTimeBase.__add__
|
(self, other)
|
return self._get_instance(min=min_new, max=max_new, unit=unit_new)
|
Adds to delivery times.
|
Adds to delivery times.
|
[
"Adds",
"to",
"delivery",
"times",
"."
] |
def __add__(self, other):
"""
Adds to delivery times.
"""
# If necessary we transform both delivery times to the same base (hours)
if self.unit != other.unit:
a = self.as_hours()
b = other.as_hours()
unit_new = DELIVERY_TIME_UNIT_HOURS
else:
a = self
b = other
unit_new = self.unit
# Now we can add both
min_new = a.min + b.min
max_new = a.max + b.max
unit_new = a.unit
return self._get_instance(min=min_new, max=max_new, unit=unit_new)
|
[
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"# If necessary we transform both delivery times to the same base (hours)",
"if",
"self",
".",
"unit",
"!=",
"other",
".",
"unit",
":",
"a",
"=",
"self",
".",
"as_hours",
"(",
")",
"b",
"=",
"other",
".",
"as_hours",
"(",
")",
"unit_new",
"=",
"DELIVERY_TIME_UNIT_HOURS",
"else",
":",
"a",
"=",
"self",
"b",
"=",
"other",
"unit_new",
"=",
"self",
".",
"unit",
"# Now we can add both",
"min_new",
"=",
"a",
".",
"min",
"+",
"b",
".",
"min",
"max_new",
"=",
"a",
".",
"max",
"+",
"b",
".",
"max",
"unit_new",
"=",
"a",
".",
"unit",
"return",
"self",
".",
"_get_instance",
"(",
"min",
"=",
"min_new",
",",
"max",
"=",
"max_new",
",",
"unit",
"=",
"unit_new",
")"
] |
https://github.com/diefenbach/django-lfs/blob/3bbcb3453d324c181ec68d11d5d35115a60a2fd5/lfs/catalog/models.py#L2609-L2628
|
|
TencentCloud/tencentcloud-sdk-python
|
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
|
tencentcloud/cdn/v20180606/models.py
|
python
|
RemoteAuthentication.__init__
|
(self)
|
r"""
:param Switch: 远程鉴权开关;
on : 开启;
off: 关闭;
注意:此字段可能返回 null,表示取不到有效值。
:type Switch: str
:param RemoteAuthenticationRules: 远程鉴权规则配置
注意:此字段可能返回 null,表示取不到有效值。
:type RemoteAuthenticationRules: list of RemoteAuthenticationRule
:param Server: 远程鉴权Server
注意:此字段可能返回 null,表示取不到有效值。
:type Server: str
|
r"""
:param Switch: 远程鉴权开关;
on : 开启;
off: 关闭;
注意:此字段可能返回 null,表示取不到有效值。
:type Switch: str
:param RemoteAuthenticationRules: 远程鉴权规则配置
注意:此字段可能返回 null,表示取不到有效值。
:type RemoteAuthenticationRules: list of RemoteAuthenticationRule
:param Server: 远程鉴权Server
注意:此字段可能返回 null,表示取不到有效值。
:type Server: str
|
[
"r",
":",
"param",
"Switch",
":",
"远程鉴权开关;",
"on",
":",
"开启",
";",
"off",
":",
"关闭;",
"注意:此字段可能返回",
"null,表示取不到有效值。",
":",
"type",
"Switch",
":",
"str",
":",
"param",
"RemoteAuthenticationRules",
":",
"远程鉴权规则配置",
"注意:此字段可能返回",
"null,表示取不到有效值。",
":",
"type",
"RemoteAuthenticationRules",
":",
"list",
"of",
"RemoteAuthenticationRule",
":",
"param",
"Server",
":",
"远程鉴权Server",
"注意:此字段可能返回",
"null,表示取不到有效值。",
":",
"type",
"Server",
":",
"str"
] |
def __init__(self):
r"""
:param Switch: 远程鉴权开关;
on : 开启;
off: 关闭;
注意:此字段可能返回 null,表示取不到有效值。
:type Switch: str
:param RemoteAuthenticationRules: 远程鉴权规则配置
注意:此字段可能返回 null,表示取不到有效值。
:type RemoteAuthenticationRules: list of RemoteAuthenticationRule
:param Server: 远程鉴权Server
注意:此字段可能返回 null,表示取不到有效值。
:type Server: str
"""
self.Switch = None
self.RemoteAuthenticationRules = None
self.Server = None
|
[
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"Switch",
"=",
"None",
"self",
".",
"RemoteAuthenticationRules",
"=",
"None",
"self",
".",
"Server",
"=",
"None"
] |
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cdn/v20180606/models.py#L11293-L11309
|
||
khanhnamle1994/natural-language-processing
|
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
|
assignment1/.env/lib/python2.7/site-packages/numpy/lib/function_base.py
|
python
|
vectorize._get_ufunc_and_otypes
|
(self, func, args)
|
return ufunc, otypes
|
Return (ufunc, otypes).
|
Return (ufunc, otypes).
|
[
"Return",
"(",
"ufunc",
"otypes",
")",
"."
] |
def _get_ufunc_and_otypes(self, func, args):
"""Return (ufunc, otypes)."""
# frompyfunc will fail if args is empty
if not args:
raise ValueError('args can not be empty')
if self.otypes:
otypes = self.otypes
nout = len(otypes)
# Note logic here: We only *use* self._ufunc if func is self.pyfunc
# even though we set self._ufunc regardless.
if func is self.pyfunc and self._ufunc is not None:
ufunc = self._ufunc
else:
ufunc = self._ufunc = frompyfunc(func, len(args), nout)
else:
# Get number of outputs and output types by calling the function on
# the first entries of args. We also cache the result to prevent
# the subsequent call when the ufunc is evaluated.
# Assumes that ufunc first evaluates the 0th elements in the input
# arrays (the input values are not checked to ensure this)
inputs = [asarray(_a).flat[0] for _a in args]
outputs = func(*inputs)
# Performance note: profiling indicates that -- for simple
# functions at least -- this wrapping can almost double the
# execution time.
# Hence we make it optional.
if self.cache:
_cache = [outputs]
def _func(*vargs):
if _cache:
return _cache.pop()
else:
return func(*vargs)
else:
_func = func
if isinstance(outputs, tuple):
nout = len(outputs)
else:
nout = 1
outputs = (outputs,)
otypes = ''.join([asarray(outputs[_k]).dtype.char
for _k in range(nout)])
# Performance note: profiling indicates that creating the ufunc is
# not a significant cost compared with wrapping so it seems not
# worth trying to cache this.
ufunc = frompyfunc(_func, len(args), nout)
return ufunc, otypes
|
[
"def",
"_get_ufunc_and_otypes",
"(",
"self",
",",
"func",
",",
"args",
")",
":",
"# frompyfunc will fail if args is empty",
"if",
"not",
"args",
":",
"raise",
"ValueError",
"(",
"'args can not be empty'",
")",
"if",
"self",
".",
"otypes",
":",
"otypes",
"=",
"self",
".",
"otypes",
"nout",
"=",
"len",
"(",
"otypes",
")",
"# Note logic here: We only *use* self._ufunc if func is self.pyfunc",
"# even though we set self._ufunc regardless.",
"if",
"func",
"is",
"self",
".",
"pyfunc",
"and",
"self",
".",
"_ufunc",
"is",
"not",
"None",
":",
"ufunc",
"=",
"self",
".",
"_ufunc",
"else",
":",
"ufunc",
"=",
"self",
".",
"_ufunc",
"=",
"frompyfunc",
"(",
"func",
",",
"len",
"(",
"args",
")",
",",
"nout",
")",
"else",
":",
"# Get number of outputs and output types by calling the function on",
"# the first entries of args. We also cache the result to prevent",
"# the subsequent call when the ufunc is evaluated.",
"# Assumes that ufunc first evaluates the 0th elements in the input",
"# arrays (the input values are not checked to ensure this)",
"inputs",
"=",
"[",
"asarray",
"(",
"_a",
")",
".",
"flat",
"[",
"0",
"]",
"for",
"_a",
"in",
"args",
"]",
"outputs",
"=",
"func",
"(",
"*",
"inputs",
")",
"# Performance note: profiling indicates that -- for simple",
"# functions at least -- this wrapping can almost double the",
"# execution time.",
"# Hence we make it optional.",
"if",
"self",
".",
"cache",
":",
"_cache",
"=",
"[",
"outputs",
"]",
"def",
"_func",
"(",
"*",
"vargs",
")",
":",
"if",
"_cache",
":",
"return",
"_cache",
".",
"pop",
"(",
")",
"else",
":",
"return",
"func",
"(",
"*",
"vargs",
")",
"else",
":",
"_func",
"=",
"func",
"if",
"isinstance",
"(",
"outputs",
",",
"tuple",
")",
":",
"nout",
"=",
"len",
"(",
"outputs",
")",
"else",
":",
"nout",
"=",
"1",
"outputs",
"=",
"(",
"outputs",
",",
")",
"otypes",
"=",
"''",
".",
"join",
"(",
"[",
"asarray",
"(",
"outputs",
"[",
"_k",
"]",
")",
".",
"dtype",
".",
"char",
"for",
"_k",
"in",
"range",
"(",
"nout",
")",
"]",
")",
"# Performance note: profiling indicates that creating the ufunc is",
"# not a significant cost compared with wrapping so it seems not",
"# worth trying to cache this.",
"ufunc",
"=",
"frompyfunc",
"(",
"_func",
",",
"len",
"(",
"args",
")",
",",
"nout",
")",
"return",
"ufunc",
",",
"otypes"
] |
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/numpy/lib/function_base.py#L1702-L1756
|
|
python/cpython
|
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
|
Lib/turtle.py
|
python
|
RawTurtle.ondrag
|
(self, fun, btn=1, add=None)
|
Bind fun to mouse-move event on this turtle on canvas.
Arguments:
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
btn -- number of the mouse-button defaults to 1 (left mouse button).
Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.
Example (for a Turtle instance named turtle):
>>> turtle.ondrag(turtle.goto)
Subsequently clicking and dragging a Turtle will move it
across the screen thereby producing handdrawings (if pen is
down).
|
Bind fun to mouse-move event on this turtle on canvas.
|
[
"Bind",
"fun",
"to",
"mouse",
"-",
"move",
"event",
"on",
"this",
"turtle",
"on",
"canvas",
"."
] |
def ondrag(self, fun, btn=1, add=None):
"""Bind fun to mouse-move event on this turtle on canvas.
Arguments:
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
btn -- number of the mouse-button defaults to 1 (left mouse button).
Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.
Example (for a Turtle instance named turtle):
>>> turtle.ondrag(turtle.goto)
Subsequently clicking and dragging a Turtle will move it
across the screen thereby producing handdrawings (if pen is
down).
"""
self.screen._ondrag(self.turtle._item, fun, btn, add)
|
[
"def",
"ondrag",
"(",
"self",
",",
"fun",
",",
"btn",
"=",
"1",
",",
"add",
"=",
"None",
")",
":",
"self",
".",
"screen",
".",
"_ondrag",
"(",
"self",
".",
"turtle",
".",
"_item",
",",
"fun",
",",
"btn",
",",
"add",
")"
] |
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/turtle.py#L3587-L3605
|
||
sametmax/Django--an-app-at-a-time
|
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
|
ignore_this_directory/django/db/backends/oracle/introspection.py
|
python
|
DatabaseIntrospection.get_table_description
|
(self, cursor, table_name)
|
return description
|
Return a description of the table with the DB-API cursor.description
interface.
|
Return a description of the table with the DB-API cursor.description
interface.
|
[
"Return",
"a",
"description",
"of",
"the",
"table",
"with",
"the",
"DB",
"-",
"API",
"cursor",
".",
"description",
"interface",
"."
] |
def get_table_description(self, cursor, table_name):
"""
Return a description of the table with the DB-API cursor.description
interface.
"""
# user_tab_columns gives data default for columns
cursor.execute("""
SELECT
column_name,
data_default,
CASE
WHEN char_used IS NULL THEN data_length
ELSE char_length
END as internal_size,
CASE
WHEN identity_column = 'YES' THEN 1
ELSE 0
END as is_autofield
FROM user_tab_cols
WHERE table_name = UPPER(%s)""", [table_name])
field_map = {
column: (internal_size, default if default != 'NULL' else None, is_autofield)
for column, default, internal_size, is_autofield in cursor.fetchall()
}
self.cache_bust_counter += 1
cursor.execute("SELECT * FROM {} WHERE ROWNUM < 2 AND {} > 0".format(
self.connection.ops.quote_name(table_name),
self.cache_bust_counter))
description = []
for desc in cursor.description:
name = desc[0]
internal_size, default, is_autofield = field_map[name]
name = name % {} # cx_Oracle, for some reason, doubles percent signs.
description.append(FieldInfo(
self.identifier_converter(name), *desc[1:3], internal_size, desc[4] or 0,
desc[5] or 0, *desc[6:], default, is_autofield,
))
return description
|
[
"def",
"get_table_description",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"# user_tab_columns gives data default for columns",
"cursor",
".",
"execute",
"(",
"\"\"\"\n SELECT\n column_name,\n data_default,\n CASE\n WHEN char_used IS NULL THEN data_length\n ELSE char_length\n END as internal_size,\n CASE\n WHEN identity_column = 'YES' THEN 1\n ELSE 0\n END as is_autofield\n FROM user_tab_cols\n WHERE table_name = UPPER(%s)\"\"\"",
",",
"[",
"table_name",
"]",
")",
"field_map",
"=",
"{",
"column",
":",
"(",
"internal_size",
",",
"default",
"if",
"default",
"!=",
"'NULL'",
"else",
"None",
",",
"is_autofield",
")",
"for",
"column",
",",
"default",
",",
"internal_size",
",",
"is_autofield",
"in",
"cursor",
".",
"fetchall",
"(",
")",
"}",
"self",
".",
"cache_bust_counter",
"+=",
"1",
"cursor",
".",
"execute",
"(",
"\"SELECT * FROM {} WHERE ROWNUM < 2 AND {} > 0\"",
".",
"format",
"(",
"self",
".",
"connection",
".",
"ops",
".",
"quote_name",
"(",
"table_name",
")",
",",
"self",
".",
"cache_bust_counter",
")",
")",
"description",
"=",
"[",
"]",
"for",
"desc",
"in",
"cursor",
".",
"description",
":",
"name",
"=",
"desc",
"[",
"0",
"]",
"internal_size",
",",
"default",
",",
"is_autofield",
"=",
"field_map",
"[",
"name",
"]",
"name",
"=",
"name",
"%",
"{",
"}",
"# cx_Oracle, for some reason, doubles percent signs.",
"description",
".",
"append",
"(",
"FieldInfo",
"(",
"self",
".",
"identifier_converter",
"(",
"name",
")",
",",
"*",
"desc",
"[",
"1",
":",
"3",
"]",
",",
"internal_size",
",",
"desc",
"[",
"4",
"]",
"or",
"0",
",",
"desc",
"[",
"5",
"]",
"or",
"0",
",",
"*",
"desc",
"[",
"6",
":",
"]",
",",
"default",
",",
"is_autofield",
",",
")",
")",
"return",
"description"
] |
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/db/backends/oracle/introspection.py#L67-L104
|
|
qutip/qutip
|
52d01da181a21b810c3407812c670f35fdc647e8
|
qutip/nonmarkov/bofin_solvers.py
|
python
|
HEOMSolver._configure_solver
|
(self)
|
Set up the solver.
|
Set up the solver.
|
[
"Set",
"up",
"the",
"solver",
"."
] |
def _configure_solver(self):
""" Set up the solver. """
RHSmat = self._rhs(self._L0.data)
assert isinstance(RHSmat, sp.csr_matrix)
if self._is_timedep:
# In the time dependent case, we construct the parameters
# for the ODE gradient function _dsuper_list_td under the
# assumption that RHSmat(t) = RHSmat + time dependent terms
# that only affect the diagonal blocks of the RHS matrix.
# This assumption holds because only _grad_n dependents on
# the system Liovillian (and not _grad_prev or _grad_next).
h_identity_mat = sp.identity(self._n_ados, format="csr")
H_list = self.H_sys.to_list()
solver_params = [[RHSmat]]
for idx in range(1, len(H_list)):
temp_mat = sp.kron(
h_identity_mat, liouvillian(H_list[idx][0])
)
solver_params.append([temp_mat, H_list[idx][1]])
solver = scipy.integrate.ode(self._dsuper_list_td)
solver.set_f_params(solver_params)
else:
solver = scipy.integrate.ode(cy_ode_rhs)
solver.set_f_params(RHSmat.data, RHSmat.indices, RHSmat.indptr)
solver.set_integrator(
"zvode",
method=self.options.method,
order=self.options.order,
atol=self.options.atol,
rtol=self.options.rtol,
nsteps=self.options.nsteps,
first_step=self.options.first_step,
min_step=self.options.min_step,
max_step=self.options.max_step,
)
self._ode = solver
self.RHSmat = RHSmat
|
[
"def",
"_configure_solver",
"(",
"self",
")",
":",
"RHSmat",
"=",
"self",
".",
"_rhs",
"(",
"self",
".",
"_L0",
".",
"data",
")",
"assert",
"isinstance",
"(",
"RHSmat",
",",
"sp",
".",
"csr_matrix",
")",
"if",
"self",
".",
"_is_timedep",
":",
"# In the time dependent case, we construct the parameters",
"# for the ODE gradient function _dsuper_list_td under the",
"# assumption that RHSmat(t) = RHSmat + time dependent terms",
"# that only affect the diagonal blocks of the RHS matrix.",
"# This assumption holds because only _grad_n dependents on",
"# the system Liovillian (and not _grad_prev or _grad_next).",
"h_identity_mat",
"=",
"sp",
".",
"identity",
"(",
"self",
".",
"_n_ados",
",",
"format",
"=",
"\"csr\"",
")",
"H_list",
"=",
"self",
".",
"H_sys",
".",
"to_list",
"(",
")",
"solver_params",
"=",
"[",
"[",
"RHSmat",
"]",
"]",
"for",
"idx",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"H_list",
")",
")",
":",
"temp_mat",
"=",
"sp",
".",
"kron",
"(",
"h_identity_mat",
",",
"liouvillian",
"(",
"H_list",
"[",
"idx",
"]",
"[",
"0",
"]",
")",
")",
"solver_params",
".",
"append",
"(",
"[",
"temp_mat",
",",
"H_list",
"[",
"idx",
"]",
"[",
"1",
"]",
"]",
")",
"solver",
"=",
"scipy",
".",
"integrate",
".",
"ode",
"(",
"self",
".",
"_dsuper_list_td",
")",
"solver",
".",
"set_f_params",
"(",
"solver_params",
")",
"else",
":",
"solver",
"=",
"scipy",
".",
"integrate",
".",
"ode",
"(",
"cy_ode_rhs",
")",
"solver",
".",
"set_f_params",
"(",
"RHSmat",
".",
"data",
",",
"RHSmat",
".",
"indices",
",",
"RHSmat",
".",
"indptr",
")",
"solver",
".",
"set_integrator",
"(",
"\"zvode\"",
",",
"method",
"=",
"self",
".",
"options",
".",
"method",
",",
"order",
"=",
"self",
".",
"options",
".",
"order",
",",
"atol",
"=",
"self",
".",
"options",
".",
"atol",
",",
"rtol",
"=",
"self",
".",
"options",
".",
"rtol",
",",
"nsteps",
"=",
"self",
".",
"options",
".",
"nsteps",
",",
"first_step",
"=",
"self",
".",
"options",
".",
"first_step",
",",
"min_step",
"=",
"self",
".",
"options",
".",
"min_step",
",",
"max_step",
"=",
"self",
".",
"options",
".",
"max_step",
",",
")",
"self",
".",
"_ode",
"=",
"solver",
"self",
".",
"RHSmat",
"=",
"RHSmat"
] |
https://github.com/qutip/qutip/blob/52d01da181a21b810c3407812c670f35fdc647e8/qutip/nonmarkov/bofin_solvers.py#L656-L698
|
||
xlwings/xlwings
|
44395c4d18b46f76249279b7d0965e640291499c
|
xlwings/main.py
|
python
|
load
|
(index=1, header=1, chunksize=5000)
|
return values
|
Loads the selected cell(s) of the active workbook into a pandas DataFrame. If you select a single cell that has
adjacent cells, the range is auto-expanded (via current region) and turned into a pandas DataFrame. If you don't
have pandas installed, it returns the values as nested lists.
.. note::
Only use this in an interactive context like e.g. a Jupyter notebook! Don't use this in a script as it depends
on the active book.
Parameters
----------
index : bool or int, default 1
Defines the number of columns on the left that will be turned into the DataFrame's index
header : bool or int, default 1
Defines the number of rows at the top that will be turned into the DataFrame's columns
chunksize : int, default 5000
Chunks the loading of big arrays.
Examples
--------
>>> import xlwings as xw
>>> xw.load()
See also: :meth:`view <xlwings.view>`
.. versionchanged:: 0.23.1
|
Loads the selected cell(s) of the active workbook into a pandas DataFrame. If you select a single cell that has
adjacent cells, the range is auto-expanded (via current region) and turned into a pandas DataFrame. If you don't
have pandas installed, it returns the values as nested lists.
|
[
"Loads",
"the",
"selected",
"cell",
"(",
"s",
")",
"of",
"the",
"active",
"workbook",
"into",
"a",
"pandas",
"DataFrame",
".",
"If",
"you",
"select",
"a",
"single",
"cell",
"that",
"has",
"adjacent",
"cells",
"the",
"range",
"is",
"auto",
"-",
"expanded",
"(",
"via",
"current",
"region",
")",
"and",
"turned",
"into",
"a",
"pandas",
"DataFrame",
".",
"If",
"you",
"don",
"t",
"have",
"pandas",
"installed",
"it",
"returns",
"the",
"values",
"as",
"nested",
"lists",
"."
] |
def load(index=1, header=1, chunksize=5000):
"""
Loads the selected cell(s) of the active workbook into a pandas DataFrame. If you select a single cell that has
adjacent cells, the range is auto-expanded (via current region) and turned into a pandas DataFrame. If you don't
have pandas installed, it returns the values as nested lists.
.. note::
Only use this in an interactive context like e.g. a Jupyter notebook! Don't use this in a script as it depends
on the active book.
Parameters
----------
index : bool or int, default 1
Defines the number of columns on the left that will be turned into the DataFrame's index
header : bool or int, default 1
Defines the number of rows at the top that will be turned into the DataFrame's columns
chunksize : int, default 5000
Chunks the loading of big arrays.
Examples
--------
>>> import xlwings as xw
>>> xw.load()
See also: :meth:`view <xlwings.view>`
.. versionchanged:: 0.23.1
"""
selection = books.active.selection
if selection.shape == (1, 1):
selection = selection.current_region
if pd:
values = selection.options(pd.DataFrame, index=index, header=header, chunksize=chunksize).value
else:
values = selection.options(chunksize=chunksize).value
return values
|
[
"def",
"load",
"(",
"index",
"=",
"1",
",",
"header",
"=",
"1",
",",
"chunksize",
"=",
"5000",
")",
":",
"selection",
"=",
"books",
".",
"active",
".",
"selection",
"if",
"selection",
".",
"shape",
"==",
"(",
"1",
",",
"1",
")",
":",
"selection",
"=",
"selection",
".",
"current_region",
"if",
"pd",
":",
"values",
"=",
"selection",
".",
"options",
"(",
"pd",
".",
"DataFrame",
",",
"index",
"=",
"index",
",",
"header",
"=",
"header",
",",
"chunksize",
"=",
"chunksize",
")",
".",
"value",
"else",
":",
"values",
"=",
"selection",
".",
"options",
"(",
"chunksize",
"=",
"chunksize",
")",
".",
"value",
"return",
"values"
] |
https://github.com/xlwings/xlwings/blob/44395c4d18b46f76249279b7d0965e640291499c/xlwings/main.py#L4081-L4118
|
|
tomplus/kubernetes_asyncio
|
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
|
kubernetes_asyncio/client/api/authentication_v1_api.py
|
python
|
AuthenticationV1Api.create_token_review_with_http_info
|
(self, body, **kwargs)
|
return self.api_client.call_api(
'/apis/authentication.k8s.io/v1/tokenreviews', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1TokenReview', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
|
create_token_review # noqa: E501
create a TokenReview # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_token_review_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param V1TokenReview body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1TokenReview, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
|
create_token_review # noqa: E501
|
[
"create_token_review",
"#",
"noqa",
":",
"E501"
] |
def create_token_review_with_http_info(self, body, **kwargs): # noqa: E501
"""create_token_review # noqa: E501
create a TokenReview # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_token_review_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param V1TokenReview body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1TokenReview, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'body',
'dry_run',
'field_manager',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_token_review" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_token_review`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/authentication.k8s.io/v1/tokenreviews', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1TokenReview', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
|
[
"def",
"create_token_review_with_http_info",
"(",
"self",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"local_var_params",
"=",
"locals",
"(",
")",
"all_params",
"=",
"[",
"'body'",
",",
"'dry_run'",
",",
"'field_manager'",
",",
"'pretty'",
"]",
"all_params",
".",
"extend",
"(",
"[",
"'async_req'",
",",
"'_return_http_data_only'",
",",
"'_preload_content'",
",",
"'_request_timeout'",
"]",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"local_var_params",
"[",
"'kwargs'",
"]",
")",
":",
"if",
"key",
"not",
"in",
"all_params",
":",
"raise",
"ApiTypeError",
"(",
"\"Got an unexpected keyword argument '%s'\"",
"\" to method create_token_review\"",
"%",
"key",
")",
"local_var_params",
"[",
"key",
"]",
"=",
"val",
"del",
"local_var_params",
"[",
"'kwargs'",
"]",
"# verify the required parameter 'body' is set",
"if",
"self",
".",
"api_client",
".",
"client_side_validation",
"and",
"(",
"'body'",
"not",
"in",
"local_var_params",
"or",
"# noqa: E501",
"local_var_params",
"[",
"'body'",
"]",
"is",
"None",
")",
":",
"# noqa: E501",
"raise",
"ApiValueError",
"(",
"\"Missing the required parameter `body` when calling `create_token_review`\"",
")",
"# noqa: E501",
"collection_formats",
"=",
"{",
"}",
"path_params",
"=",
"{",
"}",
"query_params",
"=",
"[",
"]",
"if",
"'dry_run'",
"in",
"local_var_params",
"and",
"local_var_params",
"[",
"'dry_run'",
"]",
"is",
"not",
"None",
":",
"# noqa: E501",
"query_params",
".",
"append",
"(",
"(",
"'dryRun'",
",",
"local_var_params",
"[",
"'dry_run'",
"]",
")",
")",
"# noqa: E501",
"if",
"'field_manager'",
"in",
"local_var_params",
"and",
"local_var_params",
"[",
"'field_manager'",
"]",
"is",
"not",
"None",
":",
"# noqa: E501",
"query_params",
".",
"append",
"(",
"(",
"'fieldManager'",
",",
"local_var_params",
"[",
"'field_manager'",
"]",
")",
")",
"# noqa: E501",
"if",
"'pretty'",
"in",
"local_var_params",
"and",
"local_var_params",
"[",
"'pretty'",
"]",
"is",
"not",
"None",
":",
"# noqa: E501",
"query_params",
".",
"append",
"(",
"(",
"'pretty'",
",",
"local_var_params",
"[",
"'pretty'",
"]",
")",
")",
"# noqa: E501",
"header_params",
"=",
"{",
"}",
"form_params",
"=",
"[",
"]",
"local_var_files",
"=",
"{",
"}",
"body_params",
"=",
"None",
"if",
"'body'",
"in",
"local_var_params",
":",
"body_params",
"=",
"local_var_params",
"[",
"'body'",
"]",
"# HTTP header `Accept`",
"header_params",
"[",
"'Accept'",
"]",
"=",
"self",
".",
"api_client",
".",
"select_header_accept",
"(",
"[",
"'application/json'",
",",
"'application/yaml'",
",",
"'application/vnd.kubernetes.protobuf'",
"]",
")",
"# noqa: E501",
"# Authentication setting",
"auth_settings",
"=",
"[",
"'BearerToken'",
"]",
"# noqa: E501",
"return",
"self",
".",
"api_client",
".",
"call_api",
"(",
"'/apis/authentication.k8s.io/v1/tokenreviews'",
",",
"'POST'",
",",
"path_params",
",",
"query_params",
",",
"header_params",
",",
"body",
"=",
"body_params",
",",
"post_params",
"=",
"form_params",
",",
"files",
"=",
"local_var_files",
",",
"response_type",
"=",
"'V1TokenReview'",
",",
"# noqa: E501",
"auth_settings",
"=",
"auth_settings",
",",
"async_req",
"=",
"local_var_params",
".",
"get",
"(",
"'async_req'",
")",
",",
"_return_http_data_only",
"=",
"local_var_params",
".",
"get",
"(",
"'_return_http_data_only'",
")",
",",
"# noqa: E501",
"_preload_content",
"=",
"local_var_params",
".",
"get",
"(",
"'_preload_content'",
",",
"True",
")",
",",
"_request_timeout",
"=",
"local_var_params",
".",
"get",
"(",
"'_request_timeout'",
")",
",",
"collection_formats",
"=",
"collection_formats",
")"
] |
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/authentication_v1_api.py#L67-L166
|
|
google/trax
|
d6cae2067dedd0490b78d831033607357e975015
|
trax/data/inputs.py
|
python
|
lower_endian_to_number
|
(l, base)
|
return sum([d * (base**i) for i, d in enumerate(l)])
|
Helper function: convert a list of digits in the given base to a number.
|
Helper function: convert a list of digits in the given base to a number.
|
[
"Helper",
"function",
":",
"convert",
"a",
"list",
"of",
"digits",
"in",
"the",
"given",
"base",
"to",
"a",
"number",
"."
] |
def lower_endian_to_number(l, base):
"""Helper function: convert a list of digits in the given base to a number."""
return sum([d * (base**i) for i, d in enumerate(l)])
|
[
"def",
"lower_endian_to_number",
"(",
"l",
",",
"base",
")",
":",
"return",
"sum",
"(",
"[",
"d",
"*",
"(",
"base",
"**",
"i",
")",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"l",
")",
"]",
")"
] |
https://github.com/google/trax/blob/d6cae2067dedd0490b78d831033607357e975015/trax/data/inputs.py#L1045-L1047
|
|
cea-sec/miasm
|
09376c524aedc7920a7eda304d6095e12f6958f4
|
miasm/core/ctypesmngr.py
|
python
|
CAstTypes.ast_to_typeid_struct
|
(self, ast)
|
return decl
|
Return the CTypeBase of an Struct ast
|
Return the CTypeBase of an Struct ast
|
[
"Return",
"the",
"CTypeBase",
"of",
"an",
"Struct",
"ast"
] |
def ast_to_typeid_struct(self, ast):
"""Return the CTypeBase of an Struct ast"""
name = self.gen_uniq_name() if ast.name is None else ast.name
args = []
if ast.decls:
for arg in ast.decls:
if arg.name is None:
arg_name = self.gen_anon_name()
else:
arg_name = arg.name
args.append((arg_name, self.ast_to_typeid(arg)))
decl = CTypeStruct(name, args)
return decl
|
[
"def",
"ast_to_typeid_struct",
"(",
"self",
",",
"ast",
")",
":",
"name",
"=",
"self",
".",
"gen_uniq_name",
"(",
")",
"if",
"ast",
".",
"name",
"is",
"None",
"else",
"ast",
".",
"name",
"args",
"=",
"[",
"]",
"if",
"ast",
".",
"decls",
":",
"for",
"arg",
"in",
"ast",
".",
"decls",
":",
"if",
"arg",
".",
"name",
"is",
"None",
":",
"arg_name",
"=",
"self",
".",
"gen_anon_name",
"(",
")",
"else",
":",
"arg_name",
"=",
"arg",
".",
"name",
"args",
".",
"append",
"(",
"(",
"arg_name",
",",
"self",
".",
"ast_to_typeid",
"(",
"arg",
")",
")",
")",
"decl",
"=",
"CTypeStruct",
"(",
"name",
",",
"args",
")",
"return",
"decl"
] |
https://github.com/cea-sec/miasm/blob/09376c524aedc7920a7eda304d6095e12f6958f4/miasm/core/ctypesmngr.py#L563-L575
|
|
LuxCoreRender/BlendLuxCore
|
bf31ca58501d54c02acd97001b6db7de81da7cbf
|
utils/render.py
|
python
|
update_status_msg
|
(stats, engine, scene, config, time_until_film_refresh)
|
Show stats string in UI.
This function is only used for final renders, not viewport renders.
|
Show stats string in UI.
This function is only used for final renders, not viewport renders.
|
[
"Show",
"stats",
"string",
"in",
"UI",
".",
"This",
"function",
"is",
"only",
"used",
"for",
"final",
"renders",
"not",
"viewport",
"renders",
"."
] |
def update_status_msg(stats, engine, scene, config, time_until_film_refresh):
"""
Show stats string in UI.
This function is only used for final renders, not viewport renders.
"""
pretty_stats = get_pretty_stats(config, stats, scene)
# Update the stats that are shown in the image tools area
render_slot_stats = engine.exporter.stats
render_slot_stats.update_from_luxcore_stats(stats)
if time_until_film_refresh <= 0:
if engine.has_denoiser() and scene.luxcore.denoiser.refresh:
refresh_message = "Running denoiser and refreshing film..."
else:
refresh_message = "Refreshing film..."
else:
refresh_message = "Film refresh in %d s" % math.ceil(time_until_film_refresh)
# Note: the first argument is only shown in the UI.
# The second argument is shown in the UI and printed in the console
# when rendering in batch mode, so we use this to show the stats.
engine.update_stats("", pretty_stats + " | " + refresh_message)
# Update progress bar if we have halt conditions
using_hybridbackforward = utils.using_hybridbackforward(scene)
halt = utils.get_halt_conditions(scene)
if halt.enable and (halt.use_time or halt.use_samples
or (halt.use_light_samples and using_hybridbackforward)
or halt.use_noise_thresh):
samples_eye = stats.Get("stats.renderengine.pass.eye").GetInt()
samples_light = stats.Get("stats.renderengine.pass.light").GetInt()
rendered_time = stats.Get("stats.renderengine.time").GetFloat()
percent = 0
if halt.use_time:
percent = rendered_time / halt.time
if halt.use_samples and halt.use_light_samples and using_hybridbackforward:
# Using both eye pass limit and light pass limit
# Because both sample limits must be reached for haltspp to trigger,
# take the smaller (slower) of the two percentages
percent_eye = samples_eye / halt.samples
percent_light = samples_light / halt.light_samples
percent_samples = min(percent_eye, percent_light)
percent = max(percent, percent_samples)
elif halt.use_samples:
# Using only eye pass limit (or not using hybridbackforward)
if scene.luxcore.config.using_only_lighttracing():
rendered_samples = samples_light
else:
rendered_samples = samples_eye
percent_samples = rendered_samples / halt.samples
percent = max(percent, percent_samples)
elif halt.use_light_samples and using_hybridbackforward:
# Using only light pass limit
percent_samples = samples_light / halt.light_samples
percent = max(percent, percent_samples)
if halt.use_noise_thresh:
convergence = stats.Get("stats.renderengine.convergence").GetFloat()
percent = max(percent, convergence)
engine.update_progress(percent)
else:
# Reset to 0 in case the user disables the halt conditions during render
engine.update_progress(0)
if "TILE" in config.GetProperties().Get("renderengine.type").GetString():
TileStats.film_width, TileStats.film_height = utils.calc_filmsize(scene)
tile_w = stats.Get("stats.tilepath.tiles.size.x").GetInt()
tile_h = stats.Get("stats.tilepath.tiles.size.y").GetInt()
TileStats.width, TileStats.height = tile_w, tile_h
TileStats.pending_coords = stats.Get('stats.tilepath.tiles.pending.coords').GetInts()
TileStats.pending_passcounts = stats.Get('stats.tilepath.tiles.pending.pass').GetInts()
TileStats.converged_coords = stats.Get('stats.tilepath.tiles.converged.coords').GetInts()
TileStats.converged_passcounts = stats.Get('stats.tilepath.tiles.converged.pass').GetInts()
TileStats.notconverged_coords = stats.Get('stats.tilepath.tiles.notconverged.coords').GetInts()
TileStats.notconverged_passcounts = stats.Get('stats.tilepath.tiles.notconverged.pass').GetInts()
|
[
"def",
"update_status_msg",
"(",
"stats",
",",
"engine",
",",
"scene",
",",
"config",
",",
"time_until_film_refresh",
")",
":",
"pretty_stats",
"=",
"get_pretty_stats",
"(",
"config",
",",
"stats",
",",
"scene",
")",
"# Update the stats that are shown in the image tools area",
"render_slot_stats",
"=",
"engine",
".",
"exporter",
".",
"stats",
"render_slot_stats",
".",
"update_from_luxcore_stats",
"(",
"stats",
")",
"if",
"time_until_film_refresh",
"<=",
"0",
":",
"if",
"engine",
".",
"has_denoiser",
"(",
")",
"and",
"scene",
".",
"luxcore",
".",
"denoiser",
".",
"refresh",
":",
"refresh_message",
"=",
"\"Running denoiser and refreshing film...\"",
"else",
":",
"refresh_message",
"=",
"\"Refreshing film...\"",
"else",
":",
"refresh_message",
"=",
"\"Film refresh in %d s\"",
"%",
"math",
".",
"ceil",
"(",
"time_until_film_refresh",
")",
"# Note: the first argument is only shown in the UI.",
"# The second argument is shown in the UI and printed in the console",
"# when rendering in batch mode, so we use this to show the stats.",
"engine",
".",
"update_stats",
"(",
"\"\"",
",",
"pretty_stats",
"+",
"\" | \"",
"+",
"refresh_message",
")",
"# Update progress bar if we have halt conditions",
"using_hybridbackforward",
"=",
"utils",
".",
"using_hybridbackforward",
"(",
"scene",
")",
"halt",
"=",
"utils",
".",
"get_halt_conditions",
"(",
"scene",
")",
"if",
"halt",
".",
"enable",
"and",
"(",
"halt",
".",
"use_time",
"or",
"halt",
".",
"use_samples",
"or",
"(",
"halt",
".",
"use_light_samples",
"and",
"using_hybridbackforward",
")",
"or",
"halt",
".",
"use_noise_thresh",
")",
":",
"samples_eye",
"=",
"stats",
".",
"Get",
"(",
"\"stats.renderengine.pass.eye\"",
")",
".",
"GetInt",
"(",
")",
"samples_light",
"=",
"stats",
".",
"Get",
"(",
"\"stats.renderengine.pass.light\"",
")",
".",
"GetInt",
"(",
")",
"rendered_time",
"=",
"stats",
".",
"Get",
"(",
"\"stats.renderengine.time\"",
")",
".",
"GetFloat",
"(",
")",
"percent",
"=",
"0",
"if",
"halt",
".",
"use_time",
":",
"percent",
"=",
"rendered_time",
"/",
"halt",
".",
"time",
"if",
"halt",
".",
"use_samples",
"and",
"halt",
".",
"use_light_samples",
"and",
"using_hybridbackforward",
":",
"# Using both eye pass limit and light pass limit",
"# Because both sample limits must be reached for haltspp to trigger,",
"# take the smaller (slower) of the two percentages",
"percent_eye",
"=",
"samples_eye",
"/",
"halt",
".",
"samples",
"percent_light",
"=",
"samples_light",
"/",
"halt",
".",
"light_samples",
"percent_samples",
"=",
"min",
"(",
"percent_eye",
",",
"percent_light",
")",
"percent",
"=",
"max",
"(",
"percent",
",",
"percent_samples",
")",
"elif",
"halt",
".",
"use_samples",
":",
"# Using only eye pass limit (or not using hybridbackforward)",
"if",
"scene",
".",
"luxcore",
".",
"config",
".",
"using_only_lighttracing",
"(",
")",
":",
"rendered_samples",
"=",
"samples_light",
"else",
":",
"rendered_samples",
"=",
"samples_eye",
"percent_samples",
"=",
"rendered_samples",
"/",
"halt",
".",
"samples",
"percent",
"=",
"max",
"(",
"percent",
",",
"percent_samples",
")",
"elif",
"halt",
".",
"use_light_samples",
"and",
"using_hybridbackforward",
":",
"# Using only light pass limit",
"percent_samples",
"=",
"samples_light",
"/",
"halt",
".",
"light_samples",
"percent",
"=",
"max",
"(",
"percent",
",",
"percent_samples",
")",
"if",
"halt",
".",
"use_noise_thresh",
":",
"convergence",
"=",
"stats",
".",
"Get",
"(",
"\"stats.renderengine.convergence\"",
")",
".",
"GetFloat",
"(",
")",
"percent",
"=",
"max",
"(",
"percent",
",",
"convergence",
")",
"engine",
".",
"update_progress",
"(",
"percent",
")",
"else",
":",
"# Reset to 0 in case the user disables the halt conditions during render",
"engine",
".",
"update_progress",
"(",
"0",
")",
"if",
"\"TILE\"",
"in",
"config",
".",
"GetProperties",
"(",
")",
".",
"Get",
"(",
"\"renderengine.type\"",
")",
".",
"GetString",
"(",
")",
":",
"TileStats",
".",
"film_width",
",",
"TileStats",
".",
"film_height",
"=",
"utils",
".",
"calc_filmsize",
"(",
"scene",
")",
"tile_w",
"=",
"stats",
".",
"Get",
"(",
"\"stats.tilepath.tiles.size.x\"",
")",
".",
"GetInt",
"(",
")",
"tile_h",
"=",
"stats",
".",
"Get",
"(",
"\"stats.tilepath.tiles.size.y\"",
")",
".",
"GetInt",
"(",
")",
"TileStats",
".",
"width",
",",
"TileStats",
".",
"height",
"=",
"tile_w",
",",
"tile_h",
"TileStats",
".",
"pending_coords",
"=",
"stats",
".",
"Get",
"(",
"'stats.tilepath.tiles.pending.coords'",
")",
".",
"GetInts",
"(",
")",
"TileStats",
".",
"pending_passcounts",
"=",
"stats",
".",
"Get",
"(",
"'stats.tilepath.tiles.pending.pass'",
")",
".",
"GetInts",
"(",
")",
"TileStats",
".",
"converged_coords",
"=",
"stats",
".",
"Get",
"(",
"'stats.tilepath.tiles.converged.coords'",
")",
".",
"GetInts",
"(",
")",
"TileStats",
".",
"converged_passcounts",
"=",
"stats",
".",
"Get",
"(",
"'stats.tilepath.tiles.converged.pass'",
")",
".",
"GetInts",
"(",
")",
"TileStats",
".",
"notconverged_coords",
"=",
"stats",
".",
"Get",
"(",
"'stats.tilepath.tiles.notconverged.coords'",
")",
".",
"GetInts",
"(",
")",
"TileStats",
".",
"notconverged_passcounts",
"=",
"stats",
".",
"Get",
"(",
"'stats.tilepath.tiles.notconverged.pass'",
")",
".",
"GetInts",
"(",
")"
] |
https://github.com/LuxCoreRender/BlendLuxCore/blob/bf31ca58501d54c02acd97001b6db7de81da7cbf/utils/render.py#L73-L150
|
||
pyserial/pyserial
|
31fa4807d73ed4eb9891a88a15817b439c4eea2d
|
serial/urlhandler/protocol_spy.py
|
python
|
FormatHexdump.rx
|
(self, data)
|
show received data as hex dump
|
show received data as hex dump
|
[
"show",
"received",
"data",
"as",
"hex",
"dump"
] |
def rx(self, data):
"""show received data as hex dump"""
if self.color:
self.output.write(self.rx_color)
if data:
for offset, row in hexdump(data):
self.write_line(time.time() - self.start_time, 'RX', '{:04X} '.format(offset), row)
else:
self.write_line(time.time() - self.start_time, 'RX', '<empty>')
|
[
"def",
"rx",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"color",
":",
"self",
".",
"output",
".",
"write",
"(",
"self",
".",
"rx_color",
")",
"if",
"data",
":",
"for",
"offset",
",",
"row",
"in",
"hexdump",
"(",
"data",
")",
":",
"self",
".",
"write_line",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"start_time",
",",
"'RX'",
",",
"'{:04X} '",
".",
"format",
"(",
"offset",
")",
",",
"row",
")",
"else",
":",
"self",
".",
"write_line",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"start_time",
",",
"'RX'",
",",
"'<empty>'",
")"
] |
https://github.com/pyserial/pyserial/blob/31fa4807d73ed4eb9891a88a15817b439c4eea2d/serial/urlhandler/protocol_spy.py#L132-L140
|
||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
|
cb692f527e4e819b6c228187c5702d990a180043
|
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/logging/config.py
|
python
|
DictConfigurator.add_filters
|
(self, filterer, filters)
|
Add filters to a filterer from a list of names.
|
Add filters to a filterer from a list of names.
|
[
"Add",
"filters",
"to",
"a",
"filterer",
"from",
"a",
"list",
"of",
"names",
"."
] |
def add_filters(self, filterer, filters):
"""Add filters to a filterer from a list of names."""
for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError, e:
raise ValueError('Unable to add filter %r: %s' % (f, e))
|
[
"def",
"add_filters",
"(",
"self",
",",
"filterer",
",",
"filters",
")",
":",
"for",
"f",
"in",
"filters",
":",
"try",
":",
"filterer",
".",
"addFilter",
"(",
"self",
".",
"config",
"[",
"'filters'",
"]",
"[",
"f",
"]",
")",
"except",
"StandardError",
",",
"e",
":",
"raise",
"ValueError",
"(",
"'Unable to add filter %r: %s'",
"%",
"(",
"f",
",",
"e",
")",
")"
] |
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/logging/config.py#L672-L678
|
||
MongoEngine/mongoengine
|
8af88780370920389a9436682c5029f32d888631
|
mongoengine/queryset/base.py
|
python
|
BaseQuerySet.limit
|
(self, n)
|
return queryset
|
Limit the number of returned documents to `n`. This may also be
achieved using array-slicing syntax (e.g. ``User.objects[:5]``).
:param n: the maximum number of objects to return if n is greater than 0.
When 0 is passed, returns all the documents in the cursor
|
Limit the number of returned documents to `n`. This may also be
achieved using array-slicing syntax (e.g. ``User.objects[:5]``).
|
[
"Limit",
"the",
"number",
"of",
"returned",
"documents",
"to",
"n",
".",
"This",
"may",
"also",
"be",
"achieved",
"using",
"array",
"-",
"slicing",
"syntax",
"(",
"e",
".",
"g",
".",
"User",
".",
"objects",
"[",
":",
"5",
"]",
")",
"."
] |
def limit(self, n):
"""Limit the number of returned documents to `n`. This may also be
achieved using array-slicing syntax (e.g. ``User.objects[:5]``).
:param n: the maximum number of objects to return if n is greater than 0.
When 0 is passed, returns all the documents in the cursor
"""
queryset = self.clone()
queryset._limit = n
queryset._empty = False # cancels the effect of empty
# If a cursor object has already been created, apply the limit to it.
if queryset._cursor_obj:
queryset._cursor_obj.limit(queryset._limit)
return queryset
|
[
"def",
"limit",
"(",
"self",
",",
"n",
")",
":",
"queryset",
"=",
"self",
".",
"clone",
"(",
")",
"queryset",
".",
"_limit",
"=",
"n",
"queryset",
".",
"_empty",
"=",
"False",
"# cancels the effect of empty",
"# If a cursor object has already been created, apply the limit to it.",
"if",
"queryset",
".",
"_cursor_obj",
":",
"queryset",
".",
"_cursor_obj",
".",
"limit",
"(",
"queryset",
".",
"_limit",
")",
"return",
"queryset"
] |
https://github.com/MongoEngine/mongoengine/blob/8af88780370920389a9436682c5029f32d888631/mongoengine/queryset/base.py#L843-L858
|
|
panchunguang/ccks_baidu_entity_link
|
f6eb5298620b460f2f1222a3b182d15c938c4ea2
|
code/ER_ner_bert_crf.py
|
python
|
get_input
|
(input_file)
|
return inputs
|
[] |
def get_input(input_file):
data=pd.read_pickle(input_file)
inputs=[data['ids'],data['seg'],np.expand_dims(data['labels'],axis=-1)]
return inputs
|
[
"def",
"get_input",
"(",
"input_file",
")",
":",
"data",
"=",
"pd",
".",
"read_pickle",
"(",
"input_file",
")",
"inputs",
"=",
"[",
"data",
"[",
"'ids'",
"]",
",",
"data",
"[",
"'seg'",
"]",
",",
"np",
".",
"expand_dims",
"(",
"data",
"[",
"'labels'",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"]",
"return",
"inputs"
] |
https://github.com/panchunguang/ccks_baidu_entity_link/blob/f6eb5298620b460f2f1222a3b182d15c938c4ea2/code/ER_ner_bert_crf.py#L84-L87
|
|||
tudelft3d/Random3Dcity
|
7fbd61bba4685b8a68a51434cb8ce0fb9ede32f5
|
generateCityGML.py
|
python
|
b2s
|
(exts)
|
return surfaces
|
Convert two points of a solid into its bounding box.
(Cube-like solid parallel with axes.)
|
Convert two points of a solid into its bounding box.
(Cube-like solid parallel with axes.)
|
[
"Convert",
"two",
"points",
"of",
"a",
"solid",
"into",
"its",
"bounding",
"box",
".",
"(",
"Cube",
"-",
"like",
"solid",
"parallel",
"with",
"axes",
".",
")"
] |
def b2s(exts):
"""Convert two points of a solid into its bounding box.
(Cube-like solid parallel with axes.)
"""
p0x = exts[0][0]
p0y = exts[0][1]
p0 = str(p0x) + ' ' + str(p0y) + ' ' + '0.0'
p0T = str(p0x) + ' ' + str(p0y) + ' ' + str(exts[1])
p1x = exts[0][2]
p1y = exts[0][3]
p1 = str(p1x) + ' ' + str(p1y) + ' ' + '0.0'
p1T = str(p1x) + ' ' + str(p1y) + ' ' + str(exts[1])
pb = str(p1x) + ' ' + str(p0y) + ' ' + '0.0'
pbT = str(p1x) + ' ' + str(p0y) + ' ' + str(exts[1])
pu = str(p0x) + ' ' + str(p1y) + ' ' + '0.0'
puT = str(p0x) + ' ' + str(p1y) + ' ' + str(exts[1])
surfaces = []
surfaces.append("%s %s %s %s %s" % (p0, pu, p1, pb, p0))
surfaces.append("%s %s %s %s %s" % (p0T, pbT, p1T, puT, p0T))
surfaces.append("%s %s %s %s %s" % (p0, pb, pbT, p0T, p0))
surfaces.append("%s %s %s %s %s" % (pb, p1, p1T, pbT, pb))
surfaces.append("%s %s %s %s %s" % (p1, pu, puT, p1T, p1))
surfaces.append("%s %s %s %s %s" % (pu, p0, p0T, puT, pu))
return surfaces
|
[
"def",
"b2s",
"(",
"exts",
")",
":",
"p0x",
"=",
"exts",
"[",
"0",
"]",
"[",
"0",
"]",
"p0y",
"=",
"exts",
"[",
"0",
"]",
"[",
"1",
"]",
"p0",
"=",
"str",
"(",
"p0x",
")",
"+",
"' '",
"+",
"str",
"(",
"p0y",
")",
"+",
"' '",
"+",
"'0.0'",
"p0T",
"=",
"str",
"(",
"p0x",
")",
"+",
"' '",
"+",
"str",
"(",
"p0y",
")",
"+",
"' '",
"+",
"str",
"(",
"exts",
"[",
"1",
"]",
")",
"p1x",
"=",
"exts",
"[",
"0",
"]",
"[",
"2",
"]",
"p1y",
"=",
"exts",
"[",
"0",
"]",
"[",
"3",
"]",
"p1",
"=",
"str",
"(",
"p1x",
")",
"+",
"' '",
"+",
"str",
"(",
"p1y",
")",
"+",
"' '",
"+",
"'0.0'",
"p1T",
"=",
"str",
"(",
"p1x",
")",
"+",
"' '",
"+",
"str",
"(",
"p1y",
")",
"+",
"' '",
"+",
"str",
"(",
"exts",
"[",
"1",
"]",
")",
"pb",
"=",
"str",
"(",
"p1x",
")",
"+",
"' '",
"+",
"str",
"(",
"p0y",
")",
"+",
"' '",
"+",
"'0.0'",
"pbT",
"=",
"str",
"(",
"p1x",
")",
"+",
"' '",
"+",
"str",
"(",
"p0y",
")",
"+",
"' '",
"+",
"str",
"(",
"exts",
"[",
"1",
"]",
")",
"pu",
"=",
"str",
"(",
"p0x",
")",
"+",
"' '",
"+",
"str",
"(",
"p1y",
")",
"+",
"' '",
"+",
"'0.0'",
"puT",
"=",
"str",
"(",
"p0x",
")",
"+",
"' '",
"+",
"str",
"(",
"p1y",
")",
"+",
"' '",
"+",
"str",
"(",
"exts",
"[",
"1",
"]",
")",
"surfaces",
"=",
"[",
"]",
"surfaces",
".",
"append",
"(",
"\"%s %s %s %s %s\"",
"%",
"(",
"p0",
",",
"pu",
",",
"p1",
",",
"pb",
",",
"p0",
")",
")",
"surfaces",
".",
"append",
"(",
"\"%s %s %s %s %s\"",
"%",
"(",
"p0T",
",",
"pbT",
",",
"p1T",
",",
"puT",
",",
"p0T",
")",
")",
"surfaces",
".",
"append",
"(",
"\"%s %s %s %s %s\"",
"%",
"(",
"p0",
",",
"pb",
",",
"pbT",
",",
"p0T",
",",
"p0",
")",
")",
"surfaces",
".",
"append",
"(",
"\"%s %s %s %s %s\"",
"%",
"(",
"pb",
",",
"p1",
",",
"p1T",
",",
"pbT",
",",
"pb",
")",
")",
"surfaces",
".",
"append",
"(",
"\"%s %s %s %s %s\"",
"%",
"(",
"p1",
",",
"pu",
",",
"puT",
",",
"p1T",
",",
"p1",
")",
")",
"surfaces",
".",
"append",
"(",
"\"%s %s %s %s %s\"",
"%",
"(",
"pu",
",",
"p0",
",",
"p0T",
",",
"puT",
",",
"pu",
")",
")",
"return",
"surfaces"
] |
https://github.com/tudelft3d/Random3Dcity/blob/7fbd61bba4685b8a68a51434cb8ce0fb9ede32f5/generateCityGML.py#L4186-L4213
|
|
openshift/openshift-tools
|
1188778e728a6e4781acf728123e5b356380fe6f
|
ansible/roles/lib_openshift_3.2/library/oc_pvc.py
|
python
|
PersistentVolumeClaim.access_modes
|
(self, data)
|
access_modes property setter
|
access_modes property setter
|
[
"access_modes",
"property",
"setter"
] |
def access_modes(self, data):
''' access_modes property setter'''
self._access_modes = data
|
[
"def",
"access_modes",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_access_modes",
"=",
"data"
] |
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/library/oc_pvc.py#L979-L981
|
||
deanishe/alfred-workflow
|
70d04df5bded8e501ce3bb82fa55ecc1f947f240
|
workflow/update.py
|
python
|
Version.tuple
|
(self)
|
return (self.major, self.minor, self.patch, self.suffix)
|
Version number as a tuple of major, minor, patch, pre-release.
|
Version number as a tuple of major, minor, patch, pre-release.
|
[
"Version",
"number",
"as",
"a",
"tuple",
"of",
"major",
"minor",
"patch",
"pre",
"-",
"release",
"."
] |
def tuple(self):
"""Version number as a tuple of major, minor, patch, pre-release."""
return (self.major, self.minor, self.patch, self.suffix)
|
[
"def",
"tuple",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"major",
",",
"self",
".",
"minor",
",",
"self",
".",
"patch",
",",
"self",
".",
"suffix",
")"
] |
https://github.com/deanishe/alfred-workflow/blob/70d04df5bded8e501ce3bb82fa55ecc1f947f240/workflow/update.py#L285-L287
|
|
Suor/sublime-reform
|
605c240501d7ff9e38c38ec4a3a9c37d11561776
|
funcy.py
|
python
|
iffy
|
(pred, action=EMPTY, default=identity)
|
[] |
def iffy(pred, action=EMPTY, default=identity):
if action is EMPTY:
return iffy(bool, pred)
else:
return lambda v: action(v) if pred(v) else \
default(v) if callable(default) else \
default
|
[
"def",
"iffy",
"(",
"pred",
",",
"action",
"=",
"EMPTY",
",",
"default",
"=",
"identity",
")",
":",
"if",
"action",
"is",
"EMPTY",
":",
"return",
"iffy",
"(",
"bool",
",",
"pred",
")",
"else",
":",
"return",
"lambda",
"v",
":",
"action",
"(",
"v",
")",
"if",
"pred",
"(",
"v",
")",
"else",
"default",
"(",
"v",
")",
"if",
"callable",
"(",
"default",
")",
"else",
"default"
] |
https://github.com/Suor/sublime-reform/blob/605c240501d7ff9e38c38ec4a3a9c37d11561776/funcy.py#L122-L128
|
||||
fooof-tools/fooof
|
14d6196e0b60c7e6da95b5cf858b20adcc5fc0ac
|
fooof/core/strings.py
|
python
|
_format
|
(str_lst, concise)
|
return output
|
Format a string for printing.
Parameters
----------
str_lst : list of str
List containing all elements for the string, each element representing a line.
concise : bool, optional, default: False
Whether to print the report in a concise mode, or not.
Returns
-------
output : str
Formatted string, ready for printing.
|
Format a string for printing.
|
[
"Format",
"a",
"string",
"for",
"printing",
"."
] |
def _format(str_lst, concise):
"""Format a string for printing.
Parameters
----------
str_lst : list of str
List containing all elements for the string, each element representing a line.
concise : bool, optional, default: False
Whether to print the report in a concise mode, or not.
Returns
-------
output : str
Formatted string, ready for printing.
"""
# Set centering value - use a smaller value if in concise mode
center_val = SCV if concise else LCV
# Expand the section markers to full width
str_lst[0] = str_lst[0] * center_val
str_lst[-1] = str_lst[-1] * center_val
# Drop blank lines, if concise
str_lst = list(filter(lambda x: x != '', str_lst)) if concise else str_lst
# Convert list to a single string representation, centering each line
output = '\n'.join([string.center(center_val) for string in str_lst])
return output
|
[
"def",
"_format",
"(",
"str_lst",
",",
"concise",
")",
":",
"# Set centering value - use a smaller value if in concise mode",
"center_val",
"=",
"SCV",
"if",
"concise",
"else",
"LCV",
"# Expand the section markers to full width",
"str_lst",
"[",
"0",
"]",
"=",
"str_lst",
"[",
"0",
"]",
"*",
"center_val",
"str_lst",
"[",
"-",
"1",
"]",
"=",
"str_lst",
"[",
"-",
"1",
"]",
"*",
"center_val",
"# Drop blank lines, if concise",
"str_lst",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"!=",
"''",
",",
"str_lst",
")",
")",
"if",
"concise",
"else",
"str_lst",
"# Convert list to a single string representation, centering each line",
"output",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"string",
".",
"center",
"(",
"center_val",
")",
"for",
"string",
"in",
"str_lst",
"]",
")",
"return",
"output"
] |
https://github.com/fooof-tools/fooof/blob/14d6196e0b60c7e6da95b5cf858b20adcc5fc0ac/fooof/core/strings.py#L467-L496
|
|
huggingface/transformers
|
623b4f7c63f60cce917677ee704d6c93ee960b4b
|
src/transformers/models/xlnet/modeling_tf_xlnet.py
|
python
|
TFXLNetLayer.call
|
(
self,
output_h,
output_g,
non_tgt_mask,
attn_mask,
pos_emb,
seg_mat,
mems,
target_mapping,
head_mask,
output_attentions,
training=False,
)
|
return outputs
|
[] |
def call(
self,
output_h,
output_g,
non_tgt_mask,
attn_mask,
pos_emb,
seg_mat,
mems,
target_mapping,
head_mask,
output_attentions,
training=False,
):
outputs = self.rel_attn(
output_h,
output_g,
non_tgt_mask,
attn_mask,
pos_emb,
seg_mat,
mems,
target_mapping,
head_mask,
output_attentions,
training=training,
)
output_h, output_g = outputs[:2]
if output_g is not None:
output_g = self.ff(output_g, training=training)
output_h = self.ff(output_h, training=training)
outputs = (output_h, output_g) + outputs[2:] # Add again attentions if there are there
return outputs
|
[
"def",
"call",
"(",
"self",
",",
"output_h",
",",
"output_g",
",",
"non_tgt_mask",
",",
"attn_mask",
",",
"pos_emb",
",",
"seg_mat",
",",
"mems",
",",
"target_mapping",
",",
"head_mask",
",",
"output_attentions",
",",
"training",
"=",
"False",
",",
")",
":",
"outputs",
"=",
"self",
".",
"rel_attn",
"(",
"output_h",
",",
"output_g",
",",
"non_tgt_mask",
",",
"attn_mask",
",",
"pos_emb",
",",
"seg_mat",
",",
"mems",
",",
"target_mapping",
",",
"head_mask",
",",
"output_attentions",
",",
"training",
"=",
"training",
",",
")",
"output_h",
",",
"output_g",
"=",
"outputs",
"[",
":",
"2",
"]",
"if",
"output_g",
"is",
"not",
"None",
":",
"output_g",
"=",
"self",
".",
"ff",
"(",
"output_g",
",",
"training",
"=",
"training",
")",
"output_h",
"=",
"self",
".",
"ff",
"(",
"output_h",
",",
"training",
"=",
"training",
")",
"outputs",
"=",
"(",
"output_h",
",",
"output_g",
")",
"+",
"outputs",
"[",
"2",
":",
"]",
"# Add again attentions if there are there",
"return",
"outputs"
] |
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/xlnet/modeling_tf_xlnet.py#L363-L397
|
|||
pupil-labs/pupil
|
a712f94c9f38afddd64c841362e167b8ce293769
|
pupil_src/shared_modules/video_overlay/utils/image_manipulation.py
|
python
|
HorizontalFlip.apply_to
|
(self, image, parameter, *, is_fake_frame, **kwargs)
|
parameter: boolean indicating if image should be flipped
|
parameter: boolean indicating if image should be flipped
|
[
"parameter",
":",
"boolean",
"indicating",
"if",
"image",
"should",
"be",
"flipped"
] |
def apply_to(self, image, parameter, *, is_fake_frame, **kwargs):
"""parameter: boolean indicating if image should be flipped"""
if parameter and not is_fake_frame:
return np.fliplr(image)
else:
return image
|
[
"def",
"apply_to",
"(",
"self",
",",
"image",
",",
"parameter",
",",
"*",
",",
"is_fake_frame",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"parameter",
"and",
"not",
"is_fake_frame",
":",
"return",
"np",
".",
"fliplr",
"(",
"image",
")",
"else",
":",
"return",
"image"
] |
https://github.com/pupil-labs/pupil/blob/a712f94c9f38afddd64c841362e167b8ce293769/pupil_src/shared_modules/video_overlay/utils/image_manipulation.py#L40-L45
|
||
SteveDoyle2/pyNastran
|
eda651ac2d4883d95a34951f8a002ff94f642a1a
|
pyNastran/gui/utils/qt/checks/qlineedit.py
|
python
|
check_name_length
|
(cell)
|
Verifies that the string has at least 1 non-whitespace character.
Parameters
----------
cell : QLineEdit
a QLineEdit containing a string.
|
Verifies that the string has at least 1 non-whitespace character.
|
[
"Verifies",
"that",
"the",
"string",
"has",
"at",
"least",
"1",
"non",
"-",
"whitespace",
"character",
"."
] |
def check_name_length(cell):
"""
Verifies that the string has at least 1 non-whitespace character.
Parameters
----------
cell : QLineEdit
a QLineEdit containing a string.
"""
cell_value = cell.text()
text = cell_value.strip()
if len(text):
cell.setStyleSheet("QLineEdit{background: white;}")
return text, True
else:
cell.setStyleSheet("QLineEdit{background: red;}")
return None, False
|
[
"def",
"check_name_length",
"(",
"cell",
")",
":",
"cell_value",
"=",
"cell",
".",
"text",
"(",
")",
"text",
"=",
"cell_value",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"text",
")",
":",
"cell",
".",
"setStyleSheet",
"(",
"\"QLineEdit{background: white;}\"",
")",
"return",
"text",
",",
"True",
"else",
":",
"cell",
".",
"setStyleSheet",
"(",
"\"QLineEdit{background: red;}\"",
")",
"return",
"None",
",",
"False"
] |
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/gui/utils/qt/checks/qlineedit.py#L176-L193
|
||
MalloyDelacroix/DownloaderForReddit
|
e2547a6d1f119b31642445e64cb21f4568ce4012
|
DownloaderForReddit/extractors/base_extractor.py
|
python
|
BaseExtractor.get_url_key
|
(cls)
|
return cls.url_key
|
Returns the url_key that each subclass must contain. The url_key is used to indicate keywords that are domain
specific. The url_key must be so that if the extractor finds the key in a supplied url, the extractor object
to which the key belongs can be selected to perform the link extraction.
:return: A key that that if found in a url means this extractor is selected to be used for link extraction.
:rtype: str
|
Returns the url_key that each subclass must contain. The url_key is used to indicate keywords that are domain
specific. The url_key must be so that if the extractor finds the key in a supplied url, the extractor object
to which the key belongs can be selected to perform the link extraction.
:return: A key that that if found in a url means this extractor is selected to be used for link extraction.
:rtype: str
|
[
"Returns",
"the",
"url_key",
"that",
"each",
"subclass",
"must",
"contain",
".",
"The",
"url_key",
"is",
"used",
"to",
"indicate",
"keywords",
"that",
"are",
"domain",
"specific",
".",
"The",
"url_key",
"must",
"be",
"so",
"that",
"if",
"the",
"extractor",
"finds",
"the",
"key",
"in",
"a",
"supplied",
"url",
"the",
"extractor",
"object",
"to",
"which",
"the",
"key",
"belongs",
"can",
"be",
"selected",
"to",
"perform",
"the",
"link",
"extraction",
".",
":",
"return",
":",
"A",
"key",
"that",
"that",
"if",
"found",
"in",
"a",
"url",
"means",
"this",
"extractor",
"is",
"selected",
"to",
"be",
"used",
"for",
"link",
"extraction",
".",
":",
"rtype",
":",
"str"
] |
def get_url_key(cls):
"""
Returns the url_key that each subclass must contain. The url_key is used to indicate keywords that are domain
specific. The url_key must be so that if the extractor finds the key in a supplied url, the extractor object
to which the key belongs can be selected to perform the link extraction.
:return: A key that that if found in a url means this extractor is selected to be used for link extraction.
:rtype: str
"""
return cls.url_key
|
[
"def",
"get_url_key",
"(",
"cls",
")",
":",
"return",
"cls",
".",
"url_key"
] |
https://github.com/MalloyDelacroix/DownloaderForReddit/blob/e2547a6d1f119b31642445e64cb21f4568ce4012/DownloaderForReddit/extractors/base_extractor.py#L70-L78
|
|
asyml/texar
|
a23f021dae289a3d768dc099b220952111da04fd
|
examples/transformer/utils/preprocess.py
|
python
|
get_preprocess_args
|
()
|
return config
|
Data preprocessing options.
|
Data preprocessing options.
|
[
"Data",
"preprocessing",
"options",
"."
] |
def get_preprocess_args():
"""Data preprocessing options."""
class Config():
pass
config = Config()
parser = argparse.ArgumentParser(description='Preprocessing Options')
parser.add_argument('--source_vocab', type=int, default=40000,
help='Vocabulary size of source language')
parser.add_argument('--target_vocab', type=int, default=40000,
help='Vocabulary size of target language')
parser.add_argument('--tok', dest='tok', action='store_true',
help='tokenized and lowercased')
parser.set_defaults(tok=False)
parser.add_argument('--max_seq_length', type=int, default=70)
parser.add_argument('--pre_encoding', type=str, default='spm')
parser.add_argument('--src', type=str, default='en')
parser.add_argument('--tgt', type=str, default='vi')
parser.add_argument('--input_dir', '-i', type=str,
default='./data/en_vi/data/', help='Input directory')
parser.add_argument('--save_data', type=str, default='preprocess',
help='Output file for the prepared data')
parser.parse_args(namespace=config)
# keep consistent with original implementation
# pylint:disable=attribute-defined-outside-init
config.input = config.input_dir
config.source_train = 'train.' + config.src
config.target_train = 'train.' + config.tgt
config.source_valid = 'valid.' + config.src
config.target_valid = 'valid.' + config.tgt
config.source_test = 'test.' + config.src
config.target_test = 'test.' + config.tgt
return config
|
[
"def",
"get_preprocess_args",
"(",
")",
":",
"class",
"Config",
"(",
")",
":",
"pass",
"config",
"=",
"Config",
"(",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Preprocessing Options'",
")",
"parser",
".",
"add_argument",
"(",
"'--source_vocab'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"40000",
",",
"help",
"=",
"'Vocabulary size of source language'",
")",
"parser",
".",
"add_argument",
"(",
"'--target_vocab'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"40000",
",",
"help",
"=",
"'Vocabulary size of target language'",
")",
"parser",
".",
"add_argument",
"(",
"'--tok'",
",",
"dest",
"=",
"'tok'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'tokenized and lowercased'",
")",
"parser",
".",
"set_defaults",
"(",
"tok",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'--max_seq_length'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"70",
")",
"parser",
".",
"add_argument",
"(",
"'--pre_encoding'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'spm'",
")",
"parser",
".",
"add_argument",
"(",
"'--src'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'en'",
")",
"parser",
".",
"add_argument",
"(",
"'--tgt'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'vi'",
")",
"parser",
".",
"add_argument",
"(",
"'--input_dir'",
",",
"'-i'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'./data/en_vi/data/'",
",",
"help",
"=",
"'Input directory'",
")",
"parser",
".",
"add_argument",
"(",
"'--save_data'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'preprocess'",
",",
"help",
"=",
"'Output file for the prepared data'",
")",
"parser",
".",
"parse_args",
"(",
"namespace",
"=",
"config",
")",
"# keep consistent with original implementation",
"# pylint:disable=attribute-defined-outside-init",
"config",
".",
"input",
"=",
"config",
".",
"input_dir",
"config",
".",
"source_train",
"=",
"'train.'",
"+",
"config",
".",
"src",
"config",
".",
"target_train",
"=",
"'train.'",
"+",
"config",
".",
"tgt",
"config",
".",
"source_valid",
"=",
"'valid.'",
"+",
"config",
".",
"src",
"config",
".",
"target_valid",
"=",
"'valid.'",
"+",
"config",
".",
"tgt",
"config",
".",
"source_test",
"=",
"'test.'",
"+",
"config",
".",
"src",
"config",
".",
"target_test",
"=",
"'test.'",
"+",
"config",
".",
"tgt",
"return",
"config"
] |
https://github.com/asyml/texar/blob/a23f021dae289a3d768dc099b220952111da04fd/examples/transformer/utils/preprocess.py#L98-L130
|
|
Tautulli/Tautulli
|
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
|
lib/pyparsing/core.py
|
python
|
MatchFirst.__init__
|
(self, exprs: IterableType[ParserElement], savelist: bool = False)
|
[] |
def __init__(self, exprs: IterableType[ParserElement], savelist: bool = False):
super().__init__(exprs, savelist)
if self.exprs:
self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)
else:
self.mayReturnEmpty = True
|
[
"def",
"__init__",
"(",
"self",
",",
"exprs",
":",
"IterableType",
"[",
"ParserElement",
"]",
",",
"savelist",
":",
"bool",
"=",
"False",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"exprs",
",",
"savelist",
")",
"if",
"self",
".",
"exprs",
":",
"self",
".",
"mayReturnEmpty",
"=",
"any",
"(",
"e",
".",
"mayReturnEmpty",
"for",
"e",
"in",
"self",
".",
"exprs",
")",
"self",
".",
"skipWhitespace",
"=",
"all",
"(",
"e",
".",
"skipWhitespace",
"for",
"e",
"in",
"self",
".",
"exprs",
")",
"else",
":",
"self",
".",
"mayReturnEmpty",
"=",
"True"
] |
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/pyparsing/core.py#L4046-L4052
|
||||
SymbiFlow/symbiflow-arch-defs
|
f38793112ff78a06de9f1e3269bd22543e29729f
|
xc/common/utils/prjxray_form_channels.py
|
python
|
traverse_pip
|
(conn, wire_in_tile_pkey)
|
return None
|
Given a generic wire, find (if any) the wire on the other side of a pip.
Returns None if no wire or pip connects to this wire.
|
Given a generic wire, find (if any) the wire on the other side of a pip.
|
[
"Given",
"a",
"generic",
"wire",
"find",
"(",
"if",
"any",
")",
"the",
"wire",
"on",
"the",
"other",
"side",
"of",
"a",
"pip",
"."
] |
def traverse_pip(conn, wire_in_tile_pkey):
""" Given a generic wire, find (if any) the wire on the other side of a pip.
Returns None if no wire or pip connects to this wire.
"""
cur = conn.cursor()
cur.execute(
"""
SELECT src_wire_in_tile_pkey FROM pip_in_tile WHERE
is_pseudo = 0 AND
dest_wire_in_tile_pkey = ?
;""", (wire_in_tile_pkey, )
)
result = cur.fetchone()
if result is not None:
return result[0]
cur.execute(
"""
SELECT dest_wire_in_tile_pkey FROM pip_in_tile WHERE
is_pseudo = 0 AND
src_wire_in_tile_pkey = ?
;""", (wire_in_tile_pkey, )
)
result = cur.fetchone()
if result is not None:
return result[0]
return None
|
[
"def",
"traverse_pip",
"(",
"conn",
",",
"wire_in_tile_pkey",
")",
":",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"\"\"\"\nSELECT src_wire_in_tile_pkey FROM pip_in_tile WHERE\n is_pseudo = 0 AND\n dest_wire_in_tile_pkey = ?\n ;\"\"\"",
",",
"(",
"wire_in_tile_pkey",
",",
")",
")",
"result",
"=",
"cur",
".",
"fetchone",
"(",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"[",
"0",
"]",
"cur",
".",
"execute",
"(",
"\"\"\"\nSELECT dest_wire_in_tile_pkey FROM pip_in_tile WHERE\n is_pseudo = 0 AND\n src_wire_in_tile_pkey = ?\n ;\"\"\"",
",",
"(",
"wire_in_tile_pkey",
",",
")",
")",
"result",
"=",
"cur",
".",
"fetchone",
"(",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"[",
"0",
"]",
"return",
"None"
] |
https://github.com/SymbiFlow/symbiflow-arch-defs/blob/f38793112ff78a06de9f1e3269bd22543e29729f/xc/common/utils/prjxray_form_channels.py#L1605-L1637
|
|
google/qkeras
|
e0faa69b3a3d99850b06c5793e6831b7d9b83306
|
qkeras/autoqkeras/autoqkeras_internal.py
|
python
|
AutoQKHyperModel._adjust_limit
|
(self, default)
|
Makes sure limit has all the fields required.
|
Makes sure limit has all the fields required.
|
[
"Makes",
"sure",
"limit",
"has",
"all",
"the",
"fields",
"required",
"."
] |
def _adjust_limit(self, default):
"""Makes sure limit has all the fields required."""
if isinstance(default, list):
assert 3 <= len(default) <= 4
else:
default = [default] * 3
# we consider that if name is not there, we will ignore the layer
for name in REGISTERED_LAYERS:
if name in self.limit:
length = len(self.limit[name])
if length < 4 and name in SEQUENCE_LAYERS:
assert len(default) == 4
self.limit[name] = self.limit[name] + default[length:]
elif length < 3:
# No recurrent limit needed for non recurrent layers
self.limit[name] = self.limit[name] + default[length:2] + default[-1:]
|
[
"def",
"_adjust_limit",
"(",
"self",
",",
"default",
")",
":",
"if",
"isinstance",
"(",
"default",
",",
"list",
")",
":",
"assert",
"3",
"<=",
"len",
"(",
"default",
")",
"<=",
"4",
"else",
":",
"default",
"=",
"[",
"default",
"]",
"*",
"3",
"# we consider that if name is not there, we will ignore the layer",
"for",
"name",
"in",
"REGISTERED_LAYERS",
":",
"if",
"name",
"in",
"self",
".",
"limit",
":",
"length",
"=",
"len",
"(",
"self",
".",
"limit",
"[",
"name",
"]",
")",
"if",
"length",
"<",
"4",
"and",
"name",
"in",
"SEQUENCE_LAYERS",
":",
"assert",
"len",
"(",
"default",
")",
"==",
"4",
"self",
".",
"limit",
"[",
"name",
"]",
"=",
"self",
".",
"limit",
"[",
"name",
"]",
"+",
"default",
"[",
"length",
":",
"]",
"elif",
"length",
"<",
"3",
":",
"# No recurrent limit needed for non recurrent layers",
"self",
".",
"limit",
"[",
"name",
"]",
"=",
"self",
".",
"limit",
"[",
"name",
"]",
"+",
"default",
"[",
"length",
":",
"2",
"]",
"+",
"default",
"[",
"-",
"1",
":",
"]"
] |
https://github.com/google/qkeras/blob/e0faa69b3a3d99850b06c5793e6831b7d9b83306/qkeras/autoqkeras/autoqkeras_internal.py#L178-L194
|
||
open-cogsci/OpenSesame
|
c4a3641b097a80a76937edbd8c365f036bcc9705
|
libqtopensesame/items/feedpad.py
|
python
|
feedpad.init_edit_widget
|
(self)
|
desc:
Initializes the widget.
|
desc:
Initializes the widget.
|
[
"desc",
":",
"Initializes",
"the",
"widget",
"."
] |
def init_edit_widget(self):
"""
desc:
Initializes the widget.
"""
qtplugin.init_edit_widget(self, False)
self.canvas = sketchpad_canvas(self)
self.sketchpad_widget = sketchpad_widget(self)
self.add_widget(self.sketchpad_widget)
self.auto_add_widget(self.sketchpad_widget.ui.edit_duration,
u'duration')
self.sketchpad_widget.ui.edit_duration.setValidator(
duration_validator(self))
self.first_refresh = True
self._lock = False
|
[
"def",
"init_edit_widget",
"(",
"self",
")",
":",
"qtplugin",
".",
"init_edit_widget",
"(",
"self",
",",
"False",
")",
"self",
".",
"canvas",
"=",
"sketchpad_canvas",
"(",
"self",
")",
"self",
".",
"sketchpad_widget",
"=",
"sketchpad_widget",
"(",
"self",
")",
"self",
".",
"add_widget",
"(",
"self",
".",
"sketchpad_widget",
")",
"self",
".",
"auto_add_widget",
"(",
"self",
".",
"sketchpad_widget",
".",
"ui",
".",
"edit_duration",
",",
"u'duration'",
")",
"self",
".",
"sketchpad_widget",
".",
"ui",
".",
"edit_duration",
".",
"setValidator",
"(",
"duration_validator",
"(",
"self",
")",
")",
"self",
".",
"first_refresh",
"=",
"True",
"self",
".",
"_lock",
"=",
"False"
] |
https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/libqtopensesame/items/feedpad.py#L37-L53
|
||
home-assistant/core
|
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
|
homeassistant/helpers/script.py
|
python
|
trace_action
|
(hass, script_run, stop, variables)
|
Trace action execution.
|
Trace action execution.
|
[
"Trace",
"action",
"execution",
"."
] |
async def trace_action(hass, script_run, stop, variables):
"""Trace action execution."""
path = trace_path_get()
trace_element = action_trace_append(variables, path)
trace_stack_push(trace_stack_cv, trace_element)
trace_id = trace_id_get()
if trace_id:
key = trace_id[0]
run_id = trace_id[1]
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
if key in breakpoints and (
(
run_id in breakpoints[key]
and (
path in breakpoints[key][run_id]
or NODE_ANY in breakpoints[key][run_id]
)
)
or (
RUN_ID_ANY in breakpoints[key]
and (
path in breakpoints[key][RUN_ID_ANY]
or NODE_ANY in breakpoints[key][RUN_ID_ANY]
)
)
):
async_dispatcher_send(hass, SCRIPT_BREAKPOINT_HIT, key, run_id, path)
done = asyncio.Event()
@callback
def async_continue_stop(command=None):
if command == "stop":
stop.set()
done.set()
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
remove_signal1 = async_dispatcher_connect(hass, signal, async_continue_stop)
remove_signal2 = async_dispatcher_connect(
hass, SCRIPT_DEBUG_CONTINUE_ALL, async_continue_stop
)
tasks = [hass.async_create_task(flag.wait()) for flag in (stop, done)]
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in tasks:
task.cancel()
remove_signal1()
remove_signal2()
try:
yield trace_element
except _StopScript as ex:
trace_element.set_error(ex.__cause__ or ex)
raise ex
except Exception as ex:
trace_element.set_error(ex)
raise ex
finally:
trace_stack_pop(trace_stack_cv)
|
[
"async",
"def",
"trace_action",
"(",
"hass",
",",
"script_run",
",",
"stop",
",",
"variables",
")",
":",
"path",
"=",
"trace_path_get",
"(",
")",
"trace_element",
"=",
"action_trace_append",
"(",
"variables",
",",
"path",
")",
"trace_stack_push",
"(",
"trace_stack_cv",
",",
"trace_element",
")",
"trace_id",
"=",
"trace_id_get",
"(",
")",
"if",
"trace_id",
":",
"key",
"=",
"trace_id",
"[",
"0",
"]",
"run_id",
"=",
"trace_id",
"[",
"1",
"]",
"breakpoints",
"=",
"hass",
".",
"data",
"[",
"DATA_SCRIPT_BREAKPOINTS",
"]",
"if",
"key",
"in",
"breakpoints",
"and",
"(",
"(",
"run_id",
"in",
"breakpoints",
"[",
"key",
"]",
"and",
"(",
"path",
"in",
"breakpoints",
"[",
"key",
"]",
"[",
"run_id",
"]",
"or",
"NODE_ANY",
"in",
"breakpoints",
"[",
"key",
"]",
"[",
"run_id",
"]",
")",
")",
"or",
"(",
"RUN_ID_ANY",
"in",
"breakpoints",
"[",
"key",
"]",
"and",
"(",
"path",
"in",
"breakpoints",
"[",
"key",
"]",
"[",
"RUN_ID_ANY",
"]",
"or",
"NODE_ANY",
"in",
"breakpoints",
"[",
"key",
"]",
"[",
"RUN_ID_ANY",
"]",
")",
")",
")",
":",
"async_dispatcher_send",
"(",
"hass",
",",
"SCRIPT_BREAKPOINT_HIT",
",",
"key",
",",
"run_id",
",",
"path",
")",
"done",
"=",
"asyncio",
".",
"Event",
"(",
")",
"@",
"callback",
"def",
"async_continue_stop",
"(",
"command",
"=",
"None",
")",
":",
"if",
"command",
"==",
"\"stop\"",
":",
"stop",
".",
"set",
"(",
")",
"done",
".",
"set",
"(",
")",
"signal",
"=",
"SCRIPT_DEBUG_CONTINUE_STOP",
".",
"format",
"(",
"key",
",",
"run_id",
")",
"remove_signal1",
"=",
"async_dispatcher_connect",
"(",
"hass",
",",
"signal",
",",
"async_continue_stop",
")",
"remove_signal2",
"=",
"async_dispatcher_connect",
"(",
"hass",
",",
"SCRIPT_DEBUG_CONTINUE_ALL",
",",
"async_continue_stop",
")",
"tasks",
"=",
"[",
"hass",
".",
"async_create_task",
"(",
"flag",
".",
"wait",
"(",
")",
")",
"for",
"flag",
"in",
"(",
"stop",
",",
"done",
")",
"]",
"await",
"asyncio",
".",
"wait",
"(",
"tasks",
",",
"return_when",
"=",
"asyncio",
".",
"FIRST_COMPLETED",
")",
"for",
"task",
"in",
"tasks",
":",
"task",
".",
"cancel",
"(",
")",
"remove_signal1",
"(",
")",
"remove_signal2",
"(",
")",
"try",
":",
"yield",
"trace_element",
"except",
"_StopScript",
"as",
"ex",
":",
"trace_element",
".",
"set_error",
"(",
"ex",
".",
"__cause__",
"or",
"ex",
")",
"raise",
"ex",
"except",
"Exception",
"as",
"ex",
":",
"trace_element",
".",
"set_error",
"(",
"ex",
")",
"raise",
"ex",
"finally",
":",
"trace_stack_pop",
"(",
"trace_stack_cv",
")"
] |
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/script.py#L137-L196
|
||
zhl2008/awd-platform
|
0416b31abea29743387b10b3914581fbe8e7da5e
|
web_flaskbb/Python-2.7.9/Lib/optparse.py
|
python
|
OptionParser._get_args
|
(self, args)
|
[] |
def _get_args(self, args):
if args is None:
return sys.argv[1:]
else:
return args[:]
|
[
"def",
"_get_args",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
"is",
"None",
":",
"return",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"else",
":",
"return",
"args",
"[",
":",
"]"
] |
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/optparse.py#L1362-L1366
|
||||
mupen64plus/mupen64plus-ui-python
|
e24679436a93e8aae0aa664dc4b2dea40d8236c1
|
src/m64py/core/vidext.py
|
python
|
Video.quit
|
(self)
|
return M64ERR_SUCCESS
|
Shuts down the video system.
|
Shuts down the video system.
|
[
"Shuts",
"down",
"the",
"video",
"system",
"."
] |
def quit(self):
"""Shuts down the video system."""
if self.glcontext:
self.glcontext.doneCurrent()
self.glcontext = None
return M64ERR_SUCCESS
|
[
"def",
"quit",
"(",
"self",
")",
":",
"if",
"self",
".",
"glcontext",
":",
"self",
".",
"glcontext",
".",
"doneCurrent",
"(",
")",
"self",
".",
"glcontext",
"=",
"None",
"return",
"M64ERR_SUCCESS"
] |
https://github.com/mupen64plus/mupen64plus-ui-python/blob/e24679436a93e8aae0aa664dc4b2dea40d8236c1/src/m64py/core/vidext.py#L75-L80
|
|
hasegaw/IkaLog
|
bd476da541fcc296f792d4db76a6b9174c4777ad
|
ikalog/outputs/twitter.py
|
python
|
Twitter.check_import
|
(self)
|
[] |
def check_import(self):
try:
from requests_oauthlib import OAuth1Session
except:
print("モジュール requests_oauthlib がロードできませんでした。 Twitter 投稿ができません。")
print("インストールするには以下のコマンドを利用してください。\n pip install requests_oauthlib\n")
|
[
"def",
"check_import",
"(",
"self",
")",
":",
"try",
":",
"from",
"requests_oauthlib",
"import",
"OAuth1Session",
"except",
":",
"print",
"(",
"\"モジュール requests_oauthlib がロードできませんでした。 Twitter 投稿ができません。\")",
"",
"print",
"(",
"\"インストールするには以下のコマンドを利用してください。\\n pip install requests_oauthlib\\n\")",
""
] |
https://github.com/hasegaw/IkaLog/blob/bd476da541fcc296f792d4db76a6b9174c4777ad/ikalog/outputs/twitter.py#L540-L545
|
||||
osmr/imgclsmob
|
f2993d3ce73a2f7ddba05da3891defb08547d504
|
tensorflow2/tf2cv/models/fastseresnet.py
|
python
|
fastseresnet101b
|
(**kwargs)
|
return get_fastseresnet(blocks=101, conv1_stride=False, model_name="fastseresnet101b", **kwargs)
|
Fast-SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tensorflow/models'
Location for keeping the model parameters.
|
Fast-SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
|
[
"Fast",
"-",
"SE",
"-",
"ResNet",
"-",
"101",
"model",
"with",
"stride",
"at",
"the",
"second",
"convolution",
"in",
"bottleneck",
"block",
"from",
"Squeeze",
"-",
"and",
"-",
"Excitation",
"Networks",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1709",
".",
"01507",
"."
] |
def fastseresnet101b(**kwargs):
"""
Fast-SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tensorflow/models'
Location for keeping the model parameters.
"""
return get_fastseresnet(blocks=101, conv1_stride=False, model_name="fastseresnet101b", **kwargs)
|
[
"def",
"fastseresnet101b",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"get_fastseresnet",
"(",
"blocks",
"=",
"101",
",",
"conv1_stride",
"=",
"False",
",",
"model_name",
"=",
"\"fastseresnet101b\"",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/tensorflow2/tf2cv/models/fastseresnet.py#L269-L281
|
|
scanlime/coastermelt
|
dd9a536a6928424a5f479fd9e6b5476e34763c06
|
backdoor/dump.py
|
python
|
read_block
|
(d, address, size, max_round_trips = None, fast = False, addr_space = 'arm')
|
return read_word_aligned_block(d, word_address, word_size,
max_round_trips=max_round_trips, fast=fast, addr_space=addr_space
)[sub_begin:sub_end]
|
Read a block of memory, return it as a string.
Reads using LDR (word-aligned) reads only. The requested block
does not need to be aligned.
If max_round_trips is set, we stop after that many round-trip
commands to the device. This can be used for real-time applications
where it may be better to have some data soon than all the data later.
If 'fast' is set, this uses a much faster DMA-based approach that probably
doesn't work in all cases.
|
Read a block of memory, return it as a string.
|
[
"Read",
"a",
"block",
"of",
"memory",
"return",
"it",
"as",
"a",
"string",
"."
] |
def read_block(d, address, size, max_round_trips = None, fast = False, addr_space = 'arm'):
"""Read a block of memory, return it as a string.
Reads using LDR (word-aligned) reads only. The requested block
does not need to be aligned.
If max_round_trips is set, we stop after that many round-trip
commands to the device. This can be used for real-time applications
where it may be better to have some data soon than all the data later.
If 'fast' is set, this uses a much faster DMA-based approach that probably
doesn't work in all cases.
"""
# Convert to half-open interval [address, end)
# Round beginning of interval down to nearest word
# Round end of interval up to nearest word
end = address + size
word_address = address & ~3
word_end = (end + 3) & ~3
word_size = word_end - word_address
# Where in the larger interval is our original block?
sub_begin = address - word_address
sub_end = sub_begin + size
return read_word_aligned_block(d, word_address, word_size,
max_round_trips=max_round_trips, fast=fast, addr_space=addr_space
)[sub_begin:sub_end]
|
[
"def",
"read_block",
"(",
"d",
",",
"address",
",",
"size",
",",
"max_round_trips",
"=",
"None",
",",
"fast",
"=",
"False",
",",
"addr_space",
"=",
"'arm'",
")",
":",
"# Convert to half-open interval [address, end)",
"# Round beginning of interval down to nearest word",
"# Round end of interval up to nearest word",
"end",
"=",
"address",
"+",
"size",
"word_address",
"=",
"address",
"&",
"~",
"3",
"word_end",
"=",
"(",
"end",
"+",
"3",
")",
"&",
"~",
"3",
"word_size",
"=",
"word_end",
"-",
"word_address",
"# Where in the larger interval is our original block?",
"sub_begin",
"=",
"address",
"-",
"word_address",
"sub_end",
"=",
"sub_begin",
"+",
"size",
"return",
"read_word_aligned_block",
"(",
"d",
",",
"word_address",
",",
"word_size",
",",
"max_round_trips",
"=",
"max_round_trips",
",",
"fast",
"=",
"fast",
",",
"addr_space",
"=",
"addr_space",
")",
"[",
"sub_begin",
":",
"sub_end",
"]"
] |
https://github.com/scanlime/coastermelt/blob/dd9a536a6928424a5f479fd9e6b5476e34763c06/backdoor/dump.py#L160-L188
|
|
aws/aws-sam-cli
|
2aa7bf01b2e0b0864ef63b1898a8b30577443acc
|
samcli/lib/providers/sam_stack_provider.py
|
python
|
SamLocalStackProvider.get_stacks
|
(
template_file: str,
stack_path: str = "",
name: str = "",
parameter_overrides: Optional[Dict] = None,
global_parameter_overrides: Optional[Dict] = None,
metadata: Optional[Dict] = None,
)
|
return stacks, remote_stack_full_paths
|
Recursively extract stacks from a template file.
Parameters
----------
template_file: str
the file path of the template to extract stacks from
stack_path: str
the stack path of the parent stack, for root stack, it is ""
name: str
the name of the stack associated with the template_file, for root stack, it is ""
parameter_overrides: Optional[Dict]
Optional dictionary of values for SAM template parameters that might want
to get substituted within the template
global_parameter_overrides: Optional[Dict]
Optional dictionary of values for SAM template global parameters
that might want to get substituted within the template and its child templates
metadata: Optional[Dict]
Optional dictionary of nested stack resource metadata values.
Returns
-------
stacks: List[Stack]
The list of stacks extracted from template_file
remote_stack_full_paths : List[str]
The list of full paths of detected remote stacks
|
Recursively extract stacks from a template file.
|
[
"Recursively",
"extract",
"stacks",
"from",
"a",
"template",
"file",
"."
] |
def get_stacks(
template_file: str,
stack_path: str = "",
name: str = "",
parameter_overrides: Optional[Dict] = None,
global_parameter_overrides: Optional[Dict] = None,
metadata: Optional[Dict] = None,
) -> Tuple[List[Stack], List[str]]:
"""
Recursively extract stacks from a template file.
Parameters
----------
template_file: str
the file path of the template to extract stacks from
stack_path: str
the stack path of the parent stack, for root stack, it is ""
name: str
the name of the stack associated with the template_file, for root stack, it is ""
parameter_overrides: Optional[Dict]
Optional dictionary of values for SAM template parameters that might want
to get substituted within the template
global_parameter_overrides: Optional[Dict]
Optional dictionary of values for SAM template global parameters
that might want to get substituted within the template and its child templates
metadata: Optional[Dict]
Optional dictionary of nested stack resource metadata values.
Returns
-------
stacks: List[Stack]
The list of stacks extracted from template_file
remote_stack_full_paths : List[str]
The list of full paths of detected remote stacks
"""
template_dict = get_template_data(template_file)
stacks = [
Stack(
stack_path,
name,
template_file,
SamLocalStackProvider.merge_parameter_overrides(parameter_overrides, global_parameter_overrides),
template_dict,
metadata,
)
]
remote_stack_full_paths: List[str] = []
current = SamLocalStackProvider(
template_file, stack_path, template_dict, parameter_overrides, global_parameter_overrides
)
remote_stack_full_paths.extend(current.remote_stack_full_paths)
for child_stack in current.get_all():
stacks_in_child, remote_stack_full_paths_in_child = SamLocalStackProvider.get_stacks(
child_stack.location,
os.path.join(stack_path, stacks[0].stack_id),
child_stack.name,
child_stack.parameters,
global_parameter_overrides,
child_stack.metadata,
)
stacks.extend(stacks_in_child)
remote_stack_full_paths.extend(remote_stack_full_paths_in_child)
return stacks, remote_stack_full_paths
|
[
"def",
"get_stacks",
"(",
"template_file",
":",
"str",
",",
"stack_path",
":",
"str",
"=",
"\"\"",
",",
"name",
":",
"str",
"=",
"\"\"",
",",
"parameter_overrides",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
",",
"global_parameter_overrides",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
",",
"metadata",
":",
"Optional",
"[",
"Dict",
"]",
"=",
"None",
",",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Stack",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"template_dict",
"=",
"get_template_data",
"(",
"template_file",
")",
"stacks",
"=",
"[",
"Stack",
"(",
"stack_path",
",",
"name",
",",
"template_file",
",",
"SamLocalStackProvider",
".",
"merge_parameter_overrides",
"(",
"parameter_overrides",
",",
"global_parameter_overrides",
")",
",",
"template_dict",
",",
"metadata",
",",
")",
"]",
"remote_stack_full_paths",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"current",
"=",
"SamLocalStackProvider",
"(",
"template_file",
",",
"stack_path",
",",
"template_dict",
",",
"parameter_overrides",
",",
"global_parameter_overrides",
")",
"remote_stack_full_paths",
".",
"extend",
"(",
"current",
".",
"remote_stack_full_paths",
")",
"for",
"child_stack",
"in",
"current",
".",
"get_all",
"(",
")",
":",
"stacks_in_child",
",",
"remote_stack_full_paths_in_child",
"=",
"SamLocalStackProvider",
".",
"get_stacks",
"(",
"child_stack",
".",
"location",
",",
"os",
".",
"path",
".",
"join",
"(",
"stack_path",
",",
"stacks",
"[",
"0",
"]",
".",
"stack_id",
")",
",",
"child_stack",
".",
"name",
",",
"child_stack",
".",
"parameters",
",",
"global_parameter_overrides",
",",
"child_stack",
".",
"metadata",
",",
")",
"stacks",
".",
"extend",
"(",
"stacks_in_child",
")",
"remote_stack_full_paths",
".",
"extend",
"(",
"remote_stack_full_paths_in_child",
")",
"return",
"stacks",
",",
"remote_stack_full_paths"
] |
https://github.com/aws/aws-sam-cli/blob/2aa7bf01b2e0b0864ef63b1898a8b30577443acc/samcli/lib/providers/sam_stack_provider.py#L194-L259
|
|
naftaliharris/tauthon
|
5587ceec329b75f7caf6d65a036db61ac1bae214
|
Lib/lib-tk/Tkinter.py
|
python
|
Misc.unbind_class
|
(self, className, sequence)
|
Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
all functions.
|
Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
all functions.
|
[
"Unbind",
"for",
"all",
"widgets",
"with",
"bindtag",
"CLASSNAME",
"for",
"event",
"SEQUENCE",
"all",
"functions",
"."
] |
def unbind_class(self, className, sequence):
"""Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
all functions."""
self.tk.call('bind', className , sequence, '')
|
[
"def",
"unbind_class",
"(",
"self",
",",
"className",
",",
"sequence",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"'bind'",
",",
"className",
",",
"sequence",
",",
"''",
")"
] |
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/lib-tk/Tkinter.py#L1129-L1132
|
||
home-assistant/core
|
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
|
homeassistant/components/smartthings/climate.py
|
python
|
SmartThingsAirConditioner.current_temperature
|
(self)
|
return self._device.status.temperature
|
Return the current temperature.
|
Return the current temperature.
|
[
"Return",
"the",
"current",
"temperature",
"."
] |
def current_temperature(self):
"""Return the current temperature."""
return self._device.status.temperature
|
[
"def",
"current_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"status",
".",
"temperature"
] |
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/smartthings/climate.py#L417-L419
|
|
openshift/openshift-tools
|
1188778e728a6e4781acf728123e5b356380fe6f
|
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_edit.py
|
python
|
Utils.cleanup
|
(files)
|
Clean up on exit
|
Clean up on exit
|
[
"Clean",
"up",
"on",
"exit"
] |
def cleanup(files):
'''Clean up on exit '''
for sfile in files:
if os.path.exists(sfile):
if os.path.isdir(sfile):
shutil.rmtree(sfile)
elif os.path.isfile(sfile):
os.remove(sfile)
|
[
"def",
"cleanup",
"(",
"files",
")",
":",
"for",
"sfile",
"in",
"files",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"sfile",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"sfile",
")",
":",
"shutil",
".",
"rmtree",
"(",
"sfile",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"sfile",
")",
":",
"os",
".",
"remove",
"(",
"sfile",
")"
] |
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_edit.py#L1275-L1282
|
||
tp4a/teleport
|
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
|
server/www/packages/packages-windows/x86/tornado/template.py
|
python
|
_TemplateReader.remaining
|
(self)
|
return len(self.text) - self.pos
|
[] |
def remaining(self) -> int:
return len(self.text) - self.pos
|
[
"def",
"remaining",
"(",
"self",
")",
"->",
"int",
":",
"return",
"len",
"(",
"self",
".",
"text",
")",
"-",
"self",
".",
"pos"
] |
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/tornado/template.py#L808-L809
|
|||
Yelp/Tron
|
d60b015163418bf66f638e4c12337289ad8c040a
|
tron/serialize/filehandler.py
|
python
|
FileHandleManager.remove
|
(self, fh_wrapper)
|
Remove the fh_wrapper from the cache and access_order.
|
Remove the fh_wrapper from the cache and access_order.
|
[
"Remove",
"the",
"fh_wrapper",
"from",
"the",
"cache",
"and",
"access_order",
"."
] |
def remove(self, fh_wrapper):
"""Remove the fh_wrapper from the cache and access_order."""
if fh_wrapper.name in self.cache:
del self.cache[fh_wrapper.name]
|
[
"def",
"remove",
"(",
"self",
",",
"fh_wrapper",
")",
":",
"if",
"fh_wrapper",
".",
"name",
"in",
"self",
".",
"cache",
":",
"del",
"self",
".",
"cache",
"[",
"fh_wrapper",
".",
"name",
"]"
] |
https://github.com/Yelp/Tron/blob/d60b015163418bf66f638e4c12337289ad8c040a/tron/serialize/filehandler.py#L151-L154
|
||
tensorflow/tensorboard
|
61d11d99ef034c30ba20b6a7840c8eededb9031c
|
tensorboard/plugins/projector/projector_plugin.py
|
python
|
ProjectorPlugin.__init__
|
(self, context)
|
Instantiates ProjectorPlugin via TensorBoard core.
Args:
context: A base_plugin.TBContext instance.
|
Instantiates ProjectorPlugin via TensorBoard core.
|
[
"Instantiates",
"ProjectorPlugin",
"via",
"TensorBoard",
"core",
"."
] |
def __init__(self, context):
"""Instantiates ProjectorPlugin via TensorBoard core.
Args:
context: A base_plugin.TBContext instance.
"""
self.data_provider = context.data_provider
self.logdir = context.logdir
self.readers = {}
self._run_paths = None
self._configs = {}
self.config_fpaths = None
self.tensor_cache = LRUCache(_TENSOR_CACHE_CAPACITY)
# Whether the plugin is active (has meaningful data to process and serve).
# Once the plugin is deemed active, we no longer re-compute the value
# because doing so is potentially expensive.
self._is_active = False
# The running thread that is currently determining whether the plugin is
# active. If such a thread exists, do not start a duplicate thread.
self._thread_for_determining_is_active = None
|
[
"def",
"__init__",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"data_provider",
"=",
"context",
".",
"data_provider",
"self",
".",
"logdir",
"=",
"context",
".",
"logdir",
"self",
".",
"readers",
"=",
"{",
"}",
"self",
".",
"_run_paths",
"=",
"None",
"self",
".",
"_configs",
"=",
"{",
"}",
"self",
".",
"config_fpaths",
"=",
"None",
"self",
".",
"tensor_cache",
"=",
"LRUCache",
"(",
"_TENSOR_CACHE_CAPACITY",
")",
"# Whether the plugin is active (has meaningful data to process and serve).",
"# Once the plugin is deemed active, we no longer re-compute the value",
"# because doing so is potentially expensive.",
"self",
".",
"_is_active",
"=",
"False",
"# The running thread that is currently determining whether the plugin is",
"# active. If such a thread exists, do not start a duplicate thread.",
"self",
".",
"_thread_for_determining_is_active",
"=",
"None"
] |
https://github.com/tensorflow/tensorboard/blob/61d11d99ef034c30ba20b6a7840c8eededb9031c/tensorboard/plugins/projector/projector_plugin.py#L238-L259
|
||
quodlibet/mutagen
|
399513b167ed00c4b7a9ef98dfe591a276efb701
|
mutagen/oggvorbis.py
|
python
|
OggVorbisInfo.__init__
|
(self, fileobj)
|
Raises ogg.error, IOError
|
Raises ogg.error, IOError
|
[
"Raises",
"ogg",
".",
"error",
"IOError"
] |
def __init__(self, fileobj):
"""Raises ogg.error, IOError"""
page = OggPage(fileobj)
if not page.packets:
raise OggVorbisHeaderError("page has not packets")
while not page.packets[0].startswith(b"\x01vorbis"):
page = OggPage(fileobj)
if not page.first:
raise OggVorbisHeaderError(
"page has ID header, but doesn't start a stream")
if len(page.packets[0]) < 28:
raise OggVorbisHeaderError(
"page contains a packet too short to be valid")
(self.channels, self.sample_rate, max_bitrate, nominal_bitrate,
min_bitrate) = struct.unpack("<BI3i", page.packets[0][11:28])
if self.sample_rate == 0:
raise OggVorbisHeaderError("sample rate can't be zero")
self.serial = page.serial
max_bitrate = max(0, max_bitrate)
min_bitrate = max(0, min_bitrate)
nominal_bitrate = max(0, nominal_bitrate)
if nominal_bitrate == 0:
self.bitrate = (max_bitrate + min_bitrate) // 2
elif max_bitrate and max_bitrate < nominal_bitrate:
# If the max bitrate is less than the nominal, we know
# the nominal is wrong.
self.bitrate = max_bitrate
elif min_bitrate > nominal_bitrate:
self.bitrate = min_bitrate
else:
self.bitrate = nominal_bitrate
|
[
"def",
"__init__",
"(",
"self",
",",
"fileobj",
")",
":",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"if",
"not",
"page",
".",
"packets",
":",
"raise",
"OggVorbisHeaderError",
"(",
"\"page has not packets\"",
")",
"while",
"not",
"page",
".",
"packets",
"[",
"0",
"]",
".",
"startswith",
"(",
"b\"\\x01vorbis\"",
")",
":",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"if",
"not",
"page",
".",
"first",
":",
"raise",
"OggVorbisHeaderError",
"(",
"\"page has ID header, but doesn't start a stream\"",
")",
"if",
"len",
"(",
"page",
".",
"packets",
"[",
"0",
"]",
")",
"<",
"28",
":",
"raise",
"OggVorbisHeaderError",
"(",
"\"page contains a packet too short to be valid\"",
")",
"(",
"self",
".",
"channels",
",",
"self",
".",
"sample_rate",
",",
"max_bitrate",
",",
"nominal_bitrate",
",",
"min_bitrate",
")",
"=",
"struct",
".",
"unpack",
"(",
"\"<BI3i\"",
",",
"page",
".",
"packets",
"[",
"0",
"]",
"[",
"11",
":",
"28",
"]",
")",
"if",
"self",
".",
"sample_rate",
"==",
"0",
":",
"raise",
"OggVorbisHeaderError",
"(",
"\"sample rate can't be zero\"",
")",
"self",
".",
"serial",
"=",
"page",
".",
"serial",
"max_bitrate",
"=",
"max",
"(",
"0",
",",
"max_bitrate",
")",
"min_bitrate",
"=",
"max",
"(",
"0",
",",
"min_bitrate",
")",
"nominal_bitrate",
"=",
"max",
"(",
"0",
",",
"nominal_bitrate",
")",
"if",
"nominal_bitrate",
"==",
"0",
":",
"self",
".",
"bitrate",
"=",
"(",
"max_bitrate",
"+",
"min_bitrate",
")",
"//",
"2",
"elif",
"max_bitrate",
"and",
"max_bitrate",
"<",
"nominal_bitrate",
":",
"# If the max bitrate is less than the nominal, we know",
"# the nominal is wrong.",
"self",
".",
"bitrate",
"=",
"max_bitrate",
"elif",
"min_bitrate",
">",
"nominal_bitrate",
":",
"self",
".",
"bitrate",
"=",
"min_bitrate",
"else",
":",
"self",
".",
"bitrate",
"=",
"nominal_bitrate"
] |
https://github.com/quodlibet/mutagen/blob/399513b167ed00c4b7a9ef98dfe591a276efb701/mutagen/oggvorbis.py#L54-L87
|
||
aiidateam/aiida-core
|
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
|
aiida/schedulers/plugins/lsf.py
|
python
|
LsfJobResource.accepts_default_mpiprocs_per_machine
|
(cls)
|
return False
|
Return True if this JobResource accepts a 'default_mpiprocs_per_machine'
key, False otherwise.
|
Return True if this JobResource accepts a 'default_mpiprocs_per_machine'
key, False otherwise.
|
[
"Return",
"True",
"if",
"this",
"JobResource",
"accepts",
"a",
"default_mpiprocs_per_machine",
"key",
"False",
"otherwise",
"."
] |
def accepts_default_mpiprocs_per_machine(cls):
"""
Return True if this JobResource accepts a 'default_mpiprocs_per_machine'
key, False otherwise.
"""
return False
|
[
"def",
"accepts_default_mpiprocs_per_machine",
"(",
"cls",
")",
":",
"return",
"False"
] |
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/schedulers/plugins/lsf.py#L162-L167
|
|
phantomcyber/playbooks
|
9e850ecc44cb98c5dde53784744213a1ed5799bd
|
ip_investigate_and_report.py
|
python
|
send_email_bad_domain
|
(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs)
|
return
|
[] |
def send_email_bad_domain(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
phantom.debug('send_email_bad_domain() called')
#phantom.debug('Action: {0} {1}'.format(action['name'], ('SUCCEEDED' if success else 'FAILED')))
# collect data for 'send_email_bad_domain' call
parameters = []
# build parameters list for 'send_email_bad_domain' call
parameters.append({
'cc': "",
'to': "[email protected]",
'bcc': "",
'body': "Check phantom to see output results for bad port scan.",
'from': "[email protected]",
'headers': "",
'subject': "Port Scan detected from bad domain",
'attachments': "",
})
phantom.act(action="send email", parameters=parameters, assets=['smtp'], callback=set_severity_4, name="send_email_bad_domain")
return
|
[
"def",
"send_email_bad_domain",
"(",
"action",
"=",
"None",
",",
"success",
"=",
"None",
",",
"container",
"=",
"None",
",",
"results",
"=",
"None",
",",
"handle",
"=",
"None",
",",
"filtered_artifacts",
"=",
"None",
",",
"filtered_results",
"=",
"None",
",",
"custom_function",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"phantom",
".",
"debug",
"(",
"'send_email_bad_domain() called'",
")",
"#phantom.debug('Action: {0} {1}'.format(action['name'], ('SUCCEEDED' if success else 'FAILED')))",
"# collect data for 'send_email_bad_domain' call",
"parameters",
"=",
"[",
"]",
"# build parameters list for 'send_email_bad_domain' call",
"parameters",
".",
"append",
"(",
"{",
"'cc'",
":",
"\"\"",
",",
"'to'",
":",
"\"[email protected]\"",
",",
"'bcc'",
":",
"\"\"",
",",
"'body'",
":",
"\"Check phantom to see output results for bad port scan.\"",
",",
"'from'",
":",
"\"[email protected]\"",
",",
"'headers'",
":",
"\"\"",
",",
"'subject'",
":",
"\"Port Scan detected from bad domain\"",
",",
"'attachments'",
":",
"\"\"",
",",
"}",
")",
"phantom",
".",
"act",
"(",
"action",
"=",
"\"send email\"",
",",
"parameters",
"=",
"parameters",
",",
"assets",
"=",
"[",
"'smtp'",
"]",
",",
"callback",
"=",
"set_severity_4",
",",
"name",
"=",
"\"send_email_bad_domain\"",
")",
"return"
] |
https://github.com/phantomcyber/playbooks/blob/9e850ecc44cb98c5dde53784744213a1ed5799bd/ip_investigate_and_report.py#L246-L269
|
|||
enthought/mayavi
|
2103a273568b8f0bd62328801aafbd6252543ae8
|
tvtk/misc.py
|
python
|
write_data
|
(dataset, fname, **kwargs)
|
Given a TVTK `dataset` this writes the `dataset` to a VTK XML
file having file name `fname`.
If the given file name has no extension, one is automatically picked
based on the dataset and an XML file is written out. If the
filename has a '.vtk' extension an old style VTK file is written.
If any other extension is specified, an XML file is written out with
the given extension.
Any additional keyword arguments are passed to the writer used.
|
Given a TVTK `dataset` this writes the `dataset` to a VTK XML
file having file name `fname`.
|
[
"Given",
"a",
"TVTK",
"dataset",
"this",
"writes",
"the",
"dataset",
"to",
"a",
"VTK",
"XML",
"file",
"having",
"file",
"name",
"fname",
"."
] |
def write_data(dataset, fname, **kwargs):
"""Given a TVTK `dataset` this writes the `dataset` to a VTK XML
file having file name `fname`.
If the given file name has no extension, one is automatically picked
based on the dataset and an XML file is written out. If the
filename has a '.vtk' extension an old style VTK file is written.
If any other extension is specified, an XML file is written out with
the given extension.
Any additional keyword arguments are passed to the writer used.
"""
err_msg = "Can only write tvtk.DataSet instances "\
"'got %s instead"%(dataset.__class__.__name__)
assert isinstance(dataset, tvtk.DataSet), err_msg
# Mapping to determine appropriate extension and writer.
d2r = {'vtkImageData': ('.vti', tvtk.StructuredPointsWriter),
'vtkRectilinearGrid': ('.vtr', tvtk.RectilinearGridWriter),
'vtkStructuredGrid': ('.vts', tvtk.StructuredGridWriter),
'vtkPolyData': ('.vtp', tvtk.PolyDataWriter),
'vtkUnstructuredGrid': ('.vtu', tvtk.UnstructuredGridWriter)
}
for type in d2r:
if dataset.is_a(type):
datatype = d2r[type]
break
ext = splitext(fname)[1]
if ext == '.vtk':
file_name = fname
writer = datatype[1]
elif len(ext) == 0:
file_name = fname + datatype[0]
writer = tvtk.XMLDataSetWriter
else:
file_name = fname
writer = tvtk.XMLDataSetWriter
w = writer(file_name=file_name, **kwargs)
configure_input_data(w, dataset)
w.write()
|
[
"def",
"write_data",
"(",
"dataset",
",",
"fname",
",",
"*",
"*",
"kwargs",
")",
":",
"err_msg",
"=",
"\"Can only write tvtk.DataSet instances \"",
"\"'got %s instead\"",
"%",
"(",
"dataset",
".",
"__class__",
".",
"__name__",
")",
"assert",
"isinstance",
"(",
"dataset",
",",
"tvtk",
".",
"DataSet",
")",
",",
"err_msg",
"# Mapping to determine appropriate extension and writer.",
"d2r",
"=",
"{",
"'vtkImageData'",
":",
"(",
"'.vti'",
",",
"tvtk",
".",
"StructuredPointsWriter",
")",
",",
"'vtkRectilinearGrid'",
":",
"(",
"'.vtr'",
",",
"tvtk",
".",
"RectilinearGridWriter",
")",
",",
"'vtkStructuredGrid'",
":",
"(",
"'.vts'",
",",
"tvtk",
".",
"StructuredGridWriter",
")",
",",
"'vtkPolyData'",
":",
"(",
"'.vtp'",
",",
"tvtk",
".",
"PolyDataWriter",
")",
",",
"'vtkUnstructuredGrid'",
":",
"(",
"'.vtu'",
",",
"tvtk",
".",
"UnstructuredGridWriter",
")",
"}",
"for",
"type",
"in",
"d2r",
":",
"if",
"dataset",
".",
"is_a",
"(",
"type",
")",
":",
"datatype",
"=",
"d2r",
"[",
"type",
"]",
"break",
"ext",
"=",
"splitext",
"(",
"fname",
")",
"[",
"1",
"]",
"if",
"ext",
"==",
"'.vtk'",
":",
"file_name",
"=",
"fname",
"writer",
"=",
"datatype",
"[",
"1",
"]",
"elif",
"len",
"(",
"ext",
")",
"==",
"0",
":",
"file_name",
"=",
"fname",
"+",
"datatype",
"[",
"0",
"]",
"writer",
"=",
"tvtk",
".",
"XMLDataSetWriter",
"else",
":",
"file_name",
"=",
"fname",
"writer",
"=",
"tvtk",
".",
"XMLDataSetWriter",
"w",
"=",
"writer",
"(",
"file_name",
"=",
"file_name",
",",
"*",
"*",
"kwargs",
")",
"configure_input_data",
"(",
"w",
",",
"dataset",
")",
"w",
".",
"write",
"(",
")"
] |
https://github.com/enthought/mayavi/blob/2103a273568b8f0bd62328801aafbd6252543ae8/tvtk/misc.py#L16-L59
|
||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
|
cb692f527e4e819b6c228187c5702d990a180043
|
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/abc.py
|
python
|
abstractmethod
|
(funcobj)
|
return funcobj
|
A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A
class that has a metaclass derived from ABCMeta cannot be
instantiated unless all of its abstract methods are overridden.
The abstract methods can be called using any of the normal
'super' call mechanisms.
Usage:
class C:
__metaclass__ = ABCMeta
@abstractmethod
def my_abstract_method(self, ...):
...
|
A decorator indicating abstract methods.
|
[
"A",
"decorator",
"indicating",
"abstract",
"methods",
"."
] |
def abstractmethod(funcobj):
"""A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A
class that has a metaclass derived from ABCMeta cannot be
instantiated unless all of its abstract methods are overridden.
The abstract methods can be called using any of the normal
'super' call mechanisms.
Usage:
class C:
__metaclass__ = ABCMeta
@abstractmethod
def my_abstract_method(self, ...):
...
"""
funcobj.__isabstractmethod__ = True
return funcobj
|
[
"def",
"abstractmethod",
"(",
"funcobj",
")",
":",
"funcobj",
".",
"__isabstractmethod__",
"=",
"True",
"return",
"funcobj"
] |
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/abc.py#L15-L33
|
|
dagster-io/dagster
|
b27d569d5fcf1072543533a0c763815d96f90b8f
|
python_modules/dagster/dagster/core/execution/results.py
|
python
|
SolidExecutionResult.failure_data
|
(self)
|
Union[None, StepFailureData]: Any data corresponding to this step's failure, if it
failed.
|
Union[None, StepFailureData]: Any data corresponding to this step's failure, if it
failed.
|
[
"Union",
"[",
"None",
"StepFailureData",
"]",
":",
"Any",
"data",
"corresponding",
"to",
"this",
"step",
"s",
"failure",
"if",
"it",
"failed",
"."
] |
def failure_data(self):
"""Union[None, StepFailureData]: Any data corresponding to this step's failure, if it
failed."""
for step_event in self.compute_step_events:
if step_event.event_type == DagsterEventType.STEP_FAILURE:
return step_event.step_failure_data
|
[
"def",
"failure_data",
"(",
"self",
")",
":",
"for",
"step_event",
"in",
"self",
".",
"compute_step_events",
":",
"if",
"step_event",
".",
"event_type",
"==",
"DagsterEventType",
".",
"STEP_FAILURE",
":",
"return",
"step_event",
".",
"step_failure_data"
] |
https://github.com/dagster-io/dagster/blob/b27d569d5fcf1072543533a0c763815d96f90b8f/python_modules/dagster/dagster/core/execution/results.py#L569-L574
|
||
buke/GreenOdoo
|
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
|
runtime/python/lib/python2.7/logging/__init__.py
|
python
|
FileHandler.emit
|
(self, record)
|
Emit a record.
If the stream was not opened because 'delay' was specified in the
constructor, open it before calling the superclass's emit.
|
Emit a record.
|
[
"Emit",
"a",
"record",
"."
] |
def emit(self, record):
"""
Emit a record.
If the stream was not opened because 'delay' was specified in the
constructor, open it before calling the superclass's emit.
"""
if self.stream is None:
self.stream = self._open()
StreamHandler.emit(self, record)
|
[
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"if",
"self",
".",
"stream",
"is",
"None",
":",
"self",
".",
"stream",
"=",
"self",
".",
"_open",
"(",
")",
"StreamHandler",
".",
"emit",
"(",
"self",
",",
"record",
")"
] |
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/logging/__init__.py#L930-L939
|
||
openhatch/oh-mainline
|
ce29352a034e1223141dcc2f317030bbc3359a51
|
vendor/packages/twisted/twisted/internet/_sslverify.py
|
python
|
Certificate.loadPEM
|
(Class, data)
|
return Class.load(data, crypto.FILETYPE_PEM)
|
Load a certificate from a PEM-format data string.
@rtype: C{Class}
|
Load a certificate from a PEM-format data string.
|
[
"Load",
"a",
"certificate",
"from",
"a",
"PEM",
"-",
"format",
"data",
"string",
"."
] |
def loadPEM(Class, data):
"""
Load a certificate from a PEM-format data string.
@rtype: C{Class}
"""
return Class.load(data, crypto.FILETYPE_PEM)
|
[
"def",
"loadPEM",
"(",
"Class",
",",
"data",
")",
":",
"return",
"Class",
".",
"load",
"(",
"data",
",",
"crypto",
".",
"FILETYPE_PEM",
")"
] |
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/internet/_sslverify.py#L198-L204
|
|
Kismuz/btgym
|
7fb3316e67f1d7a17c620630fb62fb29428b2cec
|
btgym/server.py
|
python
|
BTgymServer.get_global_time
|
(self)
|
return data_server_response['message']['timestamp']
|
Asks dataserver for current dataset global_time.
Returns:
POSIX timestamp
|
Asks dataserver for current dataset global_time.
|
[
"Asks",
"dataserver",
"for",
"current",
"dataset",
"global_time",
"."
] |
def get_global_time(self):
"""
Asks dataserver for current dataset global_time.
Returns:
POSIX timestamp
"""
data_server_response = self._comm_with_timeout(
socket=self.data_socket,
message={'ctrl': '_get_global_time'}
)
if data_server_response['status'] in 'ok':
pass
else:
msg = 'BtgymServer_sampling_attempt: data_server @{} unreachable with status: <{}>.'. \
format(self.data_network_address, data_server_response['status'])
self.log.error(msg)
raise ConnectionError(msg)
return data_server_response['message']['timestamp']
|
[
"def",
"get_global_time",
"(",
"self",
")",
":",
"data_server_response",
"=",
"self",
".",
"_comm_with_timeout",
"(",
"socket",
"=",
"self",
".",
"data_socket",
",",
"message",
"=",
"{",
"'ctrl'",
":",
"'_get_global_time'",
"}",
")",
"if",
"data_server_response",
"[",
"'status'",
"]",
"in",
"'ok'",
":",
"pass",
"else",
":",
"msg",
"=",
"'BtgymServer_sampling_attempt: data_server @{} unreachable with status: <{}>.'",
".",
"format",
"(",
"self",
".",
"data_network_address",
",",
"data_server_response",
"[",
"'status'",
"]",
")",
"self",
".",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"ConnectionError",
"(",
"msg",
")",
"return",
"data_server_response",
"[",
"'message'",
"]",
"[",
"'timestamp'",
"]"
] |
https://github.com/Kismuz/btgym/blob/7fb3316e67f1d7a17c620630fb62fb29428b2cec/btgym/server.py#L437-L457
|
|
jonathanslenders/asyncio-redis
|
50d71a53798967f7fdf1be36b8447e322dedc5ee
|
asyncio_redis/protocol.py
|
python
|
RedisProtocol.sinter
|
(self, tr, keys: ListOf(NativeType))
|
return self._query(tr, b"sinter", *map(self.encode_from_native, keys))
|
Intersect multiple sets
|
Intersect multiple sets
|
[
"Intersect",
"multiple",
"sets"
] |
def sinter(self, tr, keys: ListOf(NativeType)) -> SetReply:
"""Intersect multiple sets
"""
return self._query(tr, b"sinter", *map(self.encode_from_native, keys))
|
[
"def",
"sinter",
"(",
"self",
",",
"tr",
",",
"keys",
":",
"ListOf",
"(",
"NativeType",
")",
")",
"->",
"SetReply",
":",
"return",
"self",
".",
"_query",
"(",
"tr",
",",
"b\"sinter\"",
",",
"*",
"map",
"(",
"self",
".",
"encode_from_native",
",",
"keys",
")",
")"
] |
https://github.com/jonathanslenders/asyncio-redis/blob/50d71a53798967f7fdf1be36b8447e322dedc5ee/asyncio_redis/protocol.py#L1553-L1556
|
|
OpenCobolIDE/OpenCobolIDE
|
c78d0d335378e5fe0a5e74f53c19b68b55e85388
|
open_cobol_ide/extlibs/keyring/backends/kwallet.py
|
python
|
DBusKeyring.__init__
|
(self, *arg, **kw)
|
[] |
def __init__(self, *arg, **kw):
super(DBusKeyring, self).__init__(*arg, **kw)
self.handle = -1
|
[
"def",
"__init__",
"(",
"self",
",",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
":",
"super",
"(",
"DBusKeyring",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
"self",
".",
"handle",
"=",
"-",
"1"
] |
https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/keyring/backends/kwallet.py#L34-L36
|
||||
webpy/webpy
|
62245f7da4aab8f8607c192b98d5ef93873f995b
|
web/utils.py
|
python
|
_EmailMessage.default_email_sender
|
(self, message_text)
|
[] |
def default_email_sender(self, message_text):
try:
from . import webapi
except ImportError:
webapi = Storage(config=Storage())
sendmail = webapi.config.get("sendmail_path", "/usr/sbin/sendmail")
assert not self.from_address.startswith("-"), "security"
for r in self.recipients:
assert not r.startswith("-"), "security"
cmd = [sendmail, "-f", self.from_address] + self.recipients
p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
p.stdin.write(message_text.encode("utf-8"))
p.stdin.close()
p.wait()
|
[
"def",
"default_email_sender",
"(",
"self",
",",
"message_text",
")",
":",
"try",
":",
"from",
".",
"import",
"webapi",
"except",
"ImportError",
":",
"webapi",
"=",
"Storage",
"(",
"config",
"=",
"Storage",
"(",
")",
")",
"sendmail",
"=",
"webapi",
".",
"config",
".",
"get",
"(",
"\"sendmail_path\"",
",",
"\"/usr/sbin/sendmail\"",
")",
"assert",
"not",
"self",
".",
"from_address",
".",
"startswith",
"(",
"\"-\"",
")",
",",
"\"security\"",
"for",
"r",
"in",
"self",
".",
"recipients",
":",
"assert",
"not",
"r",
".",
"startswith",
"(",
"\"-\"",
")",
",",
"\"security\"",
"cmd",
"=",
"[",
"sendmail",
",",
"\"-f\"",
",",
"self",
".",
"from_address",
"]",
"+",
"self",
".",
"recipients",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
")",
"p",
".",
"stdin",
".",
"write",
"(",
"message_text",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"p",
".",
"stdin",
".",
"close",
"(",
")",
"p",
".",
"wait",
"(",
")"
] |
https://github.com/webpy/webpy/blob/62245f7da4aab8f8607c192b98d5ef93873f995b/web/utils.py#L1595-L1613
|
||||
securesystemslab/zippy
|
ff0e84ac99442c2c55fe1d285332cfd4e185e089
|
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/matching/wrappers.py
|
python
|
ConstantScoreWrapperMatcher._replacement
|
(self, newchild)
|
return self.__class__(newchild, score=self._score)
|
[] |
def _replacement(self, newchild):
return self.__class__(newchild, score=self._score)
|
[
"def",
"_replacement",
"(",
"self",
",",
"newchild",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"newchild",
",",
"score",
"=",
"self",
".",
"_score",
")"
] |
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/matching/wrappers.py#L500-L501
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.