nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/db_manager/db_plugins/postgis/connector.py
python
PostGisDBConnector.renamesSchema
(self, schema, new_schema)
Renames a schema in database
Renames a schema in database
[ "Renames", "a", "schema", "in", "database" ]
def renamesSchema(self, schema, new_schema): """Renames a schema in database """ sql = u"ALTER SCHEMA %s RENAME TO %s" % (self.quoteId(schema), self.quoteId(new_schema)) self._execute_and_commit(sql)
[ "def", "renamesSchema", "(", "self", ",", "schema", ",", "new_schema", ")", ":", "sql", "=", "u\"ALTER SCHEMA %s RENAME TO %s\"", "%", "(", "self", ".", "quoteId", "(", "schema", ")", ",", "self", ".", "quoteId", "(", "new_schema", ")", ")", "self", ".", "_execute_and_commit", "(", "sql", ")" ]
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/postgis/connector.py#L1043-L1046
JumpingYang001/webrtc
c03d6e965e1f54aeadd670e491eabe5fdb8db968
tools_webrtc/vim/webrtc.ycm_extra_conf.py
python
GetClangOptionsFromNinjaForFilename
(webrtc_root, filename)
return GetClangOptionsFromCommandLine(clang_line, out_dir, additional_flags)
Returns the Clang command line options needed for building |filename|. Command line options are based on the command used by ninja for building |filename|. If |filename| is a .h file, uses its companion .cc or .cpp file. If a suitable companion file can't be located or if ninja doesn't know about |filename|, then uses default source files in WebRTC for determining the commandline. Args: webrtc_root: (String) Path to src/. filename: (String) Absolute path to source file being edited. Returns: (List of Strings) The list of command line flags for this source file. Can be empty.
Returns the Clang command line options needed for building |filename|.
[ "Returns", "the", "Clang", "command", "line", "options", "needed", "for", "building", "|filename|", "." ]
def GetClangOptionsFromNinjaForFilename(webrtc_root, filename): """Returns the Clang command line options needed for building |filename|. Command line options are based on the command used by ninja for building |filename|. If |filename| is a .h file, uses its companion .cc or .cpp file. If a suitable companion file can't be located or if ninja doesn't know about |filename|, then uses default source files in WebRTC for determining the commandline. Args: webrtc_root: (String) Path to src/. filename: (String) Absolute path to source file being edited. Returns: (List of Strings) The list of command line flags for this source file. Can be empty. """ if not webrtc_root: return [] # Generally, everyone benefits from including WebRTC's src/, because all of # WebRTC's includes are relative to that. additional_flags = ['-I' + os.path.join(webrtc_root)] # Version of Clang used to compile WebRTC can be newer then version of # libclang that YCM uses for completion. So it's possible that YCM's libclang # doesn't know about some used warning options, which causes compilation # warnings (and errors, because of '-Werror'); additional_flags.append('-Wno-unknown-warning-option') sys.path.append(os.path.join(webrtc_root, 'tools', 'vim')) from ninja_output import GetNinjaOutputDirectory out_dir = GetNinjaOutputDirectory(webrtc_root) basename, extension = os.path.splitext(filename) if extension == '.h': candidates = [basename + ext for ext in _HEADER_ALTERNATES] else: candidates = [filename] clang_line = None buildable_extension = extension for candidate in candidates: clang_line = GetClangCommandLineFromNinjaForSource(out_dir, candidate) if clang_line: buildable_extension = os.path.splitext(candidate)[1] break additional_flags += _EXTENSION_FLAGS.get(buildable_extension, []) if not clang_line: # If ninja didn't know about filename or it's companion files, then try a # default build target. It is possible that the file is new, or build.ninja # is stale. clang_line = GetClangCommandLineFromNinjaForSource( out_dir, GetDefaultSourceFile(webrtc_root, filename)) if not clang_line: return additional_flags return GetClangOptionsFromCommandLine(clang_line, out_dir, additional_flags)
[ "def", "GetClangOptionsFromNinjaForFilename", "(", "webrtc_root", ",", "filename", ")", ":", "if", "not", "webrtc_root", ":", "return", "[", "]", "# Generally, everyone benefits from including WebRTC's src/, because all of", "# WebRTC's includes are relative to that.", "additional_flags", "=", "[", "'-I'", "+", "os", ".", "path", ".", "join", "(", "webrtc_root", ")", "]", "# Version of Clang used to compile WebRTC can be newer then version of", "# libclang that YCM uses for completion. So it's possible that YCM's libclang", "# doesn't know about some used warning options, which causes compilation", "# warnings (and errors, because of '-Werror');", "additional_flags", ".", "append", "(", "'-Wno-unknown-warning-option'", ")", "sys", ".", "path", ".", "append", "(", "os", ".", "path", ".", "join", "(", "webrtc_root", ",", "'tools'", ",", "'vim'", ")", ")", "from", "ninja_output", "import", "GetNinjaOutputDirectory", "out_dir", "=", "GetNinjaOutputDirectory", "(", "webrtc_root", ")", "basename", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "extension", "==", "'.h'", ":", "candidates", "=", "[", "basename", "+", "ext", "for", "ext", "in", "_HEADER_ALTERNATES", "]", "else", ":", "candidates", "=", "[", "filename", "]", "clang_line", "=", "None", "buildable_extension", "=", "extension", "for", "candidate", "in", "candidates", ":", "clang_line", "=", "GetClangCommandLineFromNinjaForSource", "(", "out_dir", ",", "candidate", ")", "if", "clang_line", ":", "buildable_extension", "=", "os", ".", "path", ".", "splitext", "(", "candidate", ")", "[", "1", "]", "break", "additional_flags", "+=", "_EXTENSION_FLAGS", ".", "get", "(", "buildable_extension", ",", "[", "]", ")", "if", "not", "clang_line", ":", "# If ninja didn't know about filename or it's companion files, then try a", "# default build target. It is possible that the file is new, or build.ninja", "# is stale.", "clang_line", "=", "GetClangCommandLineFromNinjaForSource", "(", "out_dir", ",", "GetDefaultSourceFile", "(", "webrtc_root", ",", "filename", ")", ")", "if", "not", "clang_line", ":", "return", "additional_flags", "return", "GetClangOptionsFromCommandLine", "(", "clang_line", ",", "out_dir", ",", "additional_flags", ")" ]
https://github.com/JumpingYang001/webrtc/blob/c03d6e965e1f54aeadd670e491eabe5fdb8db968/tools_webrtc/vim/webrtc.ycm_extra_conf.py#L274-L335
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/descriptor.py
python
ServiceDescriptor.CopyToProto
(self, proto)
Copies this to a descriptor_pb2.ServiceDescriptorProto. Args: proto: An empty descriptor_pb2.ServiceDescriptorProto.
Copies this to a descriptor_pb2.ServiceDescriptorProto.
[ "Copies", "this", "to", "a", "descriptor_pb2", ".", "ServiceDescriptorProto", "." ]
def CopyToProto(self, proto): """Copies this to a descriptor_pb2.ServiceDescriptorProto. Args: proto: An empty descriptor_pb2.ServiceDescriptorProto. """ # This function is overriden to give a better doc comment. super(ServiceDescriptor, self).CopyToProto(proto)
[ "def", "CopyToProto", "(", "self", ",", "proto", ")", ":", "# This function is overriden to give a better doc comment.", "super", "(", "ServiceDescriptor", ",", "self", ")", ".", "CopyToProto", "(", "proto", ")" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/descriptor.py#L604-L611
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/lib/debug_data.py
python
DebugDumpDir.run_feed_keys_info
(self)
return output[0] if len(output) == 1 else output
Get a str representation of the feed_dict used in the Session.run() call. Returns: If the information is available from one `Session.run` call, a `str` obtained from `repr(feed_dict)`. If the information is available from multiple `Session.run` calls, a `list` of `str` obtained from `repr(feed_dict)`. If the information is not available, `None`.
Get a str representation of the feed_dict used in the Session.run() call.
[ "Get", "a", "str", "representation", "of", "the", "feed_dict", "used", "in", "the", "Session", ".", "run", "()", "call", "." ]
def run_feed_keys_info(self): """Get a str representation of the feed_dict used in the Session.run() call. Returns: If the information is available from one `Session.run` call, a `str` obtained from `repr(feed_dict)`. If the information is available from multiple `Session.run` calls, a `list` of `str` obtained from `repr(feed_dict)`. If the information is not available, `None`. """ output = self._run_feed_keys_info return output[0] if len(output) == 1 else output
[ "def", "run_feed_keys_info", "(", "self", ")", ":", "output", "=", "self", ".", "_run_feed_keys_info", "return", "output", "[", "0", "]", "if", "len", "(", "output", ")", "==", "1", "else", "output" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/lib/debug_data.py#L1319-L1331
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/program.py
python
Program.__getitem__
(self, key)
return self._members[key]
Get a member such as uniforms, uniform blocks, subroutines, attributes and varyings by name. .. code-block:: python # Get a uniform uniform = program['color'] # Uniform values can be set on the returned object # or the `__setitem__` shortcut can be used. program['color'].value = 1.0, 1.0, 1.0, 1.0 # Still when writing byte data we need to use the `write()` method program['color'].write(buffer)
Get a member such as uniforms, uniform blocks, subroutines, attributes and varyings by name.
[ "Get", "a", "member", "such", "as", "uniforms", "uniform", "blocks", "subroutines", "attributes", "and", "varyings", "by", "name", "." ]
def __getitem__(self, key) -> Union[Uniform, UniformBlock, Subroutine, Attribute, Varying]: """Get a member such as uniforms, uniform blocks, subroutines, attributes and varyings by name. .. code-block:: python # Get a uniform uniform = program['color'] # Uniform values can be set on the returned object # or the `__setitem__` shortcut can be used. program['color'].value = 1.0, 1.0, 1.0, 1.0 # Still when writing byte data we need to use the `write()` method program['color'].write(buffer) """ return self._members[key]
[ "def", "__getitem__", "(", "self", ",", "key", ")", "->", "Union", "[", "Uniform", ",", "UniformBlock", ",", "Subroutine", ",", "Attribute", ",", "Varying", "]", ":", "return", "self", ".", "_members", "[", "key", "]" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/program.py#L73-L89
facebookresearch/habitat-sim
63b6c71d9ca8adaefb140b198196f5d0ca1f1e34
src_python/habitat_sim/registry.py
python
_Registry.get_pose_extractor
(cls, name: str)
return cls._get_impl("pose_extractor", name)
r"""Retrieve the pose_extractor registered under ``name`` :param name: The name provided to `register_pose_extractor`
r"""Retrieve the pose_extractor registered under ``name``
[ "r", "Retrieve", "the", "pose_extractor", "registered", "under", "name" ]
def get_pose_extractor(cls, name: str): r"""Retrieve the pose_extractor registered under ``name`` :param name: The name provided to `register_pose_extractor` """ return cls._get_impl("pose_extractor", name)
[ "def", "get_pose_extractor", "(", "cls", ",", "name", ":", "str", ")", ":", "return", "cls", ".", "_get_impl", "(", "\"pose_extractor\"", ",", "name", ")" ]
https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/src_python/habitat_sim/registry.py#L160-L165
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge2.py
python
ExodusModel.rename_element_block
(self, element_block_id, new_element_block_id)
Change an element block id or name. This function can be used to change either the element block id or name. If 'new_element_block_id' is an integer, it will change the id. If it is a string, it will change the name. Example: >>> model.rename_element_block(1, 100) >>> model.rename_element_block(1, 'block_1')
Change an element block id or name.
[ "Change", "an", "element", "block", "id", "or", "name", "." ]
def rename_element_block(self, element_block_id, new_element_block_id): """ Change an element block id or name. This function can be used to change either the element block id or name. If 'new_element_block_id' is an integer, it will change the id. If it is a string, it will change the name. Example: >>> model.rename_element_block(1, 100) >>> model.rename_element_block(1, 'block_1') """ [element_block_id] = self._format_element_block_id_list( [element_block_id], single=True) # if we're just changing the name if type(new_element_block_id) is str: # if the same name already, just exit if (self.element_blocks[element_block_id][0] == new_element_block_id): return # if the name already exists, issue a warning if self.element_block_exists(new_element_block_id): self._exists_warning('"' + new_element_block_id + '"', 'element block') # rename it self.element_blocks[ element_block_id][0] = new_element_block_id return assert type(new_element_block_id) is int # rename the block self._rename_entity('element block', element_block_id, new_element_block_id, self.get_element_block_ids, self.element_blocks) # adjust side sets for side_set_id in self.get_side_set_ids(): members = self.get_side_set_members(side_set_id) new_members = [] for member in members: if member[0] == element_block_id: member = list(member) member[0] = new_element_block_id member = tuple(member) new_members.append(member) members[:] = new_members
[ "def", "rename_element_block", "(", "self", ",", "element_block_id", ",", "new_element_block_id", ")", ":", "[", "element_block_id", "]", "=", "self", ".", "_format_element_block_id_list", "(", "[", "element_block_id", "]", ",", "single", "=", "True", ")", "# if we're just changing the name", "if", "type", "(", "new_element_block_id", ")", "is", "str", ":", "# if the same name already, just exit", "if", "(", "self", ".", "element_blocks", "[", "element_block_id", "]", "[", "0", "]", "==", "new_element_block_id", ")", ":", "return", "# if the name already exists, issue a warning", "if", "self", ".", "element_block_exists", "(", "new_element_block_id", ")", ":", "self", ".", "_exists_warning", "(", "'\"'", "+", "new_element_block_id", "+", "'\"'", ",", "'element block'", ")", "# rename it", "self", ".", "element_blocks", "[", "element_block_id", "]", "[", "0", "]", "=", "new_element_block_id", "return", "assert", "type", "(", "new_element_block_id", ")", "is", "int", "# rename the block", "self", ".", "_rename_entity", "(", "'element block'", ",", "element_block_id", ",", "new_element_block_id", ",", "self", ".", "get_element_block_ids", ",", "self", ".", "element_blocks", ")", "# adjust side sets", "for", "side_set_id", "in", "self", ".", "get_side_set_ids", "(", ")", ":", "members", "=", "self", ".", "get_side_set_members", "(", "side_set_id", ")", "new_members", "=", "[", "]", "for", "member", "in", "members", ":", "if", "member", "[", "0", "]", "==", "element_block_id", ":", "member", "=", "list", "(", "member", ")", "member", "[", "0", "]", "=", "new_element_block_id", "member", "=", "tuple", "(", "member", ")", "new_members", ".", "append", "(", "member", ")", "members", "[", ":", "]", "=", "new_members" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L4036-L4083
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/start_try_job.py
python
_CanDownloadBuilds
(master_name)
return master_name.startswith('ChromiumPerf')
Checks whether bisecting using archives is supported.
Checks whether bisecting using archives is supported.
[ "Checks", "whether", "bisecting", "using", "archives", "is", "supported", "." ]
def _CanDownloadBuilds(master_name): """Checks whether bisecting using archives is supported.""" return master_name.startswith('ChromiumPerf')
[ "def", "_CanDownloadBuilds", "(", "master_name", ")", ":", "return", "master_name", ".", "startswith", "(", "'ChromiumPerf'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/start_try_job.py#L388-L390
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBAddress.__get_load_addr_property__
(self)
return self.GetLoadAddress (target)
Get the load address for a lldb.SBAddress using the current target.
Get the load address for a lldb.SBAddress using the current target.
[ "Get", "the", "load", "address", "for", "a", "lldb", ".", "SBAddress", "using", "the", "current", "target", "." ]
def __get_load_addr_property__ (self): '''Get the load address for a lldb.SBAddress using the current target.''' return self.GetLoadAddress (target)
[ "def", "__get_load_addr_property__", "(", "self", ")", ":", "return", "self", ".", "GetLoadAddress", "(", "target", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L996-L998
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/groupby/ops.py
python
BaseGrouper.groups
(self)
dict {group name -> group labels}
dict {group name -> group labels}
[ "dict", "{", "group", "name", "-", ">", "group", "labels", "}" ]
def groups(self) -> dict[Hashable, np.ndarray]: """dict {group name -> group labels}""" if len(self.groupings) == 1: return self.groupings[0].groups else: to_groupby = zip(*(ping.grouping_vector for ping in self.groupings)) index = Index(to_groupby) return self.axis.groupby(index)
[ "def", "groups", "(", "self", ")", "->", "dict", "[", "Hashable", ",", "np", ".", "ndarray", "]", ":", "if", "len", "(", "self", ".", "groupings", ")", "==", "1", ":", "return", "self", ".", "groupings", "[", "0", "]", ".", "groups", "else", ":", "to_groupby", "=", "zip", "(", "*", "(", "ping", ".", "grouping_vector", "for", "ping", "in", "self", ".", "groupings", ")", ")", "index", "=", "Index", "(", "to_groupby", ")", "return", "self", ".", "axis", ".", "groupby", "(", "index", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/groupby/ops.py#L894-L901
facebookarchive/LogDevice
ce7726050edc49a1e15d9160e81c890736b779e2
build/fbcode_builder/getdeps/builder.py
python
CargoBuilder._resolve_crate_to_path
(crate, git_conf)
Tries to find <crate> in git_conf["inst_dir"] by searching a [package] keyword followed by name = "<crate>".
Tries to find <crate> in git_conf["inst_dir"] by searching a [package] keyword followed by name = "<crate>".
[ "Tries", "to", "find", "<crate", ">", "in", "git_conf", "[", "inst_dir", "]", "by", "searching", "a", "[", "package", "]", "keyword", "followed", "by", "name", "=", "<crate", ">", "." ]
def _resolve_crate_to_path(crate, git_conf): """ Tries to find <crate> in git_conf["inst_dir"] by searching a [package] keyword followed by name = "<crate>". """ source_dir = git_conf["source_dir"] search_pattern = '[package]\nname = "{}"'.format(crate) for root, _, files in os.walk(source_dir): for fname in files: if fname == "Cargo.toml": with open(os.path.join(root, fname), "r") as f: if search_pattern in f.read(): return root raise Exception("Failed to found crate {} in path {}".format(crate, source_dir))
[ "def", "_resolve_crate_to_path", "(", "crate", ",", "git_conf", ")", ":", "source_dir", "=", "git_conf", "[", "\"source_dir\"", "]", "search_pattern", "=", "'[package]\\nname = \"{}\"'", ".", "format", "(", "crate", ")", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "source_dir", ")", ":", "for", "fname", "in", "files", ":", "if", "fname", "==", "\"Cargo.toml\"", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "root", ",", "fname", ")", ",", "\"r\"", ")", "as", "f", ":", "if", "search_pattern", "in", "f", ".", "read", "(", ")", ":", "return", "root", "raise", "Exception", "(", "\"Failed to found crate {} in path {}\"", ".", "format", "(", "crate", ",", "source_dir", ")", ")" ]
https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/build/fbcode_builder/getdeps/builder.py#L1289-L1304
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/mox.py
python
MockAnything.__getattr__
(self, method_name)
return self._CreateMockMethod(method_name)
Intercept method calls on this object. A new MockMethod is returned that is aware of the MockAnything's state (record or replay). The call will be recorded or replayed by the MockMethod's __call__. Args: # method name: the name of the method being called. method_name: str Returns: A new MockMethod aware of MockAnything's state (record or replay).
Intercept method calls on this object.
[ "Intercept", "method", "calls", "on", "this", "object", "." ]
def __getattr__(self, method_name): """Intercept method calls on this object. A new MockMethod is returned that is aware of the MockAnything's state (record or replay). The call will be recorded or replayed by the MockMethod's __call__. Args: # method name: the name of the method being called. method_name: str Returns: A new MockMethod aware of MockAnything's state (record or replay). """ return self._CreateMockMethod(method_name)
[ "def", "__getattr__", "(", "self", ",", "method_name", ")", ":", "return", "self", ".", "_CreateMockMethod", "(", "method_name", ")" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/mox.py#L278-L293
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/parse/standard_method.py
python
ms_len
(data)
return data.__len__()
Implementation of `len`.
Implementation of `len`.
[ "Implementation", "of", "len", "." ]
def ms_len(data): """Implementation of `len`.""" return data.__len__()
[ "def", "ms_len", "(", "data", ")", ":", "return", "data", ".", "__len__", "(", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/standard_method.py#L1443-L1445
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/importlib-metadata/py3/importlib_metadata/_meta.py
python
PackageMetadata.get_all
(self, name: str, failobj: _T = ...)
Return all values associated with a possibly multi-valued key.
Return all values associated with a possibly multi-valued key.
[ "Return", "all", "values", "associated", "with", "a", "possibly", "multi", "-", "valued", "key", "." ]
def get_all(self, name: str, failobj: _T = ...) -> Union[List[Any], _T]: """ Return all values associated with a possibly multi-valued key. """
[ "def", "get_all", "(", "self", ",", "name", ":", "str", ",", "failobj", ":", "_T", "=", "...", ")", "->", "Union", "[", "List", "[", "Any", "]", ",", "_T", "]", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/importlib-metadata/py3/importlib_metadata/_meta.py#L21-L24
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
GBSpan.__eq__
(*args, **kwargs)
return _core_.GBSpan___eq__(*args, **kwargs)
__eq__(self, PyObject other) -> bool Compare wxGBSpan for equality.
__eq__(self, PyObject other) -> bool
[ "__eq__", "(", "self", "PyObject", "other", ")", "-", ">", "bool" ]
def __eq__(*args, **kwargs): """ __eq__(self, PyObject other) -> bool Compare wxGBSpan for equality. """ return _core_.GBSpan___eq__(*args, **kwargs)
[ "def", "__eq__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GBSpan___eq__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L15672-L15678
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/nn_ops.py
python
softmax_v2
(logits, axis=None, name=None)
return _wrap_2d_function(logits, gen_nn_ops.softmax, axis, name)
Computes softmax activations. Used for multi-class predictions. The sum of all outputs generated by softmax is 1. This function performs the equivalent of ```python softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis, keepdims=True) ``` Example usage: >>> softmax = tf.nn.softmax([-1, 0., 1.]) >>> softmax <tf.Tensor: shape=(3,), dtype=float32, numpy=array([0.09003057, 0.24472848, 0.66524094], dtype=float32)> >>> sum(softmax) <tf.Tensor: shape=(), dtype=float32, numpy=1.0> Args: logits: A non-empty `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. axis: The dimension softmax would be performed on. The default is -1 which indicates the last dimension. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type and shape as `logits`. Raises: InvalidArgumentError: if `logits` is empty or `axis` is beyond the last dimension of `logits`.
Computes softmax activations.
[ "Computes", "softmax", "activations", "." ]
def softmax_v2(logits, axis=None, name=None): """Computes softmax activations. Used for multi-class predictions. The sum of all outputs generated by softmax is 1. This function performs the equivalent of ```python softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis, keepdims=True) ``` Example usage: >>> softmax = tf.nn.softmax([-1, 0., 1.]) >>> softmax <tf.Tensor: shape=(3,), dtype=float32, numpy=array([0.09003057, 0.24472848, 0.66524094], dtype=float32)> >>> sum(softmax) <tf.Tensor: shape=(), dtype=float32, numpy=1.0> Args: logits: A non-empty `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. axis: The dimension softmax would be performed on. The default is -1 which indicates the last dimension. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type and shape as `logits`. Raises: InvalidArgumentError: if `logits` is empty or `axis` is beyond the last dimension of `logits`. """ if axis is None: axis = -1 return _wrap_2d_function(logits, gen_nn_ops.softmax, axis, name)
[ "def", "softmax_v2", "(", "logits", ",", "axis", "=", "None", ",", "name", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "-", "1", "return", "_wrap_2d_function", "(", "logits", ",", "gen_nn_ops", ".", "softmax", ",", "axis", ",", "name", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/nn_ops.py#L3827-L3863
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/input.py
python
TurnIntIntoStrInList
(the_list)
Given list the_list, recursively converts all integers into strings.
Given list the_list, recursively converts all integers into strings.
[ "Given", "list", "the_list", "recursively", "converts", "all", "integers", "into", "strings", "." ]
def TurnIntIntoStrInList(the_list): """Given list the_list, recursively converts all integers into strings. """ for index in xrange(0, len(the_list)): item = the_list[index] if type(item) is int: the_list[index] = str(item) elif type(item) is dict: TurnIntIntoStrInDict(item) elif type(item) is list: TurnIntIntoStrInList(item)
[ "def", "TurnIntIntoStrInList", "(", "the_list", ")", ":", "for", "index", "in", "xrange", "(", "0", ",", "len", "(", "the_list", ")", ")", ":", "item", "=", "the_list", "[", "index", "]", "if", "type", "(", "item", ")", "is", "int", ":", "the_list", "[", "index", "]", "=", "str", "(", "item", ")", "elif", "type", "(", "item", ")", "is", "dict", ":", "TurnIntIntoStrInDict", "(", "item", ")", "elif", "type", "(", "item", ")", "is", "list", ":", "TurnIntIntoStrInList", "(", "item", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/input.py#L2649-L2659
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
CustomTreeCtrl.GetItemType
(self, item)
return item.GetType()
Returns the item type. :param `item`: an instance of :class:`GenericTreeItem`. :return: An integer representing the item type. :see: :meth:`~CustomTreeCtrl.SetItemType` for a description of valid item types.
Returns the item type.
[ "Returns", "the", "item", "type", "." ]
def GetItemType(self, item): """ Returns the item type. :param `item`: an instance of :class:`GenericTreeItem`. :return: An integer representing the item type. :see: :meth:`~CustomTreeCtrl.SetItemType` for a description of valid item types. """ return item.GetType()
[ "def", "GetItemType", "(", "self", ",", "item", ")", ":", "return", "item", ".", "GetType", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L4335-L4346
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/generator/analyzer.py
python
_AddBuildTargets
(target, roots, add_if_no_ancestor, result)
Recurses through all targets that depend on |target|, adding all targets that need to be built (and are in |roots|) to |result|. roots: set of root targets. add_if_no_ancestor: If true and there are no ancestors of |target| then add |target| to |result|. |target| must still be in |roots|. result: targets that need to be built are added here.
Recurses through all targets that depend on |target|, adding all targets that need to be built (and are in |roots|) to |result|. roots: set of root targets. add_if_no_ancestor: If true and there are no ancestors of |target| then add |target| to |result|. |target| must still be in |roots|. result: targets that need to be built are added here.
[ "Recurses", "through", "all", "targets", "that", "depend", "on", "|target|", "adding", "all", "targets", "that", "need", "to", "be", "built", "(", "and", "are", "in", "|roots|", ")", "to", "|result|", ".", "roots", ":", "set", "of", "root", "targets", ".", "add_if_no_ancestor", ":", "If", "true", "and", "there", "are", "no", "ancestors", "of", "|target|", "then", "add", "|target|", "to", "|result|", ".", "|target|", "must", "still", "be", "in", "|roots|", ".", "result", ":", "targets", "that", "need", "to", "be", "built", "are", "added", "here", "." ]
def _AddBuildTargets(target, roots, add_if_no_ancestor, result): """Recurses through all targets that depend on |target|, adding all targets that need to be built (and are in |roots|) to |result|. roots: set of root targets. add_if_no_ancestor: If true and there are no ancestors of |target| then add |target| to |result|. |target| must still be in |roots|. result: targets that need to be built are added here.""" if target.visited: return target.visited = True target.in_roots = not target.back_deps and target in roots for back_dep_target in target.back_deps: _AddBuildTargets(back_dep_target, roots, False, result) target.added_to_compile_targets |= back_dep_target.added_to_compile_targets target.in_roots |= back_dep_target.in_roots # Always add 'executable' targets. Even though they may be built by other # targets that depend upon them it makes detection of what is going to be # built easier. if target.in_roots and \ (target.is_executable or (not target.added_to_compile_targets and (add_if_no_ancestor or target.requires_build))): result.add(target) target.added_to_compile_targets = True
[ "def", "_AddBuildTargets", "(", "target", ",", "roots", ",", "add_if_no_ancestor", ",", "result", ")", ":", "if", "target", ".", "visited", ":", "return", "target", ".", "visited", "=", "True", "target", ".", "in_roots", "=", "not", "target", ".", "back_deps", "and", "target", "in", "roots", "for", "back_dep_target", "in", "target", ".", "back_deps", ":", "_AddBuildTargets", "(", "back_dep_target", ",", "roots", ",", "False", ",", "result", ")", "target", ".", "added_to_compile_targets", "|=", "back_dep_target", ".", "added_to_compile_targets", "target", ".", "in_roots", "|=", "back_dep_target", ".", "in_roots", "# Always add 'executable' targets. Even though they may be built by other", "# targets that depend upon them it makes detection of what is going to be", "# built easier.", "if", "target", ".", "in_roots", "and", "(", "target", ".", "is_executable", "or", "(", "not", "target", ".", "added_to_compile_targets", "and", "(", "add_if_no_ancestor", "or", "target", ".", "requires_build", ")", ")", ")", ":", "result", ".", "add", "(", "target", ")", "target", ".", "added_to_compile_targets", "=", "True" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/analyzer.py#L397-L423
bh107/bohrium
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
bridge/npbackend/bohrium/summations.py
python
argmax
(a, axis=None, out=None)
Returns the indices of the maximum values along an axis. Parameters ---------- a : array_like Input array. axis : int, optional By default, the index is into the flattened array, otherwise along the specified axis. out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Returns ------- index_array : ndarray of ints Array of indices into the array. It has the same shape as `a.shape` with the dimension along `axis` removed. See Also -------- ndarray.argmax, argmin amax : The maximum value along a given axis. unravel_index : Convert a flat index into an index tuple. Notes ----- In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned. Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.argmax(a) 5 >>> np.argmax(a, axis=0) array([1, 1, 1]) >>> np.argmax(a, axis=1) array([2, 2]) >>> b = np.arange(6) >>> b[1] = 5 >>> b array([0, 5, 2, 3, 4, 5]) >>> np.argmax(b) # Only the first occurrence is returned. 1
Returns the indices of the maximum values along an axis. Parameters ---------- a : array_like Input array. axis : int, optional By default, the index is into the flattened array, otherwise along the specified axis. out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Returns ------- index_array : ndarray of ints Array of indices into the array. It has the same shape as `a.shape` with the dimension along `axis` removed. See Also -------- ndarray.argmax, argmin amax : The maximum value along a given axis. unravel_index : Convert a flat index into an index tuple. Notes ----- In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned. Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.argmax(a) 5 >>> np.argmax(a, axis=0) array([1, 1, 1]) >>> np.argmax(a, axis=1) array([2, 2]) >>> b = np.arange(6) >>> b[1] = 5 >>> b array([0, 5, 2, 3, 4, 5]) >>> np.argmax(b) # Only the first occurrence is returned. 1
[ "Returns", "the", "indices", "of", "the", "maximum", "values", "along", "an", "axis", ".", "Parameters", "----------", "a", ":", "array_like", "Input", "array", ".", "axis", ":", "int", "optional", "By", "default", "the", "index", "is", "into", "the", "flattened", "array", "otherwise", "along", "the", "specified", "axis", ".", "out", ":", "array", "optional", "If", "provided", "the", "result", "will", "be", "inserted", "into", "this", "array", ".", "It", "should", "be", "of", "the", "appropriate", "shape", "and", "dtype", ".", "Returns", "-------", "index_array", ":", "ndarray", "of", "ints", "Array", "of", "indices", "into", "the", "array", ".", "It", "has", "the", "same", "shape", "as", "a", ".", "shape", "with", "the", "dimension", "along", "axis", "removed", ".", "See", "Also", "--------", "ndarray", ".", "argmax", "argmin", "amax", ":", "The", "maximum", "value", "along", "a", "given", "axis", ".", "unravel_index", ":", "Convert", "a", "flat", "index", "into", "an", "index", "tuple", ".", "Notes", "-----", "In", "case", "of", "multiple", "occurrences", "of", "the", "maximum", "values", "the", "indices", "corresponding", "to", "the", "first", "occurrence", "are", "returned", ".", "Examples", "--------", ">>>", "a", "=", "np", ".", "arange", "(", "6", ")", ".", "reshape", "(", "2", "3", ")", ">>>", "a", "array", "(", "[[", "0", "1", "2", "]", "[", "3", "4", "5", "]]", ")", ">>>", "np", ".", "argmax", "(", "a", ")", "5", ">>>", "np", ".", "argmax", "(", "a", "axis", "=", "0", ")", "array", "(", "[", "1", "1", "1", "]", ")", ">>>", "np", ".", "argmax", "(", "a", "axis", "=", "1", ")", "array", "(", "[", "2", "2", "]", ")", ">>>", "b", "=", "np", ".", "arange", "(", "6", ")", ">>>", "b", "[", "1", "]", "=", "5", ">>>", "b", "array", "(", "[", "0", "5", "2", "3", "4", "5", "]", ")", ">>>", "np", ".", "argmax", "(", "b", ")", "#", "Only", "the", "first", "occurrence", "is", "returned", ".", "1" ]
def argmax(a, axis=None, out=None): """ Returns the indices of the maximum values along an axis. Parameters ---------- a : array_like Input array. axis : int, optional By default, the index is into the flattened array, otherwise along the specified axis. out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Returns ------- index_array : ndarray of ints Array of indices into the array. It has the same shape as `a.shape` with the dimension along `axis` removed. See Also -------- ndarray.argmax, argmin amax : The maximum value along a given axis. unravel_index : Convert a flat index into an index tuple. Notes ----- In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned. Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.argmax(a) 5 >>> np.argmax(a, axis=0) array([1, 1, 1]) >>> np.argmax(a, axis=1) array([2, 2]) >>> b = np.arange(6) >>> b[1] = 5 >>> b array([0, 5, 2, 3, 4, 5]) >>> np.argmax(b) # Only the first occurrence is returned. 1 """ if not bhary.check(a): return numpy.argmax(a, axis=axis, out=out) if axis is None or (a.ndim == 1 and axis == 0): a = array_manipulation.flatten(a, always_copy=False) ret = reorganization.flatnonzero(a == max(a))[0] else: warnings.warn("Bohrium does not support the 'axis' argument, " "it will be handled by the original NumPy.", UserWarning, 2) return numpy.argmax(a.copy2numpy(), axis=axis) if out is None: return ret else: out[...] = ret return out
[ "def", "argmax", "(", "a", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "if", "not", "bhary", ".", "check", "(", "a", ")", ":", "return", "numpy", ".", "argmax", "(", "a", ",", "axis", "=", "axis", ",", "out", "=", "out", ")", "if", "axis", "is", "None", "or", "(", "a", ".", "ndim", "==", "1", "and", "axis", "==", "0", ")", ":", "a", "=", "array_manipulation", ".", "flatten", "(", "a", ",", "always_copy", "=", "False", ")", "ret", "=", "reorganization", ".", "flatnonzero", "(", "a", "==", "max", "(", "a", ")", ")", "[", "0", "]", "else", ":", "warnings", ".", "warn", "(", "\"Bohrium does not support the 'axis' argument, \"", "\"it will be handled by the original NumPy.\"", ",", "UserWarning", ",", "2", ")", "return", "numpy", ".", "argmax", "(", "a", ".", "copy2numpy", "(", ")", ",", "axis", "=", "axis", ")", "if", "out", "is", "None", ":", "return", "ret", "else", ":", "out", "[", "...", "]", "=", "ret", "return", "out" ]
https://github.com/bh107/bohrium/blob/5b83e7117285fefc7779ed0e9acb0f8e74c7e068/bridge/npbackend/bohrium/summations.py#L346-L408
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Text.window_names
(self)
return self.tk.splitlist( self.tk.call(self._w, 'window', 'names'))
Return all names of embedded windows in this widget.
Return all names of embedded windows in this widget.
[ "Return", "all", "names", "of", "embedded", "windows", "in", "this", "widget", "." ]
def window_names(self): """Return all names of embedded windows in this widget.""" return self.tk.splitlist( self.tk.call(self._w, 'window', 'names'))
[ "def", "window_names", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'window'", ",", "'names'", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L3424-L3427
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/io/netcdf.py
python
netcdf_file.flush
(self)
Perform a sync-to-disk flush if the `netcdf_file` object is in write mode. See Also -------- sync : Identical function
Perform a sync-to-disk flush if the `netcdf_file` object is in write mode.
[ "Perform", "a", "sync", "-", "to", "-", "disk", "flush", "if", "the", "netcdf_file", "object", "is", "in", "write", "mode", "." ]
def flush(self): """ Perform a sync-to-disk flush if the `netcdf_file` object is in write mode. See Also -------- sync : Identical function """ if hasattr(self, 'mode') and self.mode in 'wa': self._write()
[ "def", "flush", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'mode'", ")", "and", "self", ".", "mode", "in", "'wa'", ":", "self", ".", "_write", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/netcdf.py#L379-L389
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/linalg/_interpolative_backend.py
python
idz_diffsnorm
(m, n, matveca, matveca2, matvec, matvec2, its=20)
return _id.idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its)
Estimate spectral norm of the difference of two complex matrices by the randomized power method. :param m: Matrix row dimension. :type m: int :param n: Matrix column dimension. :type n: int :param matveca: Function to apply the adjoint of the first matrix to a vector, with call signature `y = matveca(x)`, where `x` and `y` are the input and output vectors, respectively. :type matveca: function :param matveca2: Function to apply the adjoint of the second matrix to a vector, with call signature `y = matveca2(x)`, where `x` and `y` are the input and output vectors, respectively. :type matveca2: function :param matvec: Function to apply the first matrix to a vector, with call signature `y = matvec(x)`, where `x` and `y` are the input and output vectors, respectively. :type matvec: function :param matvec2: Function to apply the second matrix to a vector, with call signature `y = matvec2(x)`, where `x` and `y` are the input and output vectors, respectively. :type matvec2: function :param its: Number of power method iterations. :type its: int :return: Spectral norm estimate of matrix difference. :rtype: float
Estimate spectral norm of the difference of two complex matrices by the randomized power method.
[ "Estimate", "spectral", "norm", "of", "the", "difference", "of", "two", "complex", "matrices", "by", "the", "randomized", "power", "method", "." ]
def idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its=20): """ Estimate spectral norm of the difference of two complex matrices by the randomized power method. :param m: Matrix row dimension. :type m: int :param n: Matrix column dimension. :type n: int :param matveca: Function to apply the adjoint of the first matrix to a vector, with call signature `y = matveca(x)`, where `x` and `y` are the input and output vectors, respectively. :type matveca: function :param matveca2: Function to apply the adjoint of the second matrix to a vector, with call signature `y = matveca2(x)`, where `x` and `y` are the input and output vectors, respectively. :type matveca2: function :param matvec: Function to apply the first matrix to a vector, with call signature `y = matvec(x)`, where `x` and `y` are the input and output vectors, respectively. :type matvec: function :param matvec2: Function to apply the second matrix to a vector, with call signature `y = matvec2(x)`, where `x` and `y` are the input and output vectors, respectively. :type matvec2: function :param its: Number of power method iterations. :type its: int :return: Spectral norm estimate of matrix difference. :rtype: float """ return _id.idz_diffsnorm(m, n, matveca, matveca2, matvec, matvec2, its)
[ "def", "idz_diffsnorm", "(", "m", ",", "n", ",", "matveca", ",", "matveca2", ",", "matvec", ",", "matvec2", ",", "its", "=", "20", ")", ":", "return", "_id", ".", "idz_diffsnorm", "(", "m", ",", "n", ",", "matveca", ",", "matveca2", ",", "matvec", ",", "matvec2", ",", "its", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/_interpolative_backend.py#L1168-L1207
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/adapters.py
python
HTTPAdapter.add_headers
(self, request, **kwargs)
Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send().
Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
[ "Add", "any", "headers", "needed", "by", "the", "connection", ".", "As", "of", "v2", ".", "0", "this", "does", "nothing", "by", "default", "but", "is", "left", "for", "overriding", "by", "users", "that", "subclass", "the", ":", "class", ":", "HTTPAdapter", "<requests", ".", "adapters", ".", "HTTPAdapter", ">", "." ]
def add_headers(self, request, **kwargs): """Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send(). """ pass
[ "def", "add_headers", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "pass" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/adapters.py#L358-L370
apache/trafodion
8455c839ad6b6d7b6e04edda5715053095b78046
core/sqf/src/seatrans/hbase-trx/src/main/python/thrift1/gen-py/hbase/Hbase.py
python
Iface.scannerGetList
(self, id, nbRows)
Returns, starting at the scanner's current row value nbRows worth of rows and advances to the next row in the table. When there are no more rows in the table, or a key greater-than-or-equal-to the scanner's specified stopRow is reached, an empty list is returned. @return a TRowResult containing the current row and a map of the columns to TCells. @throws IllegalArgument if ScannerID is invalid @throws NotFound when the scanner reaches the end Parameters: - id: id of a scanner returned by scannerOpen - nbRows: number of results to return
Returns, starting at the scanner's current row value nbRows worth of rows and advances to the next row in the table. When there are no more rows in the table, or a key greater-than-or-equal-to the scanner's specified stopRow is reached, an empty list is returned.
[ "Returns", "starting", "at", "the", "scanner", "s", "current", "row", "value", "nbRows", "worth", "of", "rows", "and", "advances", "to", "the", "next", "row", "in", "the", "table", ".", "When", "there", "are", "no", "more", "rows", "in", "the", "table", "or", "a", "key", "greater", "-", "than", "-", "or", "-", "equal", "-", "to", "the", "scanner", "s", "specified", "stopRow", "is", "reached", "an", "empty", "list", "is", "returned", "." ]
def scannerGetList(self, id, nbRows): """ Returns, starting at the scanner's current row value nbRows worth of rows and advances to the next row in the table. When there are no more rows in the table, or a key greater-than-or-equal-to the scanner's specified stopRow is reached, an empty list is returned. @return a TRowResult containing the current row and a map of the columns to TCells. @throws IllegalArgument if ScannerID is invalid @throws NotFound when the scanner reaches the end Parameters: - id: id of a scanner returned by scannerOpen - nbRows: number of results to return """ pass
[ "def", "scannerGetList", "(", "self", ",", "id", ",", "nbRows", ")", ":", "pass" ]
https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/core/sqf/src/seatrans/hbase-trx/src/main/python/thrift1/gen-py/hbase/Hbase.py#L559-L576
martinmoene/span-lite
8f7935ff4e502ee023990d356d6578b8293eda74
script/create-vcpkg.py
python
portfile_path
( args )
return tpl_path_vcpkg_portfile.format( vcpkg=args.vcpkg_root, prj=args.project )
Create path like vcpks/ports/_project_/portfile.cmake
Create path like vcpks/ports/_project_/portfile.cmake
[ "Create", "path", "like", "vcpks", "/", "ports", "/", "_project_", "/", "portfile", ".", "cmake" ]
def portfile_path( args ): """Create path like vcpks/ports/_project_/portfile.cmake""" return tpl_path_vcpkg_portfile.format( vcpkg=args.vcpkg_root, prj=args.project )
[ "def", "portfile_path", "(", "args", ")", ":", "return", "tpl_path_vcpkg_portfile", ".", "format", "(", "vcpkg", "=", "args", ".", "vcpkg_root", ",", "prj", "=", "args", ".", "project", ")" ]
https://github.com/martinmoene/span-lite/blob/8f7935ff4e502ee023990d356d6578b8293eda74/script/create-vcpkg.py#L118-L120
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
clang/bindings/python/clang/cindex.py
python
TranslationUnit.get_file
(self, filename)
return File.from_name(self, filename)
Obtain a File from this translation unit.
Obtain a File from this translation unit.
[ "Obtain", "a", "File", "from", "this", "translation", "unit", "." ]
def get_file(self, filename): """Obtain a File from this translation unit.""" return File.from_name(self, filename)
[ "def", "get_file", "(", "self", ",", "filename", ")", ":", "return", "File", ".", "from_name", "(", "self", ",", "filename", ")" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/bindings/python/clang/cindex.py#L2907-L2910
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
modules/thermal_hydraulics/python/peacock/UnitConversion.py
python
Unit.to
(self, value)
return None
Convert the 'value' from the common base unit into my unit @param value[float] Input value @return Converted value
Convert the 'value' from the common base unit into my unit
[ "Convert", "the", "value", "from", "the", "common", "base", "unit", "into", "my", "unit" ]
def to(self, value): """ Convert the 'value' from the common base unit into my unit @param value[float] Input value @return Converted value """ return None
[ "def", "to", "(", "self", ",", "value", ")", ":", "return", "None" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/modules/thermal_hydraulics/python/peacock/UnitConversion.py#L26-L33
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py
python
Block._interpolate_with_fill
( self, method="pad", axis=0, inplace=False, limit=None, fill_value=None, coerce=False, downcast=None, )
return self._maybe_downcast(blocks, downcast)
fillna but using the interpolate machinery
fillna but using the interpolate machinery
[ "fillna", "but", "using", "the", "interpolate", "machinery" ]
def _interpolate_with_fill( self, method="pad", axis=0, inplace=False, limit=None, fill_value=None, coerce=False, downcast=None, ): """ fillna but using the interpolate machinery """ inplace = validate_bool_kwarg(inplace, "inplace") # if we are coercing, then don't force the conversion # if the block can't hold the type if coerce: if not self._can_hold_na: if inplace: return [self] else: return [self.copy()] values = self.values if inplace else self.values.copy() # We only get here for non-ExtensionBlock fill_value = convert_scalar(self.values, fill_value) values = missing.interpolate_2d( values, method=method, axis=axis, limit=limit, fill_value=fill_value, dtype=self.dtype, ) blocks = [self.make_block_same_class(values, ndim=self.ndim)] return self._maybe_downcast(blocks, downcast)
[ "def", "_interpolate_with_fill", "(", "self", ",", "method", "=", "\"pad\"", ",", "axis", "=", "0", ",", "inplace", "=", "False", ",", "limit", "=", "None", ",", "fill_value", "=", "None", ",", "coerce", "=", "False", ",", "downcast", "=", "None", ",", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "\"inplace\"", ")", "# if we are coercing, then don't force the conversion", "# if the block can't hold the type", "if", "coerce", ":", "if", "not", "self", ".", "_can_hold_na", ":", "if", "inplace", ":", "return", "[", "self", "]", "else", ":", "return", "[", "self", ".", "copy", "(", ")", "]", "values", "=", "self", ".", "values", "if", "inplace", "else", "self", ".", "values", ".", "copy", "(", ")", "# We only get here for non-ExtensionBlock", "fill_value", "=", "convert_scalar", "(", "self", ".", "values", ",", "fill_value", ")", "values", "=", "missing", ".", "interpolate_2d", "(", "values", ",", "method", "=", "method", ",", "axis", "=", "axis", ",", "limit", "=", "limit", ",", "fill_value", "=", "fill_value", ",", "dtype", "=", "self", ".", "dtype", ",", ")", "blocks", "=", "[", "self", ".", "make_block_same_class", "(", "values", ",", "ndim", "=", "self", ".", "ndim", ")", "]", "return", "self", ".", "_maybe_downcast", "(", "blocks", ",", "downcast", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L1173-L1211
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
CommandLinkButton.SetMainLabel
(*args, **kwargs)
return _controls_.CommandLinkButton_SetMainLabel(*args, **kwargs)
SetMainLabel(self, String mainLabel)
SetMainLabel(self, String mainLabel)
[ "SetMainLabel", "(", "self", "String", "mainLabel", ")" ]
def SetMainLabel(*args, **kwargs): """SetMainLabel(self, String mainLabel)""" return _controls_.CommandLinkButton_SetMainLabel(*args, **kwargs)
[ "def", "SetMainLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "CommandLinkButton_SetMainLabel", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L7841-L7843
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py
python
Notebook.add
(self, child, **kw)
Adds a new tab to the notebook. If window is currently managed by the notebook but hidden, it is restored to its previous position.
Adds a new tab to the notebook.
[ "Adds", "a", "new", "tab", "to", "the", "notebook", "." ]
def add(self, child, **kw): """Adds a new tab to the notebook. If window is currently managed by the notebook but hidden, it is restored to its previous position.""" self.tk.call(self._w, "add", child, *(_format_optdict(kw)))
[ "def", "add", "(", "self", ",", "child", ",", "*", "*", "kw", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"add\"", ",", "child", ",", "*", "(", "_format_optdict", "(", "kw", ")", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py#L834-L839
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
samples/networking/05-small-chat/AIRepository.py
python
AIRepository.deallocateChannel
(self, doID)
This method will be called whenever a client disconnects from the server. The given doID is the ID of the client who left us.
This method will be called whenever a client disconnects from the server. The given doID is the ID of the client who left us.
[ "This", "method", "will", "be", "called", "whenever", "a", "client", "disconnects", "from", "the", "server", ".", "The", "given", "doID", "is", "the", "ID", "of", "the", "client", "who", "left", "us", "." ]
def deallocateChannel(self, doID): """ This method will be called whenever a client disconnects from the server. The given doID is the ID of the client who left us. """ print("Client left us: ", doID)
[ "def", "deallocateChannel", "(", "self", ",", "doID", ")", ":", "print", "(", "\"Client left us: \"", ",", "doID", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/samples/networking/05-small-chat/AIRepository.py#L78-L81
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/gbpdistro_support.py
python
get_owner_name
(url)
return result
Given a gbpdistro url, returns the name of the github user in the url. If the url is not a valid github url it returns the default `ros`. This information is used to set the homebrew tap name, see: https://github.com/ros-infrastructure/rosdep/pull/17 :returns: The github account in the given gbpdistro url
Given a gbpdistro url, returns the name of the github user in the url.
[ "Given", "a", "gbpdistro", "url", "returns", "the", "name", "of", "the", "github", "user", "in", "the", "url", "." ]
def get_owner_name(url): """ Given a gbpdistro url, returns the name of the github user in the url. If the url is not a valid github url it returns the default `ros`. This information is used to set the homebrew tap name, see: https://github.com/ros-infrastructure/rosdep/pull/17 :returns: The github account in the given gbpdistro url """ result = 'ros' try: parsed = urlparse.urlparse(url) if parsed.netloc == 'github.com': result = parsed.path.split('/')[1] except (ValueError, IndexError): pass return result
[ "def", "get_owner_name", "(", "url", ")", ":", "result", "=", "'ros'", "try", ":", "parsed", "=", "urlparse", ".", "urlparse", "(", "url", ")", "if", "parsed", ".", "netloc", "==", "'github.com'", ":", "result", "=", "parsed", ".", "path", ".", "split", "(", "'/'", ")", "[", "1", "]", "except", "(", "ValueError", ",", "IndexError", ")", ":", "pass", "return", "result" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/gbpdistro_support.py#L42-L60
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/so3.py
python
cross_product
(w : Vector3)
return [0.,w[2],-w[1], -w[2],0.,w[0], w[1],-w[0],0.]
Returns the cross product matrix associated with w. The matrix [w]R is the derivative of the matrix R as it rotates about the axis w/||w|| with angular velocity ||w||.
Returns the cross product matrix associated with w.
[ "Returns", "the", "cross", "product", "matrix", "associated", "with", "w", "." ]
def cross_product(w : Vector3) -> Rotation: """Returns the cross product matrix associated with w. The matrix [w]R is the derivative of the matrix R as it rotates about the axis w/||w|| with angular velocity ||w||. """ return [0.,w[2],-w[1], -w[2],0.,w[0], w[1],-w[0],0.]
[ "def", "cross_product", "(", "w", ":", "Vector3", ")", "->", "Rotation", ":", "return", "[", "0.", ",", "w", "[", "2", "]", ",", "-", "w", "[", "1", "]", ",", "-", "w", "[", "2", "]", ",", "0.", ",", "w", "[", "0", "]", ",", "w", "[", "1", "]", ",", "-", "w", "[", "0", "]", ",", "0.", "]" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/so3.py#L290-L296
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/pyserial/serial/sermsdos.py
python
Serial.getCD
(self)
Eead terminal status line
Eead terminal status line
[ "Eead", "terminal", "status", "line" ]
def getCD(self): """Eead terminal status line""" raise NotImplementedError
[ "def", "getCD", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/sermsdos.py#L189-L191
mavlink/MAVSDK
42a7b2c96d55a72342c6d1657c101b557b5a0f94
tools/generate_markdown_from_doxygen_xml.py
python
cppEnum.markdown
(self,aDisplayInclude=False)
return output_string
Markdown for the enum, with details
Markdown for the enum, with details
[ "Markdown", "for", "the", "enum", "with", "details" ]
def markdown(self,aDisplayInclude=False): """ Markdown for the enum, with details """ output_string='' output_string+='\n\n### enum %s {#%s}\n' % (self.name,self.id) if aDisplayInclude: output_string+='\n```\n#include: %s\n```\n' % (self.location) output_string+='\n\n%s' % markdown_any_tag(self.briefdescription).strip() output_string+='\n\n%s' % markdown_any_tag(self.detaileddescription).strip() if len(self.enum_values)>0: output_string+='\n\nValue | Description\n--- | ---' for enum_value in self.enum_values: output_string+='\n<span id="%s"></span> `%s` | %s %s' % (enum_value.id,enum_value.name, markdown_any_tag(enum_value.briefdescription).strip(),markdown_any_tag(enum_value.detaileddescription).strip()) if len(self.seealso)>0: output_string+=self.seealso if args.debug: output_string+='\n\n' output_string+='<!-- inbodydescription: %s --> \n' % markdown_any_tag(self.inbodydescription).strip() output_string+='<!-- prot: %s -->\n' % self.prot output_string+='<!-- static: %s -->\n' % self.static return output_string
[ "def", "markdown", "(", "self", ",", "aDisplayInclude", "=", "False", ")", ":", "output_string", "=", "''", "output_string", "+=", "'\\n\\n### enum %s {#%s}\\n'", "%", "(", "self", ".", "name", ",", "self", ".", "id", ")", "if", "aDisplayInclude", ":", "output_string", "+=", "'\\n```\\n#include: %s\\n```\\n'", "%", "(", "self", ".", "location", ")", "output_string", "+=", "'\\n\\n%s'", "%", "markdown_any_tag", "(", "self", ".", "briefdescription", ")", ".", "strip", "(", ")", "output_string", "+=", "'\\n\\n%s'", "%", "markdown_any_tag", "(", "self", ".", "detaileddescription", ")", ".", "strip", "(", ")", "if", "len", "(", "self", ".", "enum_values", ")", ">", "0", ":", "output_string", "+=", "'\\n\\nValue | Description\\n--- | ---'", "for", "enum_value", "in", "self", ".", "enum_values", ":", "output_string", "+=", "'\\n<span id=\"%s\"></span> `%s` | %s %s'", "%", "(", "enum_value", ".", "id", ",", "enum_value", ".", "name", ",", "markdown_any_tag", "(", "enum_value", ".", "briefdescription", ")", ".", "strip", "(", ")", ",", "markdown_any_tag", "(", "enum_value", ".", "detaileddescription", ")", ".", "strip", "(", ")", ")", "if", "len", "(", "self", ".", "seealso", ")", ">", "0", ":", "output_string", "+=", "self", ".", "seealso", "if", "args", ".", "debug", ":", "output_string", "+=", "'\\n\\n'", "output_string", "+=", "'<!-- inbodydescription: %s --> \\n'", "%", "markdown_any_tag", "(", "self", ".", "inbodydescription", ")", ".", "strip", "(", ")", "output_string", "+=", "'<!-- prot: %s -->\\n'", "%", "self", ".", "prot", "output_string", "+=", "'<!-- static: %s -->\\n'", "%", "self", ".", "static", "return", "output_string" ]
https://github.com/mavlink/MAVSDK/blob/42a7b2c96d55a72342c6d1657c101b557b5a0f94/tools/generate_markdown_from_doxygen_xml.py#L555-L585
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/reduction/instruments/sans/sans_reduction_steps.py
python
Mask.add_detector_list
(self, det_list)
Mask the given detectors @param det_list: list of detector IDs
Mask the given detectors
[ "Mask", "the", "given", "detectors" ]
def add_detector_list(self, det_list): """ Mask the given detectors @param det_list: list of detector IDs """ self.detect_list.extend(det_list)
[ "def", "add_detector_list", "(", "self", ",", "det_list", ")", ":", "self", ".", "detect_list", ".", "extend", "(", "det_list", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction/instruments/sans/sans_reduction_steps.py#L291-L296
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/appdirs.py
python
user_state_dir
(appname=None, appauthor=None, version=None, roaming=False)
return path
r"""Return full path to the user-specific state dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user state directories are: Mac OS X: same as user_data_dir Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined Win *: same as user_data_dir For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state> to extend the XDG spec and support $XDG_STATE_HOME. That means, by default "~/.local/state/<AppName>".
r"""Return full path to the user-specific state dir for this application.
[ "r", "Return", "full", "path", "to", "the", "user", "-", "specific", "state", "dir", "for", "this", "application", "." ]
def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific state dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user state directories are: Mac OS X: same as user_data_dir Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined Win *: same as user_data_dir For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state> to extend the XDG spec and support $XDG_STATE_HOME. That means, by default "~/.local/state/<AppName>". """ if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv('XDG_STATE_HOME', os.path.expanduser("~/.local/state")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path
[ "def", "user_state_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "roaming", "=", "False", ")", ":", "if", "system", "in", "[", "\"win32\"", ",", "\"darwin\"", "]", ":", "path", "=", "user_data_dir", "(", "appname", ",", "appauthor", ",", "None", ",", "roaming", ")", "else", ":", "path", "=", "os", ".", "getenv", "(", "'XDG_STATE_HOME'", ",", "os", ".", "path", ".", "expanduser", "(", "\"~/.local/state\"", ")", ")", "if", "appname", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "if", "appname", "and", "version", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "version", ")", "return", "path" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/appdirs.py#L314-L353
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/DataStructs/TopNContainer.py
python
TopNContainer.GetPts
(self)
return self.best
returns our set of points
returns our set of points
[ "returns", "our", "set", "of", "points" ]
def GetPts(self): """ returns our set of points """ return self.best
[ "def", "GetPts", "(", "self", ")", ":", "return", "self", ".", "best" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/DataStructs/TopNContainer.py#L52-L54
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py
python
DataSet.open_image_file
(self, image)
return open(self._image_file(image), 'rb')
Open image file and return file object.
Open image file and return file object.
[ "Open", "image", "file", "and", "return", "file", "object", "." ]
def open_image_file(self, image): """Open image file and return file object.""" return open(self._image_file(image), 'rb')
[ "def", "open_image_file", "(", "self", ",", "image", ")", ":", "return", "open", "(", "self", ".", "_image_file", "(", "image", ")", ",", "'rb'", ")" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/dataset.py#L66-L68
ideawu/ssdb-rocks
a3cbb322cafb2f493252829c608e2239df98c9ac
deps/rocksdb-master/linters/cpp_linter/cpplint.py
python
Search
(pattern, s)
return _regexp_compile_cache[pattern].search(s)
Searches the string for the pattern, caching the compiled regexp.
Searches the string for the pattern, caching the compiled regexp.
[ "Searches", "the", "string", "for", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s)
[ "def", "Search", "(", "pattern", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "search", "(", "s", ")" ]
https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/rocksdb-master/linters/cpp_linter/cpplint.py#L537-L541
sfzhang15/FaceBoxes
b52cc92f9362d3adc08d54666aeb9ebb62fdb7da
python/caffe/pycaffe.py
python
_Net_blobs
(self)
return self._blobs_dict
An OrderedDict (bottom to top, i.e., input to output) of network blobs indexed by name
An OrderedDict (bottom to top, i.e., input to output) of network blobs indexed by name
[ "An", "OrderedDict", "(", "bottom", "to", "top", "i", ".", "e", ".", "input", "to", "output", ")", "of", "network", "blobs", "indexed", "by", "name" ]
def _Net_blobs(self): """ An OrderedDict (bottom to top, i.e., input to output) of network blobs indexed by name """ if not hasattr(self, '_blobs_dict'): self._blobs_dict = OrderedDict(zip(self._blob_names, self._blobs)) return self._blobs_dict
[ "def", "_Net_blobs", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_blobs_dict'", ")", ":", "self", ".", "_blobs_dict", "=", "OrderedDict", "(", "zip", "(", "self", ".", "_blob_names", ",", "self", ".", "_blobs", ")", ")", "return", "self", ".", "_blobs_dict" ]
https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/python/caffe/pycaffe.py#L25-L32
msftguy/ssh-rd
a5f3a79daeac5844edebf01916c9613563f1c390
_3rd/boost_1_48_0/tools/build/v2/build/property_set.py
python
empty
()
return create ()
Returns PropertySet with empty set of properties.
Returns PropertySet with empty set of properties.
[ "Returns", "PropertySet", "with", "empty", "set", "of", "properties", "." ]
def empty (): """ Returns PropertySet with empty set of properties. """ return create ()
[ "def", "empty", "(", ")", ":", "return", "create", "(", ")" ]
https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/property_set.py#L63-L66
lrjconan/GRAN
43cb4433e6f69401c3a4a6e946ea75da6ec35d72
model/gran_mixture_bernoulli.py
python
GRANMixtureBernoulli._inference
(self, A_pad=None, edges=None, node_idx_gnn=None, node_idx_feat=None, att_idx=None)
return log_theta, log_alpha
generate adj in row-wise auto-regressive fashion
generate adj in row-wise auto-regressive fashion
[ "generate", "adj", "in", "row", "-", "wise", "auto", "-", "regressive", "fashion" ]
def _inference(self, A_pad=None, edges=None, node_idx_gnn=None, node_idx_feat=None, att_idx=None): """ generate adj in row-wise auto-regressive fashion """ B, C, N_max, _ = A_pad.shape H = self.hidden_dim K = self.block_size A_pad = A_pad.view(B * C * N_max, -1) if self.dimension_reduce: node_feat = self.decoder_input(A_pad) # BCN_max X H else: node_feat = A_pad # BCN_max X N_max ### GNN inference # pad zero as node feature for newly generated nodes (1st row) node_feat = F.pad( node_feat, (0, 0, 1, 0), 'constant', value=0.0) # (BCN_max + 1) X N_max # create symmetry-breaking edge feature for the newly generated nodes att_idx = att_idx.view(-1, 1) if self.has_rand_feat: # create random feature att_edge_feat = torch.zeros(edges.shape[0], 2 * self.att_edge_dim).to(node_feat.device) idx_new_node = (att_idx[[edges[:, 0]]] > 0).long() + (att_idx[[edges[:, 1]]] > 0).long() idx_new_node = idx_new_node.byte().squeeze() att_edge_feat[idx_new_node, :] = torch.randn( idx_new_node.long().sum(), att_edge_feat.shape[1]).to(node_feat.device) else: # create one-hot feature att_edge_feat = torch.zeros(edges.shape[0], 2 * self.att_edge_dim).to(node_feat.device) # scatter with empty index seems to cause problem on CPU but not on GPU att_edge_feat = att_edge_feat.scatter(1, att_idx[[edges[:, 0]]], 1) att_edge_feat = att_edge_feat.scatter( 1, att_idx[[edges[:, 1]]] + self.att_edge_dim, 1) # GNN inference # N.B.: node_feat is shared by multiple subgraphs within the same batch node_state = self.decoder( node_feat[node_idx_feat], edges, edge_feat=att_edge_feat) ### Pairwise predict edges diff = node_state[node_idx_gnn[:, 0], :] - node_state[node_idx_gnn[:, 1], :] log_theta = self.output_theta(diff) # B X (tt+K)K log_alpha = self.output_alpha(diff) # B X (tt+K)K log_theta = log_theta.view(-1, self.num_mix_component) # B X CN(N-1)/2 X K log_alpha = log_alpha.view(-1, self.num_mix_component) # B X CN(N-1)/2 X K return log_theta, log_alpha
[ "def", "_inference", "(", "self", ",", "A_pad", "=", "None", ",", "edges", "=", "None", ",", "node_idx_gnn", "=", "None", ",", "node_idx_feat", "=", "None", ",", "att_idx", "=", "None", ")", ":", "B", ",", "C", ",", "N_max", ",", "_", "=", "A_pad", ".", "shape", "H", "=", "self", ".", "hidden_dim", "K", "=", "self", ".", "block_size", "A_pad", "=", "A_pad", ".", "view", "(", "B", "*", "C", "*", "N_max", ",", "-", "1", ")", "if", "self", ".", "dimension_reduce", ":", "node_feat", "=", "self", ".", "decoder_input", "(", "A_pad", ")", "# BCN_max X H", "else", ":", "node_feat", "=", "A_pad", "# BCN_max X N_max", "### GNN inference", "# pad zero as node feature for newly generated nodes (1st row)", "node_feat", "=", "F", ".", "pad", "(", "node_feat", ",", "(", "0", ",", "0", ",", "1", ",", "0", ")", ",", "'constant'", ",", "value", "=", "0.0", ")", "# (BCN_max + 1) X N_max", "# create symmetry-breaking edge feature for the newly generated nodes", "att_idx", "=", "att_idx", ".", "view", "(", "-", "1", ",", "1", ")", "if", "self", ".", "has_rand_feat", ":", "# create random feature", "att_edge_feat", "=", "torch", ".", "zeros", "(", "edges", ".", "shape", "[", "0", "]", ",", "2", "*", "self", ".", "att_edge_dim", ")", ".", "to", "(", "node_feat", ".", "device", ")", "idx_new_node", "=", "(", "att_idx", "[", "[", "edges", "[", ":", ",", "0", "]", "]", "]", ">", "0", ")", ".", "long", "(", ")", "+", "(", "att_idx", "[", "[", "edges", "[", ":", ",", "1", "]", "]", "]", ">", "0", ")", ".", "long", "(", ")", "idx_new_node", "=", "idx_new_node", ".", "byte", "(", ")", ".", "squeeze", "(", ")", "att_edge_feat", "[", "idx_new_node", ",", ":", "]", "=", "torch", ".", "randn", "(", "idx_new_node", ".", "long", "(", ")", ".", "sum", "(", ")", ",", "att_edge_feat", ".", "shape", "[", "1", "]", ")", ".", "to", "(", "node_feat", ".", "device", ")", "else", ":", "# create one-hot feature", "att_edge_feat", "=", "torch", ".", "zeros", "(", "edges", ".", "shape", "[", "0", "]", ",", "2", "*", "self", ".", "att_edge_dim", ")", ".", "to", "(", "node_feat", ".", "device", ")", "# scatter with empty index seems to cause problem on CPU but not on GPU", "att_edge_feat", "=", "att_edge_feat", ".", "scatter", "(", "1", ",", "att_idx", "[", "[", "edges", "[", ":", ",", "0", "]", "]", "]", ",", "1", ")", "att_edge_feat", "=", "att_edge_feat", ".", "scatter", "(", "1", ",", "att_idx", "[", "[", "edges", "[", ":", ",", "1", "]", "]", "]", "+", "self", ".", "att_edge_dim", ",", "1", ")", "# GNN inference", "# N.B.: node_feat is shared by multiple subgraphs within the same batch", "node_state", "=", "self", ".", "decoder", "(", "node_feat", "[", "node_idx_feat", "]", ",", "edges", ",", "edge_feat", "=", "att_edge_feat", ")", "### Pairwise predict edges", "diff", "=", "node_state", "[", "node_idx_gnn", "[", ":", ",", "0", "]", ",", ":", "]", "-", "node_state", "[", "node_idx_gnn", "[", ":", ",", "1", "]", ",", ":", "]", "log_theta", "=", "self", ".", "output_theta", "(", "diff", ")", "# B X (tt+K)K", "log_alpha", "=", "self", ".", "output_alpha", "(", "diff", ")", "# B X (tt+K)K", "log_theta", "=", "log_theta", ".", "view", "(", "-", "1", ",", "self", ".", "num_mix_component", ")", "# B X CN(N-1)/2 X K", "log_alpha", "=", "log_alpha", ".", "view", "(", "-", "1", ",", "self", ".", "num_mix_component", ")", "# B X CN(N-1)/2 X K", "return", "log_theta", ",", "log_alpha" ]
https://github.com/lrjconan/GRAN/blob/43cb4433e6f69401c3a4a6e946ea75da6ec35d72/model/gran_mixture_bernoulli.py#L204-L262
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/format.py
python
read_array_header_1_0
(fp)
return _read_array_header(fp, version=(1, 0))
Read an array header from a filelike object using the 1.0 file format version. This will leave the file object located just after the header. Parameters ---------- fp : filelike object A file object or something with a `.read()` method like a file. Returns ------- shape : tuple of int The shape of the array. fortran_order : bool The array data will be written out directly if it is either C-contiguous or Fortran-contiguous. Otherwise, it will be made contiguous before writing it out. dtype : dtype The dtype of the file's data. Raises ------ ValueError If the data is invalid.
Read an array header from a filelike object using the 1.0 file format version.
[ "Read", "an", "array", "header", "from", "a", "filelike", "object", "using", "the", "1", ".", "0", "file", "format", "version", "." ]
def read_array_header_1_0(fp): """ Read an array header from a filelike object using the 1.0 file format version. This will leave the file object located just after the header. Parameters ---------- fp : filelike object A file object or something with a `.read()` method like a file. Returns ------- shape : tuple of int The shape of the array. fortran_order : bool The array data will be written out directly if it is either C-contiguous or Fortran-contiguous. Otherwise, it will be made contiguous before writing it out. dtype : dtype The dtype of the file's data. Raises ------ ValueError If the data is invalid. """ return _read_array_header(fp, version=(1, 0))
[ "def", "read_array_header_1_0", "(", "fp", ")", ":", "return", "_read_array_header", "(", "fp", ",", "version", "=", "(", "1", ",", "0", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/format.py#L464-L493
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/ops.py
python
RegisterShape.__call__
(self, f)
return f
Registers "f" as the shape function for "op_type".
Registers "f" as the shape function for "op_type".
[ "Registers", "f", "as", "the", "shape", "function", "for", "op_type", "." ]
def __call__(self, f): """Registers "f" as the shape function for "op_type".""" if f is None: # None is a special "weak" value that provides a default shape function, # and can be overridden by a non-None registration. try: _default_shape_function_registry.register(_no_shape_function, self._op_type) except KeyError: # Ignore duplicate registrations of the weak value. This can # occur if the op library input to wrapper generation # inadvertently links in one or more of the standard op # libraries. pass else: _shape_registry.register(f, self._op_type) return f
[ "def", "__call__", "(", "self", ",", "f", ")", ":", "if", "f", "is", "None", ":", "# None is a special \"weak\" value that provides a default shape function,", "# and can be overridden by a non-None registration.", "try", ":", "_default_shape_function_registry", ".", "register", "(", "_no_shape_function", ",", "self", ".", "_op_type", ")", "except", "KeyError", ":", "# Ignore duplicate registrations of the weak value. This can", "# occur if the op library input to wrapper generation", "# inadvertently links in one or more of the standard op", "# libraries.", "pass", "else", ":", "_shape_registry", ".", "register", "(", "f", ",", "self", ".", "_op_type", ")", "return", "f" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/ops.py#L1678-L1694
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/executor_manager.py
python
DataParallelExecutorGroup.backward
(self)
Perform a backward pass on each executor.
Perform a backward pass on each executor.
[ "Perform", "a", "backward", "pass", "on", "each", "executor", "." ]
def backward(self): """Perform a backward pass on each executor.""" for texec in self.train_execs: texec.backward()
[ "def", "backward", "(", "self", ")", ":", "for", "texec", "in", "self", ".", "train_execs", ":", "texec", ".", "backward", "(", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/executor_manager.py#L284-L287
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
Dialog_SetLayoutAdapter
(*args, **kwargs)
return _windows_.Dialog_SetLayoutAdapter(*args, **kwargs)
Dialog_SetLayoutAdapter(DialogLayoutAdapter adapter) -> DialogLayoutAdapter
Dialog_SetLayoutAdapter(DialogLayoutAdapter adapter) -> DialogLayoutAdapter
[ "Dialog_SetLayoutAdapter", "(", "DialogLayoutAdapter", "adapter", ")", "-", ">", "DialogLayoutAdapter" ]
def Dialog_SetLayoutAdapter(*args, **kwargs): """Dialog_SetLayoutAdapter(DialogLayoutAdapter adapter) -> DialogLayoutAdapter""" return _windows_.Dialog_SetLayoutAdapter(*args, **kwargs)
[ "def", "Dialog_SetLayoutAdapter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "Dialog_SetLayoutAdapter", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L924-L926
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
FWCore/ParameterSet/python/SequenceTypes.py
python
_ModuleSequenceType.dumpPython
(self, options=PrintOptions())
return s + "\n"
Returns a string which is the python representation of the object
Returns a string which is the python representation of the object
[ "Returns", "a", "string", "which", "is", "the", "python", "representation", "of", "the", "object" ]
def dumpPython(self, options=PrintOptions()): """Returns a string which is the python representation of the object""" s = self.dumpPythonNoNewline(options) return s + "\n"
[ "def", "dumpPython", "(", "self", ",", "options", "=", "PrintOptions", "(", ")", ")", ":", "s", "=", "self", ".", "dumpPythonNoNewline", "(", "options", ")", "return", "s", "+", "\"\\n\"" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/ParameterSet/python/SequenceTypes.py#L322-L325
devpack/android-python27
d42dd67565e104cf7b0b50eb473f615db3e69901
python-build-with-qt/sip-4.11.2/sipconfig.py
python
Makefile.generate_target_default
(self, mfile)
The default implementation of the default target. mfile is the file object.
The default implementation of the default target.
[ "The", "default", "implementation", "of", "the", "default", "target", "." ]
def generate_target_default(self, mfile): """The default implementation of the default target. mfile is the file object. """ mfile.write("\nall:\n")
[ "def", "generate_target_default", "(", "self", ",", "mfile", ")", ":", "mfile", ".", "write", "(", "\"\\nall:\\n\"", ")" ]
https://github.com/devpack/android-python27/blob/d42dd67565e104cf7b0b50eb473f615db3e69901/python-build-with-qt/sip-4.11.2/sipconfig.py#L1254-L1259
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/third_party/ipaddr/ipaddr.py
python
_BaseNet.overlaps
(self, other)
return self.network in other or self.broadcast in other or ( other.network in self or other.broadcast in self)
Tell if self is partly contained in other.
Tell if self is partly contained in other.
[ "Tell", "if", "self", "is", "partly", "contained", "in", "other", "." ]
def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network in other or self.broadcast in other or ( other.network in self or other.broadcast in self)
[ "def", "overlaps", "(", "self", ",", "other", ")", ":", "return", "self", ".", "network", "in", "other", "or", "self", ".", "broadcast", "in", "other", "or", "(", "other", ".", "network", "in", "self", "or", "other", ".", "broadcast", "in", "self", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/ipaddr/ipaddr.py#L648-L651
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
FontMapper_GetDefaultConfigPath
(*args)
return _gdi_.FontMapper_GetDefaultConfigPath(*args)
FontMapper_GetDefaultConfigPath() -> String
FontMapper_GetDefaultConfigPath() -> String
[ "FontMapper_GetDefaultConfigPath", "()", "-", ">", "String" ]
def FontMapper_GetDefaultConfigPath(*args): """FontMapper_GetDefaultConfigPath() -> String""" return _gdi_.FontMapper_GetDefaultConfigPath(*args)
[ "def", "FontMapper_GetDefaultConfigPath", "(", "*", "args", ")", ":", "return", "_gdi_", ".", "FontMapper_GetDefaultConfigPath", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L2104-L2106
webmproject/libwebm
ee0bab576c338c9807249b99588e352b7268cb62
PRESUBMIT.py
python
_RunShellCheckCmd
(input_api, output_api, bash_file)
return output_api.PresubmitError("%s\n%s (%4.2fs) failed\n%s" % (name, " ".join(cmd), duration, output[1]))
shellcheck command wrapper.
shellcheck command wrapper.
[ "shellcheck", "command", "wrapper", "." ]
def _RunShellCheckCmd(input_api, output_api, bash_file): """shellcheck command wrapper.""" cmd = ["shellcheck", "-x", "-oall", "-sbash", bash_file] name = "Check %s file." % bash_file start = input_api.time.time() output, rc = subprocess2.communicate( cmd, stdout=None, stderr=subprocess2.PIPE, universal_newlines=True) duration = input_api.time.time() - start if rc == 0: return output_api.PresubmitResult("%s\n%s (%4.2fs)\n" % (name, " ".join(cmd), duration)) return output_api.PresubmitError("%s\n%s (%4.2fs) failed\n%s" % (name, " ".join(cmd), duration, output[1]))
[ "def", "_RunShellCheckCmd", "(", "input_api", ",", "output_api", ",", "bash_file", ")", ":", "cmd", "=", "[", "\"shellcheck\"", ",", "\"-x\"", ",", "\"-oall\"", ",", "\"-sbash\"", ",", "bash_file", "]", "name", "=", "\"Check %s file.\"", "%", "bash_file", "start", "=", "input_api", ".", "time", ".", "time", "(", ")", "output", ",", "rc", "=", "subprocess2", ".", "communicate", "(", "cmd", ",", "stdout", "=", "None", ",", "stderr", "=", "subprocess2", ".", "PIPE", ",", "universal_newlines", "=", "True", ")", "duration", "=", "input_api", ".", "time", ".", "time", "(", ")", "-", "start", "if", "rc", "==", "0", ":", "return", "output_api", ".", "PresubmitResult", "(", "\"%s\\n%s (%4.2fs)\\n\"", "%", "(", "name", ",", "\" \"", ".", "join", "(", "cmd", ")", ",", "duration", ")", ")", "return", "output_api", ".", "PresubmitError", "(", "\"%s\\n%s (%4.2fs) failed\\n%s\"", "%", "(", "name", ",", "\" \"", ".", "join", "(", "cmd", ")", ",", "duration", ",", "output", "[", "1", "]", ")", ")" ]
https://github.com/webmproject/libwebm/blob/ee0bab576c338c9807249b99588e352b7268cb62/PRESUBMIT.py#L89-L101
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/tools/webforms_aggregator.py
python
Crawler.__init__
(self, url, logging_level=None)
Init crawler URL, links lists, logger, and creates a cookie temp file. The cookie temp file is needed for session cookies. Args: url: the initial "seed" url of the site. logging_level: the desired verbosity level, default is None.
Init crawler URL, links lists, logger, and creates a cookie temp file.
[ "Init", "crawler", "URL", "links", "lists", "logger", "and", "creates", "a", "cookie", "temp", "file", "." ]
def __init__(self, url, logging_level=None): """Init crawler URL, links lists, logger, and creates a cookie temp file. The cookie temp file is needed for session cookies. Args: url: the initial "seed" url of the site. logging_level: the desired verbosity level, default is None. """ if logging_level: self.logger.setLevel(logging_level) self.url_error = False url_parsed = urlparse.urlparse(url) if not url_parsed[0].startswith('http'): self.logger.error( 'Error: "%s" does not begin with http:// or https://', url) self.url_error = True return # Example: if url is 'http://www.example.com?name=john' then value [1] or # network location is 'www.example.com'. if not url_parsed[1]: self.logger.error('Error: "%s" is not a valid url', url) self.url_error = True return self._url = url self._domain = '' # Http links that contain a clue from LINK_CLUES. self._clues_general_links = [] # Http links that do not contain any clue from LINK_CLUES. self._general_links = [] # Https links that contain a clue from LINK_CLUES. self._clues_secure_links = [] # Https links that do not contain any clue from LINK_CLUES. self._secure_links = [] # All links downloaded and parsed so far. self._links_visited = [] self._retrievers_list = [] self._cookie_file = tempfile.NamedTemporaryFile( suffix='.cookie', delete=False) self._cookie_file.close() self._cookie_file = self._cookie_file.name
[ "def", "__init__", "(", "self", ",", "url", ",", "logging_level", "=", "None", ")", ":", "if", "logging_level", ":", "self", ".", "logger", ".", "setLevel", "(", "logging_level", ")", "self", ".", "url_error", "=", "False", "url_parsed", "=", "urlparse", ".", "urlparse", "(", "url", ")", "if", "not", "url_parsed", "[", "0", "]", ".", "startswith", "(", "'http'", ")", ":", "self", ".", "logger", ".", "error", "(", "'Error: \"%s\" does not begin with http:// or https://'", ",", "url", ")", "self", ".", "url_error", "=", "True", "return", "# Example: if url is 'http://www.example.com?name=john' then value [1] or", "# network location is 'www.example.com'.", "if", "not", "url_parsed", "[", "1", "]", ":", "self", ".", "logger", ".", "error", "(", "'Error: \"%s\" is not a valid url'", ",", "url", ")", "self", ".", "url_error", "=", "True", "return", "self", ".", "_url", "=", "url", "self", ".", "_domain", "=", "''", "# Http links that contain a clue from LINK_CLUES.", "self", ".", "_clues_general_links", "=", "[", "]", "# Http links that do not contain any clue from LINK_CLUES.", "self", ".", "_general_links", "=", "[", "]", "# Https links that contain a clue from LINK_CLUES.", "self", ".", "_clues_secure_links", "=", "[", "]", "# Https links that do not contain any clue from LINK_CLUES.", "self", ".", "_secure_links", "=", "[", "]", "# All links downloaded and parsed so far.", "self", ".", "_links_visited", "=", "[", "]", "self", ".", "_retrievers_list", "=", "[", "]", "self", ".", "_cookie_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.cookie'", ",", "delete", "=", "False", ")", "self", ".", "_cookie_file", ".", "close", "(", ")", "self", ".", "_cookie_file", "=", "self", ".", "_cookie_file", ".", "name" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/tools/webforms_aggregator.py#L327-L368
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/common.py
python
is_string_dtype
(arr_or_dtype)
return _is_dtype(arr_or_dtype, condition)
Check whether the provided array or dtype is of the string dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the string dtype. Examples -------- >>> is_string_dtype(str) True >>> is_string_dtype(object) True >>> is_string_dtype(int) False >>> >>> is_string_dtype(np.array(['a', 'b'])) True >>> is_string_dtype(pd.Series([1, 2])) False
Check whether the provided array or dtype is of the string dtype.
[ "Check", "whether", "the", "provided", "array", "or", "dtype", "is", "of", "the", "string", "dtype", "." ]
def is_string_dtype(arr_or_dtype) -> bool: """ Check whether the provided array or dtype is of the string dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the string dtype. Examples -------- >>> is_string_dtype(str) True >>> is_string_dtype(object) True >>> is_string_dtype(int) False >>> >>> is_string_dtype(np.array(['a', 'b'])) True >>> is_string_dtype(pd.Series([1, 2])) False """ # TODO: gh-15585: consider making the checks stricter. def condition(dtype) -> bool: return dtype.kind in ("O", "S", "U") and not is_excluded_dtype(dtype) def is_excluded_dtype(dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks) return _is_dtype(arr_or_dtype, condition)
[ "def", "is_string_dtype", "(", "arr_or_dtype", ")", "->", "bool", ":", "# TODO: gh-15585: consider making the checks stricter.", "def", "condition", "(", "dtype", ")", "->", "bool", ":", "return", "dtype", ".", "kind", "in", "(", "\"O\"", ",", "\"S\"", ",", "\"U\"", ")", "and", "not", "is_excluded_dtype", "(", "dtype", ")", "def", "is_excluded_dtype", "(", "dtype", ")", "->", "bool", ":", "\"\"\"\n These have kind = \"O\" but aren't string dtypes so need to be explicitly excluded\n \"\"\"", "is_excluded_checks", "=", "(", "is_period_dtype", ",", "is_interval_dtype", ")", "return", "any", "(", "is_excluded", "(", "dtype", ")", "for", "is_excluded", "in", "is_excluded_checks", ")", "return", "_is_dtype", "(", "arr_or_dtype", ",", "condition", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/common.py#L575-L615
intel-iot-devkit/how-to-code-samples
b4ea616f36bbfa2e042beb1698f968cfd651d79f
smart-stove-top/python/iot_smart_stove_top/scheduler.py
python
ms
(mills)
return mills * 0.001
Converts milliseconds to seconds
Converts milliseconds to seconds
[ "Converts", "milliseconds", "to", "seconds" ]
def ms(mills): """ Converts milliseconds to seconds """ return mills * 0.001
[ "def", "ms", "(", "mills", ")", ":", "return", "mills", "*", "0.001" ]
https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/smart-stove-top/python/iot_smart_stove_top/scheduler.py#L32-L38
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/module/base_module.py
python
BaseModule.iter_predict
(self, eval_data, num_batch=None, reset=True, sparse_row_id_fn=None)
Iterates over predictions. Examples -------- >>> for pred, i_batch, batch in module.iter_predict(eval_data): ... # pred is a list of outputs from the module ... # i_batch is a integer ... # batch is the data batch from the data iterator Parameters ---------- eval_data : DataIter Evaluation data to run prediction on. num_batch : int Default is ``None``, indicating running all the batches in the data iterator. reset : bool Default is ``True``, indicating whether we should reset the data iter before start doing prediction. sparse_row_id_fn : A callback function The function takes `data_batch` as an input and returns a dict of str -> NDArray. The resulting dict is used for pulling row_sparse parameters from the kvstore, where the str key is the name of the param, and the value is the row id of the param to pull.
Iterates over predictions.
[ "Iterates", "over", "predictions", "." ]
def iter_predict(self, eval_data, num_batch=None, reset=True, sparse_row_id_fn=None): """Iterates over predictions. Examples -------- >>> for pred, i_batch, batch in module.iter_predict(eval_data): ... # pred is a list of outputs from the module ... # i_batch is a integer ... # batch is the data batch from the data iterator Parameters ---------- eval_data : DataIter Evaluation data to run prediction on. num_batch : int Default is ``None``, indicating running all the batches in the data iterator. reset : bool Default is ``True``, indicating whether we should reset the data iter before start doing prediction. sparse_row_id_fn : A callback function The function takes `data_batch` as an input and returns a dict of str -> NDArray. The resulting dict is used for pulling row_sparse parameters from the kvstore, where the str key is the name of the param, and the value is the row id of the param to pull. """ assert self.binded and self.params_initialized if reset: eval_data.reset() for nbatch, eval_batch in enumerate(eval_data): if num_batch is not None and nbatch == num_batch: break self.prepare(eval_batch, sparse_row_id_fn=sparse_row_id_fn) self.forward(eval_batch, is_train=False) pad = eval_batch.pad outputs = [out[0:out.shape[0]-pad] for out in self.get_outputs()] yield (outputs, nbatch, eval_batch)
[ "def", "iter_predict", "(", "self", ",", "eval_data", ",", "num_batch", "=", "None", ",", "reset", "=", "True", ",", "sparse_row_id_fn", "=", "None", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "if", "reset", ":", "eval_data", ".", "reset", "(", ")", "for", "nbatch", ",", "eval_batch", "in", "enumerate", "(", "eval_data", ")", ":", "if", "num_batch", "is", "not", "None", "and", "nbatch", "==", "num_batch", ":", "break", "self", ".", "prepare", "(", "eval_batch", ",", "sparse_row_id_fn", "=", "sparse_row_id_fn", ")", "self", ".", "forward", "(", "eval_batch", ",", "is_train", "=", "False", ")", "pad", "=", "eval_batch", ".", "pad", "outputs", "=", "[", "out", "[", "0", ":", "out", ".", "shape", "[", "0", "]", "-", "pad", "]", "for", "out", "in", "self", ".", "get_outputs", "(", ")", "]", "yield", "(", "outputs", ",", "nbatch", ",", "eval_batch", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/module/base_module.py#L278-L316
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/inspector_protocol/markupsafe/_native.py
python
escape
(s)
return Markup(text_type(s) .replace('&', '&amp;') .replace('>', '&gt;') .replace('<', '&lt;') .replace("'", '&#39;') .replace('"', '&#34;') )
Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
[ "Convert", "the", "characters", "&", "<", ">", "and", "in", "string", "s", "to", "HTML", "-", "safe", "sequences", ".", "Use", "this", "if", "you", "need", "to", "display", "text", "that", "might", "contain", "such", "characters", "in", "HTML", ".", "Marks", "return", "value", "as", "markup", "string", "." ]
def escape(s): """Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string. """ if hasattr(s, '__html__'): return s.__html__() return Markup(text_type(s) .replace('&', '&amp;') .replace('>', '&gt;') .replace('<', '&lt;') .replace("'", '&#39;') .replace('"', '&#34;') )
[ "def", "escape", "(", "s", ")", ":", "if", "hasattr", "(", "s", ",", "'__html__'", ")", ":", "return", "s", ".", "__html__", "(", ")", "return", "Markup", "(", "text_type", "(", "s", ")", ".", "replace", "(", "'&'", ",", "'&amp;'", ")", ".", "replace", "(", "'>'", ",", "'&gt;'", ")", ".", "replace", "(", "'<'", ",", "'&lt;'", ")", ".", "replace", "(", "\"'\"", ",", "'&#39;'", ")", ".", "replace", "(", "'\"'", ",", "'&#34;'", ")", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/markupsafe/_native.py#L15-L28
supercollider/supercollider
42715a73ce2de4720174583e9b66a4510fe289a3
external_libraries/simplejson-2.3.2/encoder.py
python
JSONEncoder.iterencode
(self, o, _one_shot=False)
Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk)
Encode the given object and yield each string representation as available.
[ "Encode", "the", "given", "object", "and", "yield", "each", "string", "representation", "as", "available", "." ]
def iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=PosInf, _neginf=-PosInf): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on # the internals. if o != o: text = 'NaN' elif o == _inf: text = 'Infinity' elif o == _neginf: text = '-Infinity' else: return _repr(o) if not allow_nan: raise ValueError( "Out of range float values are not JSON compliant: " + repr(o)) return text key_memo = {} if (_one_shot and c_make_encoder is not None and self.indent is None): _iterencode = c_make_encoder( markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan, key_memo, self.use_decimal, self.namedtuple_as_object, self.tuple_as_array) else: _iterencode = _make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot, self.use_decimal, self.namedtuple_as_object, self.tuple_as_array) try: return _iterencode(o, 0) finally: key_memo.clear()
[ "def", "iterencode", "(", "self", ",", "o", ",", "_one_shot", "=", "False", ")", ":", "if", "self", ".", "check_circular", ":", "markers", "=", "{", "}", "else", ":", "markers", "=", "None", "if", "self", ".", "ensure_ascii", ":", "_encoder", "=", "encode_basestring_ascii", "else", ":", "_encoder", "=", "encode_basestring", "if", "self", ".", "encoding", "!=", "'utf-8'", ":", "def", "_encoder", "(", "o", ",", "_orig_encoder", "=", "_encoder", ",", "_encoding", "=", "self", ".", "encoding", ")", ":", "if", "isinstance", "(", "o", ",", "str", ")", ":", "o", "=", "o", ".", "decode", "(", "_encoding", ")", "return", "_orig_encoder", "(", "o", ")", "def", "floatstr", "(", "o", ",", "allow_nan", "=", "self", ".", "allow_nan", ",", "_repr", "=", "FLOAT_REPR", ",", "_inf", "=", "PosInf", ",", "_neginf", "=", "-", "PosInf", ")", ":", "# Check for specials. Note that this type of test is processor", "# and/or platform-specific, so do tests which don't depend on", "# the internals.", "if", "o", "!=", "o", ":", "text", "=", "'NaN'", "elif", "o", "==", "_inf", ":", "text", "=", "'Infinity'", "elif", "o", "==", "_neginf", ":", "text", "=", "'-Infinity'", "else", ":", "return", "_repr", "(", "o", ")", "if", "not", "allow_nan", ":", "raise", "ValueError", "(", "\"Out of range float values are not JSON compliant: \"", "+", "repr", "(", "o", ")", ")", "return", "text", "key_memo", "=", "{", "}", "if", "(", "_one_shot", "and", "c_make_encoder", "is", "not", "None", "and", "self", ".", "indent", "is", "None", ")", ":", "_iterencode", "=", "c_make_encoder", "(", "markers", ",", "self", ".", "default", ",", "_encoder", ",", "self", ".", "indent", ",", "self", ".", "key_separator", ",", "self", ".", "item_separator", ",", "self", ".", "sort_keys", ",", "self", ".", "skipkeys", ",", "self", ".", "allow_nan", ",", "key_memo", ",", "self", ".", "use_decimal", ",", "self", ".", "namedtuple_as_object", ",", "self", ".", "tuple_as_array", ")", "else", ":", "_iterencode", "=", "_make_iterencode", "(", "markers", ",", "self", ".", "default", ",", "_encoder", ",", "self", ".", "indent", ",", "floatstr", ",", "self", ".", "key_separator", ",", "self", ".", "item_separator", ",", "self", ".", "sort_keys", ",", "self", ".", "skipkeys", ",", "_one_shot", ",", "self", ".", "use_decimal", ",", "self", ".", "namedtuple_as_object", ",", "self", ".", "tuple_as_array", ")", "try", ":", "return", "_iterencode", "(", "o", ",", "0", ")", "finally", ":", "key_memo", ".", "clear", "(", ")" ]
https://github.com/supercollider/supercollider/blob/42715a73ce2de4720174583e9b66a4510fe289a3/external_libraries/simplejson-2.3.2/encoder.py#L234-L298
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cmd.py
python
Cmd.parseline
(self, line)
return cmd, arg, line
Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed.
Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed.
[ "Parse", "the", "line", "into", "a", "command", "name", "and", "a", "string", "containing", "the", "arguments", ".", "Returns", "a", "tuple", "containing", "(", "command", "args", "line", ")", ".", "command", "and", "args", "may", "be", "None", "if", "the", "line", "couldn", "t", "be", "parsed", "." ]
def parseline(self, line): """Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed. """ line = line.strip() if not line: return None, None, line elif line[0] == '?': line = 'help ' + line[1:] elif line[0] == '!': if hasattr(self, 'do_shell'): line = 'shell ' + line[1:] else: return None, None, line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], line[i:].strip() return cmd, arg, line
[ "def", "parseline", "(", "self", ",", "line", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ":", "return", "None", ",", "None", ",", "line", "elif", "line", "[", "0", "]", "==", "'?'", ":", "line", "=", "'help '", "+", "line", "[", "1", ":", "]", "elif", "line", "[", "0", "]", "==", "'!'", ":", "if", "hasattr", "(", "self", ",", "'do_shell'", ")", ":", "line", "=", "'shell '", "+", "line", "[", "1", ":", "]", "else", ":", "return", "None", ",", "None", ",", "line", "i", ",", "n", "=", "0", ",", "len", "(", "line", ")", "while", "i", "<", "n", "and", "line", "[", "i", "]", "in", "self", ".", "identchars", ":", "i", "=", "i", "+", "1", "cmd", ",", "arg", "=", "line", "[", ":", "i", "]", ",", "line", "[", "i", ":", "]", ".", "strip", "(", ")", "return", "cmd", ",", "arg", ",", "line" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cmd.py#L176-L194
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/vision/py_transforms.py
python
RandomSharpness.__call__
(self, img)
return util.random_sharpness(img, self.degrees)
Call method. Args: img (PIL Image): Image to be sharpness adjusted. Returns: PIL Image, sharpness adjusted image.
Call method.
[ "Call", "method", "." ]
def __call__(self, img): """ Call method. Args: img (PIL Image): Image to be sharpness adjusted. Returns: PIL Image, sharpness adjusted image. """ return util.random_sharpness(img, self.degrees)
[ "def", "__call__", "(", "self", ",", "img", ")", ":", "return", "util", ".", "random_sharpness", "(", "img", ",", "self", ".", "degrees", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/vision/py_transforms.py#L1780-L1791
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/nn_grad.py
python
_TopKGrad
(op, grad, _)
return [array_ops.reshape( sparse_ops.sparse_to_dense(ind, array_ops.reshape( math_ops.reduce_prod(in_shape), [1]), array_ops.reshape(grad, [-1]), validate_indices=False), in_shape), array_ops.zeros( [], dtype=dtypes.int32)]
Return the gradients for TopK. Args: op: The TopKOp for which we need to generate gradients. grad: Tensor. The gradients passed to the TopKOp. Returns: A list of two tensors, the first being the gradient w.r.t to the input and TopK, and the second being the gradient w.r.t. to the indices (all zero).
Return the gradients for TopK.
[ "Return", "the", "gradients", "for", "TopK", "." ]
def _TopKGrad(op, grad, _): """Return the gradients for TopK. Args: op: The TopKOp for which we need to generate gradients. grad: Tensor. The gradients passed to the TopKOp. Returns: A list of two tensors, the first being the gradient w.r.t to the input and TopK, and the second being the gradient w.r.t. to the indices (all zero). """ in_shape = array_ops.shape(op.inputs[0]) ind_shape = array_ops.shape(op.outputs[1]) ind_lastdim = array_ops.gather(ind_shape, array_ops.size(ind_shape) - 1) # Flatten indices to 2D. ind_2d = array_ops.reshape(op.outputs[1], array_ops.pack([-1, ind_lastdim])) in_lastdim = array_ops.gather(in_shape, array_ops.size(in_shape) - 1) outerdim = array_ops.shape(ind_2d)[0] # Compute linear indices (flattened to 1D). ind = array_ops.reshape(ind_2d + array_ops.expand_dims( math_ops.range(0, outerdim * in_lastdim, in_lastdim), -1), [-1]) # Substitute grad to appropriate locations and fill the rest with zeros, # finally reshaping it to the original input shape. return [array_ops.reshape( sparse_ops.sparse_to_dense(ind, array_ops.reshape( math_ops.reduce_prod(in_shape), [1]), array_ops.reshape(grad, [-1]), validate_indices=False), in_shape), array_ops.zeros( [], dtype=dtypes.int32)]
[ "def", "_TopKGrad", "(", "op", ",", "grad", ",", "_", ")", ":", "in_shape", "=", "array_ops", ".", "shape", "(", "op", ".", "inputs", "[", "0", "]", ")", "ind_shape", "=", "array_ops", ".", "shape", "(", "op", ".", "outputs", "[", "1", "]", ")", "ind_lastdim", "=", "array_ops", ".", "gather", "(", "ind_shape", ",", "array_ops", ".", "size", "(", "ind_shape", ")", "-", "1", ")", "# Flatten indices to 2D.", "ind_2d", "=", "array_ops", ".", "reshape", "(", "op", ".", "outputs", "[", "1", "]", ",", "array_ops", ".", "pack", "(", "[", "-", "1", ",", "ind_lastdim", "]", ")", ")", "in_lastdim", "=", "array_ops", ".", "gather", "(", "in_shape", ",", "array_ops", ".", "size", "(", "in_shape", ")", "-", "1", ")", "outerdim", "=", "array_ops", ".", "shape", "(", "ind_2d", ")", "[", "0", "]", "# Compute linear indices (flattened to 1D).", "ind", "=", "array_ops", ".", "reshape", "(", "ind_2d", "+", "array_ops", ".", "expand_dims", "(", "math_ops", ".", "range", "(", "0", ",", "outerdim", "*", "in_lastdim", ",", "in_lastdim", ")", ",", "-", "1", ")", ",", "[", "-", "1", "]", ")", "# Substitute grad to appropriate locations and fill the rest with zeros,", "# finally reshaping it to the original input shape.", "return", "[", "array_ops", ".", "reshape", "(", "sparse_ops", ".", "sparse_to_dense", "(", "ind", ",", "array_ops", ".", "reshape", "(", "math_ops", ".", "reduce_prod", "(", "in_shape", ")", ",", "[", "1", "]", ")", ",", "array_ops", ".", "reshape", "(", "grad", ",", "[", "-", "1", "]", ")", ",", "validate_indices", "=", "False", ")", ",", "in_shape", ")", ",", "array_ops", ".", "zeros", "(", "[", "]", ",", "dtype", "=", "dtypes", ".", "int32", ")", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/nn_grad.py#L407-L440
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/apiclient/googleapiclient/schema.py
python
_SchemaToStruct.emitEnd
(self, text, comment)
Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python comment.
Add text and comment to the output with line terminator.
[ "Add", "text", "and", "comment", "to", "the", "output", "with", "line", "terminator", "." ]
def emitEnd(self, text, comment): """Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python comment. """ if comment: divider = '\n' + ' ' * (self.dent + 2) + '# ' lines = comment.splitlines() lines = [x.rstrip() for x in lines] comment = divider.join(lines) self.value.extend([text, ' # ', comment, '\n']) else: self.value.extend([text, '\n'])
[ "def", "emitEnd", "(", "self", ",", "text", ",", "comment", ")", ":", "if", "comment", ":", "divider", "=", "'\\n'", "+", "' '", "*", "(", "self", ".", "dent", "+", "2", ")", "+", "'# '", "lines", "=", "comment", ".", "splitlines", "(", ")", "lines", "=", "[", "x", ".", "rstrip", "(", ")", "for", "x", "in", "lines", "]", "comment", "=", "divider", ".", "join", "(", "lines", ")", "self", ".", "value", ".", "extend", "(", "[", "text", ",", "' # '", ",", "comment", ",", "'\\n'", "]", ")", "else", ":", "self", ".", "value", ".", "extend", "(", "[", "text", ",", "'\\n'", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/apiclient/googleapiclient/schema.py#L216-L230
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Utils.py
python
h_list
(lst)
return md5(repr(lst).encode()).digest()
Hashes lists of ordered data. Using hash(tup) for tuples would be much more efficient, but Python now enforces hash randomization :param lst: list to hash :type lst: list of strings :return: hash of the list
Hashes lists of ordered data.
[ "Hashes", "lists", "of", "ordered", "data", "." ]
def h_list(lst): """ Hashes lists of ordered data. Using hash(tup) for tuples would be much more efficient, but Python now enforces hash randomization :param lst: list to hash :type lst: list of strings :return: hash of the list """ return md5(repr(lst).encode()).digest()
[ "def", "h_list", "(", "lst", ")", ":", "return", "md5", "(", "repr", "(", "lst", ")", ".", "encode", "(", ")", ")", ".", "digest", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Utils.py#L494-L505
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/egt/alpharank_visualizer.py
python
NetworkPlot.__init__
(self, payoff_tables, rhos, rho_m, pi, state_labels, num_top_profiles=None)
Initializes a network plotting object. Args: payoff_tables: List of game payoff tables, one for each agent identity. Each payoff_table may be either a 2D numpy array, or a _PayoffTableInterface object. rhos: Fixation probabilities. rho_m: Neutral fixation probability. pi: Stationary distribution of fixation Markov chain defined by rhos. state_labels: Labels corresponding to Markov states. For the single-population case, state_labels should be a list of pure strategy names. For the multi-population case, it should be a dict with (key,value) pairs: (population index,list of strategy names) num_top_profiles: Set to (int) to show only the graph nodes corresponding to the top k elements of stationary distribution, or None to show all.
Initializes a network plotting object.
[ "Initializes", "a", "network", "plotting", "object", "." ]
def __init__(self, payoff_tables, rhos, rho_m, pi, state_labels, num_top_profiles=None): """Initializes a network plotting object. Args: payoff_tables: List of game payoff tables, one for each agent identity. Each payoff_table may be either a 2D numpy array, or a _PayoffTableInterface object. rhos: Fixation probabilities. rho_m: Neutral fixation probability. pi: Stationary distribution of fixation Markov chain defined by rhos. state_labels: Labels corresponding to Markov states. For the single-population case, state_labels should be a list of pure strategy names. For the multi-population case, it should be a dict with (key,value) pairs: (population index,list of strategy names) num_top_profiles: Set to (int) to show only the graph nodes corresponding to the top k elements of stationary distribution, or None to show all. """ self.fig = plt.figure(figsize=(10, 10)) self.num_populations = len(payoff_tables) payoffs_are_hpt_format = utils.check_payoffs_are_hpt(payoff_tables) self.num_strats_per_population = ( utils.get_num_strats_per_population(payoff_tables, payoffs_are_hpt_format)) self.rhos = rhos self.rho_m = rho_m self.pi = pi self.num_profiles = len(pi) self.state_labels = state_labels self.first_run = True self.num_top_profiles = num_top_profiles if self.num_top_profiles: # More than total number of strats requested for plotting if self.num_top_profiles > self.num_profiles: self.num_top_profiles = self.num_profiles # Skip the bottom num_profiles-k stationary strategies. self.nodes_to_skip = list(self.pi.argsort()[:self.num_profiles - self.num_top_profiles]) else: self.nodes_to_skip = [] self._reset_cycle_counter()
[ "def", "__init__", "(", "self", ",", "payoff_tables", ",", "rhos", ",", "rho_m", ",", "pi", ",", "state_labels", ",", "num_top_profiles", "=", "None", ")", ":", "self", ".", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "10", ",", "10", ")", ")", "self", ".", "num_populations", "=", "len", "(", "payoff_tables", ")", "payoffs_are_hpt_format", "=", "utils", ".", "check_payoffs_are_hpt", "(", "payoff_tables", ")", "self", ".", "num_strats_per_population", "=", "(", "utils", ".", "get_num_strats_per_population", "(", "payoff_tables", ",", "payoffs_are_hpt_format", ")", ")", "self", ".", "rhos", "=", "rhos", "self", ".", "rho_m", "=", "rho_m", "self", ".", "pi", "=", "pi", "self", ".", "num_profiles", "=", "len", "(", "pi", ")", "self", ".", "state_labels", "=", "state_labels", "self", ".", "first_run", "=", "True", "self", ".", "num_top_profiles", "=", "num_top_profiles", "if", "self", ".", "num_top_profiles", ":", "# More than total number of strats requested for plotting", "if", "self", ".", "num_top_profiles", ">", "self", ".", "num_profiles", ":", "self", ".", "num_top_profiles", "=", "self", ".", "num_profiles", "# Skip the bottom num_profiles-k stationary strategies.", "self", ".", "nodes_to_skip", "=", "list", "(", "self", ".", "pi", ".", "argsort", "(", ")", "[", ":", "self", ".", "num_profiles", "-", "self", ".", "num_top_profiles", "]", ")", "else", ":", "self", ".", "nodes_to_skip", "=", "[", "]", "self", ".", "_reset_cycle_counter", "(", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/egt/alpharank_visualizer.py#L49-L97
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
FontData.SetChosenFont
(*args, **kwargs)
return _windows_.FontData_SetChosenFont(*args, **kwargs)
SetChosenFont(self, Font font) Sets the font that will be returned to the user (normally for internal use only).
SetChosenFont(self, Font font)
[ "SetChosenFont", "(", "self", "Font", "font", ")" ]
def SetChosenFont(*args, **kwargs): """ SetChosenFont(self, Font font) Sets the font that will be returned to the user (normally for internal use only). """ return _windows_.FontData_SetChosenFont(*args, **kwargs)
[ "def", "SetChosenFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "FontData_SetChosenFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L3528-L3535
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/_collections.py
python
HTTPHeaderDict.from_httplib
(cls, message)
return cls(headers)
Read headers from a Python 2 httplib message object.
Read headers from a Python 2 httplib message object.
[ "Read", "headers", "from", "a", "Python", "2", "httplib", "message", "object", "." ]
def from_httplib(cls, message): # Python 2 """Read headers from a Python 2 httplib message object.""" # python2.7 does not expose a proper API for exporting multiheaders # efficiently. This function re-reads raw lines from the message # object and extracts the multiheaders properly. headers = [] for line in message.headers: if line.startswith((' ', '\t')): key, value = headers[-1] headers[-1] = (key, value + '\r\n' + line.rstrip()) continue key, value = line.split(':', 1) headers.append((key, value.strip())) return cls(headers)
[ "def", "from_httplib", "(", "cls", ",", "message", ")", ":", "# Python 2", "# python2.7 does not expose a proper API for exporting multiheaders", "# efficiently. This function re-reads raw lines from the message ", "# object and extracts the multiheaders properly.", "headers", "=", "[", "]", "for", "line", "in", "message", ".", "headers", ":", "if", "line", ".", "startswith", "(", "(", "' '", ",", "'\\t'", ")", ")", ":", "key", ",", "value", "=", "headers", "[", "-", "1", "]", "headers", "[", "-", "1", "]", "=", "(", "key", ",", "value", "+", "'\\r\\n'", "+", "line", ".", "rstrip", "(", ")", ")", "continue", "key", ",", "value", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "headers", ".", "append", "(", "(", "key", ",", "value", ".", "strip", "(", ")", ")", ")", "return", "cls", "(", "headers", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/_collections.py#L307-L323
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/summary/event_file_inspector.py
python
get_field_to_observations_map
(generator, query_for_tag='')
return field_to_obs
Return a field to `Observations` dict for the event generator. Args: generator: A generator over event protos. query_for_tag: A string that if specified, only create observations for events with this tag name. Returns: A dict mapping keys in `TRACKED_FIELDS` to an `Observation` list.
Return a field to `Observations` dict for the event generator.
[ "Return", "a", "field", "to", "Observations", "dict", "for", "the", "event", "generator", "." ]
def get_field_to_observations_map(generator, query_for_tag=''): """Return a field to `Observations` dict for the event generator. Args: generator: A generator over event protos. query_for_tag: A string that if specified, only create observations for events with this tag name. Returns: A dict mapping keys in `TRACKED_FIELDS` to an `Observation` list. """ def increment(stat, event, tag=''): assert stat in TRACKED_FIELDS field_to_obs[stat].append(Observation(step=event.step, wall_time=event.wall_time, tag=tag)._asdict()) field_to_obs = dict([(t, []) for t in TRACKED_FIELDS]) for event in generator: ## Process the event if event.HasField('graph_def') and (not query_for_tag): increment('graph', event) if event.HasField('session_log') and (not query_for_tag): status = event.session_log.status if status == SessionLog.START: increment('sessionlog:start', event) elif status == SessionLog.STOP: increment('sessionlog:stop', event) elif status == SessionLog.CHECKPOINT: increment('sessionlog:checkpoint', event) elif event.HasField('summary'): for value in event.summary.value: if query_for_tag and value.tag != query_for_tag: continue for proto_name, display_name in SUMMARY_TYPE_TO_FIELD.items(): if value.HasField(proto_name): increment(display_name, event, value.tag) return field_to_obs
[ "def", "get_field_to_observations_map", "(", "generator", ",", "query_for_tag", "=", "''", ")", ":", "def", "increment", "(", "stat", ",", "event", ",", "tag", "=", "''", ")", ":", "assert", "stat", "in", "TRACKED_FIELDS", "field_to_obs", "[", "stat", "]", ".", "append", "(", "Observation", "(", "step", "=", "event", ".", "step", ",", "wall_time", "=", "event", ".", "wall_time", ",", "tag", "=", "tag", ")", ".", "_asdict", "(", ")", ")", "field_to_obs", "=", "dict", "(", "[", "(", "t", ",", "[", "]", ")", "for", "t", "in", "TRACKED_FIELDS", "]", ")", "for", "event", "in", "generator", ":", "## Process the event", "if", "event", ".", "HasField", "(", "'graph_def'", ")", "and", "(", "not", "query_for_tag", ")", ":", "increment", "(", "'graph'", ",", "event", ")", "if", "event", ".", "HasField", "(", "'session_log'", ")", "and", "(", "not", "query_for_tag", ")", ":", "status", "=", "event", ".", "session_log", ".", "status", "if", "status", "==", "SessionLog", ".", "START", ":", "increment", "(", "'sessionlog:start'", ",", "event", ")", "elif", "status", "==", "SessionLog", ".", "STOP", ":", "increment", "(", "'sessionlog:stop'", ",", "event", ")", "elif", "status", "==", "SessionLog", ".", "CHECKPOINT", ":", "increment", "(", "'sessionlog:checkpoint'", ",", "event", ")", "elif", "event", ".", "HasField", "(", "'summary'", ")", ":", "for", "value", "in", "event", ".", "summary", ".", "value", ":", "if", "query_for_tag", "and", "value", ".", "tag", "!=", "query_for_tag", ":", "continue", "for", "proto_name", ",", "display_name", "in", "SUMMARY_TYPE_TO_FIELD", ".", "items", "(", ")", ":", "if", "value", ".", "HasField", "(", "proto_name", ")", ":", "increment", "(", "display_name", ",", "event", ",", "value", ".", "tag", ")", "return", "field_to_obs" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/summary/event_file_inspector.py#L172-L212
apitrace/apitrace
764c9786b2312b656ce0918dff73001c6a85f46f
specs/debug.py
python
excepthook
(type, value, tb)
Automatically start the debugger on an exception. See also: - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287
Automatically start the debugger on an exception.
[ "Automatically", "start", "the", "debugger", "on", "an", "exception", "." ]
def excepthook(type, value, tb): """ Automatically start the debugger on an exception. See also: - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287 """ if hasattr(sys, 'ps1') \ or not (sys.stdin.isatty() and sys.stdout.isatty() and sys.stderr.isatty()) \ or type == SyntaxError or type == KeyboardInterrupt: # we are in interactive mode or we don't have a tty-like # device, so we call the default hook oldexcepthook(type, value, tb) else: import traceback, pdb # we are NOT in interactive mode, print the exception... traceback.print_exception(type, value, tb) print() # ...then start the debugger in post-mortem mode. pdb.pm()
[ "def", "excepthook", "(", "type", ",", "value", ",", "tb", ")", ":", "if", "hasattr", "(", "sys", ",", "'ps1'", ")", "or", "not", "(", "sys", ".", "stdin", ".", "isatty", "(", ")", "and", "sys", ".", "stdout", ".", "isatty", "(", ")", "and", "sys", ".", "stderr", ".", "isatty", "(", ")", ")", "or", "type", "==", "SyntaxError", "or", "type", "==", "KeyboardInterrupt", ":", "# we are in interactive mode or we don't have a tty-like", "# device, so we call the default hook", "oldexcepthook", "(", "type", ",", "value", ",", "tb", ")", "else", ":", "import", "traceback", ",", "pdb", "# we are NOT in interactive mode, print the exception...", "traceback", ".", "print_exception", "(", "type", ",", "value", ",", "tb", ")", "print", "(", ")", "# ...then start the debugger in post-mortem mode.", "pdb", ".", "pm", "(", ")" ]
https://github.com/apitrace/apitrace/blob/764c9786b2312b656ce0918dff73001c6a85f46f/specs/debug.py#L34-L54
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/tensor/linalg.py
python
lu_unpack
(x, y, unpack_ludata=True, unpack_pivots=True, name=None)
return p, l, u
r""" Unpack L U and P to single matrix tensor . unpack L and U matrix from LU, unpack permutation matrix P from Pivtos . P mat can be get by pivots: # ones = eye(rows) #eye matrix of rank rows # for i in range(cols): # swap(ones[i], ones[pivots[i]]) Args: x (Tensor): The LU tensor get from paddle.linalg.lu, which is combined by L and U. y (Tensor): Pivots get from paddle.linalg.lu. unpack_ludata (bool,optional): whether to unpack L and U from x. Default: True. unpack_pivots (bool, optional): whether to unpack permutation matrix P from Pivtos. Default: True. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: P (Tensor): Permutation matrix P of lu factorization. L (Tensor): The lower triangular matrix tensor of lu factorization. U (Tensor): The upper triangular matrix tensor of lu factorization. Examples: .. code-block:: python import paddle x = paddle.to_tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]).astype('float64') lu,p,info = paddle.linalg.lu(x, get_infos=True) # >>> lu: # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, # [[5. , 6. ], # [0.20000000, 0.80000000], # [0.60000000, 0.50000000]]) # >>> p # Tensor(shape=[2], dtype=int32, place=CUDAPlace(0), stop_gradient=True, # [3, 3]) # >>> info # Tensor(shape=[], dtype=int32, place=CUDAPlace(0), stop_gradient=True, # 0) P,L,U = paddle.linalg.lu_unpack(lu,p) # >>> P # (Tensor(shape=[3, 3], dtype=float64, place=CUDAPlace(0), stop_gradient=True, # [[0., 1., 0.], # [0., 0., 1.], # [1., 0., 0.]]), # >>> L # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, # [[1. , 0. ], # [0.20000000, 1. ], # [0.60000000, 0.50000000]]), # >>> U # Tensor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, # [[5. , 6. ], # [0. , 0.80000000]])) # one can verify : X = P @ L @ U ;
r""" Unpack L U and P to single matrix tensor . unpack L and U matrix from LU, unpack permutation matrix P from Pivtos .
[ "r", "Unpack", "L", "U", "and", "P", "to", "single", "matrix", "tensor", ".", "unpack", "L", "and", "U", "matrix", "from", "LU", "unpack", "permutation", "matrix", "P", "from", "Pivtos", "." ]
def lu_unpack(x, y, unpack_ludata=True, unpack_pivots=True, name=None): r""" Unpack L U and P to single matrix tensor . unpack L and U matrix from LU, unpack permutation matrix P from Pivtos . P mat can be get by pivots: # ones = eye(rows) #eye matrix of rank rows # for i in range(cols): # swap(ones[i], ones[pivots[i]]) Args: x (Tensor): The LU tensor get from paddle.linalg.lu, which is combined by L and U. y (Tensor): Pivots get from paddle.linalg.lu. unpack_ludata (bool,optional): whether to unpack L and U from x. Default: True. unpack_pivots (bool, optional): whether to unpack permutation matrix P from Pivtos. Default: True. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: P (Tensor): Permutation matrix P of lu factorization. L (Tensor): The lower triangular matrix tensor of lu factorization. U (Tensor): The upper triangular matrix tensor of lu factorization. Examples: .. code-block:: python import paddle x = paddle.to_tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]).astype('float64') lu,p,info = paddle.linalg.lu(x, get_infos=True) # >>> lu: # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, # [[5. , 6. ], # [0.20000000, 0.80000000], # [0.60000000, 0.50000000]]) # >>> p # Tensor(shape=[2], dtype=int32, place=CUDAPlace(0), stop_gradient=True, # [3, 3]) # >>> info # Tensor(shape=[], dtype=int32, place=CUDAPlace(0), stop_gradient=True, # 0) P,L,U = paddle.linalg.lu_unpack(lu,p) # >>> P # (Tensor(shape=[3, 3], dtype=float64, place=CUDAPlace(0), stop_gradient=True, # [[0., 1., 0.], # [0., 0., 1.], # [1., 0., 0.]]), # >>> L # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, # [[1. , 0. ], # [0.20000000, 1. ], # [0.60000000, 0.50000000]]), # >>> U # Tensor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True, # [[5. , 6. ], # [0. , 0.80000000]])) # one can verify : X = P @ L @ U ; """ if in_dygraph_mode(): P, L, U = _C_ops.lu_unpack(x, y, 'unpack_ludata', unpack_ludata, 'unpack_pivots', unpack_pivots) return P, L, U check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'lu_unpack') helper = LayerHelper('lu_unpack', **locals()) p = helper.create_variable_for_type_inference(dtype=x.dtype) l = helper.create_variable_for_type_inference(dtype=x.dtype) u = helper.create_variable_for_type_inference(dtype=x.dtype) attrs = dict() attrs['unpack_ludata'] = unpack_ludata attrs['unpack_pivots'] = unpack_pivots helper.append_op( type='lu_unpack', inputs={'X': x, 'Pivots': y}, outputs={'Pmat': p, 'L': l, 'U': u}, attrs=attrs) return p, l, u
[ "def", "lu_unpack", "(", "x", ",", "y", ",", "unpack_ludata", "=", "True", ",", "unpack_pivots", "=", "True", ",", "name", "=", "None", ")", ":", "if", "in_dygraph_mode", "(", ")", ":", "P", ",", "L", ",", "U", "=", "_C_ops", ".", "lu_unpack", "(", "x", ",", "y", ",", "'unpack_ludata'", ",", "unpack_ludata", ",", "'unpack_pivots'", ",", "unpack_pivots", ")", "return", "P", ",", "L", ",", "U", "check_variable_and_dtype", "(", "x", ",", "'dtype'", ",", "[", "'float32'", ",", "'float64'", "]", ",", "'lu_unpack'", ")", "helper", "=", "LayerHelper", "(", "'lu_unpack'", ",", "*", "*", "locals", "(", ")", ")", "p", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "x", ".", "dtype", ")", "l", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "x", ".", "dtype", ")", "u", "=", "helper", ".", "create_variable_for_type_inference", "(", "dtype", "=", "x", ".", "dtype", ")", "attrs", "=", "dict", "(", ")", "attrs", "[", "'unpack_ludata'", "]", "=", "unpack_ludata", "attrs", "[", "'unpack_pivots'", "]", "=", "unpack_pivots", "helper", ".", "append_op", "(", "type", "=", "'lu_unpack'", ",", "inputs", "=", "{", "'X'", ":", "x", ",", "'Pivots'", ":", "y", "}", ",", "outputs", "=", "{", "'Pmat'", ":", "p", ",", "'L'", ":", "l", ",", "'U'", ":", "u", "}", ",", "attrs", "=", "attrs", ")", "return", "p", ",", "l", ",", "u" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/linalg.py#L1929-L2022
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Appearance.setTexture1D_channels
(self, format: str, np_array2: "ndarray")
return _robotsim.Appearance_setTexture1D_channels(self, format, np_array2)
r""" Sets a 1D texture of the given width, given a 2D array of channels. Valid format strings are. Args: format (str) np_array2 (:obj:`unsigned char *`) * "": turn off texture mapping * rgb8: unsigned byte RGB colors with red in the 1st column, green in the 2nd, blue in the 3rd * bgr8: unsigned byte RGB colors with blue in the 1st column, green in the 2nd, green in the 3rd * rgba8: unsigned byte RGBA colors with red in the 1st column and alpha in the 4th * bgra8: unsigned byte RGBA colors with blue in the 1st column and alpha in the 4th * l8: unsigned byte grayscale colors, one channel
r""" Sets a 1D texture of the given width, given a 2D array of channels. Valid format strings are.
[ "r", "Sets", "a", "1D", "texture", "of", "the", "given", "width", "given", "a", "2D", "array", "of", "channels", ".", "Valid", "format", "strings", "are", "." ]
def setTexture1D_channels(self, format: str, np_array2: "ndarray") ->None: r""" Sets a 1D texture of the given width, given a 2D array of channels. Valid format strings are. Args: format (str) np_array2 (:obj:`unsigned char *`) * "": turn off texture mapping * rgb8: unsigned byte RGB colors with red in the 1st column, green in the 2nd, blue in the 3rd * bgr8: unsigned byte RGB colors with blue in the 1st column, green in the 2nd, green in the 3rd * rgba8: unsigned byte RGBA colors with red in the 1st column and alpha in the 4th * bgra8: unsigned byte RGBA colors with blue in the 1st column and alpha in the 4th * l8: unsigned byte grayscale colors, one channel """ return _robotsim.Appearance_setTexture1D_channels(self, format, np_array2)
[ "def", "setTexture1D_channels", "(", "self", ",", "format", ":", "str", ",", "np_array2", ":", "\"ndarray\"", ")", "->", "None", ":", "return", "_robotsim", ".", "Appearance_setTexture1D_channels", "(", "self", ",", "format", ",", "np_array2", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L2952-L2973
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/SimpleXMLRPCServer.py
python
CGIXMLRPCRequestHandler.handle_request
(self, request_text = None)
Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers.
Handle a single XML-RPC request passed through a CGI post method.
[ "Handle", "a", "single", "XML", "-", "RPC", "request", "passed", "through", "a", "CGI", "post", "method", "." ]
def handle_request(self, request_text = None): """Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers. """ if request_text is None and \ os.environ.get('REQUEST_METHOD', None) == 'GET': self.handle_get() else: # POST data is normally available through stdin try: length = int(os.environ.get('CONTENT_LENGTH', None)) except (TypeError, ValueError): length = -1 if request_text is None: request_text = sys.stdin.read(length) self.handle_xmlrpc(request_text)
[ "def", "handle_request", "(", "self", ",", "request_text", "=", "None", ")", ":", "if", "request_text", "is", "None", "and", "os", ".", "environ", ".", "get", "(", "'REQUEST_METHOD'", ",", "None", ")", "==", "'GET'", ":", "self", ".", "handle_get", "(", ")", "else", ":", "# POST data is normally available through stdin", "try", ":", "length", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'CONTENT_LENGTH'", ",", "None", ")", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "length", "=", "-", "1", "if", "request_text", "is", "None", ":", "request_text", "=", "sys", ".", "stdin", ".", "read", "(", "length", ")", "self", ".", "handle_xmlrpc", "(", "request_text", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/SimpleXMLRPCServer.py#L588-L608
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/s3transfer/futures.py
python
TransferMeta.size
(self)
return self._size
The size of the transfer request if known
The size of the transfer request if known
[ "The", "size", "of", "the", "transfer", "request", "if", "known" ]
def size(self): """The size of the transfer request if known""" return self._size
[ "def", "size", "(", "self", ")", ":", "return", "self", ".", "_size" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/s3transfer/futures.py#L110-L112
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py
python
CalculateVariables
(default_variables, params)
Generated variables that require params to be known.
Generated variables that require params to be known.
[ "Generated", "variables", "that", "require", "params", "to", "be", "known", "." ]
def CalculateVariables(default_variables, params): """Generated variables that require params to be known.""" generator_flags = params.get('generator_flags', {}) # Select project file format version (if unset, default to auto detecting). msvs_version = MSVSVersion.SelectVisualStudioVersion( generator_flags.get('msvs_version', 'auto')) # Stash msvs_version for later (so we don't have to probe the system twice). params['msvs_version'] = msvs_version # Set a variable so conditions can be based on msvs_version. default_variables['MSVS_VERSION'] = msvs_version.ShortName() # To determine processor word size on Windows, in addition to checking # PROCESSOR_ARCHITECTURE (which reflects the word size of the current # process), it is also necessary to check PROCESSOR_ARCITEW6432 (which # contains the actual word size of the system when running thru WOW64). if (os.environ.get('PROCESSOR_ARCHITECTURE', '').find('64') >= 0 or os.environ.get('PROCESSOR_ARCHITEW6432', '').find('64') >= 0): default_variables['MSVS_OS_BITS'] = 64 else: default_variables['MSVS_OS_BITS'] = 32
[ "def", "CalculateVariables", "(", "default_variables", ",", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "# Select project file format version (if unset, default to auto detecting).", "msvs_version", "=", "MSVSVersion", ".", "SelectVisualStudioVersion", "(", "generator_flags", ".", "get", "(", "'msvs_version'", ",", "'auto'", ")", ")", "# Stash msvs_version for later (so we don't have to probe the system twice).", "params", "[", "'msvs_version'", "]", "=", "msvs_version", "# Set a variable so conditions can be based on msvs_version.", "default_variables", "[", "'MSVS_VERSION'", "]", "=", "msvs_version", ".", "ShortName", "(", ")", "# To determine processor word size on Windows, in addition to checking", "# PROCESSOR_ARCHITECTURE (which reflects the word size of the current", "# process), it is also necessary to check PROCESSOR_ARCITEW6432 (which", "# contains the actual word size of the system when running thru WOW64).", "if", "(", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITECTURE'", ",", "''", ")", ".", "find", "(", "'64'", ")", ">=", "0", "or", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITEW6432'", ",", "''", ")", ".", "find", "(", "'64'", ")", ">=", "0", ")", ":", "default_variables", "[", "'MSVS_OS_BITS'", "]", "=", "64", "else", ":", "default_variables", "[", "'MSVS_OS_BITS'", "]", "=", "32" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py#L1696-L1718
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
cmake/std/trilinosprhelpers/TrilinosPRConfigurationBase.py
python
TrilinosPRConfigurationBase.validate_branch_constraints
(self)
return 0
Verify that the source branch is allowed. For the `master` branch, we only allow the source branch to be a protected branch named with the scheme `master_merge_YYYYMMDD_HHMMSS`
Verify that the source branch is allowed.
[ "Verify", "that", "the", "source", "branch", "is", "allowed", "." ]
def validate_branch_constraints(self): """ Verify that the source branch is allowed. For the `master` branch, we only allow the source branch to be a protected branch named with the scheme `master_merge_YYYYMMDD_HHMMSS` """ print("") print("Validate target branch constraints:") print("--- Target branch is '{}'".format(self.args.target_branch_name)) re_master_merge_source = "master_merge_[0-9]{8}_[0-9]{6}" if "master" == self.args.target_branch_name: print("--- Target branch is 'master'. Checking source branch constraints...") if not re.match(re_master_merge_source, self.args.source_branch_name): message = "+" + "="*78 + "+\n" message += "ERROR: Source branch is NOT trilinos/Trilinos::master_merge_YYYYMMDD_HHMMSS\n" message += " This violates Trilinos policy for pull requests into the master\n" message += " branch.\n" message += " Source branch provided is {}\n".format(self.args.source_branch_name) message += " Perhaps you forgot to set `develop` as the target in your PR?\n" message += "+" + "="*78 + "+\n" #print(message) sys.exit(message) print("--- target branch constraints OK") print("") return 0
[ "def", "validate_branch_constraints", "(", "self", ")", ":", "print", "(", "\"\"", ")", "print", "(", "\"Validate target branch constraints:\"", ")", "print", "(", "\"--- Target branch is '{}'\"", ".", "format", "(", "self", ".", "args", ".", "target_branch_name", ")", ")", "re_master_merge_source", "=", "\"master_merge_[0-9]{8}_[0-9]{6}\"", "if", "\"master\"", "==", "self", ".", "args", ".", "target_branch_name", ":", "print", "(", "\"--- Target branch is 'master'. Checking source branch constraints...\"", ")", "if", "not", "re", ".", "match", "(", "re_master_merge_source", ",", "self", ".", "args", ".", "source_branch_name", ")", ":", "message", "=", "\"+\"", "+", "\"=\"", "*", "78", "+", "\"+\\n\"", "message", "+=", "\"ERROR: Source branch is NOT trilinos/Trilinos::master_merge_YYYYMMDD_HHMMSS\\n\"", "message", "+=", "\" This violates Trilinos policy for pull requests into the master\\n\"", "message", "+=", "\" branch.\\n\"", "message", "+=", "\" Source branch provided is {}\\n\"", ".", "format", "(", "self", ".", "args", ".", "source_branch_name", ")", "message", "+=", "\" Perhaps you forgot to set `develop` as the target in your PR?\\n\"", "message", "+=", "\"+\"", "+", "\"=\"", "*", "78", "+", "\"+\\n\"", "#print(message)", "sys", ".", "exit", "(", "message", ")", "print", "(", "\"--- target branch constraints OK\"", ")", "print", "(", "\"\"", ")", "return", "0" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/cmake/std/trilinosprhelpers/TrilinosPRConfigurationBase.py#L489-L516
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/tensor_forest/python/ops/training_ops.py
python
_ScatterAddNdimShape
(unused_op)
return []
Shape function for ScatterAddNdim Op.
Shape function for ScatterAddNdim Op.
[ "Shape", "function", "for", "ScatterAddNdim", "Op", "." ]
def _ScatterAddNdimShape(unused_op): """Shape function for ScatterAddNdim Op.""" return []
[ "def", "_ScatterAddNdimShape", "(", "unused_op", ")", ":", "return", "[", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/tensor_forest/python/ops/training_ops.py#L95-L97
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/resources/collection.py
python
CollectionManager.iterator
(self, **kwargs)
return self._collection_cls(self._model, self._parent, self._handler, **kwargs)
Get a resource collection iterator from this manager. :rtype: :py:class:`ResourceCollection` :return: An iterable representing the collection of resources
Get a resource collection iterator from this manager.
[ "Get", "a", "resource", "collection", "iterator", "from", "this", "manager", "." ]
def iterator(self, **kwargs): """ Get a resource collection iterator from this manager. :rtype: :py:class:`ResourceCollection` :return: An iterable representing the collection of resources """ return self._collection_cls(self._model, self._parent, self._handler, **kwargs)
[ "def", "iterator", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_collection_cls", "(", "self", ".", "_model", ",", "self", ".", "_parent", ",", "self", ".", "_handler", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/resources/collection.py#L329-L337
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/google/protobuf/internal/well_known_types.py
python
Timestamp.ToJsonString
(self)
return result + '.%09dZ' % nanos
Converts Timestamp to RFC 3339 date string format. Returns: A string converted from timestamp. The string is always Z-normalized and uses 3, 6 or 9 fractional digits as required to represent the exact time. Example of the return format: '1972-01-01T10:00:20.021Z'
Converts Timestamp to RFC 3339 date string format.
[ "Converts", "Timestamp", "to", "RFC", "3339", "date", "string", "format", "." ]
def ToJsonString(self): """Converts Timestamp to RFC 3339 date string format. Returns: A string converted from timestamp. The string is always Z-normalized and uses 3, 6 or 9 fractional digits as required to represent the exact time. Example of the return format: '1972-01-01T10:00:20.021Z' """ nanos = self.nanos % _NANOS_PER_SECOND total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND seconds = total_sec % _SECONDS_PER_DAY days = (total_sec - seconds) // _SECONDS_PER_DAY dt = datetime(1970, 1, 1) + timedelta(days, seconds) result = dt.isoformat() if (nanos % 1e9) == 0: # If there are 0 fractional digits, the fractional # point '.' should be omitted when serializing. return result + 'Z' if (nanos % 1e6) == 0: # Serialize 3 fractional digits. return result + '.%03dZ' % (nanos / 1e6) if (nanos % 1e3) == 0: # Serialize 6 fractional digits. return result + '.%06dZ' % (nanos / 1e3) # Serialize 9 fractional digits. return result + '.%09dZ' % nanos
[ "def", "ToJsonString", "(", "self", ")", ":", "nanos", "=", "self", ".", "nanos", "%", "_NANOS_PER_SECOND", "total_sec", "=", "self", ".", "seconds", "+", "(", "self", ".", "nanos", "-", "nanos", ")", "//", "_NANOS_PER_SECOND", "seconds", "=", "total_sec", "%", "_SECONDS_PER_DAY", "days", "=", "(", "total_sec", "-", "seconds", ")", "//", "_SECONDS_PER_DAY", "dt", "=", "datetime", "(", "1970", ",", "1", ",", "1", ")", "+", "timedelta", "(", "days", ",", "seconds", ")", "result", "=", "dt", ".", "isoformat", "(", ")", "if", "(", "nanos", "%", "1e9", ")", "==", "0", ":", "# If there are 0 fractional digits, the fractional", "# point '.' should be omitted when serializing.", "return", "result", "+", "'Z'", "if", "(", "nanos", "%", "1e6", ")", "==", "0", ":", "# Serialize 3 fractional digits.", "return", "result", "+", "'.%03dZ'", "%", "(", "nanos", "/", "1e6", ")", "if", "(", "nanos", "%", "1e3", ")", "==", "0", ":", "# Serialize 6 fractional digits.", "return", "result", "+", "'.%06dZ'", "%", "(", "nanos", "/", "1e3", ")", "# Serialize 9 fractional digits.", "return", "result", "+", "'.%09dZ'", "%", "nanos" ]
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/well_known_types.py#L100-L126
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.GetCaretPeriod
(*args, **kwargs)
return _stc.StyledTextCtrl_GetCaretPeriod(*args, **kwargs)
GetCaretPeriod(self) -> int Get the time in milliseconds that the caret is on and off.
GetCaretPeriod(self) -> int
[ "GetCaretPeriod", "(", "self", ")", "-", ">", "int" ]
def GetCaretPeriod(*args, **kwargs): """ GetCaretPeriod(self) -> int Get the time in milliseconds that the caret is on and off. """ return _stc.StyledTextCtrl_GetCaretPeriod(*args, **kwargs)
[ "def", "GetCaretPeriod", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetCaretPeriod", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L2819-L2825
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/logging/handlers.py
python
BufferingHandler.close
(self)
Close the handler. This version just flushes and chains to the parent class' close().
Close the handler.
[ "Close", "the", "handler", "." ]
def close(self): """ Close the handler. This version just flushes and chains to the parent class' close(). """ self.flush() logging.Handler.close(self)
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "logging", ".", "Handler", ".", "close", "(", "self", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/handlers.py#L1087-L1094
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
openr/py/openr/cli/clis/config.py
python
ConfigPrefixManagerCli.config_prefix_manager
(cli_opts)
Dump prefix manager config
Dump prefix manager config
[ "Dump", "prefix", "manager", "config" ]
def config_prefix_manager(cli_opts): # noqa: B902 """Dump prefix manager config""" config.ConfigPrefixManagerCmd(cli_opts).run()
[ "def", "config_prefix_manager", "(", "cli_opts", ")", ":", "# noqa: B902", "config", ".", "ConfigPrefixManagerCmd", "(", "cli_opts", ")", ".", "run", "(", ")" ]
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/clis/config.py#L94-L97
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/ansic/cparse.py
python
p_init_declarator_1
(t)
init_declarator : declarator
init_declarator : declarator
[ "init_declarator", ":", "declarator" ]
def p_init_declarator_1(t): 'init_declarator : declarator' pass
[ "def", "p_init_declarator_1", "(", "t", ")", ":", "pass" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L173-L175
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/versioneer.py
python
get_version
()
return get_versions()["version"]
Get the short version string for this project.
Get the short version string for this project.
[ "Get", "the", "short", "version", "string", "for", "this", "project", "." ]
def get_version(): """Get the short version string for this project.""" return get_versions()["version"]
[ "def", "get_version", "(", ")", ":", "return", "get_versions", "(", ")", "[", "\"version\"", "]" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/versioneer.py#L1537-L1539
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/layer1.py
python
CloudSearchConnection.describe_scaling_parameters
(self, domain_name)
return self._make_request( action='DescribeScalingParameters', verb='POST', path='/', params=params)
Gets the scaling parameters configured for a domain. A domain's scaling parameters specify the desired search instance type and replication count. For more information, see `Configuring Scaling Options`_ in the Amazon CloudSearch Developer Guide . :type domain_name: string :param domain_name: A string that represents the name of a domain. Domain names are unique across the domains owned by an account within an AWS region. Domain names start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen).
Gets the scaling parameters configured for a domain. A domain's scaling parameters specify the desired search instance type and replication count. For more information, see `Configuring Scaling Options`_ in the Amazon CloudSearch Developer Guide .
[ "Gets", "the", "scaling", "parameters", "configured", "for", "a", "domain", ".", "A", "domain", "s", "scaling", "parameters", "specify", "the", "desired", "search", "instance", "type", "and", "replication", "count", ".", "For", "more", "information", "see", "Configuring", "Scaling", "Options", "_", "in", "the", "Amazon", "CloudSearch", "Developer", "Guide", "." ]
def describe_scaling_parameters(self, domain_name): """ Gets the scaling parameters configured for a domain. A domain's scaling parameters specify the desired search instance type and replication count. For more information, see `Configuring Scaling Options`_ in the Amazon CloudSearch Developer Guide . :type domain_name: string :param domain_name: A string that represents the name of a domain. Domain names are unique across the domains owned by an account within an AWS region. Domain names start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). """ params = {'DomainName': domain_name, } return self._make_request( action='DescribeScalingParameters', verb='POST', path='/', params=params)
[ "def", "describe_scaling_parameters", "(", "self", ",", "domain_name", ")", ":", "params", "=", "{", "'DomainName'", ":", "domain_name", ",", "}", "return", "self", ".", "_make_request", "(", "action", "=", "'DescribeScalingParameters'", ",", "verb", "=", "'POST'", ",", "path", "=", "'/'", ",", "params", "=", "params", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/layer1.py#L529-L549
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/maya/scripts/walterPanel/walterMayaTraverser.py
python
WalterMayaImplementation.findShadersPlug
(self, layersAssignation, layerName)
return self.getChildMPlug(requestedAssignation, 'shaderConnections')
Return MPlug node.layersAssignation[i].shaderConnections for requested layer.
Return MPlug node.layersAssignation[i].shaderConnections for requested layer.
[ "Return", "MPlug", "node", ".", "layersAssignation", "[", "i", "]", ".", "shaderConnections", "for", "requested", "layer", "." ]
def findShadersPlug(self, layersAssignation, layerName): """ Return MPlug node.layersAssignation[i].shaderConnections for requested layer. """ # Requested render layer layerDepend = self.getDependNode(layerName) if not layerDepend: return # Get MObject of the requested render layer to be able to comare it with # connected layers layerObject = layerDepend.object() requestedAssignation = None for i in range(layersAssignation.numElements()): # Get walterStandin.layersAssignation[i] currentLayerCompound = layersAssignation.elementByPhysicalIndex(i) # Get walterStandin.layersAssignation[i].layer layerPlug = self.getChildMPlug(currentLayerCompound, 'layer') if not layerPlug or layerPlug.isNull: continue connection = layerPlug.connectedTo(True, False) if not connection: continue # Compare the saved MObject with the first connected node. We # consider we have only one connection. if layerObject == connection[0].node(): # Save walterStandin.layersAssignation[i] requestedAssignation = currentLayerCompound break if not requestedAssignation: return # Get walterStandin.layersAssignation[i].shaderConnections return self.getChildMPlug(requestedAssignation, 'shaderConnections')
[ "def", "findShadersPlug", "(", "self", ",", "layersAssignation", ",", "layerName", ")", ":", "# Requested render layer", "layerDepend", "=", "self", ".", "getDependNode", "(", "layerName", ")", "if", "not", "layerDepend", ":", "return", "# Get MObject of the requested render layer to be able to comare it with", "# connected layers", "layerObject", "=", "layerDepend", ".", "object", "(", ")", "requestedAssignation", "=", "None", "for", "i", "in", "range", "(", "layersAssignation", ".", "numElements", "(", ")", ")", ":", "# Get walterStandin.layersAssignation[i]", "currentLayerCompound", "=", "layersAssignation", ".", "elementByPhysicalIndex", "(", "i", ")", "# Get walterStandin.layersAssignation[i].layer", "layerPlug", "=", "self", ".", "getChildMPlug", "(", "currentLayerCompound", ",", "'layer'", ")", "if", "not", "layerPlug", "or", "layerPlug", ".", "isNull", ":", "continue", "connection", "=", "layerPlug", ".", "connectedTo", "(", "True", ",", "False", ")", "if", "not", "connection", ":", "continue", "# Compare the saved MObject with the first connected node. We", "# consider we have only one connection.", "if", "layerObject", "==", "connection", "[", "0", "]", ".", "node", "(", ")", ":", "# Save walterStandin.layersAssignation[i]", "requestedAssignation", "=", "currentLayerCompound", "break", "if", "not", "requestedAssignation", ":", "return", "# Get walterStandin.layersAssignation[i].shaderConnections", "return", "self", ".", "getChildMPlug", "(", "requestedAssignation", ",", "'shaderConnections'", ")" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/walterPanel/walterMayaTraverser.py#L802-L840
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/ftplib.py
python
FTP.getwelcome
(self)
return self.welcome
Get the welcome message from the server. (this is read and squirreled away by connect())
Get the welcome message from the server. (this is read and squirreled away by connect())
[ "Get", "the", "welcome", "message", "from", "the", "server", ".", "(", "this", "is", "read", "and", "squirreled", "away", "by", "connect", "()", ")" ]
def getwelcome(self): '''Get the welcome message from the server. (this is read and squirreled away by connect())''' if self.debugging: print('*welcome*', self.sanitize(self.welcome)) return self.welcome
[ "def", "getwelcome", "(", "self", ")", ":", "if", "self", ".", "debugging", ":", "print", "(", "'*welcome*'", ",", "self", ".", "sanitize", "(", "self", ".", "welcome", ")", ")", "return", "self", ".", "welcome" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/ftplib.py#L158-L163
Jyouhou/UnrealText
dc8460a8dff37c61d5bf290b013674bb0c42d429
code/DataGenerator/ClientWrapper.py
python
WrappedClient.randomizeEnv
(self, env_type='All')
env_type = 'All', 'light_int', 'light_dir', 'light-color', 'fog'
env_type = 'All', 'light_int', 'light_dir', 'light-color', 'fog'
[ "env_type", "=", "All", "light_int", "light_dir", "light", "-", "color", "fog" ]
def randomizeEnv(self, env_type='All'): """ env_type = 'All', 'light_int', 'light_dir', 'light-color', 'fog' """ _ = self.client.request(f'vget /object/env {env_type}')
[ "def", "randomizeEnv", "(", "self", ",", "env_type", "=", "'All'", ")", ":", "_", "=", "self", ".", "client", ".", "request", "(", "f'vget /object/env {env_type}'", ")" ]
https://github.com/Jyouhou/UnrealText/blob/dc8460a8dff37c61d5bf290b013674bb0c42d429/code/DataGenerator/ClientWrapper.py#L62-L66
yyzybb537/libgo
4af17b7c67643c4d54aa354dcc77963ea07847d0
third_party/boost.context/tools/build/src/build/targets.py
python
ProjectTarget.targets_to_build
(self)
return result
Computes and returns a list of AbstractTarget instances which must be built when this project is built.
Computes and returns a list of AbstractTarget instances which must be built when this project is built.
[ "Computes", "and", "returns", "a", "list", "of", "AbstractTarget", "instances", "which", "must", "be", "built", "when", "this", "project", "is", "built", "." ]
def targets_to_build (self): """ Computes and returns a list of AbstractTarget instances which must be built when this project is built. """ result = [] if not self.built_main_targets_: self.build_main_targets () # Collect all main targets here, except for "explicit" ones. for n, t in self.main_target_.iteritems (): if not t.name () in self.explicit_targets_: result.append (t) # Collect all projects referenced via "projects-to-build" attribute. self_location = self.get ('location') for pn in self.get ('projects-to-build'): result.append (self.find(pn + "/")) return result
[ "def", "targets_to_build", "(", "self", ")", ":", "result", "=", "[", "]", "if", "not", "self", ".", "built_main_targets_", ":", "self", ".", "build_main_targets", "(", ")", "# Collect all main targets here, except for \"explicit\" ones.", "for", "n", ",", "t", "in", "self", ".", "main_target_", ".", "iteritems", "(", ")", ":", "if", "not", "t", ".", "name", "(", ")", "in", "self", ".", "explicit_targets_", ":", "result", ".", "append", "(", "t", ")", "# Collect all projects referenced via \"projects-to-build\" attribute.", "self_location", "=", "self", ".", "get", "(", "'location'", ")", "for", "pn", "in", "self", ".", "get", "(", "'projects-to-build'", ")", ":", "result", ".", "append", "(", "self", ".", "find", "(", "pn", "+", "\"/\"", ")", ")", "return", "result" ]
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/targets.py#L446-L465
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/io.py
python
RawIOBase.write
(self, b)
Write the given buffer to the IO stream. Returns the number of bytes written, which may be less than len(b).
Write the given buffer to the IO stream.
[ "Write", "the", "given", "buffer", "to", "the", "IO", "stream", "." ]
def write(self, b): """Write the given buffer to the IO stream. Returns the number of bytes written, which may be less than len(b). """ self._unsupported("write")
[ "def", "write", "(", "self", ",", "b", ")", ":", "self", ".", "_unsupported", "(", "\"write\"", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/io.py#L613-L618
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/Standard_Suite.py
python
Standard_Suite_Events.get
(self, _object, _attributes={}, **_arguments)
get: Get the data for an object Required argument: the object whose data is to be returned Keyword argument _attributes: AppleEvent attribute dictionary Returns: The data from the object
get: Get the data for an object Required argument: the object whose data is to be returned Keyword argument _attributes: AppleEvent attribute dictionary Returns: The data from the object
[ "get", ":", "Get", "the", "data", "for", "an", "object", "Required", "argument", ":", "the", "object", "whose", "data", "is", "to", "be", "returned", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "The", "data", "from", "the", "object" ]
def get(self, _object, _attributes={}, **_arguments): """get: Get the data for an object Required argument: the object whose data is to be returned Keyword argument _attributes: AppleEvent attribute dictionary Returns: The data from the object """ _code = 'core' _subcode = 'getd' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "get", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'getd'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/Standard_Suite.py#L57-L76
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cryptography/hazmat/primitives/asymmetric/rsa.py
python
rsa_recover_prime_factors
(n, e, d)
return (p, q)
Compute factors p and q from the private exponent d. We assume that n has no more than two factors. This function is adapted from code in PyCrypto.
Compute factors p and q from the private exponent d. We assume that n has no more than two factors. This function is adapted from code in PyCrypto.
[ "Compute", "factors", "p", "and", "q", "from", "the", "private", "exponent", "d", ".", "We", "assume", "that", "n", "has", "no", "more", "than", "two", "factors", ".", "This", "function", "is", "adapted", "from", "code", "in", "PyCrypto", "." ]
def rsa_recover_prime_factors(n, e, d): """ Compute factors p and q from the private exponent d. We assume that n has no more than two factors. This function is adapted from code in PyCrypto. """ # See 8.2.2(i) in Handbook of Applied Cryptography. ktot = d * e - 1 # The quantity d*e-1 is a multiple of phi(n), even, # and can be represented as t*2^s. t = ktot while t % 2 == 0: t = t // 2 # Cycle through all multiplicative inverses in Zn. # The algorithm is non-deterministic, but there is a 50% chance # any candidate a leads to successful factoring. # See "Digitalized Signatures and Public Key Functions as Intractable # as Factorization", M. Rabin, 1979 spotted = False a = 2 while not spotted and a < _MAX_RECOVERY_ATTEMPTS: k = t # Cycle through all values a^{t*2^i}=a^k while k < ktot: cand = pow(a, k, n) # Check if a^k is a non-trivial root of unity (mod n) if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: # We have found a number such that (cand-1)(cand+1)=0 (mod n). # Either of the terms divides n. p = gcd(cand + 1, n) spotted = True break k *= 2 # This value was not any good... let's try another! a += 2 if not spotted: raise ValueError("Unable to compute factors p and q from exponent d.") # Found ! q, r = divmod(n, p) assert r == 0 p, q = sorted((p, q), reverse=True) return (p, q)
[ "def", "rsa_recover_prime_factors", "(", "n", ",", "e", ",", "d", ")", ":", "# See 8.2.2(i) in Handbook of Applied Cryptography.", "ktot", "=", "d", "*", "e", "-", "1", "# The quantity d*e-1 is a multiple of phi(n), even,", "# and can be represented as t*2^s.", "t", "=", "ktot", "while", "t", "%", "2", "==", "0", ":", "t", "=", "t", "//", "2", "# Cycle through all multiplicative inverses in Zn.", "# The algorithm is non-deterministic, but there is a 50% chance", "# any candidate a leads to successful factoring.", "# See \"Digitalized Signatures and Public Key Functions as Intractable", "# as Factorization\", M. Rabin, 1979", "spotted", "=", "False", "a", "=", "2", "while", "not", "spotted", "and", "a", "<", "_MAX_RECOVERY_ATTEMPTS", ":", "k", "=", "t", "# Cycle through all values a^{t*2^i}=a^k", "while", "k", "<", "ktot", ":", "cand", "=", "pow", "(", "a", ",", "k", ",", "n", ")", "# Check if a^k is a non-trivial root of unity (mod n)", "if", "cand", "!=", "1", "and", "cand", "!=", "(", "n", "-", "1", ")", "and", "pow", "(", "cand", ",", "2", ",", "n", ")", "==", "1", ":", "# We have found a number such that (cand-1)(cand+1)=0 (mod n).", "# Either of the terms divides n.", "p", "=", "gcd", "(", "cand", "+", "1", ",", "n", ")", "spotted", "=", "True", "break", "k", "*=", "2", "# This value was not any good... let's try another!", "a", "+=", "2", "if", "not", "spotted", ":", "raise", "ValueError", "(", "\"Unable to compute factors p and q from exponent d.\"", ")", "# Found !", "q", ",", "r", "=", "divmod", "(", "n", ",", "p", ")", "assert", "r", "==", "0", "p", ",", "q", "=", "sorted", "(", "(", "p", ",", "q", ")", ",", "reverse", "=", "True", ")", "return", "(", "p", ",", "q", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/cryptography/hazmat/primitives/asymmetric/rsa.py#L225-L265
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/mailbox.py
python
Maildir._refresh
(self)
Update table of contents mapping.
Update table of contents mapping.
[ "Update", "table", "of", "contents", "mapping", "." ]
def _refresh(self): """Update table of contents mapping.""" # If it has been less than two seconds since the last _refresh() call, # we have to unconditionally re-read the mailbox just in case it has # been modified, because os.path.mtime() has a 2 sec resolution in the # most common worst case (FAT) and a 1 sec resolution typically. This # results in a few unnecessary re-reads when _refresh() is called # multiple times in that interval, but once the clock ticks over, we # will only re-read as needed. Because the filesystem might be being # served by an independent system with its own clock, we record and # compare with the mtimes from the filesystem. Because the other # system's clock might be skewing relative to our clock, we add an # extra delta to our wait. The default is one tenth second, but is an # instance variable and so can be adjusted if dealing with a # particularly skewed or irregular system. if time.time() - self._last_read > 2 + self._skewfactor: refresh = False for subdir in self._toc_mtimes: mtime = os.path.getmtime(self._paths[subdir]) if mtime > self._toc_mtimes[subdir]: refresh = True self._toc_mtimes[subdir] = mtime if not refresh: return # Refresh toc self._toc = {} for subdir in self._toc_mtimes: path = self._paths[subdir] for entry in os.listdir(path): p = os.path.join(path, entry) if os.path.isdir(p): continue uniq = entry.split(self.colon)[0] self._toc[uniq] = os.path.join(subdir, entry) self._last_read = time.time()
[ "def", "_refresh", "(", "self", ")", ":", "# If it has been less than two seconds since the last _refresh() call,", "# we have to unconditionally re-read the mailbox just in case it has", "# been modified, because os.path.mtime() has a 2 sec resolution in the", "# most common worst case (FAT) and a 1 sec resolution typically. This", "# results in a few unnecessary re-reads when _refresh() is called", "# multiple times in that interval, but once the clock ticks over, we", "# will only re-read as needed. Because the filesystem might be being", "# served by an independent system with its own clock, we record and", "# compare with the mtimes from the filesystem. Because the other", "# system's clock might be skewing relative to our clock, we add an", "# extra delta to our wait. The default is one tenth second, but is an", "# instance variable and so can be adjusted if dealing with a", "# particularly skewed or irregular system.", "if", "time", ".", "time", "(", ")", "-", "self", ".", "_last_read", ">", "2", "+", "self", ".", "_skewfactor", ":", "refresh", "=", "False", "for", "subdir", "in", "self", ".", "_toc_mtimes", ":", "mtime", "=", "os", ".", "path", ".", "getmtime", "(", "self", ".", "_paths", "[", "subdir", "]", ")", "if", "mtime", ">", "self", ".", "_toc_mtimes", "[", "subdir", "]", ":", "refresh", "=", "True", "self", ".", "_toc_mtimes", "[", "subdir", "]", "=", "mtime", "if", "not", "refresh", ":", "return", "# Refresh toc", "self", ".", "_toc", "=", "{", "}", "for", "subdir", "in", "self", ".", "_toc_mtimes", ":", "path", "=", "self", ".", "_paths", "[", "subdir", "]", "for", "entry", "in", "os", ".", "listdir", "(", "path", ")", ":", "p", "=", "os", ".", "path", ".", "join", "(", "path", ",", "entry", ")", "if", "os", ".", "path", ".", "isdir", "(", "p", ")", ":", "continue", "uniq", "=", "entry", ".", "split", "(", "self", ".", "colon", ")", "[", "0", "]", "self", ".", "_toc", "[", "uniq", "]", "=", "os", ".", "path", ".", "join", "(", "subdir", ",", "entry", ")", "self", ".", "_last_read", "=", "time", ".", "time", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L501-L535
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/pypack/altgraph/ObjectGraph.py
python
ObjectGraph.filterStack
(self, filters)
return len(visited)-1, len(removes), len(orphans)
Filter the ObjectGraph in-place by removing all edges to nodes that do not match every filter in the given filter list Returns a tuple containing the number of: (nodes_visited, nodes_removed, nodes_orphaned)
Filter the ObjectGraph in-place by removing all edges to nodes that do not match every filter in the given filter list
[ "Filter", "the", "ObjectGraph", "in", "-", "place", "by", "removing", "all", "edges", "to", "nodes", "that", "do", "not", "match", "every", "filter", "in", "the", "given", "filter", "list" ]
def filterStack(self, filters): """ Filter the ObjectGraph in-place by removing all edges to nodes that do not match every filter in the given filter list Returns a tuple containing the number of: (nodes_visited, nodes_removed, nodes_orphaned) """ visited, removes, orphans = filter_stack(self.graph, self, filters) for last_good, tail in orphans: self.graph.add_edge(last_good, tail, edge_data='orphan') for node in removes: self.graph.hide_node(node) return len(visited)-1, len(removes), len(orphans)
[ "def", "filterStack", "(", "self", ",", "filters", ")", ":", "visited", ",", "removes", ",", "orphans", "=", "filter_stack", "(", "self", ".", "graph", ",", "self", ",", "filters", ")", "for", "last_good", ",", "tail", "in", "orphans", ":", "self", ".", "graph", ".", "add_edge", "(", "last_good", ",", "tail", ",", "edge_data", "=", "'orphan'", ")", "for", "node", "in", "removes", ":", "self", ".", "graph", ".", "hide_node", "(", "node", ")", "return", "len", "(", "visited", ")", "-", "1", ",", "len", "(", "removes", ")", ",", "len", "(", "orphans", ")" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/altgraph/ObjectGraph.py#L46-L62
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiPaneInfo.CloseButton
(*args, **kwargs)
return _aui.AuiPaneInfo_CloseButton(*args, **kwargs)
CloseButton(self, bool visible=True) -> AuiPaneInfo
CloseButton(self, bool visible=True) -> AuiPaneInfo
[ "CloseButton", "(", "self", "bool", "visible", "=", "True", ")", "-", ">", "AuiPaneInfo" ]
def CloseButton(*args, **kwargs): """CloseButton(self, bool visible=True) -> AuiPaneInfo""" return _aui.AuiPaneInfo_CloseButton(*args, **kwargs)
[ "def", "CloseButton", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiPaneInfo_CloseButton", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L457-L459
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/telemetry/core/platform/__init__.py
python
Platform.IsApplicationRunning
(self, application)
return self._platform_backend.IsApplicationLaunchning(application)
Returns whether an application is currently running.
Returns whether an application is currently running.
[ "Returns", "whether", "an", "application", "is", "currently", "running", "." ]
def IsApplicationRunning(self, application): """Returns whether an application is currently running.""" return self._platform_backend.IsApplicationLaunchning(application)
[ "def", "IsApplicationRunning", "(", "self", ",", "application", ")", ":", "return", "self", ".", "_platform_backend", ".", "IsApplicationLaunchning", "(", "application", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/platform/__init__.py#L121-L123
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
python/pyarrow/filesystem.py
python
FileSystem.cat
(self, path)
Return contents of file as a bytes object. Parameters ---------- path : str File path to read content from. Returns ------- contents : bytes
Return contents of file as a bytes object.
[ "Return", "contents", "of", "file", "as", "a", "bytes", "object", "." ]
def cat(self, path): """ Return contents of file as a bytes object. Parameters ---------- path : str File path to read content from. Returns ------- contents : bytes """ with self.open(path, 'rb') as f: return f.read()
[ "def", "cat", "(", "self", ",", "path", ")", ":", "with", "self", ".", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/filesystem.py#L41-L55
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/execution.py
python
Execution.peg_offset_value
(self)
return self._peg_offset_value
Gets the peg_offset_value of this Execution. # noqa: E501 :return: The peg_offset_value of this Execution. # noqa: E501 :rtype: float
Gets the peg_offset_value of this Execution. # noqa: E501
[ "Gets", "the", "peg_offset_value", "of", "this", "Execution", ".", "#", "noqa", ":", "E501" ]
def peg_offset_value(self): """Gets the peg_offset_value of this Execution. # noqa: E501 :return: The peg_offset_value of this Execution. # noqa: E501 :rtype: float """ return self._peg_offset_value
[ "def", "peg_offset_value", "(", "self", ")", ":", "return", "self", ".", "_peg_offset_value" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/execution.py#L639-L646
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/resmokelib/logging/handlers.py
python
HTTPHandler.post
(self, endpoint, data=None, headers=None, timeout_secs=_TIMEOUT_SECS)
return response.text
Send a POST request to the specified endpoint with the supplied data. Return the response, either as a string or a JSON object based on the content type.
Send a POST request to the specified endpoint with the supplied data.
[ "Send", "a", "POST", "request", "to", "the", "specified", "endpoint", "with", "the", "supplied", "data", "." ]
def post(self, endpoint, data=None, headers=None, timeout_secs=_TIMEOUT_SECS): """Send a POST request to the specified endpoint with the supplied data. Return the response, either as a string or a JSON object based on the content type. """ data = utils.default_if_none(data, []) data = json.dumps(data) headers = utils.default_if_none(headers, {}) headers["Content-Type"] = "application/json; charset=utf-8" url = self._make_url(endpoint) with warnings.catch_warnings(): if urllib3_exceptions is not None: try: warnings.simplefilter("ignore", urllib3_exceptions.InsecurePlatformWarning) except AttributeError: # Versions of urllib3 prior to 1.10.3 didn't define InsecurePlatformWarning. # Versions of requests prior to 2.6.0 didn't have a vendored copy of urllib3 # that defined InsecurePlatformWarning. pass try: warnings.simplefilter("ignore", urllib3_exceptions.InsecureRequestWarning) except AttributeError: # Versions of urllib3 prior to 1.9 didn't define InsecureRequestWarning. # Versions of requests prior to 2.4.0 didn't have a vendored copy of urllib3 # that defined InsecureRequestWarning. pass response = self.session.post(url, data=data, headers=headers, timeout=timeout_secs, auth=self.auth_handler, verify=True) response.raise_for_status() if not response.encoding: response.encoding = "utf-8" headers = response.headers if headers["Content-Type"].startswith("application/json"): return response.json() return response.text
[ "def", "post", "(", "self", ",", "endpoint", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "timeout_secs", "=", "_TIMEOUT_SECS", ")", ":", "data", "=", "utils", ".", "default_if_none", "(", "data", ",", "[", "]", ")", "data", "=", "json", ".", "dumps", "(", "data", ")", "headers", "=", "utils", ".", "default_if_none", "(", "headers", ",", "{", "}", ")", "headers", "[", "\"Content-Type\"", "]", "=", "\"application/json; charset=utf-8\"", "url", "=", "self", ".", "_make_url", "(", "endpoint", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "if", "urllib3_exceptions", "is", "not", "None", ":", "try", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ",", "urllib3_exceptions", ".", "InsecurePlatformWarning", ")", "except", "AttributeError", ":", "# Versions of urllib3 prior to 1.10.3 didn't define InsecurePlatformWarning.", "# Versions of requests prior to 2.6.0 didn't have a vendored copy of urllib3", "# that defined InsecurePlatformWarning.", "pass", "try", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ",", "urllib3_exceptions", ".", "InsecureRequestWarning", ")", "except", "AttributeError", ":", "# Versions of urllib3 prior to 1.9 didn't define InsecureRequestWarning.", "# Versions of requests prior to 2.4.0 didn't have a vendored copy of urllib3", "# that defined InsecureRequestWarning.", "pass", "response", "=", "self", ".", "session", ".", "post", "(", "url", ",", "data", "=", "data", ",", "headers", "=", "headers", ",", "timeout", "=", "timeout_secs", ",", "auth", "=", "self", ".", "auth_handler", ",", "verify", "=", "True", ")", "response", ".", "raise_for_status", "(", ")", "if", "not", "response", ".", "encoding", ":", "response", ".", "encoding", "=", "\"utf-8\"", "headers", "=", "response", ".", "headers", "if", "headers", "[", "\"Content-Type\"", "]", ".", "startswith", "(", "\"application/json\"", ")", ":", "return", "response", ".", "json", "(", ")", "return", "response", ".", "text" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/logging/handlers.py#L190-L236
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/tpu/ops/tpu_ops.py
python
collective_permute
(x, source_target_pairs, name=None)
return gen_tpu_ops.collective_permute(x, source_target_pairs, name=name)
Permute the input tensor across replicas given source_target_pairs. For each source_target_pair <a, b>, we send replica a's input to replica b. Each replica id must only appear once in the source column. Also it must only appear once in the target column. For the replica id not in the target column, this op returns a zero tensor with the same shape and dtype of the input x. For example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing source_target_pairs=`[[0,1],[1,2],[2,3]]` gets the outputs: `[0, A, B, C]`. Args: x: The local tensor to be permuted. source_target_pairs: 2d int lists with shape [num_pairs, 2]. source_target_pairs[i][0] represents the source replica id and source_target_pairs[i][1] represents the target replica id. name: Optional op name. Returns: A `Tensor` which is permuted.
Permute the input tensor across replicas given source_target_pairs.
[ "Permute", "the", "input", "tensor", "across", "replicas", "given", "source_target_pairs", "." ]
def collective_permute(x, source_target_pairs, name=None): """Permute the input tensor across replicas given source_target_pairs. For each source_target_pair <a, b>, we send replica a's input to replica b. Each replica id must only appear once in the source column. Also it must only appear once in the target column. For the replica id not in the target column, this op returns a zero tensor with the same shape and dtype of the input x. For example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing source_target_pairs=`[[0,1],[1,2],[2,3]]` gets the outputs: `[0, A, B, C]`. Args: x: The local tensor to be permuted. source_target_pairs: 2d int lists with shape [num_pairs, 2]. source_target_pairs[i][0] represents the source replica id and source_target_pairs[i][1] represents the target replica id. name: Optional op name. Returns: A `Tensor` which is permuted. """ return gen_tpu_ops.collective_permute(x, source_target_pairs, name=name)
[ "def", "collective_permute", "(", "x", ",", "source_target_pairs", ",", "name", "=", "None", ")", ":", "return", "gen_tpu_ops", ".", "collective_permute", "(", "x", ",", "source_target_pairs", ",", "name", "=", "name", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/ops/tpu_ops.py#L108-L131
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xpathParserContext.xpathIdFunction
(self, nargs)
Implement the id() XPath function node-set id(object) The id function selects elements by their unique ID (see [5.2.1 Unique IDs]). When the argument to id is of type node-set, then the result is the union of the result of applying id to the string value of each of the nodes in the argument node-set. When the argument to id is of any other type, the argument is converted to a string as if by a call to the string function; the string is split into a whitespace-separated list of tokens (whitespace is any sequence of characters matching the production S); the result is a node-set containing the elements in the same document as the context node that have a unique ID equal to any of the tokens in the list.
Implement the id() XPath function node-set id(object) The id function selects elements by their unique ID (see [5.2.1 Unique IDs]). When the argument to id is of type node-set, then the result is the union of the result of applying id to the string value of each of the nodes in the argument node-set. When the argument to id is of any other type, the argument is converted to a string as if by a call to the string function; the string is split into a whitespace-separated list of tokens (whitespace is any sequence of characters matching the production S); the result is a node-set containing the elements in the same document as the context node that have a unique ID equal to any of the tokens in the list.
[ "Implement", "the", "id", "()", "XPath", "function", "node", "-", "set", "id", "(", "object", ")", "The", "id", "function", "selects", "elements", "by", "their", "unique", "ID", "(", "see", "[", "5", ".", "2", ".", "1", "Unique", "IDs", "]", ")", ".", "When", "the", "argument", "to", "id", "is", "of", "type", "node", "-", "set", "then", "the", "result", "is", "the", "union", "of", "the", "result", "of", "applying", "id", "to", "the", "string", "value", "of", "each", "of", "the", "nodes", "in", "the", "argument", "node", "-", "set", ".", "When", "the", "argument", "to", "id", "is", "of", "any", "other", "type", "the", "argument", "is", "converted", "to", "a", "string", "as", "if", "by", "a", "call", "to", "the", "string", "function", ";", "the", "string", "is", "split", "into", "a", "whitespace", "-", "separated", "list", "of", "tokens", "(", "whitespace", "is", "any", "sequence", "of", "characters", "matching", "the", "production", "S", ")", ";", "the", "result", "is", "a", "node", "-", "set", "containing", "the", "elements", "in", "the", "same", "document", "as", "the", "context", "node", "that", "have", "a", "unique", "ID", "equal", "to", "any", "of", "the", "tokens", "in", "the", "list", "." ]
def xpathIdFunction(self, nargs): """Implement the id() XPath function node-set id(object) The id function selects elements by their unique ID (see [5.2.1 Unique IDs]). When the argument to id is of type node-set, then the result is the union of the result of applying id to the string value of each of the nodes in the argument node-set. When the argument to id is of any other type, the argument is converted to a string as if by a call to the string function; the string is split into a whitespace-separated list of tokens (whitespace is any sequence of characters matching the production S); the result is a node-set containing the elements in the same document as the context node that have a unique ID equal to any of the tokens in the list. """ libxml2mod.xmlXPathIdFunction(self._o, nargs)
[ "def", "xpathIdFunction", "(", "self", ",", "nargs", ")", ":", "libxml2mod", ".", "xmlXPathIdFunction", "(", "self", ".", "_o", ",", "nargs", ")" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L7470-L7484