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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nortikin/sverchok | 7b460f01317c15f2681bfa3e337c5e7346f3711b | node_tree.py | python | add_use_fake_user_to_trees | () | When ever space node editor switches to another tree or creates new one,
this function will set True to `use_fake_user` of all Sverchok trees | When ever space node editor switches to another tree or creates new one,
this function will set True to `use_fake_user` of all Sverchok trees | [
"When",
"ever",
"space",
"node",
"editor",
"switches",
"to",
"another",
"tree",
"or",
"creates",
"new",
"one",
"this",
"function",
"will",
"set",
"True",
"to",
"use_fake_user",
"of",
"all",
"Sverchok",
"trees"
] | def add_use_fake_user_to_trees():
"""When ever space node editor switches to another tree or creates new one,
this function will set True to `use_fake_user` of all Sverchok trees"""
def set_fake_user():
[setattr(t, 'use_fake_user', True) for t in bpy.data.node_groups if t.bl_idname == 'SverchCustomTreeType']
bpy.msgbus.subscribe_rna(key=(bpy.types.SpaceNodeEditor, 'node_tree'), owner=object(), args=(),
notify=set_fake_user) | [
"def",
"add_use_fake_user_to_trees",
"(",
")",
":",
"def",
"set_fake_user",
"(",
")",
":",
"[",
"setattr",
"(",
"t",
",",
"'use_fake_user'",
",",
"True",
")",
"for",
"t",
"in",
"bpy",
".",
"data",
".",
"node_groups",
"if",
"t",
".",
"bl_idname",
"==",
... | https://github.com/nortikin/sverchok/blob/7b460f01317c15f2681bfa3e337c5e7346f3711b/node_tree.py#L564-L570 | ||
fzlee/alipay | 0f8eab30fea7adb43284182cc6bcac08f51b2e08 | alipay/__init__.py | python | ISVAliPay.app_auth_token | (self) | return self._app_auth_token | [] | def app_auth_token(self):
# 没有则换取token
if not self._app_auth_token:
result = self.api_alipay_open_auth_token_app(self._app_auth_code)
self._app_auth_token = result.get("app_auth_token")
if not self._app_auth_token:
msg = "Get auth token by auth code failed: {}"
raise Exception(msg.format(self._app_auth_code))
return self._app_auth_token | [
"def",
"app_auth_token",
"(",
"self",
")",
":",
"# 没有则换取token",
"if",
"not",
"self",
".",
"_app_auth_token",
":",
"result",
"=",
"self",
".",
"api_alipay_open_auth_token_app",
"(",
"self",
".",
"_app_auth_code",
")",
"self",
".",
"_app_auth_token",
"=",
"result"... | https://github.com/fzlee/alipay/blob/0f8eab30fea7adb43284182cc6bcac08f51b2e08/alipay/__init__.py#L810-L818 | |||
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/tkinter/__init__.py | python | Canvas.create_text | (self, *args, **kw) | return self._create('text', args, kw) | Create text with coordinates x1,y1. | Create text with coordinates x1,y1. | [
"Create",
"text",
"with",
"coordinates",
"x1",
"y1",
"."
] | def create_text(self, *args, **kw):
"""Create text with coordinates x1,y1."""
return self._create('text', args, kw) | [
"def",
"create_text",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_create",
"(",
"'text'",
",",
"args",
",",
"kw",
")"
] | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/tkinter/__init__.py#L2350-L2352 | |
alteryx/featuretools | d59e11082962f163540fd6e185901f65c506326a | featuretools/feature_base/feature_base.py | python | Feature.__new__ | (self, base, dataframe_name=None, groupby=None, parent_dataframe_name=None,
primitive=None, use_previous=None, where=None) | [] | def __new__(self, base, dataframe_name=None, groupby=None, parent_dataframe_name=None,
primitive=None, use_previous=None, where=None):
# either direct or identity
if primitive is None and dataframe_name is None:
return IdentityFeature(base)
elif primitive is None and dataframe_name is not None:
return DirectFeature(base, dataframe_name)
elif primitive is not None and parent_dataframe_name is not None:
assert isinstance(primitive, AggregationPrimitive) or issubclass(primitive, AggregationPrimitive)
return AggregationFeature(base, parent_dataframe_name=parent_dataframe_name,
use_previous=use_previous, where=where,
primitive=primitive)
elif primitive is not None:
assert (isinstance(primitive, TransformPrimitive) or
issubclass(primitive, TransformPrimitive))
if groupby is not None:
return GroupByTransformFeature(base,
primitive=primitive,
groupby=groupby)
return TransformFeature(base, primitive=primitive)
raise Exception("Unrecognized feature initialization") | [
"def",
"__new__",
"(",
"self",
",",
"base",
",",
"dataframe_name",
"=",
"None",
",",
"groupby",
"=",
"None",
",",
"parent_dataframe_name",
"=",
"None",
",",
"primitive",
"=",
"None",
",",
"use_previous",
"=",
"None",
",",
"where",
"=",
"None",
")",
":",
... | https://github.com/alteryx/featuretools/blob/d59e11082962f163540fd6e185901f65c506326a/featuretools/feature_base/feature_base.py#L737-L758 | ||||
JetBrains/python-skeletons | 95ad24b666e475998e5d1cc02ed53a2188036167 | sqlite3.py | python | connect | (database, timeout=5.0, detect_types=0, isolation_level=None,
check_same_thread=False, factory=None, cached_statements=100) | return sqlite3.Connection() | Opens a connection to the SQLite database file database.
:type database: bytes | unicode
:type timeout: float
:type detect_types: int
:type isolation_level: string | None
:type check_same_thread: bool
:type factory: (() -> sqlite3.Connection) | None
:rtype: sqlite3.Connection | Opens a connection to the SQLite database file database. | [
"Opens",
"a",
"connection",
"to",
"the",
"SQLite",
"database",
"file",
"database",
"."
] | def connect(database, timeout=5.0, detect_types=0, isolation_level=None,
check_same_thread=False, factory=None, cached_statements=100):
"""Opens a connection to the SQLite database file database.
:type database: bytes | unicode
:type timeout: float
:type detect_types: int
:type isolation_level: string | None
:type check_same_thread: bool
:type factory: (() -> sqlite3.Connection) | None
:rtype: sqlite3.Connection
"""
return sqlite3.Connection() | [
"def",
"connect",
"(",
"database",
",",
"timeout",
"=",
"5.0",
",",
"detect_types",
"=",
"0",
",",
"isolation_level",
"=",
"None",
",",
"check_same_thread",
"=",
"False",
",",
"factory",
"=",
"None",
",",
"cached_statements",
"=",
"100",
")",
":",
"return"... | https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/sqlite3.py#L7-L19 | |
beeware/ouroboros | a29123c6fab6a807caffbb7587cf548e0c370296 | ouroboros/tkinter/__init__.py | python | Text.window_cget | (self, index, option) | return self.tk.call(self._w, 'window', 'cget', index, option) | Return the value of OPTION of an embedded window at INDEX. | Return the value of OPTION of an embedded window at INDEX. | [
"Return",
"the",
"value",
"of",
"OPTION",
"of",
"an",
"embedded",
"window",
"at",
"INDEX",
"."
] | def window_cget(self, index, option):
"""Return the value of OPTION of an embedded window at INDEX."""
if option[:1] != '-':
option = '-' + option
if option[-1:] == '_':
option = option[:-1]
return self.tk.call(self._w, 'window', 'cget', index, option) | [
"def",
"window_cget",
"(",
"self",
",",
"index",
",",
"option",
")",
":",
"if",
"option",
"[",
":",
"1",
"]",
"!=",
"'-'",
":",
"option",
"=",
"'-'",
"+",
"option",
"if",
"option",
"[",
"-",
"1",
":",
"]",
"==",
"'_'",
":",
"option",
"=",
"opti... | https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/tkinter/__init__.py#L3281-L3287 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/google/appengine/api/search/simple_search_stub.py | python | SearchServiceStub._GetNamespace | (self, namespace) | return namespace_manager.get_namespace() | Get namespace name.
Args:
namespace: Namespace provided in request arguments.
Returns:
If namespace is None, returns the name of the current global namespace. If
namespace is not None, returns namespace. | Get namespace name. | [
"Get",
"namespace",
"name",
"."
] | def _GetNamespace(self, namespace):
"""Get namespace name.
Args:
namespace: Namespace provided in request arguments.
Returns:
If namespace is None, returns the name of the current global namespace. If
namespace is not None, returns namespace.
"""
if namespace is not None:
return namespace
return namespace_manager.get_namespace() | [
"def",
"_GetNamespace",
"(",
"self",
",",
"namespace",
")",
":",
"if",
"namespace",
"is",
"not",
"None",
":",
"return",
"namespace",
"return",
"namespace_manager",
".",
"get_namespace",
"(",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/search/simple_search_stub.py#L617-L629 | |
Yelp/mrjob | 091572e87bc24cc64be40278dd0f5c3617c98d4b | mrjob/job.py | python | MRJob._runner_class | (self) | return _runner_class(self.options.runner or 'inline') | Runner class as indicated by ``--runner``. Defaults to ``'inline'``. | Runner class as indicated by ``--runner``. Defaults to ``'inline'``. | [
"Runner",
"class",
"as",
"indicated",
"by",
"--",
"runner",
".",
"Defaults",
"to",
"inline",
"."
] | def _runner_class(self):
"""Runner class as indicated by ``--runner``. Defaults to ``'inline'``.
"""
return _runner_class(self.options.runner or 'inline') | [
"def",
"_runner_class",
"(",
"self",
")",
":",
"return",
"_runner_class",
"(",
"self",
".",
"options",
".",
"runner",
"or",
"'inline'",
")"
] | https://github.com/Yelp/mrjob/blob/091572e87bc24cc64be40278dd0f5c3617c98d4b/mrjob/job.py#L715-L718 | |
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site-packages/pip/_vendor/html5lib/treebuilders/base.py | python | Node.insertBefore | (self, node, refNode) | Insert node as a child of the current node, before refNode in the
list of child nodes. Raises ValueError if refNode is not a child of
the current node
:arg node: the node to insert
:arg refNode: the child node to insert the node before | Insert node as a child of the current node, before refNode in the
list of child nodes. Raises ValueError if refNode is not a child of
the current node | [
"Insert",
"node",
"as",
"a",
"child",
"of",
"the",
"current",
"node",
"before",
"refNode",
"in",
"the",
"list",
"of",
"child",
"nodes",
".",
"Raises",
"ValueError",
"if",
"refNode",
"is",
"not",
"a",
"child",
"of",
"the",
"current",
"node"
] | def insertBefore(self, node, refNode):
"""Insert node as a child of the current node, before refNode in the
list of child nodes. Raises ValueError if refNode is not a child of
the current node
:arg node: the node to insert
:arg refNode: the child node to insert the node before
"""
raise NotImplementedError | [
"def",
"insertBefore",
"(",
"self",
",",
"node",
",",
"refNode",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/html5lib/treebuilders/base.py#L77-L87 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/number_field/number_field.py | python | NumberField_generic.is_relative | (self) | return not self.is_absolute() | EXAMPLES::
sage: K.<a> = NumberField(x^10 - 2)
sage: K.is_absolute()
True
sage: K.is_relative()
False | EXAMPLES:: | [
"EXAMPLES",
"::"
] | def is_relative(self):
"""
EXAMPLES::
sage: K.<a> = NumberField(x^10 - 2)
sage: K.is_absolute()
True
sage: K.is_relative()
False
"""
return not self.is_absolute() | [
"def",
"is_relative",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"is_absolute",
"(",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/number_field/number_field.py#L2560-L2570 | |
wikilinks/neleval | 68f68414f6a82e3d86761b8d3083e537582bfa7f | neleval/tac.py | python | read_excluded_spans | (path) | return excluded | [] | def read_excluded_spans(path):
if path is None:
return set()
excluded = set()
with open(path) as f:
for l in f:
doc_id, start, end = l.strip().split('\t')[:3]
for i in range(int(start), int(end) + 1):
excluded.add((doc_id, str(i)))
return excluded | [
"def",
"read_excluded_spans",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"set",
"(",
")",
"excluded",
"=",
"set",
"(",
")",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"for",
"l",
"in",
"f",
":",
"doc_id",
",",
"start... | https://github.com/wikilinks/neleval/blob/68f68414f6a82e3d86761b8d3083e537582bfa7f/neleval/tac.py#L106-L116 | |||
rhinstaller/anaconda | 63edc8680f1b05cbfe11bef28703acba808c5174 | pyanaconda/core/configuration/anaconda.py | python | AnacondaConfiguration.from_defaults | (cls) | return config | Get the default Anaconda configuration.
:return: an instance of AnacondaConfiguration | Get the default Anaconda configuration. | [
"Get",
"the",
"default",
"Anaconda",
"configuration",
"."
] | def from_defaults(cls):
"""Get the default Anaconda configuration.
:return: an instance of AnacondaConfiguration
"""
config = cls()
config.set_from_defaults()
return config | [
"def",
"from_defaults",
"(",
"cls",
")",
":",
"config",
"=",
"cls",
"(",
")",
"config",
".",
"set_from_defaults",
"(",
")",
"return",
"config"
] | https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/core/configuration/anaconda.py#L139-L146 | |
entropy1337/infernal-twin | 10995cd03312e39a48ade0f114ebb0ae3a711bb8 | Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/pkg_resources/__init__.py | python | parse_requirements | (strs) | Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof. | Yield ``Requirement`` objects for each specification in `strs` | [
"Yield",
"Requirement",
"objects",
"for",
"each",
"specification",
"in",
"strs"
] | def parse_requirements(strs):
"""Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof.
"""
# create a steppable iterator, so we can handle \-continuations
lines = iter(yield_lines(strs))
def scan_list(ITEM, TERMINATOR, line, p, groups, item_name):
items = []
while not TERMINATOR(line, p):
if CONTINUE(line, p):
try:
line = next(lines)
p = 0
except StopIteration:
msg = "\\ must not appear on the last nonblank line"
raise RequirementParseError(msg)
match = ITEM(line, p)
if not match:
msg = "Expected " + item_name + " in"
raise RequirementParseError(msg, line, "at", line[p:])
items.append(match.group(*groups))
p = match.end()
match = COMMA(line, p)
if match:
# skip the comma
p = match.end()
elif not TERMINATOR(line, p):
msg = "Expected ',' or end-of-list in"
raise RequirementParseError(msg, line, "at", line[p:])
match = TERMINATOR(line, p)
# skip the terminator, if any
if match:
p = match.end()
return line, p, items
for line in lines:
match = DISTRO(line)
if not match:
raise RequirementParseError("Missing distribution spec", line)
project_name = match.group(1)
p = match.end()
extras = []
match = OBRACKET(line, p)
if match:
p = match.end()
line, p, extras = scan_list(
DISTRO, CBRACKET, line, p, (1,), "'extra' name"
)
line, p, specs = scan_list(VERSION, LINE_END, line, p, (1, 2),
"version spec")
specs = [(op, val) for op, val in specs]
yield Requirement(project_name, specs, extras) | [
"def",
"parse_requirements",
"(",
"strs",
")",
":",
"# create a steppable iterator, so we can handle \\-continuations",
"lines",
"=",
"iter",
"(",
"yield_lines",
"(",
"strs",
")",
")",
"def",
"scan_list",
"(",
"ITEM",
",",
"TERMINATOR",
",",
"line",
",",
"p",
",",... | https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/pkg_resources/__init__.py#L2865-L2926 | ||
jazzband/django-dbbackup | 3a4cdbf2b8a70ac319655ad08dd8fc5e8c0f38d8 | dbbackup/utils.py | python | datefmt_to_regex | (datefmt) | return re.compile(r'(%s)' % new_string) | Convert a strftime format string to a regex.
:param datefmt: strftime format string
:type datefmt: ``str``
:returns: Equivalent regex
:rtype: ``re.compite`` | Convert a strftime format string to a regex. | [
"Convert",
"a",
"strftime",
"format",
"string",
"to",
"a",
"regex",
"."
] | def datefmt_to_regex(datefmt):
"""
Convert a strftime format string to a regex.
:param datefmt: strftime format string
:type datefmt: ``str``
:returns: Equivalent regex
:rtype: ``re.compite``
"""
new_string = datefmt
for pat, reg in PATTERN_MATCHNG:
new_string = new_string.replace(pat, reg)
return re.compile(r'(%s)' % new_string) | [
"def",
"datefmt_to_regex",
"(",
"datefmt",
")",
":",
"new_string",
"=",
"datefmt",
"for",
"pat",
",",
"reg",
"in",
"PATTERN_MATCHNG",
":",
"new_string",
"=",
"new_string",
".",
"replace",
"(",
"pat",
",",
"reg",
")",
"return",
"re",
".",
"compile",
"(",
... | https://github.com/jazzband/django-dbbackup/blob/3a4cdbf2b8a70ac319655ad08dd8fc5e8c0f38d8/dbbackup/utils.py#L325-L338 | |
hyperledger/aries-cloudagent-python | 2f36776e99f6053ae92eed8123b5b1b2e891c02a | aries_cloudagent/core/plugin_registry.py | python | PluginRegistry.register_package | (self, package_name: str) | return list(
filter(
None,
(
self.register_plugin(module_name)
for module_name in module_names
if module_name.split(".")[-1] != "tests"
),
)
) | Register all modules (sub-packages) under a given package name. | Register all modules (sub-packages) under a given package name. | [
"Register",
"all",
"modules",
"(",
"sub",
"-",
"packages",
")",
"under",
"a",
"given",
"package",
"name",
"."
] | def register_package(self, package_name: str) -> Sequence[ModuleType]:
"""Register all modules (sub-packages) under a given package name."""
try:
module_names = ClassLoader.scan_subpackages(package_name)
except ModuleLoadError:
LOGGER.error("Plugin module package not found: %s", package_name)
module_names = []
return list(
filter(
None,
(
self.register_plugin(module_name)
for module_name in module_names
if module_name.split(".")[-1] != "tests"
),
)
) | [
"def",
"register_package",
"(",
"self",
",",
"package_name",
":",
"str",
")",
"->",
"Sequence",
"[",
"ModuleType",
"]",
":",
"try",
":",
"module_names",
"=",
"ClassLoader",
".",
"scan_subpackages",
"(",
"package_name",
")",
"except",
"ModuleLoadError",
":",
"L... | https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/core/plugin_registry.py#L180-L196 | |
openedx/edx-platform | 68dd185a0ab45862a2a61e0f803d7e03d2be71b5 | common/lib/xmodule/xmodule/x_module.py | python | ModuleSystemShim.anonymous_student_id | (self) | return None | Returns the anonymous user ID for the current user and course.
Deprecated in favor of the user service. | Returns the anonymous user ID for the current user and course. | [
"Returns",
"the",
"anonymous",
"user",
"ID",
"for",
"the",
"current",
"user",
"and",
"course",
"."
] | def anonymous_student_id(self):
"""
Returns the anonymous user ID for the current user and course.
Deprecated in favor of the user service.
"""
warnings.warn(
'runtime.anonymous_student_id is deprecated. Please use the user service instead.',
DeprecationWarning, stacklevel=3,
)
user_service = self._services.get('user')
if user_service:
return user_service.get_current_user().opt_attrs.get(ATTR_KEY_ANONYMOUS_USER_ID)
return None | [
"def",
"anonymous_student_id",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"'runtime.anonymous_student_id is deprecated. Please use the user service instead.'",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"3",
",",
")",
"user_service",
"=",
"self",
".",
... | https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/lib/xmodule/xmodule/x_module.py#L1753-L1766 | |
KalleHallden/AutoTimer | 2d954216700c4930baa154e28dbddc34609af7ce | env/lib/python2.7/site.py | python | execsitecustomize | () | Run custom site specific code, if available. | Run custom site specific code, if available. | [
"Run",
"custom",
"site",
"specific",
"code",
"if",
"available",
"."
] | def execsitecustomize():
"""Run custom site specific code, if available."""
try:
import sitecustomize
except ImportError:
pass | [
"def",
"execsitecustomize",
"(",
")",
":",
"try",
":",
"import",
"sitecustomize",
"except",
"ImportError",
":",
"pass"
] | https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site.py#L550-L555 | ||
linkedin/iris | af929ee35b8aaccef99c0ee775707e45d56ea784 | src/iris/vendors/iris_hipchat.py | python | iris_hipchat.parse_destination | (self, destination) | return room_id, token, mention | Determine room_id, token and user to mention
We accept 3 formats:
- Just a mention (@testuser)
- Room_id and Token (12341;a20asdfgjahdASDfaskw)
- Room_id, Token and mention (12341;a20asdfgjahdASDfaskw;@testuser) | Determine room_id, token and user to mention
We accept 3 formats:
- Just a mention ( | [
"Determine",
"room_id",
"token",
"and",
"user",
"to",
"mention",
"We",
"accept",
"3",
"formats",
":",
"-",
"Just",
"a",
"mention",
"("
] | def parse_destination(self, destination):
"""Determine room_id, token and user to mention
We accept 3 formats:
- Just a mention (@testuser)
- Room_id and Token (12341;a20asdfgjahdASDfaskw)
- Room_id, Token and mention (12341;a20asdfgjahdASDfaskw;@testuser)
"""
room_id = self.room_id
token = self.token
mention = ""
if destination.startswith("@"):
mention = destination
elif ";" in destination:
dparts = destination.split(";")
if len(dparts) == 3:
try:
room_id = int(dparts[0])
except ValueError:
logger.error("Invalid destination: %s. Using default room_id", destination)
token = dparts[1]
mention = dparts[2]
elif len(dparts) == 2:
try:
room_id = int(dparts[0])
except ValueError:
logger.error("Invalid destination: %s. Using default room_id", destination)
token = dparts[1]
else:
logger.error("Invalid destination: %s. Contains %s fields.", destination, len(dparts))
else:
logger.error("Invalid destination: %s. Neither @user or ; separated value.", destination)
return room_id, token, mention | [
"def",
"parse_destination",
"(",
"self",
",",
"destination",
")",
":",
"room_id",
"=",
"self",
".",
"room_id",
"token",
"=",
"self",
".",
"token",
"mention",
"=",
"\"\"",
"if",
"destination",
".",
"startswith",
"(",
"\"@\"",
")",
":",
"mention",
"=",
"de... | https://github.com/linkedin/iris/blob/af929ee35b8aaccef99c0ee775707e45d56ea784/src/iris/vendors/iris_hipchat.py#L47-L80 | |
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/calendar.py | python | format | (cols, colwidth=_colwidth, spacing=_spacing) | Prints multi-column formatting for year calendars | Prints multi-column formatting for year calendars | [
"Prints",
"multi",
"-",
"column",
"formatting",
"for",
"year",
"calendars"
] | def format(cols, colwidth=_colwidth, spacing=_spacing):
"""Prints multi-column formatting for year calendars"""
print formatstring(cols, colwidth, spacing) | [
"def",
"format",
"(",
"cols",
",",
"colwidth",
"=",
"_colwidth",
",",
"spacing",
"=",
"_spacing",
")",
":",
"print",
"formatstring",
"(",
"cols",
",",
"colwidth",
",",
"spacing",
")"
] | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/calendar.py#L595-L597 | ||
tensorflow/lingvo | ce10019243d954c3c3ebe739f7589b5eebfdf907 | lingvo/tools/gke_launch.py | python | _get_or_add | (cfg, name) | return cfg[name] | Gets cfg[name], or adds 'name' with an empty dict if not present. | Gets cfg[name], or adds 'name' with an empty dict if not present. | [
"Gets",
"cfg",
"[",
"name",
"]",
"or",
"adds",
"name",
"with",
"an",
"empty",
"dict",
"if",
"not",
"present",
"."
] | def _get_or_add(cfg, name):
"""Gets cfg[name], or adds 'name' with an empty dict if not present."""
if name not in cfg:
cfg.update({name: {}})
return cfg[name] | [
"def",
"_get_or_add",
"(",
"cfg",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"cfg",
":",
"cfg",
".",
"update",
"(",
"{",
"name",
":",
"{",
"}",
"}",
")",
"return",
"cfg",
"[",
"name",
"]"
] | https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/tools/gke_launch.py#L122-L126 | |
peterbrittain/asciimatics | 9a490faddf484ee5b9b845316f921f5888b23b18 | asciimatics/exceptions.py | python | StopApplication.__init__ | (self, message) | :param message: Error message for this exception. | :param message: Error message for this exception. | [
":",
"param",
"message",
":",
"Error",
"message",
"for",
"this",
"exception",
"."
] | def __init__(self, message):
"""
:param message: Error message for this exception.
"""
super(StopApplication, self).__init__()
self._message = message | [
"def",
"__init__",
"(",
"self",
",",
"message",
")",
":",
"super",
"(",
"StopApplication",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_message",
"=",
"message"
] | https://github.com/peterbrittain/asciimatics/blob/9a490faddf484ee5b9b845316f921f5888b23b18/asciimatics/exceptions.py#L47-L52 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_adm_registry.py | python | Utils.openshift_installed | () | return rpmquery.count() > 0 | check if openshift is installed | check if openshift is installed | [
"check",
"if",
"openshift",
"is",
"installed"
] | def openshift_installed():
''' check if openshift is installed '''
import rpm
transaction_set = rpm.TransactionSet()
rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
return rpmquery.count() > 0 | [
"def",
"openshift_installed",
"(",
")",
":",
"import",
"rpm",
"transaction_set",
"=",
"rpm",
".",
"TransactionSet",
"(",
")",
"rpmquery",
"=",
"transaction_set",
".",
"dbMatch",
"(",
"\"name\"",
",",
"\"atomic-openshift\"",
")",
"return",
"rpmquery",
".",
"count... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_adm_registry.py#L1432-L1439 | |
deepset-ai/haystack | 79fdda8a7cf393d774803608a4874f2a6e63cf6f | ui/SessionState.py | python | get | (**kwargs) | return this_session._custom_session_state | Gets a SessionState object for the current session.
Creates a new object if necessary.
Parameters
----------
**kwargs : any
Default values you want to add to the session state, if we're creating a
new one.
Example
-------
>>> session_state = get(user_name='', favorite_color='black')
>>> session_state.user_name
''
>>> session_state.user_name = 'Mary'
>>> session_state.favorite_color
'black'
Since you set user_name above, next time your script runs this will be the
result:
>>> session_state = get(user_name='', favorite_color='black')
>>> session_state.user_name
'Mary' | Gets a SessionState object for the current session.
Creates a new object if necessary.
Parameters
----------
**kwargs : any
Default values you want to add to the session state, if we're creating a
new one.
Example
-------
>>> session_state = get(user_name='', favorite_color='black')
>>> session_state.user_name
''
>>> session_state.user_name = 'Mary'
>>> session_state.favorite_color
'black'
Since you set user_name above, next time your script runs this will be the
result:
>>> session_state = get(user_name='', favorite_color='black')
>>> session_state.user_name
'Mary' | [
"Gets",
"a",
"SessionState",
"object",
"for",
"the",
"current",
"session",
".",
"Creates",
"a",
"new",
"object",
"if",
"necessary",
".",
"Parameters",
"----------",
"**",
"kwargs",
":",
"any",
"Default",
"values",
"you",
"want",
"to",
"add",
"to",
"the",
"... | def get(**kwargs):
"""Gets a SessionState object for the current session.
Creates a new object if necessary.
Parameters
----------
**kwargs : any
Default values you want to add to the session state, if we're creating a
new one.
Example
-------
>>> session_state = get(user_name='', favorite_color='black')
>>> session_state.user_name
''
>>> session_state.user_name = 'Mary'
>>> session_state.favorite_color
'black'
Since you set user_name above, next time your script runs this will be the
result:
>>> session_state = get(user_name='', favorite_color='black')
>>> session_state.user_name
'Mary'
"""
# Hack to get the session object from Streamlit.
ctx = ReportThread.get_report_ctx()
this_session = None
current_server = Server.get_current()
if hasattr(current_server, '_session_infos'):
# Streamlit < 0.56
session_infos = Server.get_current()._session_infos.values()
else:
session_infos = Server.get_current()._session_info_by_id.values()
for session_info in session_infos:
s = session_info.session
if (
# Streamlit < 0.54.0
(hasattr(s, '_main_dg') and s._main_dg == ctx.main_dg)
or
# Streamlit >= 0.54.0
(not hasattr(s, '_main_dg') and s.enqueue == ctx.enqueue)
or
# Streamlit >= 0.65.2
(not hasattr(s, '_main_dg') and s._uploaded_file_mgr == ctx.uploaded_file_mgr)
):
this_session = s
if this_session is None:
raise RuntimeError(
"Oh noes. Couldn't get your Streamlit Session object. "
'Are you doing something fancy with threads?')
# Got the session object! Now let's attach some state into it.
if not hasattr(this_session, '_custom_session_state'):
this_session._custom_session_state = SessionState(**kwargs)
return this_session._custom_session_state | [
"def",
"get",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Hack to get the session object from Streamlit.",
"ctx",
"=",
"ReportThread",
".",
"get_report_ctx",
"(",
")",
"this_session",
"=",
"None",
"current_server",
"=",
"Server",
".",
"get_current",
"(",
")",
"if",
"h... | https://github.com/deepset-ai/haystack/blob/79fdda8a7cf393d774803608a4874f2a6e63cf6f/ui/SessionState.py#L46-L105 | |
naftaliharris/tauthon | 5587ceec329b75f7caf6d65a036db61ac1bae214 | Lib/distutils/text_file.py | python | TextFile.warn | (self, msg, line=None) | Print (to stderr) a warning message tied to the current logical
line in the current file. If the current logical line in the
file spans multiple physical lines, the warning refers to the
whole range, eg. "lines 3-5". If 'line' supplied, it overrides
the current line number; it may be a list or tuple to indicate a
range of physical lines, or an integer for a single physical
line. | Print (to stderr) a warning message tied to the current logical
line in the current file. If the current logical line in the
file spans multiple physical lines, the warning refers to the
whole range, eg. "lines 3-5". If 'line' supplied, it overrides
the current line number; it may be a list or tuple to indicate a
range of physical lines, or an integer for a single physical
line. | [
"Print",
"(",
"to",
"stderr",
")",
"a",
"warning",
"message",
"tied",
"to",
"the",
"current",
"logical",
"line",
"in",
"the",
"current",
"file",
".",
"If",
"the",
"current",
"logical",
"line",
"in",
"the",
"file",
"spans",
"multiple",
"physical",
"lines",
... | def warn (self, msg, line=None):
"""Print (to stderr) a warning message tied to the current logical
line in the current file. If the current logical line in the
file spans multiple physical lines, the warning refers to the
whole range, eg. "lines 3-5". If 'line' supplied, it overrides
the current line number; it may be a list or tuple to indicate a
range of physical lines, or an integer for a single physical
line."""
sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n") | [
"def",
"warn",
"(",
"self",
",",
"msg",
",",
"line",
"=",
"None",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"warning: \"",
"+",
"self",
".",
"gen_error",
"(",
"msg",
",",
"line",
")",
"+",
"\"\\n\"",
")"
] | https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/distutils/text_file.py#L150-L158 | ||
sovrasov/flops-counter.pytorch | 29621c81b3afc21450c1e20d04f88f098c0681a8 | ptflops/flops_counter.py | python | accumulate_flops | (self) | [] | def accumulate_flops(self):
if is_supported_instance(self):
return self.__flops__
else:
sum = 0
for m in self.children():
sum += m.accumulate_flops()
return sum | [
"def",
"accumulate_flops",
"(",
"self",
")",
":",
"if",
"is_supported_instance",
"(",
"self",
")",
":",
"return",
"self",
".",
"__flops__",
"else",
":",
"sum",
"=",
"0",
"for",
"m",
"in",
"self",
".",
"children",
"(",
")",
":",
"sum",
"+=",
"m",
".",... | https://github.com/sovrasov/flops-counter.pytorch/blob/29621c81b3afc21450c1e20d04f88f098c0681a8/ptflops/flops_counter.py#L95-L102 | ||||
smart-mobile-software/gitstack | d9fee8f414f202143eb6e620529e8e5539a2af56 | python/Lib/multiprocessing/__init__.py | python | RawValue | (typecode_or_type, *args) | return RawValue(typecode_or_type, *args) | Returns a shared object | Returns a shared object | [
"Returns",
"a",
"shared",
"object"
] | def RawValue(typecode_or_type, *args):
'''
Returns a shared object
'''
from multiprocessing.sharedctypes import RawValue
return RawValue(typecode_or_type, *args) | [
"def",
"RawValue",
"(",
"typecode_or_type",
",",
"*",
"args",
")",
":",
"from",
"multiprocessing",
".",
"sharedctypes",
"import",
"RawValue",
"return",
"RawValue",
"(",
"typecode_or_type",
",",
"*",
"args",
")"
] | https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/multiprocessing/__init__.py#L234-L239 | |
awslabs/gluon-ts | 066ec3b7f47aa4ee4c061a28f35db7edbad05a98 | src/gluonts/mx/util.py | python | cumsum | (
F, x: Tensor, exclusive: bool = False, reverse: bool = False
) | return cumulative_sum.squeeze(axis=exp_dim) | r"""
Find cumulative sum on the last axis by multiplying with lower triangular
ones-matrix:
.. math::
\operatorname{cumsum}(x) =
\begin{cases}
\operatorname{ltr\_ones} \times x
& \text{for cumulative sum}\\
x \times \operatorname{ltr\_ones}
& \text{for cumulative sum in the reverse order}
\end{cases}
Also supports `exclusive` flag to start the cumsum with zero.
For example, if :math:`x = [a, b, c]`, we have
.. math::
\operatorname{cumsum}(x) =
\begin{cases}
[a, a + b, a + b + c]
& \text{if }\mathit{reverse = False, exclusive = False}\\
[0, a, a + b]
& \text{if }\mathit{reverse = False, exclusive = True}\\
[a + b + c, b + c, c]
& \text{if }\mathit{reverse = True, exclusive = False}\\
[b + c, c, 0]
& \text{if }\mathit{reverse = True, exclusive = True}\\
\end{cases}
Parameters
----------
F
The function space to use.
x
A tensor with shape :math:`(..., n)`.
exclusive
If `True`, the cumulative sum starts with zero.
reverse
If `True`, the cumulative sum is performed in the opposite direction.
Returns
-------
Tensor:
A modified tensor with identical shape and cumulative sums in the last
axis. | r"""
Find cumulative sum on the last axis by multiplying with lower triangular
ones-matrix: | [
"r",
"Find",
"cumulative",
"sum",
"on",
"the",
"last",
"axis",
"by",
"multiplying",
"with",
"lower",
"triangular",
"ones",
"-",
"matrix",
":"
] | def cumsum(
F, x: Tensor, exclusive: bool = False, reverse: bool = False
) -> Tensor:
r"""
Find cumulative sum on the last axis by multiplying with lower triangular
ones-matrix:
.. math::
\operatorname{cumsum}(x) =
\begin{cases}
\operatorname{ltr\_ones} \times x
& \text{for cumulative sum}\\
x \times \operatorname{ltr\_ones}
& \text{for cumulative sum in the reverse order}
\end{cases}
Also supports `exclusive` flag to start the cumsum with zero.
For example, if :math:`x = [a, b, c]`, we have
.. math::
\operatorname{cumsum}(x) =
\begin{cases}
[a, a + b, a + b + c]
& \text{if }\mathit{reverse = False, exclusive = False}\\
[0, a, a + b]
& \text{if }\mathit{reverse = False, exclusive = True}\\
[a + b + c, b + c, c]
& \text{if }\mathit{reverse = True, exclusive = False}\\
[b + c, c, 0]
& \text{if }\mathit{reverse = True, exclusive = True}\\
\end{cases}
Parameters
----------
F
The function space to use.
x
A tensor with shape :math:`(..., n)`.
exclusive
If `True`, the cumulative sum starts with zero.
reverse
If `True`, the cumulative sum is performed in the opposite direction.
Returns
-------
Tensor:
A modified tensor with identical shape and cumulative sums in the last
axis.
"""
# Create a new axis (for matrix multiplication) either at last location or
# last-but-one location (for reverse mode)
exp_dim = -2 if reverse else -1
# (..., 1, n) if reverse is True and (..., n, 1) otherwise
x = x.expand_dims(axis=exp_dim)
# Ones_matrix (..., n, n)
ones_matrix = F.linalg_gemm2(
F.ones_like(x),
F.ones_like(x),
transpose_a=reverse,
transpose_b=not reverse,
)
cumulative_sum = F.linalg_trmm(ones_matrix, x, rightside=reverse)
if exclusive:
cumulative_sum = cumulative_sum - x
return cumulative_sum.squeeze(axis=exp_dim) | [
"def",
"cumsum",
"(",
"F",
",",
"x",
":",
"Tensor",
",",
"exclusive",
":",
"bool",
"=",
"False",
",",
"reverse",
":",
"bool",
"=",
"False",
")",
"->",
"Tensor",
":",
"# Create a new axis (for matrix multiplication) either at last location or",
"# last-but-one locati... | https://github.com/awslabs/gluon-ts/blob/066ec3b7f47aa4ee4c061a28f35db7edbad05a98/src/gluonts/mx/util.py#L331-L401 | |
CamDavidsonPilon/lifelines | 9be26a9a8720e8536e9828e954bb91d559a3016f | lifelines/statistics.py | python | power_under_cph | (n_exp, n_con, p_exp, p_con, postulated_hazard_ratio, alpha=0.05) | return stats.norm.cdf(
np.sqrt(k * m) * abs(postulated_hazard_ratio - 1) / (k * postulated_hazard_ratio + 1) - z(1 - alpha / 2.0)
) | This computes the power of the hypothesis test that the two groups, experiment and control,
have different hazards (that is, the relative hazard ratio is different from 1.)
Parameters
----------
n_exp : integer
size of the experiment group.
n_con : integer
size of the control group.
p_exp : float
probability of failure in experimental group over period of study.
p_con : float
probability of failure in control group over period of study
postulated_hazard_ratio : float
the postulated hazard ratio
alpha : float, optional (default=0.05)
type I error rate
Returns
-------
float:
power to detect the magnitude of the hazard ratio as small as that specified by postulated_hazard_ratio.
Notes
-----
`Reference <https://cran.r-project.org/web/packages/powerSurvEpi/powerSurvEpi.pdf>`_.
See Also
--------
sample_size_necessary_under_cph | This computes the power of the hypothesis test that the two groups, experiment and control,
have different hazards (that is, the relative hazard ratio is different from 1.) | [
"This",
"computes",
"the",
"power",
"of",
"the",
"hypothesis",
"test",
"that",
"the",
"two",
"groups",
"experiment",
"and",
"control",
"have",
"different",
"hazards",
"(",
"that",
"is",
"the",
"relative",
"hazard",
"ratio",
"is",
"different",
"from",
"1",
".... | def power_under_cph(n_exp, n_con, p_exp, p_con, postulated_hazard_ratio, alpha=0.05) -> float:
"""
This computes the power of the hypothesis test that the two groups, experiment and control,
have different hazards (that is, the relative hazard ratio is different from 1.)
Parameters
----------
n_exp : integer
size of the experiment group.
n_con : integer
size of the control group.
p_exp : float
probability of failure in experimental group over period of study.
p_con : float
probability of failure in control group over period of study
postulated_hazard_ratio : float
the postulated hazard ratio
alpha : float, optional (default=0.05)
type I error rate
Returns
-------
float:
power to detect the magnitude of the hazard ratio as small as that specified by postulated_hazard_ratio.
Notes
-----
`Reference <https://cran.r-project.org/web/packages/powerSurvEpi/powerSurvEpi.pdf>`_.
See Also
--------
sample_size_necessary_under_cph
"""
def z(p):
return stats.norm.ppf(p)
m = n_exp * p_exp + n_con * p_con
k = float(n_exp) / float(n_con)
return stats.norm.cdf(
np.sqrt(k * m) * abs(postulated_hazard_ratio - 1) / (k * postulated_hazard_ratio + 1) - z(1 - alpha / 2.0)
) | [
"def",
"power_under_cph",
"(",
"n_exp",
",",
"n_con",
",",
"p_exp",
",",
"p_con",
",",
"postulated_hazard_ratio",
",",
"alpha",
"=",
"0.05",
")",
"->",
"float",
":",
"def",
"z",
"(",
"p",
")",
":",
"return",
"stats",
".",
"norm",
".",
"ppf",
"(",
"p"... | https://github.com/CamDavidsonPilon/lifelines/blob/9be26a9a8720e8536e9828e954bb91d559a3016f/lifelines/statistics.py#L288-L338 | |
pyrocko/pyrocko | b6baefb7540fb7fce6ed9b856ec0c413961a4320 | src/plot/gmtpy.py | python | escape_shell_args | (args) | return ' '.join([escape_shell_arg(x) for x in args]) | This function should be used for debugging output only - it could be
insecure. | This function should be used for debugging output only - it could be
insecure. | [
"This",
"function",
"should",
"be",
"used",
"for",
"debugging",
"output",
"only",
"-",
"it",
"could",
"be",
"insecure",
"."
] | def escape_shell_args(args):
'''
This function should be used for debugging output only - it could be
insecure.
'''
return ' '.join([escape_shell_arg(x) for x in args]) | [
"def",
"escape_shell_args",
"(",
"args",
")",
":",
"return",
"' '",
".",
"join",
"(",
"[",
"escape_shell_arg",
"(",
"x",
")",
"for",
"x",
"in",
"args",
"]",
")"
] | https://github.com/pyrocko/pyrocko/blob/b6baefb7540fb7fce6ed9b856ec0c413961a4320/src/plot/gmtpy.py#L214-L220 | |
wbond/packagecontrol.io | 9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20 | app/lib/package_control/providers/gitlab_repository_provider.py | python | GitLabRepositoryProvider.get_packages | (self, invalid_sources=None) | Uses the GitLab API to construct necessary info for a package
:param invalid_sources:
A list of URLs that should be ignored
:raises:
DownloaderException: when there is an issue download package info
ClientException: when there is an issue parsing package info
:return:
A generator of
(
'Package Name',
{
'name': name,
'description': description,
'author': author,
'homepage': homepage,
'last_modified': last modified date,
'releases': [
{
'sublime_text': '*',
'platforms': ['*'],
'url': url,
'date': date,
'version': version
}, ...
],
'previous_names': [],
'labels': [],
'sources': [the repo URL],
'readme': url,
'issues': url,
'donate': url,
'buy': None
}
)
tuples | Uses the GitLab API to construct necessary info for a package | [
"Uses",
"the",
"GitLab",
"API",
"to",
"construct",
"necessary",
"info",
"for",
"a",
"package"
] | def get_packages(self, invalid_sources=None):
"""
Uses the GitLab API to construct necessary info for a package
:param invalid_sources:
A list of URLs that should be ignored
:raises:
DownloaderException: when there is an issue download package info
ClientException: when there is an issue parsing package info
:return:
A generator of
(
'Package Name',
{
'name': name,
'description': description,
'author': author,
'homepage': homepage,
'last_modified': last modified date,
'releases': [
{
'sublime_text': '*',
'platforms': ['*'],
'url': url,
'date': date,
'version': version
}, ...
],
'previous_names': [],
'labels': [],
'sources': [the repo URL],
'readme': url,
'issues': url,
'donate': url,
'buy': None
}
)
tuples
"""
if 'get_packages' in self.cache:
for key, value in self.cache['get_packages'].items():
yield (key, value)
return
client = GitLabClient(self.settings)
if invalid_sources is not None and self.repo in invalid_sources:
raise StopIteration()
try:
repo_info = client.repo_info(self.repo)
releases = []
for download in client.download_info(self.repo):
download['sublime_text'] = '*'
download['platforms'] = ['*']
releases.append(download)
name = repo_info['name']
details = {
'name': name,
'description': repo_info['description'],
'homepage': repo_info['homepage'],
'author': repo_info['author'],
'last_modified': releases[0].get('date'),
'releases': releases,
'previous_names': [],
'labels': [],
'sources': [self.repo],
'readme': repo_info['readme'],
'issues': repo_info['issues'],
'donate': repo_info['donate'],
'buy': None
}
self.cache['get_packages'] = {name: details}
yield (name, details)
except (DownloaderException, ClientException, ProviderException) as e:
self.failed_sources[self.repo] = e
self.cache['get_packages'] = {}
raise StopIteration() | [
"def",
"get_packages",
"(",
"self",
",",
"invalid_sources",
"=",
"None",
")",
":",
"if",
"'get_packages'",
"in",
"self",
".",
"cache",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"cache",
"[",
"'get_packages'",
"]",
".",
"items",
"(",
")",
":",... | https://github.com/wbond/packagecontrol.io/blob/9f5eb7e3392e6bc2ad979ad32d3dd27ef9c00b20/app/lib/package_control/providers/gitlab_repository_provider.py#L91-L174 | ||
dask/dask | c2b962fec1ba45440fe928869dc64cfe9cc36506 | dask/dataframe/indexing.py | python | _LocIndexer._loc | (self, iindexer, cindexer) | Helper function for the .loc accessor | Helper function for the .loc accessor | [
"Helper",
"function",
"for",
"the",
".",
"loc",
"accessor"
] | def _loc(self, iindexer, cindexer):
"""Helper function for the .loc accessor"""
if isinstance(iindexer, Series):
return self._loc_series(iindexer, cindexer)
elif isinstance(iindexer, Array):
return self._loc_array(iindexer, cindexer)
elif callable(iindexer):
return self._loc(iindexer(self.obj), cindexer)
if self.obj.known_divisions:
iindexer = self._maybe_partial_time_string(iindexer)
if isinstance(iindexer, slice):
return self._loc_slice(iindexer, cindexer)
elif isinstance(iindexer, (list, np.ndarray)):
return self._loc_list(iindexer, cindexer)
elif is_series_like(iindexer) and not is_bool_dtype(iindexer.dtype):
return self._loc_list(iindexer.values, cindexer)
else:
# element should raise KeyError
return self._loc_element(iindexer, cindexer)
else:
if isinstance(iindexer, (list, np.ndarray)) or (
is_series_like(iindexer) and not is_bool_dtype(iindexer.dtype)
):
# applying map_partitions to each partition
# results in duplicated NaN rows
msg = (
"Cannot index with list against unknown division. "
"Try setting divisions using ``ddf.set_index``"
)
raise KeyError(msg)
elif not isinstance(iindexer, slice):
iindexer = slice(iindexer, iindexer)
meta = self._make_meta(iindexer, cindexer)
return self.obj.map_partitions(
methods.try_loc, iindexer, cindexer, meta=meta
) | [
"def",
"_loc",
"(",
"self",
",",
"iindexer",
",",
"cindexer",
")",
":",
"if",
"isinstance",
"(",
"iindexer",
",",
"Series",
")",
":",
"return",
"self",
".",
"_loc_series",
"(",
"iindexer",
",",
"cindexer",
")",
"elif",
"isinstance",
"(",
"iindexer",
",",... | https://github.com/dask/dask/blob/c2b962fec1ba45440fe928869dc64cfe9cc36506/dask/dataframe/indexing.py#L102-L140 | ||
shuup/shuup | 25f78cfe370109b9885b903e503faac295c7b7f2 | shuup/front/providers/form_def.py | python | FormDefProvider.get_definitions | (self, **kwargs) | return [] | :return: list of `FormDefinition`s
:rtype: list[shuup.front.providers.form_def.FormDefinition] | :return: list of `FormDefinition`s
:rtype: list[shuup.front.providers.form_def.FormDefinition] | [
":",
"return",
":",
"list",
"of",
"FormDefinition",
"s",
":",
"rtype",
":",
"list",
"[",
"shuup",
".",
"front",
".",
"providers",
".",
"form_def",
".",
"FormDefinition",
"]"
] | def get_definitions(self, **kwargs):
"""
:return: list of `FormDefinition`s
:rtype: list[shuup.front.providers.form_def.FormDefinition]
"""
return [] | [
"def",
"get_definitions",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"]"
] | https://github.com/shuup/shuup/blob/25f78cfe370109b9885b903e503faac295c7b7f2/shuup/front/providers/form_def.py#L43-L48 | |
yihui-he/KL-Loss | 66c0ed9e886a2218f4cf88c0efd4f40199bff54a | detectron/utils/py_cpu_nms.py | python | py_cpu_nms | (dets, thresh) | return keep | Pure Python NMS baseline. | Pure Python NMS baseline. | [
"Pure",
"Python",
"NMS",
"baseline",
"."
] | def py_cpu_nms(dets, thresh):
"""Pure Python NMS baseline."""
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= thresh)[0]
order = order[inds + 1]
return keep | [
"def",
"py_cpu_nms",
"(",
"dets",
",",
"thresh",
")",
":",
"x1",
"=",
"dets",
"[",
":",
",",
"0",
"]",
"y1",
"=",
"dets",
"[",
":",
",",
"1",
"]",
"x2",
"=",
"dets",
"[",
":",
",",
"2",
"]",
"y2",
"=",
"dets",
"[",
":",
",",
"3",
"]",
"... | https://github.com/yihui-he/KL-Loss/blob/66c0ed9e886a2218f4cf88c0efd4f40199bff54a/detectron/utils/py_cpu_nms.py#L175-L203 | |
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/geometry/line.py | python | LinearEntity.intersection | (self, o) | return o.intersection(self) | The intersection with another geometrical entity.
Parameters
==========
o : Point or LinearEntity
Returns
=======
intersection : list of geometrical entities
See Also
========
sympy.geometry.point.Point
Examples
========
>>> from sympy import Point, Line, Segment
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
>>> l1 = Line(p1, p2)
>>> l1.intersection(p3)
[Point(7, 7)]
>>> p4, p5 = Point(5, 0), Point(0, 3)
>>> l2 = Line(p4, p5)
>>> l1.intersection(l2)
[Point(15/8, 15/8)]
>>> p6, p7 = Point(0, 5), Point(2, 6)
>>> s1 = Segment(p6, p7)
>>> l1.intersection(s1)
[] | The intersection with another geometrical entity. | [
"The",
"intersection",
"with",
"another",
"geometrical",
"entity",
"."
] | def intersection(self, o):
"""The intersection with another geometrical entity.
Parameters
==========
o : Point or LinearEntity
Returns
=======
intersection : list of geometrical entities
See Also
========
sympy.geometry.point.Point
Examples
========
>>> from sympy import Point, Line, Segment
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
>>> l1 = Line(p1, p2)
>>> l1.intersection(p3)
[Point(7, 7)]
>>> p4, p5 = Point(5, 0), Point(0, 3)
>>> l2 = Line(p4, p5)
>>> l1.intersection(l2)
[Point(15/8, 15/8)]
>>> p6, p7 = Point(0, 5), Point(2, 6)
>>> s1 = Segment(p6, p7)
>>> l1.intersection(s1)
[]
"""
if isinstance(o, Point):
if o in self:
return [o]
else:
return []
elif isinstance(o, LinearEntity):
a1, b1, c1 = self.coefficients
a2, b2, c2 = o.coefficients
t = simplify(a1*b2 - a2*b1)
if t.equals(0) is not False: # assume they are parallel
if isinstance(self, Line):
if o.p1 in self:
return [o]
return []
elif isinstance(o, Line):
if self.p1 in o:
return [self]
return []
elif isinstance(self, Ray):
if isinstance(o, Ray):
# case 1, rays in the same direction
if self.xdirection == o.xdirection:
if self.source.x < o.source.x:
return [o]
return [self]
# case 2, rays in the opposite directions
else:
if o.source in self:
if self.source == o.source:
return [self.source]
return [Segment(o.source, self.source)]
return []
elif isinstance(o, Segment):
if o.p1 in self:
if o.p2 in self:
return [o]
return [Segment(o.p1, self.source)]
elif o.p2 in self:
return [Segment(o.p2, self.source)]
return []
elif isinstance(self, Segment):
if isinstance(o, Ray):
return o.intersection(self)
elif isinstance(o, Segment):
# A reminder that the points of Segments are ordered
# in such a way that the following works. See
# Segment.__new__ for details on the ordering.
if self.p1 not in o:
if self.p2 not in o:
# Neither of the endpoints are in o so either
# o is contained in this segment or it isn't
if o in self:
return [self]
return []
else:
# p1 not in o but p2 is. Either there is a
# segment as an intersection, or they only
# intersect at an endpoint
if self.p2 == o.p1:
return [o.p1]
return [Segment(o.p1, self.p2)]
elif self.p2 not in o:
# p2 not in o but p1 is. Either there is a
# segment as an intersection, or they only
# intersect at an endpoint
if self.p1 == o.p2:
return [o.p2]
return [Segment(o.p2, self.p1)]
# Both points of self in o so the whole segment
# is in o
return [self]
# Unknown linear entity
return []
# Not parallel, so find the point of intersection
px = simplify((b1*c2 - c1*b2) / t)
py = simplify((a2*c1 - a1*c2) / t)
inter = Point(px, py)
# we do not use a simplistic 'inter in self and inter in o'
# because that requires an equality test that is fragile;
# instead we employ some diagnostics to see if the intersection
# is valid
def inseg(self):
def _between(a, b, c):
return c >= a and c <= b or c <= a and c >= b
if _between(self.p1.x, self.p2.x, inter.x) and \
_between(self.p1.y, self.p2.y, inter.y):
return True
def inray(self):
sray = Ray(self.p1, inter)
if sray.xdirection == self.xdirection and \
sray.ydirection == self.ydirection:
return True
for i in range(2):
if isinstance(self, Line):
if isinstance(o, Line):
return [inter]
elif isinstance(o, Ray) and inray(o):
return [inter]
elif isinstance(o, Segment) and inseg(o):
return [inter]
elif isinstance(self, Ray) and inray(self):
if isinstance(o, Ray) and inray(o):
return [inter]
elif isinstance(o, Segment) and inseg(o):
return [inter]
elif isinstance(self, Segment) and inseg(self):
if isinstance(o, Segment) and inseg(o):
return [inter]
self, o = o, self
return []
return o.intersection(self) | [
"def",
"intersection",
"(",
"self",
",",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"Point",
")",
":",
"if",
"o",
"in",
"self",
":",
"return",
"[",
"o",
"]",
"else",
":",
"return",
"[",
"]",
"elif",
"isinstance",
"(",
"o",
",",
"LinearEnti... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/geometry/line.py#L625-L779 | |
fossasia/x-mario-center | fe67afe28d995dcf4e2498e305825a4859566172 | softwarecenter/backend/piston/rnrclient_pristine.py | python | RatingsAndReviewsAPI.review_stats | (self, origin='any', distroseries='any', days=None,
valid_days=(1, 3, 7)) | return self._get(url, scheme=PUBLIC_API_SCHEME) | Fetch ratings for a particular distroseries | Fetch ratings for a particular distroseries | [
"Fetch",
"ratings",
"for",
"a",
"particular",
"distroseries"
] | def review_stats(self, origin='any', distroseries='any', days=None,
valid_days=(1, 3, 7)):
"""Fetch ratings for a particular distroseries"""
url = 'review-stats/{0}/{1}/'.format(origin, distroseries)
if days is not None:
# the server only knows valid_days (1,3,7) currently
for valid_day in valid_days:
# pick the day from valid_days that is the next bigger than
# days
if days <= valid_day:
url += 'updates-last-{0}-days/'.format(valid_day)
break
return self._get(url, scheme=PUBLIC_API_SCHEME) | [
"def",
"review_stats",
"(",
"self",
",",
"origin",
"=",
"'any'",
",",
"distroseries",
"=",
"'any'",
",",
"days",
"=",
"None",
",",
"valid_days",
"=",
"(",
"1",
",",
"3",
",",
"7",
")",
")",
":",
"url",
"=",
"'review-stats/{0}/{1}/'",
".",
"format",
"... | https://github.com/fossasia/x-mario-center/blob/fe67afe28d995dcf4e2498e305825a4859566172/softwarecenter/backend/piston/rnrclient_pristine.py#L85-L97 | |
CGCookie/retopoflow | 3d8b3a47d1d661f99ab0aeb21d31370bf15de35e | retopoflow/rftool_knife/knife.py | python | Knife.main_enter | (self) | [] | def main_enter(self):
self.quick_knife = False
self.update_state_info() | [
"def",
"main_enter",
"(",
"self",
")",
":",
"self",
".",
"quick_knife",
"=",
"False",
"self",
".",
"update_state_info",
"(",
")"
] | https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/rftool_knife/knife.py#L152-L154 | ||||
git-cola/git-cola | b48b8028e0c3baf47faf7b074b9773737358163d | cola/core.py | python | run_command | (cmd, *args, **kwargs) | return (exit_code, output or UStr('', ENCODING), errors or UStr('', ENCODING)) | Run the given command to completion, and return its results.
This provides a simpler interface to the subprocess module.
The results are formatted as a 3-tuple: (exit_code, output, errors)
The other arguments are passed on to start_command(). | Run the given command to completion, and return its results. | [
"Run",
"the",
"given",
"command",
"to",
"completion",
"and",
"return",
"its",
"results",
"."
] | def run_command(cmd, *args, **kwargs):
"""Run the given command to completion, and return its results.
This provides a simpler interface to the subprocess module.
The results are formatted as a 3-tuple: (exit_code, output, errors)
The other arguments are passed on to start_command().
"""
encoding = kwargs.pop('encoding', None)
process = start_command(cmd, *args, **kwargs)
(output, errors) = communicate(process)
output = decode(output, encoding=encoding)
errors = decode(errors, encoding=encoding)
exit_code = process.returncode
return (exit_code, output or UStr('', ENCODING), errors or UStr('', ENCODING)) | [
"def",
"run_command",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"encoding",
"=",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"None",
")",
"process",
"=",
"start_command",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs... | https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/core.py#L263-L277 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/celery/utils/collections.py | python | ChainMap.__delitem__ | (self, key) | [] | def __delitem__(self, key):
# type: (Any) -> None
try:
del self.changes[self._key(key)]
except KeyError:
raise KeyError('Key not found in first mapping: {0!r}'.format(key)) | [
"def",
"__delitem__",
"(",
"self",
",",
"key",
")",
":",
"# type: (Any) -> None",
"try",
":",
"del",
"self",
".",
"changes",
"[",
"self",
".",
"_key",
"(",
"key",
")",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Key not found in first mapping... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/utils/collections.py#L289-L294 | ||||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/xml/dom/minidom.py | python | Node.getUserData | (self, key) | [] | def getUserData(self, key):
try:
return self._user_data[key][0]
except (AttributeError, KeyError):
return None | [
"def",
"getUserData",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"return",
"self",
".",
"_user_data",
"[",
"key",
"]",
"[",
"0",
"]",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"return",
"None"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/xml/dom/minidom.py#L230-L234 | ||||
openstack/nova | b49b7663e1c3073917d5844b81d38db8e86d05c4 | nova/compute/api.py | python | HostAPI.service_get_all | (self, context, filters=None, set_zones=False,
all_cells=False, cell_down_support=False) | return ret_services | Returns a list of services, optionally filtering the results.
If specified, 'filters' should be a dictionary containing services
attributes and matching values. Ie, to get a list of services for
the 'compute' topic, use filters={'topic': 'compute'}.
If all_cells=True, then scan all cells and merge the results.
If cell_down_support=True then return minimal service records
for cells that do not respond based on what we have in the
host mappings. These will have only 'binary' and 'host' set. | Returns a list of services, optionally filtering the results. | [
"Returns",
"a",
"list",
"of",
"services",
"optionally",
"filtering",
"the",
"results",
"."
] | def service_get_all(self, context, filters=None, set_zones=False,
all_cells=False, cell_down_support=False):
"""Returns a list of services, optionally filtering the results.
If specified, 'filters' should be a dictionary containing services
attributes and matching values. Ie, to get a list of services for
the 'compute' topic, use filters={'topic': 'compute'}.
If all_cells=True, then scan all cells and merge the results.
If cell_down_support=True then return minimal service records
for cells that do not respond based on what we have in the
host mappings. These will have only 'binary' and 'host' set.
"""
if filters is None:
filters = {}
disabled = filters.pop('disabled', None)
if 'availability_zone' in filters:
set_zones = True
# NOTE(danms): Eventually this all_cells nonsense should go away
# and we should always iterate over the cells. However, certain
# callers need the legacy behavior for now.
if all_cells:
services = []
service_dict = nova_context.scatter_gather_all_cells(context,
objects.ServiceList.get_all, disabled, set_zones=set_zones)
for cell_uuid, service in service_dict.items():
if not nova_context.is_cell_failure_sentinel(service):
services.extend(service)
elif cell_down_support:
unavailable_services = objects.ServiceList()
cid = [cm.id for cm in nova_context.CELLS
if cm.uuid == cell_uuid]
# We know cid[0] is in the list because we are using the
# same list that scatter_gather_all_cells used
hms = objects.HostMappingList.get_by_cell_id(context,
cid[0])
for hm in hms:
unavailable_services.objects.append(objects.Service(
binary='nova-compute', host=hm.host))
LOG.warning("Cell %s is not responding and hence only "
"partial results are available from this "
"cell.", cell_uuid)
services.extend(unavailable_services)
else:
LOG.warning("Cell %s is not responding and hence skipped "
"from the results.", cell_uuid)
else:
services = objects.ServiceList.get_all(context, disabled,
set_zones=set_zones)
ret_services = []
for service in services:
for key, val in filters.items():
if service[key] != val:
break
else:
# All filters matched.
ret_services.append(service)
return ret_services | [
"def",
"service_get_all",
"(",
"self",
",",
"context",
",",
"filters",
"=",
"None",
",",
"set_zones",
"=",
"False",
",",
"all_cells",
"=",
"False",
",",
"cell_down_support",
"=",
"False",
")",
":",
"if",
"filters",
"is",
"None",
":",
"filters",
"=",
"{",... | https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/compute/api.py#L5918-L5977 | |
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/django/contrib/localflavor/in_/forms.py | python | INStateSelect.__init__ | (self, attrs=None) | [] | def __init__(self, attrs=None):
super(INStateSelect, self).__init__(attrs, choices=STATE_CHOICES) | [
"def",
"__init__",
"(",
"self",
",",
"attrs",
"=",
"None",
")",
":",
"super",
"(",
"INStateSelect",
",",
"self",
")",
".",
"__init__",
"(",
"attrs",
",",
"choices",
"=",
"STATE_CHOICES",
")"
] | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/contrib/localflavor/in_/forms.py#L88-L89 | ||||
tensortrade-org/tensortrade | 019128713afd37590e3958a56db3ab0a3e6abe4c | tensortrade/feed/api/float/operations.py | python | truediv | (s1: "Stream[float]", s2: "Stream[float]") | return BinOp(np.divide, dtype="float")(s1, s2) | Computes the division of two float streams.
Parameters
----------
s1 : `Stream[float]`
The first float stream.
s2 : `Stream[float]` or float
The second float stream.
Returns
-------
`Stream[float]`
A stream created from dividing `s1` by `s2`. | Computes the division of two float streams. | [
"Computes",
"the",
"division",
"of",
"two",
"float",
"streams",
"."
] | def truediv(s1: "Stream[float]", s2: "Stream[float]") -> "Stream[float]":
"""Computes the division of two float streams.
Parameters
----------
s1 : `Stream[float]`
The first float stream.
s2 : `Stream[float]` or float
The second float stream.
Returns
-------
`Stream[float]`
A stream created from dividing `s1` by `s2`.
"""
if np.isscalar(s2):
s2 = Stream.constant(s2, dtype="float")
return BinOp(np.divide, dtype="float")(s1, s2)
return BinOp(np.divide, dtype="float")(s1, s2) | [
"def",
"truediv",
"(",
"s1",
":",
"\"Stream[float]\"",
",",
"s2",
":",
"\"Stream[float]\"",
")",
"->",
"\"Stream[float]\"",
":",
"if",
"np",
".",
"isscalar",
"(",
"s2",
")",
":",
"s2",
"=",
"Stream",
".",
"constant",
"(",
"s2",
",",
"dtype",
"=",
"\"fl... | https://github.com/tensortrade-org/tensortrade/blob/019128713afd37590e3958a56db3ab0a3e6abe4c/tensortrade/feed/api/float/operations.py#L140-L158 | |
snarfed/granary | ab085de2aef0cff8ac31a99b5e21443a249e8419 | granary/atom.py | python | _prepare_activity | (a, reader=True) | Preprocesses an activity to prepare it to be rendered as Atom.
Modifies a in place.
Args:
a: ActivityStreams 1 activity dict
reader: boolean, whether the output will be rendered in a feed reader.
Currently just includes location if True, not otherwise. | Preprocesses an activity to prepare it to be rendered as Atom. | [
"Preprocesses",
"an",
"activity",
"to",
"prepare",
"it",
"to",
"be",
"rendered",
"as",
"Atom",
"."
] | def _prepare_activity(a, reader=True):
"""Preprocesses an activity to prepare it to be rendered as Atom.
Modifies a in place.
Args:
a: ActivityStreams 1 activity dict
reader: boolean, whether the output will be rendered in a feed reader.
Currently just includes location if True, not otherwise.
"""
act_type = source.object_type(a)
obj = util.get_first(a, 'object', default={})
primary = obj if (not act_type or act_type == 'post') else a
# Render content as HTML; escape &s
obj['rendered_content'] = _encode_ampersands(microformats2.render_content(
primary, include_location=reader, render_attachments=True,
# Readers often obey CSS white-space: pre strictly and don't even line wrap,
# so don't use it.
# https://forum.newsblur.com/t/android-cant-read-line-pre-formatted-lines/6116
white_space_pre=False))
# Make sure every activity has the title field, since Atom <entry> requires
# the title element.
if not a.get('title'):
a['title'] = util.ellipsize(_encode_ampersands(
a.get('displayName') or a.get('content') or obj.get('title') or
obj.get('displayName') or obj.get('content') or 'Untitled'))
# strip HTML tags. the Atom spec says title is plain text:
# http://atomenabled.org/developers/syndication/#requiredEntryElements
a['title'] = xml.sax.saxutils.escape(util.parse_html(a['title']).get_text(''))
children = []
image_urls_seen = set()
image_atts = []
# normalize actors
for elem in a, obj:
_prepare_actor(elem.get('actor'))
# normalize attachments, render attached notes/articles
attachments = a.get('attachments') or obj.get('attachments') or []
for att in attachments:
att['stream'] = util.get_first(att, 'stream')
type = att.get('objectType')
if type == 'image':
att['image'] = util.get_first(att, 'image')
image_atts.append(att['image'])
continue
image_urls_seen |= set(util.get_urls(att, 'image'))
if type in ('note', 'article'):
html = microformats2.render_content(
att, include_location=reader, render_attachments=True,
white_space_pre=False)
author = att.get('author')
if author:
name = microformats2.maybe_linked_name(
microformats2.object_to_json(author).get('properties') or {})
html = f'{name.strip()}: {html}'
children.append(html)
# render image(s) that we haven't already seen
for image in image_atts + util.get_list(obj, 'image'):
if not image:
continue
url = image.get('url')
parsed = urllib.parse.urlparse(url)
rest = urllib.parse.urlunparse(('', '') + parsed[2:])
img_src_re = re.compile(r"""src *= *['"] *((https?:)?//%s)?%s *['"]""" %
(re.escape(parsed.netloc),
_encode_ampersands(re.escape(rest))))
if (url and url not in image_urls_seen and
not img_src_re.search(obj['rendered_content'])):
children.append(microformats2.img(url))
image_urls_seen.add(url)
obj['rendered_children'] = [_encode_ampersands(child) for child in children]
# make sure published and updated are strict RFC 3339 timestamps
for prop in 'published', 'updated':
val = obj.get(prop)
if val:
obj[prop] = util.maybe_iso8601_to_rfc3339(val)
# Atom timestamps are even stricter than RFC 3339: they can't be naive ie
# time zone unaware. They must have either an offset or the Z suffix.
# https://www.feedvalidator.org/docs/error/InvalidRFC3339Date.html
if not util.TIMEZONE_OFFSET_RE.search(obj[prop]):
obj[prop] += 'Z' | [
"def",
"_prepare_activity",
"(",
"a",
",",
"reader",
"=",
"True",
")",
":",
"act_type",
"=",
"source",
".",
"object_type",
"(",
"a",
")",
"obj",
"=",
"util",
".",
"get_first",
"(",
"a",
",",
"'object'",
",",
"default",
"=",
"{",
"}",
")",
"primary",
... | https://github.com/snarfed/granary/blob/ab085de2aef0cff8ac31a99b5e21443a249e8419/granary/atom.py#L339-L429 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/insights/v1/call_summaries.py | python | CallSummariesInstance.call_type | (self) | return self._properties['call_type'] | :returns: The call_type
:rtype: CallSummariesInstance.CallType | :returns: The call_type
:rtype: CallSummariesInstance.CallType | [
":",
"returns",
":",
"The",
"call_type",
":",
"rtype",
":",
"CallSummariesInstance",
".",
"CallType"
] | def call_type(self):
"""
:returns: The call_type
:rtype: CallSummariesInstance.CallType
"""
return self._properties['call_type'] | [
"def",
"call_type",
"(",
"self",
")",
":",
"return",
"self",
".",
"_properties",
"[",
"'call_type'",
"]"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/insights/v1/call_summaries.py#L393-L398 | |
stoq/stoq | c26991644d1affcf96bc2e0a0434796cabdf8448 | stoq/lib/gui/fiscalprinter.py | python | FiscalPrinterHelper.close_till | (self, close_db=True, close_ecf=True) | return retval | Closes the till
There are 3 possibilities for parameters combination:
* *total close*: Both *close_db* and *close_ecf* are ``True``.
The till on both will be closed.
* *partial close*: Both *close_db* and *close_ecf* are ``False``.
It's more like a till verification. The actual user will do it
to check and maybe remove money from till, leaving it ready
for the next one. Note that this will not emit
'till-status-changed' event, since the till will not
really close.
* *fix conflicting status*: *close_db* and *close_ecf* are
different. Use this only if you need to fix a conflicting
status, like if the DB is open but the ECF is closed, or
the other way around.
:param close_db: If the till in the DB should be closed
:param close_ecf: If the till in the ECF should be closed
:returns: True if the till was closed, otherwise False | Closes the till | [
"Closes",
"the",
"till"
] | def close_till(self, close_db=True, close_ecf=True):
"""Closes the till
There are 3 possibilities for parameters combination:
* *total close*: Both *close_db* and *close_ecf* are ``True``.
The till on both will be closed.
* *partial close*: Both *close_db* and *close_ecf* are ``False``.
It's more like a till verification. The actual user will do it
to check and maybe remove money from till, leaving it ready
for the next one. Note that this will not emit
'till-status-changed' event, since the till will not
really close.
* *fix conflicting status*: *close_db* and *close_ecf* are
different. Use this only if you need to fix a conflicting
status, like if the DB is open but the ECF is closed, or
the other way around.
:param close_db: If the till in the DB should be closed
:param close_ecf: If the till in the ECF should be closed
:returns: True if the till was closed, otherwise False
"""
is_partial = not close_db and not close_ecf
manager = get_plugin_manager()
# This behavior is only because of ECF
if not is_partial and not self._previous_day:
if (manager.is_active('ecf') and
not yesno(_("You can only close the till once per day. "
"You won't be able to make any more sales today.\n\n"
"Close the till?"),
Gtk.ResponseType.NO, _("Close Till"), _("Not now"))):
return
elif not is_partial:
# When closing from a previous day, close only what is needed.
close_db = self._close_db
close_ecf = self._close_ecf
if close_db:
till = Till.get_last_opened(self.store, api.get_current_station(self.store))
assert till
store = api.new_store()
editor_class = TillVerifyEditor if is_partial else TillClosingEditor
model = run_dialog(editor_class, self._parent, store,
previous_day=self._previous_day, close_db=close_db,
close_ecf=close_ecf)
if not model:
store.confirm(model)
store.close()
return
# TillClosingEditor closes the till
retval = store.confirm(model)
store.close()
if retval and not is_partial:
self._till_status_changed(closed=True, blocked=False)
return retval | [
"def",
"close_till",
"(",
"self",
",",
"close_db",
"=",
"True",
",",
"close_ecf",
"=",
"True",
")",
":",
"is_partial",
"=",
"not",
"close_db",
"and",
"not",
"close_ecf",
"manager",
"=",
"get_plugin_manager",
"(",
")",
"# This behavior is only because of ECF",
"i... | https://github.com/stoq/stoq/blob/c26991644d1affcf96bc2e0a0434796cabdf8448/stoq/lib/gui/fiscalprinter.py#L140-L198 | |
intake/intake | bc1d43524f9f0c38ccc5285d1f3fa02c37339372 | intake/utils.py | python | yaml_load | (stream) | Parse YAML in a context where duplicate keys raise exception | Parse YAML in a context where duplicate keys raise exception | [
"Parse",
"YAML",
"in",
"a",
"context",
"where",
"duplicate",
"keys",
"raise",
"exception"
] | def yaml_load(stream):
"""Parse YAML in a context where duplicate keys raise exception"""
with no_duplicate_yaml():
return yaml.safe_load(stream) | [
"def",
"yaml_load",
"(",
"stream",
")",
":",
"with",
"no_duplicate_yaml",
"(",
")",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"stream",
")"
] | https://github.com/intake/intake/blob/bc1d43524f9f0c38ccc5285d1f3fa02c37339372/intake/utils.py#L75-L78 | ||
wndhydrnt/python-oauth2 | d1f75e321bac049291925b9ee345bf4218f5b7a9 | oauth2/store/memory.py | python | TokenStore.delete_code | (self, code) | Deletes an authorization code after use
:param code: The authorization code. | Deletes an authorization code after use
:param code: The authorization code. | [
"Deletes",
"an",
"authorization",
"code",
"after",
"use",
":",
"param",
"code",
":",
"The",
"authorization",
"code",
"."
] | def delete_code(self, code):
"""
Deletes an authorization code after use
:param code: The authorization code.
"""
if code in self.auth_codes:
del self.auth_codes[code] | [
"def",
"delete_code",
"(",
"self",
",",
"code",
")",
":",
"if",
"code",
"in",
"self",
".",
"auth_codes",
":",
"del",
"self",
".",
"auth_codes",
"[",
"code",
"]"
] | https://github.com/wndhydrnt/python-oauth2/blob/d1f75e321bac049291925b9ee345bf4218f5b7a9/oauth2/store/memory.py#L115-L121 | ||
wwqgtxx/wwqLyParse | 33136508e52821babd9294fdecffbdf02d73a6fc | wwqLyParse/lib/python-3.7.2-embed-win32/Crypto/Math/Primality.py | python | lucas_test | (candidate) | return COMPOSITE | Perform a Lucas primality test on an integer.
The test is specified in Section C.3.3 of `FIPS PUB 186-4`__.
:Parameters:
candidate : integer
The number to test for primality.
:Returns:
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf | Perform a Lucas primality test on an integer. | [
"Perform",
"a",
"Lucas",
"primality",
"test",
"on",
"an",
"integer",
"."
] | def lucas_test(candidate):
"""Perform a Lucas primality test on an integer.
The test is specified in Section C.3.3 of `FIPS PUB 186-4`__.
:Parameters:
candidate : integer
The number to test for primality.
:Returns:
``Primality.COMPOSITE`` or ``Primality.PROBABLY_PRIME``.
.. __: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
if not isinstance(candidate, Integer):
candidate = Integer(candidate)
# Step 1
if candidate in (1, 2, 3, 5):
return PROBABLY_PRIME
if candidate.is_even() or candidate.is_perfect_square():
return COMPOSITE
# Step 2
def alternate():
value = 5
while True:
yield value
if value > 0:
value += 2
else:
value -= 2
value = -value
for D in alternate():
if candidate in (D, -D):
continue
js = Integer.jacobi_symbol(D, candidate)
if js == 0:
return COMPOSITE
if js == -1:
break
# Found D. P=1 and Q=(1-D)/4 (note that Q is guaranteed to be an integer)
# Step 3
# This is \delta(n) = n - jacobi(D/n)
K = candidate + 1
# Step 4
r = K.size_in_bits() - 1
# Step 5
# U_1=1 and V_1=P
U_i = Integer(1)
V_i = Integer(1)
U_temp = Integer(0)
V_temp = Integer(0)
# Step 6
for i in range(r - 1, -1, -1):
# Square
# U_temp = U_i * V_i % candidate
U_temp.set(U_i)
U_temp *= V_i
U_temp %= candidate
# V_temp = (((V_i ** 2 + (U_i ** 2 * D)) * K) >> 1) % candidate
V_temp.set(U_i)
V_temp *= U_i
V_temp *= D
V_temp.multiply_accumulate(V_i, V_i)
if V_temp.is_odd():
V_temp += candidate
V_temp >>= 1
V_temp %= candidate
# Multiply
if K.get_bit(i):
# U_i = (((U_temp + V_temp) * K) >> 1) % candidate
U_i.set(U_temp)
U_i += V_temp
if U_i.is_odd():
U_i += candidate
U_i >>= 1
U_i %= candidate
# V_i = (((V_temp + U_temp * D) * K) >> 1) % candidate
V_i.set(V_temp)
V_i.multiply_accumulate(U_temp, D)
if V_i.is_odd():
V_i += candidate
V_i >>= 1
V_i %= candidate
else:
U_i.set(U_temp)
V_i.set(V_temp)
# Step 7
if U_i == 0:
return PROBABLY_PRIME
return COMPOSITE | [
"def",
"lucas_test",
"(",
"candidate",
")",
":",
"if",
"not",
"isinstance",
"(",
"candidate",
",",
"Integer",
")",
":",
"candidate",
"=",
"Integer",
"(",
"candidate",
")",
"# Step 1",
"if",
"candidate",
"in",
"(",
"1",
",",
"2",
",",
"3",
",",
"5",
"... | https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/python-3.7.2-embed-win32/Crypto/Math/Primality.py#L116-L210 | |
blinktrade/bitex | a4896e7faef9c4aa0ca5325f18b77db67003764e | apps/mailer/mandrill.py | python | Tags.all_time_series | (self, ) | return self.master.call('tags/all-time-series', _params) | Return the recent history (hourly stats for the last 30 days) for all tags
Returns:
array. the array of history information::
[] (struct): the stats for a single hour::
[].time (string): the hour as a UTC date string in YYYY-MM-DD HH:MM:SS format
[].sent (integer): the number of emails that were sent during the hour
[].hard_bounces (integer): the number of emails that hard bounced during the hour
[].soft_bounces (integer): the number of emails that soft bounced during the hour
[].rejects (integer): the number of emails that were rejected during the hour
[].complaints (integer): the number of spam complaints received during the hour
[].unsubs (integer): the number of unsubscribes received during the hour
[].opens (integer): the number of emails opened during the hour
[].unique_opens (integer): the number of unique opens generated by messages sent during the hour
[].clicks (integer): the number of tracked URLs clicked during the hour
[].unique_clicks (integer): the number of unique clicks generated by messages sent during the hour
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred | Return the recent history (hourly stats for the last 30 days) for all tags | [
"Return",
"the",
"recent",
"history",
"(",
"hourly",
"stats",
"for",
"the",
"last",
"30",
"days",
")",
"for",
"all",
"tags"
] | def all_time_series(self, ):
"""Return the recent history (hourly stats for the last 30 days) for all tags
Returns:
array. the array of history information::
[] (struct): the stats for a single hour::
[].time (string): the hour as a UTC date string in YYYY-MM-DD HH:MM:SS format
[].sent (integer): the number of emails that were sent during the hour
[].hard_bounces (integer): the number of emails that hard bounced during the hour
[].soft_bounces (integer): the number of emails that soft bounced during the hour
[].rejects (integer): the number of emails that were rejected during the hour
[].complaints (integer): the number of spam complaints received during the hour
[].unsubs (integer): the number of unsubscribes received during the hour
[].opens (integer): the number of emails opened during the hour
[].unique_opens (integer): the number of unique opens generated by messages sent during the hour
[].clicks (integer): the number of tracked URLs clicked during the hour
[].unique_clicks (integer): the number of unique clicks generated by messages sent during the hour
Raises:
InvalidKeyError: The provided API key is not a valid Mandrill API key
Error: A general Mandrill error has occurred
"""
_params = {}
return self.master.call('tags/all-time-series', _params) | [
"def",
"all_time_series",
"(",
"self",
",",
")",
":",
"_params",
"=",
"{",
"}",
"return",
"self",
".",
"master",
".",
"call",
"(",
"'tags/all-time-series'",
",",
"_params",
")"
] | https://github.com/blinktrade/bitex/blob/a4896e7faef9c4aa0ca5325f18b77db67003764e/apps/mailer/mandrill.py#L1263-L1287 | |
pandas-dev/pandas | 5ba7d714014ae8feaccc0dd4a98890828cf2832d | pandas/core/computation/pytables.py | python | FilterBinOp.format | (self) | return [self.filter] | return the actual filter format | return the actual filter format | [
"return",
"the",
"actual",
"filter",
"format"
] | def format(self):
"""return the actual filter format"""
return [self.filter] | [
"def",
"format",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"filter",
"]"
] | https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/core/computation/pytables.py#L283-L285 | |
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | numba/core/pythonapi.py | python | PythonAPI.dict_new | (self, presize=0) | [] | def dict_new(self, presize=0):
if presize == 0:
fnty = Type.function(self.pyobj, ())
fn = self._get_function(fnty, name="PyDict_New")
return self.builder.call(fn, ())
else:
fnty = Type.function(self.pyobj, [self.py_ssize_t])
fn = self._get_function(fnty, name="_PyDict_NewPresized")
return self.builder.call(fn,
[Constant.int(self.py_ssize_t, presize)]) | [
"def",
"dict_new",
"(",
"self",
",",
"presize",
"=",
"0",
")",
":",
"if",
"presize",
"==",
"0",
":",
"fnty",
"=",
"Type",
".",
"function",
"(",
"self",
".",
"pyobj",
",",
"(",
")",
")",
"fn",
"=",
"self",
".",
"_get_function",
"(",
"fnty",
",",
... | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/pythonapi.py#L426-L435 | ||||
ldx/python-iptables | 542efdb739b4e3ef6f28274d23b506bf0027eec2 | iptc/easy.py | python | get_rule | (table, chain, position=0, ipv6=False, raise_exc=True) | Get a rule from a chain in a given position. 0=all rules, 1=first, n=nth position | Get a rule from a chain in a given position. 0=all rules, 1=first, n=nth position | [
"Get",
"a",
"rule",
"from",
"a",
"chain",
"in",
"a",
"given",
"position",
".",
"0",
"=",
"all",
"rules",
"1",
"=",
"first",
"n",
"=",
"nth",
"position"
] | def get_rule(table, chain, position=0, ipv6=False, raise_exc=True):
""" Get a rule from a chain in a given position. 0=all rules, 1=first, n=nth position """
try:
if position == 0:
# Return all rules
return dump_chain(table, chain, ipv6)
elif position > 0:
# Return specific rule by position
iptc_chain = _iptc_getchain(table, chain, ipv6)
iptc_rule = iptc_chain.rules[position - 1]
return decode_iptc_rule(iptc_rule, ipv6)
elif position < 0:
# Return last rule -> not available in iptables CLI
iptc_chain = _iptc_getchain(table, chain, ipv6)
iptc_rule = iptc_chain.rules[position]
return decode_iptc_rule(iptc_rule, ipv6)
except Exception as e:
if raise_exc: raise | [
"def",
"get_rule",
"(",
"table",
",",
"chain",
",",
"position",
"=",
"0",
",",
"ipv6",
"=",
"False",
",",
"raise_exc",
"=",
"True",
")",
":",
"try",
":",
"if",
"position",
"==",
"0",
":",
"# Return all rules",
"return",
"dump_chain",
"(",
"table",
",",... | https://github.com/ldx/python-iptables/blob/542efdb739b4e3ef6f28274d23b506bf0027eec2/iptc/easy.py#L120-L137 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/core.py | python | State.name | (self) | return self.attributes.get(ATTR_FRIENDLY_NAME) or self.object_id.replace(
"_", " "
) | Name of this state. | Name of this state. | [
"Name",
"of",
"this",
"state",
"."
] | def name(self) -> str:
"""Name of this state."""
return self.attributes.get(ATTR_FRIENDLY_NAME) or self.object_id.replace(
"_", " "
) | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"attributes",
".",
"get",
"(",
"ATTR_FRIENDLY_NAME",
")",
"or",
"self",
".",
"object_id",
".",
"replace",
"(",
"\"_\"",
",",
"\" \"",
")"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/core.py#L1060-L1064 | |
pallets/werkzeug | 9efe8c00dcb2b6fc086961ba304729db01912652 | src/werkzeug/routing.py | python | Rule.get_empty_kwargs | (self) | return dict(
defaults=defaults,
subdomain=self.subdomain,
methods=self.methods,
build_only=self.build_only,
endpoint=self.endpoint,
strict_slashes=self.strict_slashes,
redirect_to=self.redirect_to,
alias=self.alias,
host=self.host,
) | Provides kwargs for instantiating empty copy with empty()
Use this method to provide custom keyword arguments to the subclass of
``Rule`` when calling ``some_rule.empty()``. Helpful when the subclass
has custom keyword arguments that are needed at instantiation.
Must return a ``dict`` that will be provided as kwargs to the new
instance of ``Rule``, following the initial ``self.rule`` value which
is always provided as the first, required positional argument. | Provides kwargs for instantiating empty copy with empty() | [
"Provides",
"kwargs",
"for",
"instantiating",
"empty",
"copy",
"with",
"empty",
"()"
] | def get_empty_kwargs(self) -> t.Mapping[str, t.Any]:
"""
Provides kwargs for instantiating empty copy with empty()
Use this method to provide custom keyword arguments to the subclass of
``Rule`` when calling ``some_rule.empty()``. Helpful when the subclass
has custom keyword arguments that are needed at instantiation.
Must return a ``dict`` that will be provided as kwargs to the new
instance of ``Rule``, following the initial ``self.rule`` value which
is always provided as the first, required positional argument.
"""
defaults = None
if self.defaults:
defaults = dict(self.defaults)
return dict(
defaults=defaults,
subdomain=self.subdomain,
methods=self.methods,
build_only=self.build_only,
endpoint=self.endpoint,
strict_slashes=self.strict_slashes,
redirect_to=self.redirect_to,
alias=self.alias,
host=self.host,
) | [
"def",
"get_empty_kwargs",
"(",
"self",
")",
"->",
"t",
".",
"Mapping",
"[",
"str",
",",
"t",
".",
"Any",
"]",
":",
"defaults",
"=",
"None",
"if",
"self",
".",
"defaults",
":",
"defaults",
"=",
"dict",
"(",
"self",
".",
"defaults",
")",
"return",
"... | https://github.com/pallets/werkzeug/blob/9efe8c00dcb2b6fc086961ba304729db01912652/src/werkzeug/routing.py#L747-L772 | |
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/cinder/cinder/volume/drivers/emc/emc_smis_iscsi.py | python | EMCSMISISCSIDriver.create_volume_from_snapshot | (self, volume, snapshot) | Creates a volume from a snapshot. | Creates a volume from a snapshot. | [
"Creates",
"a",
"volume",
"from",
"a",
"snapshot",
"."
] | def create_volume_from_snapshot(self, volume, snapshot):
"""Creates a volume from a snapshot."""
self.common.create_volume_from_snapshot(volume, snapshot) | [
"def",
"create_volume_from_snapshot",
"(",
"self",
",",
"volume",
",",
"snapshot",
")",
":",
"self",
".",
"common",
".",
"create_volume_from_snapshot",
"(",
"volume",
",",
"snapshot",
")"
] | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/volume/drivers/emc/emc_smis_iscsi.py#L55-L57 | ||
natashamjaques/neural_chat | ddb977bb4602a67c460d02231e7bbf7b2cb49a97 | ParlAI/parlai/core/worlds.py | python | BatchWorld.display | (self) | return s | Display the full batch. | Display the full batch. | [
"Display",
"the",
"full",
"batch",
"."
] | def display(self):
"""Display the full batch."""
s = "[--batchsize " + str(len(self.worlds)) + "--]\n"
for i, w in enumerate(self.worlds):
s += "[batch world " + str(i) + ":]\n"
s += w.display() + '\n'
s += "[--end of batch--]"
return s | [
"def",
"display",
"(",
"self",
")",
":",
"s",
"=",
"\"[--batchsize \"",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"worlds",
")",
")",
"+",
"\"--]\\n\"",
"for",
"i",
",",
"w",
"in",
"enumerate",
"(",
"self",
".",
"worlds",
")",
":",
"s",
"+=",
"\"... | https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/core/worlds.py#L750-L757 | |
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/tkinter/ttk.py | python | Treeview.parent | (self, item) | return self.tk.call(self._w, "parent", item) | Returns the ID of the parent of item, or '' if item is at the
top level of the hierarchy. | Returns the ID of the parent of item, or '' if item is at the
top level of the hierarchy. | [
"Returns",
"the",
"ID",
"of",
"the",
"parent",
"of",
"item",
"or",
"if",
"item",
"is",
"at",
"the",
"top",
"level",
"of",
"the",
"hierarchy",
"."
] | def parent(self, item):
"""Returns the ID of the parent of item, or '' if item is at the
top level of the hierarchy."""
return self.tk.call(self._w, "parent", item) | [
"def",
"parent",
"(",
"self",
",",
"item",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"\"parent\"",
",",
"item",
")"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/tkinter/ttk.py#L1372-L1375 | |
IBM/lale | b4d6829c143a4735b06083a0e6c70d2cca244162 | lale/operators.py | python | TrainedOperator.__rshift__ | (self, other: Union[Any, "Operator"]) | [] | def __rshift__(self, other: Union[Any, "Operator"]) -> "PlannedPipeline":
... | [
"def",
"__rshift__",
"(",
"self",
",",
"other",
":",
"Union",
"[",
"Any",
",",
"\"Operator\"",
"]",
")",
"->",
"\"PlannedPipeline\"",
":",
"..."
] | https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/operators.py#L1054-L1055 | ||||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/pty.py | python | slave_open | (tty_name) | return result | slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead. | slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead. | [
"slave_open",
"(",
"tty_name",
")",
"-",
">",
"slave_fd",
"Open",
"the",
"pty",
"slave",
"and",
"acquire",
"the",
"controlling",
"terminal",
"returning",
"opened",
"filedescriptor",
".",
"Deprecated",
"use",
"openpty",
"()",
"instead",
"."
] | def slave_open(tty_name):
"""slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead."""
result = os.open(tty_name, os.O_RDWR)
try:
from fcntl import ioctl, I_PUSH
except ImportError:
return result
try:
ioctl(result, I_PUSH, "ptem")
ioctl(result, I_PUSH, "ldterm")
except OSError:
pass
return result | [
"def",
"slave_open",
"(",
"tty_name",
")",
":",
"result",
"=",
"os",
".",
"open",
"(",
"tty_name",
",",
"os",
".",
"O_RDWR",
")",
"try",
":",
"from",
"fcntl",
"import",
"ioctl",
",",
"I_PUSH",
"except",
"ImportError",
":",
"return",
"result",
"try",
":... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/pty.py#L66-L82 | |
jobovy/galpy | 8e6a230bbe24ce16938db10053f92eb17fe4bb52 | galpy/potential/MovingObjectPotential.py | python | MovingObjectPotential._phiforce | (self,R,z,phi=0.,t=0.) | return -RF*R*(numpy.cos(phi)*yd-numpy.sin(phi)*xd)/Rdist | NAME:
_phiforce
PURPOSE:
evaluate the azimuthal force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the azimuthal force
HISTORY:
2011-04-10 - Written - Bovy (NYU)
2018-10-18 - Updated for general object potential - James Lane (UofT) | NAME:
_phiforce
PURPOSE:
evaluate the azimuthal force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the azimuthal force
HISTORY:
2011-04-10 - Written - Bovy (NYU)
2018-10-18 - Updated for general object potential - James Lane (UofT) | [
"NAME",
":",
"_phiforce",
"PURPOSE",
":",
"evaluate",
"the",
"azimuthal",
"force",
"for",
"this",
"potential",
"INPUT",
":",
"R",
"-",
"Galactocentric",
"cylindrical",
"radius",
"z",
"-",
"vertical",
"height",
"phi",
"-",
"azimuth",
"t",
"-",
"time",
"OUTPUT... | def _phiforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_phiforce
PURPOSE:
evaluate the azimuthal force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the azimuthal force
HISTORY:
2011-04-10 - Written - Bovy (NYU)
2018-10-18 - Updated for general object potential - James Lane (UofT)
"""
#Cylindrical distance
Rdist = _cylR(R,phi,self._orb.R(t),self._orb.phi(t))
# Difference vector
orbz = self._orb.z(t) if self._orb.dim() == 3 else 0
(xd,yd,zd) = _cyldiff(self._orb.R(t), self._orb.phi(t), orbz,
R, phi, z)
#Evaluate cylindrical radial force.
RF = evaluateRforces(self._pot,Rdist,zd,t=t,use_physical=False)
# Return phi force, negative of phi vector to evaluate location
return -RF*R*(numpy.cos(phi)*yd-numpy.sin(phi)*xd)/Rdist | [
"def",
"_phiforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"#Cylindrical distance",
"Rdist",
"=",
"_cylR",
"(",
"R",
",",
"phi",
",",
"self",
".",
"_orb",
".",
"R",
"(",
"t",
")",
",",
"self",
"... | https://github.com/jobovy/galpy/blob/8e6a230bbe24ce16938db10053f92eb17fe4bb52/galpy/potential/MovingObjectPotential.py#L143-L169 | |
dbrattli/aioreactive | e057264a5905964c68d443b98b3e602279b3b9ed | aioreactive/create.py | python | empty | () | return AsyncAnonymousObservable(subscribe_async) | Returns an observable sequence with no elements. | Returns an observable sequence with no elements. | [
"Returns",
"an",
"observable",
"sequence",
"with",
"no",
"elements",
"."
] | def empty() -> AsyncObservable[Any]:
"""Returns an observable sequence with no elements."""
async def subscribe_async(aobv: AsyncObserver[Any]) -> AsyncDisposable:
await aobv.aclose()
return AsyncDisposable.empty()
return AsyncAnonymousObservable(subscribe_async) | [
"def",
"empty",
"(",
")",
"->",
"AsyncObservable",
"[",
"Any",
"]",
":",
"async",
"def",
"subscribe_async",
"(",
"aobv",
":",
"AsyncObserver",
"[",
"Any",
"]",
")",
"->",
"AsyncDisposable",
":",
"await",
"aobv",
".",
"aclose",
"(",
")",
"return",
"AsyncD... | https://github.com/dbrattli/aioreactive/blob/e057264a5905964c68d443b98b3e602279b3b9ed/aioreactive/create.py#L115-L122 | |
ifwe/digsby | f5fe00244744aa131e07f09348d10563f3d8fa99 | digsby/src/plugins/feed_trends/feed_trends.py | python | OneRiotAdSource.request_ads | (self, success, error=None) | requests a set of ads from oneriot | requests a set of ads from oneriot | [
"requests",
"a",
"set",
"of",
"ads",
"from",
"oneriot"
] | def request_ads(self, success, error=None):
'''requests a set of ads from oneriot'''
def on_success(req, resp):
try:
data = resp.read()
ads = NewsItemList.from_xml(data, filter_html=True)
log.info('got %d ads', len(ads) if ads else 0)
except Exception as e:
traceback.print_exc()
if error is not None:
error(e)
log.error('error retrieving ads')
else:
success(ads)
log.info('requesting feed ads from %r' % self.url)
self.update_count += 1
asynchttp.httpopen(self.url, success=on_success, error=error) | [
"def",
"request_ads",
"(",
"self",
",",
"success",
",",
"error",
"=",
"None",
")",
":",
"def",
"on_success",
"(",
"req",
",",
"resp",
")",
":",
"try",
":",
"data",
"=",
"resp",
".",
"read",
"(",
")",
"ads",
"=",
"NewsItemList",
".",
"from_xml",
"("... | https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/plugins/feed_trends/feed_trends.py#L910-L928 | ||
alberanid/imdbpy | 88cf37772186e275eff212857f512669086b382c | imdb/helpers.py | python | makeObject2Txt | (movieTxt=None, personTxt=None, characterTxt=None,
companyTxt=None, joiner=' / ',
applyToValues=lambda x: x, _recurse=True) | return object2txt | Return a function useful to pretty-print Movie, Person,
Character and Company instances.
*movieTxt* -- how to format a Movie object.
*personTxt* -- how to format a Person object.
*characterTxt* -- how to format a Character object.
*companyTxt* -- how to format a Company object.
*joiner* -- string used to join a list of objects.
*applyToValues* -- function to apply to values.
*_recurse* -- if True (default) manage only the given object. | Return a function useful to pretty-print Movie, Person,
Character and Company instances. | [
"Return",
"a",
"function",
"useful",
"to",
"pretty",
"-",
"print",
"Movie",
"Person",
"Character",
"and",
"Company",
"instances",
"."
] | def makeObject2Txt(movieTxt=None, personTxt=None, characterTxt=None,
companyTxt=None, joiner=' / ',
applyToValues=lambda x: x, _recurse=True):
""""Return a function useful to pretty-print Movie, Person,
Character and Company instances.
*movieTxt* -- how to format a Movie object.
*personTxt* -- how to format a Person object.
*characterTxt* -- how to format a Character object.
*companyTxt* -- how to format a Company object.
*joiner* -- string used to join a list of objects.
*applyToValues* -- function to apply to values.
*_recurse* -- if True (default) manage only the given object.
"""
# Some useful defaults.
if movieTxt is None:
movieTxt = '%(long imdb title)s'
if personTxt is None:
personTxt = '%(long imdb name)s'
if characterTxt is None:
characterTxt = '%(long imdb name)s'
if companyTxt is None:
companyTxt = '%(long imdb name)s'
def object2txt(obj, _limitRecursion=None):
"""Pretty-print objects."""
# Prevent unlimited recursion.
if _limitRecursion is None:
_limitRecursion = 0
elif _limitRecursion > 5:
return ''
_limitRecursion += 1
if isinstance(obj, (list, tuple)):
return joiner.join([object2txt(o, _limitRecursion=_limitRecursion)
for o in obj])
elif isinstance(obj, dict):
# XXX: not exactly nice, neither useful, I fear.
return joiner.join(
['%s::%s' % (object2txt(k, _limitRecursion=_limitRecursion),
object2txt(v, _limitRecursion=_limitRecursion))
for k, v in list(obj.items())]
)
objData = {}
if isinstance(obj, Movie):
objData['movieID'] = obj.movieID
outs = movieTxt
elif isinstance(obj, Person):
objData['personID'] = obj.personID
outs = personTxt
elif isinstance(obj, Character):
objData['characterID'] = obj.characterID
outs = characterTxt
elif isinstance(obj, Company):
objData['companyID'] = obj.companyID
outs = companyTxt
else:
return obj
def _excludeFalseConditionals(matchobj):
# Return an empty string if the conditional is false/empty.
condition = matchobj.group(1)
proceed = obj.get(condition) or getattr(obj, condition, None)
if proceed:
return matchobj.group(2)
else:
return ''
while re_conditional.search(outs):
outs = re_conditional.sub(_excludeFalseConditionals, outs)
for key in re_subst.findall(outs):
value = obj.get(key) or getattr(obj, key, None)
if not isinstance(value, str):
if not _recurse:
if value:
value = str(value)
if value:
value = object2txt(value, _limitRecursion=_limitRecursion)
elif value:
value = applyToValues(str(value))
if not value:
value = ''
elif not isinstance(value, str):
value = str(value)
outs = outs.replace('%(' + key + ')s', value)
return outs
return object2txt | [
"def",
"makeObject2Txt",
"(",
"movieTxt",
"=",
"None",
",",
"personTxt",
"=",
"None",
",",
"characterTxt",
"=",
"None",
",",
"companyTxt",
"=",
"None",
",",
"joiner",
"=",
"' / '",
",",
"applyToValues",
"=",
"lambda",
"x",
":",
"x",
",",
"_recurse",
"=",... | https://github.com/alberanid/imdbpy/blob/88cf37772186e275eff212857f512669086b382c/imdb/helpers.py#L118-L202 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/plat-mac/aetools.py | python | TalkTo.__init__ | (self, signature=None, start=0, timeout=0) | Create a communication channel with a particular application.
Addressing the application is done by specifying either a
4-byte signature, an AEDesc or an object that will __aepack__
to an AEDesc. | Create a communication channel with a particular application. | [
"Create",
"a",
"communication",
"channel",
"with",
"a",
"particular",
"application",
"."
] | def __init__(self, signature=None, start=0, timeout=0):
"""Create a communication channel with a particular application.
Addressing the application is done by specifying either a
4-byte signature, an AEDesc or an object that will __aepack__
to an AEDesc.
"""
self.target_signature = None
if signature is None:
signature = self._signature
if type(signature) == AEDescType:
self.target = signature
elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
self.target = signature.__aepack__()
elif type(signature) == StringType and len(signature) == 4:
self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
self.target_signature = signature
else:
raise TypeError, "signature should be 4-char string or AEDesc"
self.send_flags = AppleEvents.kAEWaitReply
self.send_priority = AppleEvents.kAENormalPriority
if timeout:
self.send_timeout = timeout
else:
self.send_timeout = AppleEvents.kAEDefaultTimeout
if start:
self._start() | [
"def",
"__init__",
"(",
"self",
",",
"signature",
"=",
"None",
",",
"start",
"=",
"0",
",",
"timeout",
"=",
"0",
")",
":",
"self",
".",
"target_signature",
"=",
"None",
"if",
"signature",
"is",
"None",
":",
"signature",
"=",
"self",
".",
"_signature",
... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/plat-mac/aetools.py#L163-L189 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.py | python | decode | (input, fallback_encoding, errors='replace') | return encoding.codec_info.decode(input, errors)[0], encoding | Decode a single string.
:param input: A byte string
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:return:
A ``(output, encoding)`` tuple of an Unicode string
and an :obj:`Encoding`. | Decode a single string. | [
"Decode",
"a",
"single",
"string",
"."
] | def decode(input, fallback_encoding, errors='replace'):
"""
Decode a single string.
:param input: A byte string
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:return:
A ``(output, encoding)`` tuple of an Unicode string
and an :obj:`Encoding`.
"""
# Fail early if `encoding` is an invalid label.
fallback_encoding = _get_encoding(fallback_encoding)
bom_encoding, input = _detect_bom(input)
encoding = bom_encoding or fallback_encoding
return encoding.codec_info.decode(input, errors)[0], encoding | [
"def",
"decode",
"(",
"input",
",",
"fallback_encoding",
",",
"errors",
"=",
"'replace'",
")",
":",
"# Fail early if `encoding` is an invalid label.",
"fallback_encoding",
"=",
"_get_encoding",
"(",
"fallback_encoding",
")",
"bom_encoding",
",",
"input",
"=",
"_detect_b... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.py#L139-L158 | |
kanzure/nanoengineer | 874e4c9f8a9190f093625b267f9767e19f82e6c4 | cad/src/ne1_ui/MWsemantics.py | python | MWsemantics._init_after_geometry_is_set | (self) | return | Do whatever initialization of self needs to wait until its geometry has been set.
[Should be called only once, after geometry is set; can be called before self is shown.
As of 070531, this is called directly from main.py, after our __init__ but before we're first shown.] | Do whatever initialization of self needs to wait until its geometry has been set.
[Should be called only once, after geometry is set; can be called before self is shown.
As of 070531, this is called directly from main.py, after our __init__ but before we're first shown.] | [
"Do",
"whatever",
"initialization",
"of",
"self",
"needs",
"to",
"wait",
"until",
"its",
"geometry",
"has",
"been",
"set",
".",
"[",
"Should",
"be",
"called",
"only",
"once",
"after",
"geometry",
"is",
"set",
";",
"can",
"be",
"called",
"before",
"self",
... | def _init_after_geometry_is_set(self): #bruce 060104 renamed this from startRun and replaced its docstring.
"""
Do whatever initialization of self needs to wait until its geometry has been set.
[Should be called only once, after geometry is set; can be called before self is shown.
As of 070531, this is called directly from main.py, after our __init__ but before we're first shown.]
"""
# older docstring:
# After the main window(its size and location) has been setup, begin to run the program from this method.
# [Huaicai 11/1/05: try to fix the initial MMKitWin off screen problem by splitting from the __init__() method]
self.win_update() # bruce 041222
undo_internals.just_before_mainwindow_init_returns() # (this is now misnamed, now that it's not part of __init__)
return | [
"def",
"_init_after_geometry_is_set",
"(",
"self",
")",
":",
"#bruce 060104 renamed this from startRun and replaced its docstring.",
"# older docstring:",
"# After the main window(its size and location) has been setup, begin to run the program from this method.",
"# [Huaicai 11/1/05: try to fix th... | https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/ne1_ui/MWsemantics.py#L628-L640 | |
cool-RR/python_toolbox | cb9ef64b48f1d03275484d707dc5079b6701ad0c | python_toolbox/third_party/envelopes/envelope.py | python | Envelope.clear_headers | (self) | Clears custom headers. | Clears custom headers. | [
"Clears",
"custom",
"headers",
"."
] | def clear_headers(self):
"""Clears custom headers."""
self._headers = {} | [
"def",
"clear_headers",
"(",
"self",
")",
":",
"self",
".",
"_headers",
"=",
"{",
"}"
] | https://github.com/cool-RR/python_toolbox/blob/cb9ef64b48f1d03275484d707dc5079b6701ad0c/python_toolbox/third_party/envelopes/envelope.py#L225-L227 | ||
tao12345666333/tornado-zh | e9e8519beb147d9e1290f6a4fa7d61123d1ecb1c | tornado/iostream.py | python | BaseIOStream.write_to_fd | (self, data) | Attempts to write ``data`` to the underlying file.
Returns the number of bytes written. | Attempts to write ``data`` to the underlying file. | [
"Attempts",
"to",
"write",
"data",
"to",
"the",
"underlying",
"file",
"."
] | def write_to_fd(self, data):
"""Attempts to write ``data`` to the underlying file.
Returns the number of bytes written.
"""
raise NotImplementedError() | [
"def",
"write_to_fd",
"(",
"self",
",",
"data",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/tao12345666333/tornado-zh/blob/e9e8519beb147d9e1290f6a4fa7d61123d1ecb1c/tornado/iostream.py#L202-L207 | ||
google/tangent | 6533e83af09de7345d1b438512679992f080dcc9 | tangent/funcsigs.py | python | Signature.replace | (self, parameters=_void, return_annotation=_void) | return type(self)(parameters,
return_annotation=return_annotation) | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy. | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy. | [
"Creates",
"a",
"customized",
"copy",
"of",
"the",
"Signature",
".",
"Pass",
"parameters",
"and",
"/",
"or",
"return_annotation",
"arguments",
"to",
"override",
"them",
"in",
"the",
"new",
"copy",
"."
] | def replace(self, parameters=_void, return_annotation=_void):
'''Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
'''
if parameters is _void:
parameters = self.parameters.values()
if return_annotation is _void:
return_annotation = self._return_annotation
return type(self)(parameters,
return_annotation=return_annotation) | [
"def",
"replace",
"(",
"self",
",",
"parameters",
"=",
"_void",
",",
"return_annotation",
"=",
"_void",
")",
":",
"if",
"parameters",
"is",
"_void",
":",
"parameters",
"=",
"self",
".",
"parameters",
".",
"values",
"(",
")",
"if",
"return_annotation",
"is"... | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/funcsigs.py#L626-L639 | |
shiweibsw/Translation-Tools | 2fbbf902364e557fa7017f9a74a8797b7440c077 | venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/html5lib/treebuilders/base.py | python | TreeBuilder.insertElementTable | (self, token) | return element | Create an element and insert it into the tree | Create an element and insert it into the tree | [
"Create",
"an",
"element",
"and",
"insert",
"it",
"into",
"the",
"tree"
] | def insertElementTable(self, token):
"""Create an element and insert it into the tree"""
element = self.createElement(token)
if self.openElements[-1].name not in tableInsertModeElements:
return self.insertElementNormal(token)
else:
# We should be in the InTable mode. This means we want to do
# special magic element rearranging
parent, insertBefore = self.getTableMisnestedNodePosition()
if insertBefore is None:
parent.appendChild(element)
else:
parent.insertBefore(element, insertBefore)
self.openElements.append(element)
return element | [
"def",
"insertElementTable",
"(",
"self",
",",
"token",
")",
":",
"element",
"=",
"self",
".",
"createElement",
"(",
"token",
")",
"if",
"self",
".",
"openElements",
"[",
"-",
"1",
"]",
".",
"name",
"not",
"in",
"tableInsertModeElements",
":",
"return",
... | https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/html5lib/treebuilders/base.py#L302-L316 | |
jachris/cook | dd451e11f9aef05ba54bd57cf03e941526ffceef | cook/misc.py | python | run | (
command, outputs, inputs=None, message=None, env=None, timeout=None,
cwd=None
) | [] | def run(
command, outputs, inputs=None, message=None, env=None, timeout=None,
cwd=None
):
inputs = core.resolve(inputs or [])
outputs = core.build(outputs)
command[0] = core.which(command[0])
yield core.publish(
inputs=inputs + [command[0]],
outputs=outputs,
message=message or 'Running "{}"'.format(command[0]),
check=[env, command]
)
real = []
for token in command:
if token == '$INPUTS':
real.extend(inputs)
elif token == '$OUTPUTS':
real.extend(outputs)
else:
real.append(token)
core.call(real, env=env, timeout=timeout, cwd=cwd) | [
"def",
"run",
"(",
"command",
",",
"outputs",
",",
"inputs",
"=",
"None",
",",
"message",
"=",
"None",
",",
"env",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"inputs",
"=",
"core",
".",
"resolve",
"(",
"inputs",
... | https://github.com/jachris/cook/blob/dd451e11f9aef05ba54bd57cf03e941526ffceef/cook/misc.py#L5-L28 | ||||
aparo/django-elasticsearch | 8fd25bd86b58cfc0d6490cfac08e4846ab4ddf97 | django_elasticsearch/manager.py | python | QuerySet.exec_js | (self, code, *fields, **options) | return collection.database.eval(code, *fields) | Execute a Javascript function on the server. A list of fields may be
provided, which will be translated to their correct names and supplied
as the arguments to the function. A few extra variables are added to
the function's scope: ``collection``, which is the name of the
collection in use; ``query``, which is an object representing the
current query; and ``options``, which is an object containing any
options specified as keyword arguments.
As fields in MongoEngine may use different names in the database (set
using the :attr:`db_field` keyword argument to a :class:`Field`
constructor), a mechanism exists for replacing MongoEngine field names
with the database field names in Javascript code. When accessing a
field, use square-bracket notation, and prefix the MongoEngine field
name with a tilde (~).
:param code: a string of Javascript code to execute
:param fields: fields that you will be using in your function, which
will be passed in to your function as arguments
:param options: options that you want available to the function
(accessed in Javascript through the ``options`` object) | Execute a Javascript function on the server. A list of fields may be
provided, which will be translated to their correct names and supplied
as the arguments to the function. A few extra variables are added to
the function's scope: ``collection``, which is the name of the
collection in use; ``query``, which is an object representing the
current query; and ``options``, which is an object containing any
options specified as keyword arguments. | [
"Execute",
"a",
"Javascript",
"function",
"on",
"the",
"server",
".",
"A",
"list",
"of",
"fields",
"may",
"be",
"provided",
"which",
"will",
"be",
"translated",
"to",
"their",
"correct",
"names",
"and",
"supplied",
"as",
"the",
"arguments",
"to",
"the",
"f... | def exec_js(self, code, *fields, **options):
"""
Execute a Javascript function on the server. A list of fields may be
provided, which will be translated to their correct names and supplied
as the arguments to the function. A few extra variables are added to
the function's scope: ``collection``, which is the name of the
collection in use; ``query``, which is an object representing the
current query; and ``options``, which is an object containing any
options specified as keyword arguments.
As fields in MongoEngine may use different names in the database (set
using the :attr:`db_field` keyword argument to a :class:`Field`
constructor), a mechanism exists for replacing MongoEngine field names
with the database field names in Javascript code. When accessing a
field, use square-bracket notation, and prefix the MongoEngine field
name with a tilde (~).
:param code: a string of Javascript code to execute
:param fields: fields that you will be using in your function, which
will be passed in to your function as arguments
:param options: options that you want available to the function
(accessed in Javascript through the ``options`` object)
"""
# code = self._sub_js_fields(code)
fields = [QuerySet._translate_field_name(self._document, f) for f in fields]
collection = self._collection
scope = {
'collection': collection.name,
'options': options or {},
}
query = self._query
if self._where_clause:
query['$where'] = self._where_clause
scope['query'] = query
code = pymongo.code.Code(code, scope=scope)
return collection.database.eval(code, *fields) | [
"def",
"exec_js",
"(",
"self",
",",
"code",
",",
"*",
"fields",
",",
"*",
"*",
"options",
")",
":",
"# code = self._sub_js_fields(code)",
"fields",
"=",
"[",
"QuerySet",
".",
"_translate_field_name",
"(",
"self",
".",
"_document",
",",
"f",
")",
"for"... | https://github.com/aparo/django-elasticsearch/blob/8fd25bd86b58cfc0d6490cfac08e4846ab4ddf97/django_elasticsearch/manager.py#L727-L767 | |
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/distutils/cmd.py | python | Command.get_sub_commands | (self) | return commands | Determine the sub-commands that are relevant in the current
distribution (ie., that need to be run). This is based on the
'sub_commands' class attribute: each tuple in that list may include
a method that we call to determine if the subcommand needs to be
run for the current distribution. Return a list of command names. | Determine the sub-commands that are relevant in the current
distribution (ie., that need to be run). This is based on the
'sub_commands' class attribute: each tuple in that list may include
a method that we call to determine if the subcommand needs to be
run for the current distribution. Return a list of command names. | [
"Determine",
"the",
"sub",
"-",
"commands",
"that",
"are",
"relevant",
"in",
"the",
"current",
"distribution",
"(",
"ie",
".",
"that",
"need",
"to",
"be",
"run",
")",
".",
"This",
"is",
"based",
"on",
"the",
"sub_commands",
"class",
"attribute",
":",
"ea... | def get_sub_commands(self):
"""Determine the sub-commands that are relevant in the current
distribution (ie., that need to be run). This is based on the
'sub_commands' class attribute: each tuple in that list may include
a method that we call to determine if the subcommand needs to be
run for the current distribution. Return a list of command names.
"""
commands = []
for (cmd_name, method) in self.sub_commands:
if method is None or method(self):
commands.append(cmd_name)
return commands | [
"def",
"get_sub_commands",
"(",
"self",
")",
":",
"commands",
"=",
"[",
"]",
"for",
"(",
"cmd_name",
",",
"method",
")",
"in",
"self",
".",
"sub_commands",
":",
"if",
"method",
"is",
"None",
"or",
"method",
"(",
"self",
")",
":",
"commands",
".",
"ap... | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/distutils/cmd.py#L315-L326 | |
CalebBell/thermo | 572a47d1b03d49fe609b8d5f826fa6a7cde00828 | thermo/utils/tp_dependent_property.py | python | TPDependentProperty.test_method_validity_P | (self, T, P, method) | return validity | r'''Method to test the validity of a specified method for a given
temperature. Demo function for testing only;
must be implemented according to the methods available for each
individual method. Include the interpolation check here.
Parameters
----------
T : float
Temperature at which to determine the validity of the method, [K]
P : float
Pressure at which to determine the validity of the method, [Pa]
method : str
Method name to use
Returns
-------
validity : bool
Whether or not a specifid method is valid | r'''Method to test the validity of a specified method for a given
temperature. Demo function for testing only;
must be implemented according to the methods available for each
individual method. Include the interpolation check here. | [
"r",
"Method",
"to",
"test",
"the",
"validity",
"of",
"a",
"specified",
"method",
"for",
"a",
"given",
"temperature",
".",
"Demo",
"function",
"for",
"testing",
"only",
";",
"must",
"be",
"implemented",
"according",
"to",
"the",
"methods",
"available",
"for"... | def test_method_validity_P(self, T, P, method):
r'''Method to test the validity of a specified method for a given
temperature. Demo function for testing only;
must be implemented according to the methods available for each
individual method. Include the interpolation check here.
Parameters
----------
T : float
Temperature at which to determine the validity of the method, [K]
P : float
Pressure at which to determine the validity of the method, [Pa]
method : str
Method name to use
Returns
-------
validity : bool
Whether or not a specifid method is valid
'''
if method in self.tabular_data_P:
if self.tabular_extrapolation_permitted:
validity = True
else:
Ts, Ps, properties = self.tabular_data_P[method]
validity = Ts[0] < T < Ts[-1] and Ps[0] < P < Ps[-1]
elif method in self.all_methods_P:
Tmin, Tmax = self.T_limits[method]
validity = Tmin < T < Tmax
else:
raise ValueError("method '%s' not valid" %method)
return validity | [
"def",
"test_method_validity_P",
"(",
"self",
",",
"T",
",",
"P",
",",
"method",
")",
":",
"if",
"method",
"in",
"self",
".",
"tabular_data_P",
":",
"if",
"self",
".",
"tabular_extrapolation_permitted",
":",
"validity",
"=",
"True",
"else",
":",
"Ts",
",",... | https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/utils/tp_dependent_property.py#L322-L353 | |
OpenEndedGroup/Field | 4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c | Contents/lib/python/tokenize.py | python | tokenize | (readline, tokeneater=printtoken) | The tokenize() function accepts two parameters: one representing the
input stream, and one providing an output mechanism for tokenize().
The first parameter, readline, must be a callable object which provides
the same interface as the readline() method of built-in file objects.
Each call to the function should return one line of input as a string.
The second parameter, tokeneater, must also be a callable object. It is
called once for each token, with five arguments, corresponding to the
tuples generated by generate_tokens(). | The tokenize() function accepts two parameters: one representing the
input stream, and one providing an output mechanism for tokenize(). | [
"The",
"tokenize",
"()",
"function",
"accepts",
"two",
"parameters",
":",
"one",
"representing",
"the",
"input",
"stream",
"and",
"one",
"providing",
"an",
"output",
"mechanism",
"for",
"tokenize",
"()",
"."
] | def tokenize(readline, tokeneater=printtoken):
"""
The tokenize() function accepts two parameters: one representing the
input stream, and one providing an output mechanism for tokenize().
The first parameter, readline, must be a callable object which provides
the same interface as the readline() method of built-in file objects.
Each call to the function should return one line of input as a string.
The second parameter, tokeneater, must also be a callable object. It is
called once for each token, with five arguments, corresponding to the
tuples generated by generate_tokens().
"""
try:
tokenize_loop(readline, tokeneater)
except StopTokenizing:
pass | [
"def",
"tokenize",
"(",
"readline",
",",
"tokeneater",
"=",
"printtoken",
")",
":",
"try",
":",
"tokenize_loop",
"(",
"readline",
",",
"tokeneater",
")",
"except",
"StopTokenizing",
":",
"pass"
] | https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/tokenize.py#L139-L155 | ||
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/tools/inject/lib/core/common.py | python | findDynamicContent | (firstPage, secondPage) | This function checks if the provided pages have dynamic content. If they
are dynamic, proper markings will be made | This function checks if the provided pages have dynamic content. If they
are dynamic, proper markings will be made | [
"This",
"function",
"checks",
"if",
"the",
"provided",
"pages",
"have",
"dynamic",
"content",
".",
"If",
"they",
"are",
"dynamic",
"proper",
"markings",
"will",
"be",
"made"
] | def findDynamicContent(firstPage, secondPage):
"""
This function checks if the provided pages have dynamic content. If they
are dynamic, proper markings will be made
"""
if not firstPage or not secondPage:
return
infoMsg = "searching for dynamic content"
logger.info(infoMsg)
blocks = SequenceMatcher(None, firstPage, secondPage).get_matching_blocks()
kb.dynamicMarkings = []
# Removing too small matching blocks
for block in blocks[:]:
(_, _, length) = block
if length <= DYNAMICITY_MARK_LENGTH:
blocks.remove(block)
# Making of dynamic markings based on prefix/suffix principle
if len(blocks) > 0:
blocks.insert(0, None)
blocks.append(None)
for i in xrange(len(blocks) - 1):
prefix = firstPage[blocks[i][0]:blocks[i][0] + blocks[i][2]] if blocks[i] else None
suffix = firstPage[blocks[i + 1][0]:blocks[i + 1][0] + blocks[i + 1][2]] if blocks[i + 1] else None
if prefix is None and blocks[i + 1][0] == 0:
continue
if suffix is None and (blocks[i][0] + blocks[i][2] >= len(firstPage)):
continue
prefix = trimAlphaNum(prefix)
suffix = trimAlphaNum(suffix)
kb.dynamicMarkings.append((prefix[-DYNAMICITY_MARK_LENGTH / 2:] if prefix else None, suffix[:DYNAMICITY_MARK_LENGTH / 2] if suffix else None))
if len(kb.dynamicMarkings) > 0:
infoMsg = "dynamic content marked for removal (%d region%s)" % (len(kb.dynamicMarkings), 's' if len(kb.dynamicMarkings) > 1 else '')
logger.info(infoMsg) | [
"def",
"findDynamicContent",
"(",
"firstPage",
",",
"secondPage",
")",
":",
"if",
"not",
"firstPage",
"or",
"not",
"secondPage",
":",
"return",
"infoMsg",
"=",
"\"searching for dynamic content\"",
"logger",
".",
"info",
"(",
"infoMsg",
")",
"blocks",
"=",
"Seque... | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/lib/core/common.py#L2564-L2608 | ||
F8LEFT/DecLLVM | d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c | python/idaapi.py | python | idainfo.__init__ | (self, *args) | __init__(self) -> idainfo | __init__(self) -> idainfo | [
"__init__",
"(",
"self",
")",
"-",
">",
"idainfo"
] | def __init__(self, *args):
"""
__init__(self) -> idainfo
"""
this = _idaapi.new_idainfo(*args)
try: self.this.append(this)
except: self.this = this | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"this",
"=",
"_idaapi",
".",
"new_idainfo",
"(",
"*",
"args",
")",
"try",
":",
"self",
".",
"this",
".",
"append",
"(",
"this",
")",
"except",
":",
"self",
".",
"this",
"=",
"this"
] | https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L2803-L2809 | ||
GoogleCloudPlatform/professional-services | 0c707aa97437f3d154035ef8548109b7882f71da | tools/quota-monitoring-alerting/python/main.py | python | metrics_save | () | return save_metrics(request) | Endpoint to recieve metric save request(s). | Endpoint to recieve metric save request(s). | [
"Endpoint",
"to",
"recieve",
"metric",
"save",
"request",
"(",
"s",
")",
"."
] | def metrics_save():
"""Endpoint to recieve metric save request(s)."""
return save_metrics(request) | [
"def",
"metrics_save",
"(",
")",
":",
"return",
"save_metrics",
"(",
"request",
")"
] | https://github.com/GoogleCloudPlatform/professional-services/blob/0c707aa97437f3d154035ef8548109b7882f71da/tools/quota-monitoring-alerting/python/main.py#L125-L127 | |
PaddlePaddle/PaddleHub | 107ee7e1a49d15e9c94da3956475d88a53fc165f | modules/text/language_model/lda_novel/model.py | python | TopicModel.word_topic_value | (self, word_id, topic_id) | return word_dict[topic_id] | Return value of specific word under specific topic in the model. | Return value of specific word under specific topic in the model. | [
"Return",
"value",
"of",
"specific",
"word",
"under",
"specific",
"topic",
"in",
"the",
"model",
"."
] | def word_topic_value(self, word_id, topic_id):
"""Return value of specific word under specific topic in the model.
"""
word_dict = self.__word_topic[word_id]
if topic_id not in word_dict:
return 0
return word_dict[topic_id] | [
"def",
"word_topic_value",
"(",
"self",
",",
"word_id",
",",
"topic_id",
")",
":",
"word_dict",
"=",
"self",
".",
"__word_topic",
"[",
"word_id",
"]",
"if",
"topic_id",
"not",
"in",
"word_dict",
":",
"return",
"0",
"return",
"word_dict",
"[",
"topic_id",
"... | https://github.com/PaddlePaddle/PaddleHub/blob/107ee7e1a49d15e9c94da3956475d88a53fc165f/modules/text/language_model/lda_novel/model.py#L49-L55 | |
openstack/openstacksdk | 58384268487fa854f21c470b101641ab382c9897 | openstack/placement/v1/_proxy.py | python | Proxy.delete_resource_class | (self, resource_class, ignore_missing=True) | Delete a resource class
:param resource_class: The value can be either the ID of a resource
class or an
:class:`~openstack.placement.v1.resource_class.ResourceClass`,
instance.
:param bool ignore_missing: When set to ``False``
:class:`~openstack.exceptions.ResourceNotFound` will be raised when
the resource class does not exist. When set to ``True``, no
exception will be set when attempting to delete a nonexistent
resource class.
:returns: ``None`` | Delete a resource class | [
"Delete",
"a",
"resource",
"class"
] | def delete_resource_class(self, resource_class, ignore_missing=True):
"""Delete a resource class
:param resource_class: The value can be either the ID of a resource
class or an
:class:`~openstack.placement.v1.resource_class.ResourceClass`,
instance.
:param bool ignore_missing: When set to ``False``
:class:`~openstack.exceptions.ResourceNotFound` will be raised when
the resource class does not exist. When set to ``True``, no
exception will be set when attempting to delete a nonexistent
resource class.
:returns: ``None``
"""
self._delete(
_resource_class.ResourceClass,
resource_class,
ignore_missing=ignore_missing,
) | [
"def",
"delete_resource_class",
"(",
"self",
",",
"resource_class",
",",
"ignore_missing",
"=",
"True",
")",
":",
"self",
".",
"_delete",
"(",
"_resource_class",
".",
"ResourceClass",
",",
"resource_class",
",",
"ignore_missing",
"=",
"ignore_missing",
",",
")"
] | https://github.com/openstack/openstacksdk/blob/58384268487fa854f21c470b101641ab382c9897/openstack/placement/v1/_proxy.py#L34-L53 | ||
nickoala/telepot | 4bfe4eeb5e48b40e72976ee085a1b0a941ef3cf2 | telepot/aio/__init__.py | python | Bot.getStickerSet | (self, name) | return await self._api_request('getStickerSet', _rectify(p)) | See: https://core.telegram.org/bots/api#getstickerset | See: https://core.telegram.org/bots/api#getstickerset | [
"See",
":",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api#getstickerset"
] | async def getStickerSet(self, name):
"""
See: https://core.telegram.org/bots/api#getstickerset
"""
p = _strip(locals())
return await self._api_request('getStickerSet', _rectify(p)) | [
"async",
"def",
"getStickerSet",
"(",
"self",
",",
"name",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
")",
"return",
"await",
"self",
".",
"_api_request",
"(",
"'getStickerSet'",
",",
"_rectify",
"(",
"p",
")",
")"
] | https://github.com/nickoala/telepot/blob/4bfe4eeb5e48b40e72976ee085a1b0a941ef3cf2/telepot/aio/__init__.py#L525-L530 | |
petl-developers/petl | 012cc7faf79d2fa8147a2cfe3a8b39b110f77051 | petl/transform/unpacks.py | python | unpack | (table, field, newfields=None, include_original=False, missing=None) | return UnpackView(table, field, newfields=newfields,
include_original=include_original, missing=missing) | Unpack data values that are lists or tuples. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... [1, ['a', 'b']],
... [2, ['c', 'd']],
... [3, ['e', 'f']]]
>>> table2 = etl.unpack(table1, 'bar', ['baz', 'quux'])
>>> table2
+-----+-----+------+
| foo | baz | quux |
+=====+=====+======+
| 1 | 'a' | 'b' |
+-----+-----+------+
| 2 | 'c' | 'd' |
+-----+-----+------+
| 3 | 'e' | 'f' |
+-----+-----+------+
This function will attempt to unpack exactly the number of values as
given by the number of new fields specified. If there are more values
than new fields, remaining values will not be unpacked. If there are less
values than new fields, `missing` values will be added.
See also :func:`petl.transform.unpacks.unpackdict`. | Unpack data values that are lists or tuples. E.g.:: | [
"Unpack",
"data",
"values",
"that",
"are",
"lists",
"or",
"tuples",
".",
"E",
".",
"g",
".",
"::"
] | def unpack(table, field, newfields=None, include_original=False, missing=None):
"""
Unpack data values that are lists or tuples. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... [1, ['a', 'b']],
... [2, ['c', 'd']],
... [3, ['e', 'f']]]
>>> table2 = etl.unpack(table1, 'bar', ['baz', 'quux'])
>>> table2
+-----+-----+------+
| foo | baz | quux |
+=====+=====+======+
| 1 | 'a' | 'b' |
+-----+-----+------+
| 2 | 'c' | 'd' |
+-----+-----+------+
| 3 | 'e' | 'f' |
+-----+-----+------+
This function will attempt to unpack exactly the number of values as
given by the number of new fields specified. If there are more values
than new fields, remaining values will not be unpacked. If there are less
values than new fields, `missing` values will be added.
See also :func:`petl.transform.unpacks.unpackdict`.
"""
return UnpackView(table, field, newfields=newfields,
include_original=include_original, missing=missing) | [
"def",
"unpack",
"(",
"table",
",",
"field",
",",
"newfields",
"=",
"None",
",",
"include_original",
"=",
"False",
",",
"missing",
"=",
"None",
")",
":",
"return",
"UnpackView",
"(",
"table",
",",
"field",
",",
"newfields",
"=",
"newfields",
",",
"includ... | https://github.com/petl-developers/petl/blob/012cc7faf79d2fa8147a2cfe3a8b39b110f77051/petl/transform/unpacks.py#L12-L43 | |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | 5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e | deep-learning/multi-frameworks/common/utils.py | python | yield_mb_tn | (X, y, batchsize=64, shuffle=False) | Function yields mini-batches for time-series, layout=TN | Function yields mini-batches for time-series, layout=TN | [
"Function",
"yields",
"mini",
"-",
"batches",
"for",
"time",
"-",
"series",
"layout",
"=",
"TN"
] | def yield_mb_tn(X, y, batchsize=64, shuffle=False):
""" Function yields mini-batches for time-series, layout=TN """
if shuffle:
X, y = shuffle_data(X, y)
# Reshape
X = np.swapaxes(X, 0, 1)
# Only complete batches are submitted
for i in range(X.shape[-1] // batchsize):
yield X[..., i*batchsize:(i + 1)*batchsize], y[i * batchsize:(i + 1) * batchsize] | [
"def",
"yield_mb_tn",
"(",
"X",
",",
"y",
",",
"batchsize",
"=",
"64",
",",
"shuffle",
"=",
"False",
")",
":",
"if",
"shuffle",
":",
"X",
",",
"y",
"=",
"shuffle_data",
"(",
"X",
",",
"y",
")",
"# Reshape",
"X",
"=",
"np",
".",
"swapaxes",
"(",
... | https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/deep-learning/multi-frameworks/common/utils.py#L126-L134 | ||
aiogram/aiogram | 4d2d81138681d730270819579f22b3a0001c43a5 | aiogram/types/chat.py | python | ChatActions.upload_photo | (cls, sleep=None) | Do upload_photo
:param sleep: sleep timeout
:return: | Do upload_photo | [
"Do",
"upload_photo"
] | async def upload_photo(cls, sleep=None):
"""
Do upload_photo
:param sleep: sleep timeout
:return:
"""
await cls._do(cls.UPLOAD_PHOTO, sleep) | [
"async",
"def",
"upload_photo",
"(",
"cls",
",",
"sleep",
"=",
"None",
")",
":",
"await",
"cls",
".",
"_do",
"(",
"cls",
".",
"UPLOAD_PHOTO",
",",
"sleep",
")"
] | https://github.com/aiogram/aiogram/blob/4d2d81138681d730270819579f22b3a0001c43a5/aiogram/types/chat.py#L801-L808 | ||
kbandla/dpkt | 7a91ae53bb20563607f32e6781ef40d2efe6520d | dpkt/pcapng.py | python | _padded | (s) | return struct_pack('%ss' % _align32b(len(s)), s) | Return bytes `s` padded with zeroes to align to the 32-bit boundary | Return bytes `s` padded with zeroes to align to the 32-bit boundary | [
"Return",
"bytes",
"s",
"padded",
"with",
"zeroes",
"to",
"align",
"to",
"the",
"32",
"-",
"bit",
"boundary"
] | def _padded(s):
"""Return bytes `s` padded with zeroes to align to the 32-bit boundary"""
return struct_pack('%ss' % _align32b(len(s)), s) | [
"def",
"_padded",
"(",
"s",
")",
":",
"return",
"struct_pack",
"(",
"'%ss'",
"%",
"_align32b",
"(",
"len",
"(",
"s",
")",
")",
",",
"s",
")"
] | https://github.com/kbandla/dpkt/blob/7a91ae53bb20563607f32e6781ef40d2efe6520d/dpkt/pcapng.py#L95-L97 | |
barseghyanartur/django-elasticsearch-dsl-drf | 8fe35265d44501269b2603570773be47f20fa471 | examples/simple/books/models/city.py | python | City.location_field_indexing | (self) | return {
'lat': self.latitude,
'lon': self.longitude,
} | Location for indexing.
Used in Elasticsearch indexing/tests of `geo_distance` native filter. | Location for indexing. | [
"Location",
"for",
"indexing",
"."
] | def location_field_indexing(self):
"""Location for indexing.
Used in Elasticsearch indexing/tests of `geo_distance` native filter.
"""
return {
'lat': self.latitude,
'lon': self.longitude,
} | [
"def",
"location_field_indexing",
"(",
"self",
")",
":",
"return",
"{",
"'lat'",
":",
"self",
".",
"latitude",
",",
"'lon'",
":",
"self",
".",
"longitude",
",",
"}"
] | https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/blob/8fe35265d44501269b2603570773be47f20fa471/examples/simple/books/models/city.py#L41-L49 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/numpy/lib/type_check.py | python | imag | (val) | return asanyarray(val).imag | Return the imaginary part of the elements of the array.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray
Output array. If `val` is real, the type of `val` is used for the
output. If `val` has complex elements, the returned type is float.
See Also
--------
real, angle, real_if_close
Examples
--------
>>> a = np.array([1+2j, 3+4j, 5+6j])
>>> a.imag
array([ 2., 4., 6.])
>>> a.imag = np.array([8, 10, 12])
>>> a
array([ 1. +8.j, 3.+10.j, 5.+12.j]) | Return the imaginary part of the elements of the array. | [
"Return",
"the",
"imaginary",
"part",
"of",
"the",
"elements",
"of",
"the",
"array",
"."
] | def imag(val):
"""
Return the imaginary part of the elements of the array.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray
Output array. If `val` is real, the type of `val` is used for the
output. If `val` has complex elements, the returned type is float.
See Also
--------
real, angle, real_if_close
Examples
--------
>>> a = np.array([1+2j, 3+4j, 5+6j])
>>> a.imag
array([ 2., 4., 6.])
>>> a.imag = np.array([8, 10, 12])
>>> a
array([ 1. +8.j, 3.+10.j, 5.+12.j])
"""
return asanyarray(val).imag | [
"def",
"imag",
"(",
"val",
")",
":",
"return",
"asanyarray",
"(",
"val",
")",
".",
"imag"
] | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/numpy/lib/type_check.py#L141-L170 | |
nltk/nltk | 3f74ac55681667d7ef78b664557487145f51eb02 | nltk/tree/parented.py | python | ParentedTree.parent | (self) | return self._parent | The parent of this tree, or None if it has no parent. | The parent of this tree, or None if it has no parent. | [
"The",
"parent",
"of",
"this",
"tree",
"or",
"None",
"if",
"it",
"has",
"no",
"parent",
"."
] | def parent(self):
"""The parent of this tree, or None if it has no parent."""
return self._parent | [
"def",
"parent",
"(",
"self",
")",
":",
"return",
"self",
".",
"_parent"
] | https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/tree/parented.py#L325-L327 | |
bjmayor/hacker | e3ce2ad74839c2733b27dac6c0f495e0743e1866 | venv/lib/python3.5/site-packages/pkg_resources/__init__.py | python | IResourceProvider.get_resource_string | (manager, resource_name) | Return a string containing the contents of `resource_name`
`manager` must be an ``IResourceManager`` | Return a string containing the contents of `resource_name` | [
"Return",
"a",
"string",
"containing",
"the",
"contents",
"of",
"resource_name"
] | def get_resource_string(manager, resource_name):
"""Return a string containing the contents of `resource_name`
`manager` must be an ``IResourceManager``""" | [
"def",
"get_resource_string",
"(",
"manager",
",",
"resource_name",
")",
":"
] | https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/pkg_resources/__init__.py#L614-L617 | ||
openhatch/oh-mainline | ce29352a034e1223141dcc2f317030bbc3359a51 | vendor/packages/Django/django/contrib/gis/sitemaps/kml.py | python | KMLSitemap.get_urls | (self, page=1, site=None) | return urls | This method is overrridden so the appropriate `geo_format` attribute
is placed on each URL element. | This method is overrridden so the appropriate `geo_format` attribute
is placed on each URL element. | [
"This",
"method",
"is",
"overrridden",
"so",
"the",
"appropriate",
"geo_format",
"attribute",
"is",
"placed",
"on",
"each",
"URL",
"element",
"."
] | def get_urls(self, page=1, site=None):
"""
This method is overrridden so the appropriate `geo_format` attribute
is placed on each URL element.
"""
urls = Sitemap.get_urls(self, page=page, site=site)
for url in urls: url['geo_format'] = self.geo_format
return urls | [
"def",
"get_urls",
"(",
"self",
",",
"page",
"=",
"1",
",",
"site",
"=",
"None",
")",
":",
"urls",
"=",
"Sitemap",
".",
"get_urls",
"(",
"self",
",",
"page",
"=",
"page",
",",
"site",
"=",
"site",
")",
"for",
"url",
"in",
"urls",
":",
"url",
"[... | https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/Django/django/contrib/gis/sitemaps/kml.py#L43-L50 | |
CaptainEven/RepNet-MDNet-VehicleReID | d3d184331206ca4bdb5ea399e5b90a9ccc53b400 | InitRepNet.py | python | ArcFC.__init__ | (self,
in_features,
out_features,
s=30.0,
m=0.50,
easy_margin=False) | ArcMargin
:param in_features:
:param out_features:
:param s:
:param m:
:param easy_margin: | ArcMargin
:param in_features:
:param out_features:
:param s:
:param m:
:param easy_margin: | [
"ArcMargin",
":",
"param",
"in_features",
":",
":",
"param",
"out_features",
":",
":",
"param",
"s",
":",
":",
"param",
"m",
":",
":",
"param",
"easy_margin",
":"
] | def __init__(self,
in_features,
out_features,
s=30.0,
m=0.50,
easy_margin=False):
"""
ArcMargin
:param in_features:
:param out_features:
:param s:
:param m:
:param easy_margin:
"""
super(ArcFC, self).__init__()
self.in_features = in_features
self.out_features = out_features
print('=> in dim: %d, out dim: %d' % (self.in_features, self.out_features))
self.s = s
self.m = m
# 根据输入输出dim确定初始化权重
self.weight = Parameter(torch.FloatTensor(out_features, in_features))
torch.nn.init.xavier_uniform_(self.weight)
self.easy_margin = easy_margin
self.cos_m = math.cos(m)
self.sin_m = math.sin(m)
self.th = math.cos(math.pi - m)
self.mm = math.sin(math.pi - m) * m | [
"def",
"__init__",
"(",
"self",
",",
"in_features",
",",
"out_features",
",",
"s",
"=",
"30.0",
",",
"m",
"=",
"0.50",
",",
"easy_margin",
"=",
"False",
")",
":",
"super",
"(",
"ArcFC",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"in_... | https://github.com/CaptainEven/RepNet-MDNet-VehicleReID/blob/d3d184331206ca4bdb5ea399e5b90a9ccc53b400/InitRepNet.py#L31-L61 | ||
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/sklearn/model_selection/_search.py | python | ParameterGrid.__getitem__ | (self, ind) | Get the parameters that would be ``ind``th in iteration
Parameters
----------
ind : int
The iteration index
Returns
-------
params : dict of string to any
Equal to list(self)[ind] | Get the parameters that would be ``ind``th in iteration | [
"Get",
"the",
"parameters",
"that",
"would",
"be",
"ind",
"th",
"in",
"iteration"
] | def __getitem__(self, ind):
"""Get the parameters that would be ``ind``th in iteration
Parameters
----------
ind : int
The iteration index
Returns
-------
params : dict of string to any
Equal to list(self)[ind]
"""
# This is used to make discrete sampling without replacement memory
# efficient.
for sub_grid in self.param_grid:
# XXX: could memoize information used here
if not sub_grid:
if ind == 0:
return {}
else:
ind -= 1
continue
# Reverse so most frequent cycling parameter comes first
keys, values_lists = zip(*sorted(sub_grid.items())[::-1])
sizes = [len(v_list) for v_list in values_lists]
total = np.product(sizes)
if ind >= total:
# Try the next grid
ind -= total
else:
out = {}
for key, v_list, n in zip(keys, values_lists, sizes):
ind, offset = divmod(ind, n)
out[key] = v_list[offset]
return out
raise IndexError('ParameterGrid index out of range') | [
"def",
"__getitem__",
"(",
"self",
",",
"ind",
")",
":",
"# This is used to make discrete sampling without replacement memory",
"# efficient.",
"for",
"sub_grid",
"in",
"self",
".",
"param_grid",
":",
"# XXX: could memoize information used here",
"if",
"not",
"sub_grid",
":... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/sklearn/model_selection/_search.py#L122-L161 | ||
google/coursebuilder-core | 08f809db3226d9269e30d5edd0edd33bd22041f4 | coursebuilder/controllers/sites.py | python | set_path_info | (path) | Stores PATH_INFO in thread local. | Stores PATH_INFO in thread local. | [
"Stores",
"PATH_INFO",
"in",
"thread",
"local",
"."
] | def set_path_info(path):
"""Stores PATH_INFO in thread local."""
if not path:
raise Exception('Use \'unset()\' instead.')
if has_path_info():
raise Exception('Expected no path set.')
try:
PATH_INFO_THREAD_LOCAL.path = path
PATH_INFO_THREAD_LOCAL.old_namespace = namespace_manager.get_namespace()
namespace_manager.set_namespace(
ApplicationContext.get_namespace_name_for_request())
finally:
try:
caching.RequestScopedSingleton.clear_all()
finally:
models.MemcacheManager.clear_readonly_cache() | [
"def",
"set_path_info",
"(",
"path",
")",
":",
"if",
"not",
"path",
":",
"raise",
"Exception",
"(",
"'Use \\'unset()\\' instead.'",
")",
"if",
"has_path_info",
"(",
")",
":",
"raise",
"Exception",
"(",
"'Expected no path set.'",
")",
"try",
":",
"PATH_INFO_THREA... | https://github.com/google/coursebuilder-core/blob/08f809db3226d9269e30d5edd0edd33bd22041f4/coursebuilder/controllers/sites.py#L999-L1014 | ||
OfflineIMAP/offlineimap | e70d3992a0e9bb0fcdf3c94e1edf25a4124dfcd2 | offlineimap/bundled_imaplib2.py | python | IMAP4._CRAM_MD5_AUTH | (self, challenge) | return self.user + " " + hmac.HMAC(pwd, challenge, 'md5').hexdigest() | Authobject to use with CRAM-MD5 authentication. | Authobject to use with CRAM-MD5 authentication. | [
"Authobject",
"to",
"use",
"with",
"CRAM",
"-",
"MD5",
"authentication",
"."
] | def _CRAM_MD5_AUTH(self, challenge):
"""Authobject to use with CRAM-MD5 authentication."""
import hmac
pwd = (self.password.encode('ASCII') if isinstance(self.password, str)
else self.password)
return self.user + " " + hmac.HMAC(pwd, challenge, 'md5').hexdigest() | [
"def",
"_CRAM_MD5_AUTH",
"(",
"self",
",",
"challenge",
")",
":",
"import",
"hmac",
"pwd",
"=",
"(",
"self",
".",
"password",
".",
"encode",
"(",
"'ASCII'",
")",
"if",
"isinstance",
"(",
"self",
".",
"password",
",",
"str",
")",
"else",
"self",
".",
... | https://github.com/OfflineIMAP/offlineimap/blob/e70d3992a0e9bb0fcdf3c94e1edf25a4124dfcd2/offlineimap/bundled_imaplib2.py#L974-L979 | |
giantbranch/python-hacker-code | addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d | 我手敲的代码(中文注释)/chapter11/immlib/immlib.py | python | Debugger.setBreakpoint | (self, address) | return debugger.Setbreakpoint(address, flags, "") | Set a Breakpoint.
@type address: DWORD
@param address: Address for the breakpoint | Set a Breakpoint. | [
"Set",
"a",
"Breakpoint",
"."
] | def setBreakpoint(self, address):
"""
Set a Breakpoint.
@type address: DWORD
@param address: Address for the breakpoint
"""
flags = BpFlags["TY_ACTIVE"]
return debugger.Setbreakpoint(address, flags, "") | [
"def",
"setBreakpoint",
"(",
"self",
",",
"address",
")",
":",
"flags",
"=",
"BpFlags",
"[",
"\"TY_ACTIVE\"",
"]",
"return",
"debugger",
".",
"Setbreakpoint",
"(",
"address",
",",
"flags",
",",
"\"\"",
")"
] | https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/immlib/immlib.py#L1889-L1897 | |
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/yaml/constructor.py | python | Constructor.construct_python_str | (self, node) | return self.construct_scalar(node).encode('utf-8') | [] | def construct_python_str(self, node):
return self.construct_scalar(node).encode('utf-8') | [
"def",
"construct_python_str",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"construct_scalar",
"(",
"node",
")",
".",
"encode",
"(",
"'utf-8'",
")"
] | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/yaml/constructor.py#L469-L470 | |||
tahoe-lafs/tahoe-lafs | 766a53b5208c03c45ca0a98e97eee76870276aa1 | src/allmydata/interfaces.py | python | IDirectoryNode.get_readonly_uri | () | The dirnode ('1') URI returned by this method can be used in
set_uri() on a different directory ('2') to 'mount' a reference to
this directory ('1') under the other ('2'). This URI is just a
string, so it can be passed around through email or other out-of-band
protocol. | The dirnode ('1') URI returned by this method can be used in
set_uri() on a different directory ('2') to 'mount' a reference to
this directory ('1') under the other ('2'). This URI is just a
string, so it can be passed around through email or other out-of-band
protocol. | [
"The",
"dirnode",
"(",
"1",
")",
"URI",
"returned",
"by",
"this",
"method",
"can",
"be",
"used",
"in",
"set_uri",
"()",
"on",
"a",
"different",
"directory",
"(",
"2",
")",
"to",
"mount",
"a",
"reference",
"to",
"this",
"directory",
"(",
"1",
")",
"un... | def get_readonly_uri():
"""
The dirnode ('1') URI returned by this method can be used in
set_uri() on a different directory ('2') to 'mount' a reference to
this directory ('1') under the other ('2'). This URI is just a
string, so it can be passed around through email or other out-of-band
protocol.
""" | [
"def",
"get_readonly_uri",
"(",
")",
":"
] | https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/interfaces.py#L1307-L1314 | ||
theislab/anndata | 664e32b0aa6625fe593370d37174384c05abfd4e | anndata/_io/specs/methods.py | python | write_recarray | (f, k, elem, dataset_kwargs=MappingProxyType({})) | [] | def write_recarray(f, k, elem, dataset_kwargs=MappingProxyType({})):
f.create_dataset(k, data=_to_hdf5_vlen_strings(elem), **dataset_kwargs) | [
"def",
"write_recarray",
"(",
"f",
",",
"k",
",",
"elem",
",",
"dataset_kwargs",
"=",
"MappingProxyType",
"(",
"{",
"}",
")",
")",
":",
"f",
".",
"create_dataset",
"(",
"k",
",",
"data",
"=",
"_to_hdf5_vlen_strings",
"(",
"elem",
")",
",",
"*",
"*",
... | https://github.com/theislab/anndata/blob/664e32b0aa6625fe593370d37174384c05abfd4e/anndata/_io/specs/methods.py#L397-L398 | ||||
tribe29/checkmk | 6260f2512e159e311f426e16b84b19d0b8e9ad0c | cmk/gui/watolib/host_attributes.py | python | ABCHostAttribute.filter_matches | (self, crit: Any, value: Any, hostname: HostName) | return crit == value | Checks if the give value matches the search attributes
that are represented by the current HTML variables. | Checks if the give value matches the search attributes
that are represented by the current HTML variables. | [
"Checks",
"if",
"the",
"give",
"value",
"matches",
"the",
"search",
"attributes",
"that",
"are",
"represented",
"by",
"the",
"current",
"HTML",
"variables",
"."
] | def filter_matches(self, crit: Any, value: Any, hostname: HostName) -> bool:
"""Checks if the give value matches the search attributes
that are represented by the current HTML variables."""
return crit == value | [
"def",
"filter_matches",
"(",
"self",
",",
"crit",
":",
"Any",
",",
"value",
":",
"Any",
",",
"hostname",
":",
"HostName",
")",
"->",
"bool",
":",
"return",
"crit",
"==",
"value"
] | https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/gui/watolib/host_attributes.py#L359-L362 | |
fluentpython/notebooks | 0f6e1e8d1686743dacd9281df7c5b5921812010a | attic/sequences/str_concat.py | python | list_joiner | (lines) | return ''.join(parts) | [] | def list_joiner(lines):
parts = []
for line in lines:
parts.append(line)
return ''.join(parts) | [
"def",
"list_joiner",
"(",
"lines",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"parts",
".",
"append",
"(",
"line",
")",
"return",
"''",
".",
"join",
"(",
"parts",
")"
] | https://github.com/fluentpython/notebooks/blob/0f6e1e8d1686743dacd9281df7c5b5921812010a/attic/sequences/str_concat.py#L26-L30 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.