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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | FindDialogEvent.SetFlags | (*args, **kwargs) | return _windows_.FindDialogEvent_SetFlags(*args, **kwargs) | SetFlags(self, int flags) | SetFlags(self, int flags) | [
"SetFlags",
"(",
"self",
"int",
"flags",
")"
] | def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _windows_.FindDialogEvent_SetFlags(*args, **kwargs) | [
"def",
"SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"FindDialogEvent_SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L3847-L3849 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/mcnp.py | python | PtracReader.read_next | (self, format, number=1, auto=False, raw_format=False) | Helper method for reading records from the Ptrac file.
All binary records consist of the record content's length in bytes,
the content itself and then the length again.
format can be one of the struct module's format characters (i.e. i
for an int, f for a float, s for a string).
The length of the record can either be hard-coded by setting the
number parameter (e.g. to read 10 floats) or determined automatically
by setting auto=True.
Setting the parameter raw_format to True means that the format string
will not be expanded by number, but will be used directly. | Helper method for reading records from the Ptrac file.
All binary records consist of the record content's length in bytes,
the content itself and then the length again.
format can be one of the struct module's format characters (i.e. i
for an int, f for a float, s for a string).
The length of the record can either be hard-coded by setting the
number parameter (e.g. to read 10 floats) or determined automatically
by setting auto=True.
Setting the parameter raw_format to True means that the format string
will not be expanded by number, but will be used directly. | [
"Helper",
"method",
"for",
"reading",
"records",
"from",
"the",
"Ptrac",
"file",
".",
"All",
"binary",
"records",
"consist",
"of",
"the",
"record",
"content",
"s",
"length",
"in",
"bytes",
"the",
"content",
"itself",
"and",
"then",
"the",
"length",
"again",
... | def read_next(self, format, number=1, auto=False, raw_format=False):
"""Helper method for reading records from the Ptrac file.
All binary records consist of the record content's length in bytes,
the content itself and then the length again.
format can be one of the struct module's format characters (i.e. i
for an int, f for a float, s for a string).
The length of the record can either be hard-coded by setting the
number parameter (e.g. to read 10 floats) or determined automatically
by setting auto=True.
Setting the parameter raw_format to True means that the format string
will not be expanded by number, but will be used directly.
"""
if self.eightbytes and (not raw_format) and format == 'f':
format = 'd'
if self.eightbytes and (not raw_format) and format == 'i':
format = 'q'
# how long is one field of the read values
format_length = 1
if format in ['h', 'H'] and not raw_format:
format_length = 2
elif format in ['i', 'I', 'l', 'L', 'f'] and not raw_format:
format_length = 4
elif format in ['d', 'q', 'Q'] and not raw_format:
format_length = 8
if auto and not raw_format:
b = self.f.read(4)
if b == b'':
raise EOFError
length = struct.unpack(self.endianness.encode() + b'i', b)[0]
number = length // format_length
b = self.f.read(length + 4)
tmp = struct.unpack(b"".join([self.endianness.encode(),
(format*number).encode(), b'i']), b)
length2 = tmp[-1]
tmp = tmp[:-1]
else:
bytes_to_read = number * format_length + 8
b = self.f.read(bytes_to_read)
if b == b'':
raise EOFError
fmt_string = self.endianness + "i"
if raw_format:
fmt_string += format + "i"
else:
fmt_string += format * number + "i"
tmp = struct.unpack(fmt_string.encode(), b)
length = tmp[0]
length2 = tmp[-1]
tmp = tmp[1:-1]
assert length == length2
if format == 's':
# return just one string
return b''.join(tmp).decode()
elif number == 1:
# just return the number and not a tuple containing just the number
return tmp[0]
else:
# convert tuple to list
return list(tmp) | [
"def",
"read_next",
"(",
"self",
",",
"format",
",",
"number",
"=",
"1",
",",
"auto",
"=",
"False",
",",
"raw_format",
"=",
"False",
")",
":",
"if",
"self",
".",
"eightbytes",
"and",
"(",
"not",
"raw_format",
")",
"and",
"format",
"==",
"'f'",
":",
... | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/mcnp.py#L1089-L1157 | ||
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py | python | SourceLocation.offset | (self) | return self._get_instantiation()[3] | Get the file offset represented by this source location. | Get the file offset represented by this source location. | [
"Get",
"the",
"file",
"offset",
"represented",
"by",
"this",
"source",
"location",
"."
] | def offset(self):
"""Get the file offset represented by this source location."""
return self._get_instantiation()[3] | [
"def",
"offset",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_instantiation",
"(",
")",
"[",
"3",
"]"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py#L213-L215 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBBroadcaster.AddInitialEventsToListener | (self, listener, requested_events) | return _lldb.SBBroadcaster_AddInitialEventsToListener(self, listener, requested_events) | AddInitialEventsToListener(SBBroadcaster self, SBListener listener, uint32_t requested_events) | AddInitialEventsToListener(SBBroadcaster self, SBListener listener, uint32_t requested_events) | [
"AddInitialEventsToListener",
"(",
"SBBroadcaster",
"self",
"SBListener",
"listener",
"uint32_t",
"requested_events",
")"
] | def AddInitialEventsToListener(self, listener, requested_events):
"""AddInitialEventsToListener(SBBroadcaster self, SBListener listener, uint32_t requested_events)"""
return _lldb.SBBroadcaster_AddInitialEventsToListener(self, listener, requested_events) | [
"def",
"AddInitialEventsToListener",
"(",
"self",
",",
"listener",
",",
"requested_events",
")",
":",
"return",
"_lldb",
".",
"SBBroadcaster_AddInitialEventsToListener",
"(",
"self",
",",
"listener",
",",
"requested_events",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L2436-L2438 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | uCSIsCatLt | (code) | return ret | Check whether the character is part of Lt UCS Category | Check whether the character is part of Lt UCS Category | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Lt",
"UCS",
"Category"
] | def uCSIsCatLt(code):
"""Check whether the character is part of Lt UCS Category """
ret = libxml2mod.xmlUCSIsCatLt(code)
return ret | [
"def",
"uCSIsCatLt",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCatLt",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L2289-L2292 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/io/mmio.py | python | MMFile.read | (self, source) | Reads the contents of a Matrix Market file-like 'source' into a matrix.
Parameters
----------
source : str or file-like
Matrix Market filename (extensions .mtx, .mtz.gz)
or open file object.
Returns
-------
a : ndarray or coo_matrix
Dense or sparse matrix depending on the matrix format in the
Matrix Market file. | Reads the contents of a Matrix Market file-like 'source' into a matrix. | [
"Reads",
"the",
"contents",
"of",
"a",
"Matrix",
"Market",
"file",
"-",
"like",
"source",
"into",
"a",
"matrix",
"."
] | def read(self, source):
"""
Reads the contents of a Matrix Market file-like 'source' into a matrix.
Parameters
----------
source : str or file-like
Matrix Market filename (extensions .mtx, .mtz.gz)
or open file object.
Returns
-------
a : ndarray or coo_matrix
Dense or sparse matrix depending on the matrix format in the
Matrix Market file.
"""
stream, close_it = self._open(source)
try:
self._parse_header(stream)
return self._parse_body(stream)
finally:
if close_it:
stream.close() | [
"def",
"read",
"(",
"self",
",",
"source",
")",
":",
"stream",
",",
"close_it",
"=",
"self",
".",
"_open",
"(",
"source",
")",
"try",
":",
"self",
".",
"_parse_header",
"(",
"stream",
")",
"return",
"self",
".",
"_parse_body",
"(",
"stream",
")",
"fi... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/mmio.py#L395-L419 | ||
bristolcrypto/SPDZ-2 | 721abfae849625a02ea49aabc534f9cf41ca643f | Compiler/comparison.py | python | KMulC | (a) | return p | Return just the product of all items in a | Return just the product of all items in a | [
"Return",
"just",
"the",
"product",
"of",
"all",
"items",
"in",
"a"
] | def KMulC(a):
"""
Return just the product of all items in a
"""
from types import sint, cint
p = sint()
if use_inv:
PreMulC_with_inverses(p, a)
else:
PreMulC_without_inverses(p, a)
return p | [
"def",
"KMulC",
"(",
"a",
")",
":",
"from",
"types",
"import",
"sint",
",",
"cint",
"p",
"=",
"sint",
"(",
")",
"if",
"use_inv",
":",
"PreMulC_with_inverses",
"(",
"p",
",",
"a",
")",
"else",
":",
"PreMulC_without_inverses",
"(",
"p",
",",
"a",
")",
... | https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/comparison.py#L500-L510 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py | python | UnsetVariable | (output, variable_name) | Unsets a CMake variable. | Unsets a CMake variable. | [
"Unsets",
"a",
"CMake",
"variable",
"."
] | def UnsetVariable(output, variable_name):
"""Unsets a CMake variable."""
output.write('unset(')
output.write(variable_name)
output.write(')\n') | [
"def",
"UnsetVariable",
"(",
"output",
",",
"variable_name",
")",
":",
"output",
".",
"write",
"(",
"'unset('",
")",
"output",
".",
"write",
"(",
"variable_name",
")",
"output",
".",
"write",
"(",
"')\\n'",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py#L203-L207 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/serve/push/search/core/search_push_manager.py | python | SearchPushManager.HandleLocalTransferRequest | (self, request, response) | Handles Local Transferring request.
Args:
request: request object.
response: response object.
Raises:
SearchPushServeException, psycopg2.Warning/Error. | Handles Local Transferring request. | [
"Handles",
"Local",
"Transferring",
"request",
"."
] | def HandleLocalTransferRequest(self, request, response):
"""Handles Local Transferring request.
Args:
request: request object.
response: response object.
Raises:
SearchPushServeException, psycopg2.Warning/Error.
"""
logger.debug("HandleLocalTransferRequest...")
src_path = request.GetParameter(constants.FILE_PATH)
dest_path = request.GetParameter(constants.DEST_FILE_PATH)
if (not src_path) or (not dest_path):
raise exceptions.SearchPushServeException(
"HandleLocalTransferRequest: Missing src/dest paths")
src_path = os.path.normpath(src_path)
dest_path = os.path.normpath(dest_path)
logger.debug("HandleLocalTransferRequest: %s to %s", src_path, dest_path)
force_copy = request.IsForceCopy()
prefer_copy = request.IsPreferCopy()
if serve_utils.LocalTransfer(src_path, dest_path,
force_copy, prefer_copy, self.allow_symlinks):
http_io.ResponseWriter.AddBodyElement(
response, constants.HDR_STATUS_CODE, constants.STATUS_SUCCESS)
else:
raise exceptions.SearchPushServeException(
"Local transfer FAILED: from %s to %s" % (src_path, dest_path)) | [
"def",
"HandleLocalTransferRequest",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"logger",
".",
"debug",
"(",
"\"HandleLocalTransferRequest...\"",
")",
"src_path",
"=",
"request",
".",
"GetParameter",
"(",
"constants",
".",
"FILE_PATH",
")",
"dest_path... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/push/search/core/search_push_manager.py#L415-L444 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_collections_abc.py | python | MutableMapping.update | (*args, **kwds) | D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v | D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v | [
"D",
".",
"update",
"(",
"[",
"E",
"]",
"**",
"F",
")",
"-",
">",
"None",
".",
"Update",
"D",
"from",
"mapping",
"/",
"iterable",
"E",
"and",
"F",
".",
"If",
"E",
"present",
"and",
"has",
"a",
".",
"keys",
"()",
"method",
"does",
":",
"for",
... | def update(*args, **kwds):
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v
'''
if not args:
raise TypeError("descriptor 'update' of 'MutableMapping' object "
"needs an argument")
self, *args = args
if len(args) > 1:
raise TypeError('update expected at most 1 arguments, got %d' %
len(args))
if args:
other = args[0]
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value | [
"def",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"not",
"args",
":",
"raise",
"TypeError",
"(",
"\"descriptor 'update' of 'MutableMapping' object \"",
"\"needs an argument\"",
")",
"self",
",",
"",
"*",
"args",
"=",
"args",
"if",
"le... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_collections_abc.py#L824-L849 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | MenuItemList_iterator.next | (*args, **kwargs) | return _core_.MenuItemList_iterator_next(*args, **kwargs) | next(self) -> MenuItem | next(self) -> MenuItem | [
"next",
"(",
"self",
")",
"-",
">",
"MenuItem"
] | def next(*args, **kwargs):
"""next(self) -> MenuItem"""
return _core_.MenuItemList_iterator_next(*args, **kwargs) | [
"def",
"next",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MenuItemList_iterator_next",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L11954-L11956 | |
infinisql/infinisql | 6e858e142196e20b6779e1ee84c4a501e246c1f8 | manager/infinisqlmgr/getifaddrs.py | python | getifaddrs | () | Wraps the C getifaddrs call, returns a list of pythonic ifaddrs | Wraps the C getifaddrs call, returns a list of pythonic ifaddrs | [
"Wraps",
"the",
"C",
"getifaddrs",
"call",
"returns",
"a",
"list",
"of",
"pythonic",
"ifaddrs"
] | def getifaddrs():
'''Wraps the C getifaddrs call, returns a list of pythonic ifaddrs'''
ifap = POINTER(struct_ifaddrs)()
result = _getifaddrs(pointer(ifap))
if result == -1:
raise OSError(get_errno())
elif result == 0:
pass
else:
assert False, result
del result
try:
retval = []
for ifa in ifap_iter(ifap):
family, addr = pythonize_sockaddr(ifa.ifa_addr.contents)
retval.append(py_ifaddrs(
name=ifa.ifa_name,
family=family,
flags=ifa.ifa_flags,
addr=addr,
netmask=pythonize_sockaddr_for_netmask(ifa.ifa_netmask.contents) if ifa.ifa_netmask else None,))
return retval
finally:
_freeifaddrs(ifap) | [
"def",
"getifaddrs",
"(",
")",
":",
"ifap",
"=",
"POINTER",
"(",
"struct_ifaddrs",
")",
"(",
")",
"result",
"=",
"_getifaddrs",
"(",
"pointer",
"(",
"ifap",
")",
")",
"if",
"result",
"==",
"-",
"1",
":",
"raise",
"OSError",
"(",
"get_errno",
"(",
")"... | https://github.com/infinisql/infinisql/blob/6e858e142196e20b6779e1ee84c4a501e246c1f8/manager/infinisqlmgr/getifaddrs.py#L141-L164 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.GetUseVerticalScrollBar | (*args, **kwargs) | return _stc.StyledTextCtrl_GetUseVerticalScrollBar(*args, **kwargs) | GetUseVerticalScrollBar(self) -> bool
Is the vertical scroll bar visible? | GetUseVerticalScrollBar(self) -> bool | [
"GetUseVerticalScrollBar",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetUseVerticalScrollBar(*args, **kwargs):
"""
GetUseVerticalScrollBar(self) -> bool
Is the vertical scroll bar visible?
"""
return _stc.StyledTextCtrl_GetUseVerticalScrollBar(*args, **kwargs) | [
"def",
"GetUseVerticalScrollBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetUseVerticalScrollBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L4244-L4250 | |
tomahawk-player/tomahawk-resolvers | 7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d | archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/decoder.py | python | _StructPackDecoder | (wire_type, format) | return _SimpleDecoder(wire_type, InnerDecode) | Return a constructor for a decoder for a fixed-width field.
Args:
wire_type: The field's wire type.
format: The format string to pass to struct.unpack(). | Return a constructor for a decoder for a fixed-width field. | [
"Return",
"a",
"constructor",
"for",
"a",
"decoder",
"for",
"a",
"fixed",
"-",
"width",
"field",
"."
] | def _StructPackDecoder(wire_type, format):
"""Return a constructor for a decoder for a fixed-width field.
Args:
wire_type: The field's wire type.
format: The format string to pass to struct.unpack().
"""
value_size = struct.calcsize(format)
local_unpack = struct.unpack
# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
# not enough to make a significant difference.
# Note that we expect someone up-stack to catch struct.error and convert
# it to _DecodeError -- this way we don't have to set up exception-
# handling blocks every time we parse one value.
def InnerDecode(buffer, pos):
new_pos = pos + value_size
result = local_unpack(format, buffer[pos:new_pos])[0]
return (result, new_pos)
return _SimpleDecoder(wire_type, InnerDecode) | [
"def",
"_StructPackDecoder",
"(",
"wire_type",
",",
"format",
")",
":",
"value_size",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"local_unpack",
"=",
"struct",
".",
"unpack",
"# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but",
"# not ... | https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/decoder.py#L254-L276 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py | python | Bits._setint | (self, int_, length=None) | Reset the bitstring to have given signed int interpretation. | Reset the bitstring to have given signed int interpretation. | [
"Reset",
"the",
"bitstring",
"to",
"have",
"given",
"signed",
"int",
"interpretation",
"."
] | def _setint(self, int_, length=None):
"""Reset the bitstring to have given signed int interpretation."""
# If no length given, and we've previously been given a length, use it.
if length is None and hasattr(self, 'len') and self.len != 0:
length = self.len
if length is None or length == 0:
raise CreationError("A non-zero length must be specified with an int initialiser.")
if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)):
raise CreationError("{0} is too large a signed integer for a bitstring of length {1}. "
"The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)),
(1 << (length - 1)) - 1)
if int_ >= 0:
self._setuint(int_, length)
return
# TODO: We should decide whether to just use the _setuint, or to do the bit flipping,
# based upon which will be quicker. If the -ive number is less than half the maximum
# possible then it's probably quicker to do the bit flipping...
# Do the 2's complement thing. Add one, set to minus number, then flip bits.
int_ += 1
self._setuint(-int_, length)
self._invert_all() | [
"def",
"_setint",
"(",
"self",
",",
"int_",
",",
"length",
"=",
"None",
")",
":",
"# If no length given, and we've previously been given a length, use it.",
"if",
"length",
"is",
"None",
"and",
"hasattr",
"(",
"self",
",",
"'len'",
")",
"and",
"self",
".",
"len"... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L1406-L1427 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/utils/path.py | python | unquote_filename | (name, win32=(sys.platform=='win32')) | return name | On Windows, remove leading and trailing quotes from filenames.
This function has been deprecated and should not be used any more:
unquoting is now taken care of by :func:`IPython.utils.process.arg_split`. | On Windows, remove leading and trailing quotes from filenames. | [
"On",
"Windows",
"remove",
"leading",
"and",
"trailing",
"quotes",
"from",
"filenames",
"."
] | def unquote_filename(name, win32=(sys.platform=='win32')):
""" On Windows, remove leading and trailing quotes from filenames.
This function has been deprecated and should not be used any more:
unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
"""
warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
"be used anymore", DeprecationWarning, stacklevel=2)
if win32:
if name.startswith(("'", '"')) and name.endswith(("'", '"')):
name = name[1:-1]
return name | [
"def",
"unquote_filename",
"(",
"name",
",",
"win32",
"=",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
")",
":",
"warn",
"(",
"\"'unquote_filename' is deprecated since IPython 5.0 and should not \"",
"\"be used anymore\"",
",",
"DeprecationWarning",
",",
"stackle... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/path.py#L73-L84 | |
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/sets/sets.py | python | Set.__hash__ | (self) | A Set cannot be hashed. | A Set cannot be hashed. | [
"A",
"Set",
"cannot",
"be",
"hashed",
"."
] | def __hash__(self):
"""A Set cannot be hashed."""
# We inherit object.__hash__, so we must deny this explicitly
raise TypeError, "Can't hash a Set, only an ImmutableSet." | [
"def",
"__hash__",
"(",
"self",
")",
":",
"# We inherit object.__hash__, so we must deny this explicitly",
"raise",
"TypeError",
",",
"\"Can't hash a Set, only an ImmutableSet.\""
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/sets/sets.py#L438-L441 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py | python | Dir._morph | (self) | Turn a file system Node (either a freshly initialized directory
object or a separate Entry object) into a proper directory object.
Set up this directory's entries and hook it into the file
system tree. Specify that directories (this Node) don't use
signatures for calculating whether they're current. | Turn a file system Node (either a freshly initialized directory
object or a separate Entry object) into a proper directory object. | [
"Turn",
"a",
"file",
"system",
"Node",
"(",
"either",
"a",
"freshly",
"initialized",
"directory",
"object",
"or",
"a",
"separate",
"Entry",
"object",
")",
"into",
"a",
"proper",
"directory",
"object",
"."
] | def _morph(self):
"""Turn a file system Node (either a freshly initialized directory
object or a separate Entry object) into a proper directory object.
Set up this directory's entries and hook it into the file
system tree. Specify that directories (this Node) don't use
signatures for calculating whether they're current.
"""
self.repositories = []
self.srcdir = None
self.entries = {}
self.entries['.'] = self
self.entries['..'] = self.dir
self.cwd = self
self.searched = 0
self._sconsign = None
self.variant_dirs = []
self.root = self.dir.root
self.changed_since_last_build = 3
self._func_sconsign = 1
self._func_exists = 2
self._func_get_contents = 2
self._abspath = SCons.Util.silent_intern(self.dir.entry_abspath(self.name))
self._labspath = SCons.Util.silent_intern(self.dir.entry_labspath(self.name))
if self.dir._path == '.':
self._path = SCons.Util.silent_intern(self.name)
else:
self._path = SCons.Util.silent_intern(self.dir.entry_path(self.name))
if self.dir._tpath == '.':
self._tpath = SCons.Util.silent_intern(self.name)
else:
self._tpath = SCons.Util.silent_intern(self.dir.entry_tpath(self.name))
self._path_elements = self.dir._path_elements + [self]
# For directories, we make a difference between the directory
# 'name' and the directory 'dirname'. The 'name' attribute is
# used when we need to print the 'name' of the directory or
# when we it is used as the last part of a path. The 'dirname'
# is used when the directory is not the last element of the
# path. The main reason for making that distinction is that
# for RoorDir's the dirname can not be easily inferred from
# the name. For example, we have to add a '/' after a drive
# letter but not after a UNC path prefix ('//').
self.dirname = self.name + OS_SEP
# Don't just reset the executor, replace its action list,
# because it might have some pre-or post-actions that need to
# be preserved.
#
# But don't reset the executor if there is a non-null executor
# attached already. The existing executor might have other
# targets, in which case replacing the action list with a
# Mkdir action is a big mistake.
if not hasattr(self, 'executor'):
self.builder = get_MkdirBuilder()
self.get_executor().set_action_list(self.builder.action)
else:
# Prepend MkdirBuilder action to existing action list
l = self.get_executor().action_list
a = get_MkdirBuilder().action
l.insert(0, a)
self.get_executor().set_action_list(l) | [
"def",
"_morph",
"(",
"self",
")",
":",
"self",
".",
"repositories",
"=",
"[",
"]",
"self",
".",
"srcdir",
"=",
"None",
"self",
".",
"entries",
"=",
"{",
"}",
"self",
".",
"entries",
"[",
"'.'",
"]",
"=",
"self",
"self",
".",
"entries",
"[",
"'..... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Node/FS.py#L1539-L1603 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/prefdlg.py | python | DocSyntaxPanel.OnSynChange | (evt) | Handles the events from checkbox and choice control for this panel
@param evt: event that called this handler
@postcondition: all text controls are updated to reflect the changes
made in these controls. | Handles the events from checkbox and choice control for this panel
@param evt: event that called this handler
@postcondition: all text controls are updated to reflect the changes
made in these controls. | [
"Handles",
"the",
"events",
"from",
"checkbox",
"and",
"choice",
"control",
"for",
"this",
"panel",
"@param",
"evt",
":",
"event",
"that",
"called",
"this",
"handler",
"@postcondition",
":",
"all",
"text",
"controls",
"are",
"updated",
"to",
"reflect",
"the",
... | def OnSynChange(evt):
"""Handles the events from checkbox and choice control for this panel
@param evt: event that called this handler
@postcondition: all text controls are updated to reflect the changes
made in these controls.
"""
e_id = evt.GetId()
e_obj = evt.GetEventObject()
if e_id in (ed_glob.ID_PREF_SYNTHEME, ed_glob.ID_SYNTAX):
Profile_Set(ed_glob.ID_2_PROF[e_id], e_obj.GetValue())
else:
evt.Skip() | [
"def",
"OnSynChange",
"(",
"evt",
")",
":",
"e_id",
"=",
"evt",
".",
"GetId",
"(",
")",
"e_obj",
"=",
"evt",
".",
"GetEventObject",
"(",
")",
"if",
"e_id",
"in",
"(",
"ed_glob",
".",
"ID_PREF_SYNTHEME",
",",
"ed_glob",
".",
"ID_SYNTAX",
")",
":",
"Pr... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/prefdlg.py#L1174-L1186 | ||
google/perfetto | fe68c7a7f7657aa71ced68efb126dcac4107c745 | tools/write_version_header.py | python | get_latest_release | (changelog_path) | Returns a string like 'v9.0'.
It does so by searching the latest version mentioned in the CHANGELOG. | Returns a string like 'v9.0'. | [
"Returns",
"a",
"string",
"like",
"v9",
".",
"0",
"."
] | def get_latest_release(changelog_path):
"""Returns a string like 'v9.0'.
It does so by searching the latest version mentioned in the CHANGELOG."""
if not changelog_path:
if os.path.exists('CHANGELOG'):
changelog_path = 'CHANGELOG'
else:
changelog_path = os.path.join(PROJECT_ROOT, 'CHANGELOG')
with open(changelog_path) as f:
for line in f.readlines():
m = re.match('^(v\d+[.]\d+)\s.*$', line)
if m is not None:
return m.group(1)
raise Exception('Failed to fetch Perfetto version from %s' % changelog_path) | [
"def",
"get_latest_release",
"(",
"changelog_path",
")",
":",
"if",
"not",
"changelog_path",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'CHANGELOG'",
")",
":",
"changelog_path",
"=",
"'CHANGELOG'",
"else",
":",
"changelog_path",
"=",
"os",
".",
"path... | https://github.com/google/perfetto/blob/fe68c7a7f7657aa71ced68efb126dcac4107c745/tools/write_version_header.py#L41-L55 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/SConsOptions.py | python | SConsOptionGroup.format_help | (self, formatter) | return result | Format an option group's help text, outdenting the title so it's
flush with the "SCons Options" title we print at the top. | Format an option group's help text, outdenting the title so it's
flush with the "SCons Options" title we print at the top. | [
"Format",
"an",
"option",
"group",
"s",
"help",
"text",
"outdenting",
"the",
"title",
"so",
"it",
"s",
"flush",
"with",
"the",
"SCons",
"Options",
"title",
"we",
"print",
"at",
"the",
"top",
"."
] | def format_help(self, formatter):
"""
Format an option group's help text, outdenting the title so it's
flush with the "SCons Options" title we print at the top.
"""
formatter.dedent()
result = formatter.format_heading(self.title)
formatter.indent()
result = result + optparse.OptionContainer.format_help(self, formatter)
return result | [
"def",
"format_help",
"(",
"self",
",",
"formatter",
")",
":",
"formatter",
".",
"dedent",
"(",
")",
"result",
"=",
"formatter",
".",
"format_heading",
"(",
"self",
".",
"title",
")",
"formatter",
".",
"indent",
"(",
")",
"result",
"=",
"result",
"+",
... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Script/SConsOptions.py#L256-L265 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-fft/python/fft/logpwrfft.py | python | _logpwrfft_base.sample_rate | (self) | return self._sd.sample_rate() | Return the current sample rate. | Return the current sample rate. | [
"Return",
"the",
"current",
"sample",
"rate",
"."
] | def sample_rate(self):
"""
Return the current sample rate.
"""
return self._sd.sample_rate() | [
"def",
"sample_rate",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sd",
".",
"sample_rate",
"(",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-fft/python/fft/logpwrfft.py#L126-L130 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/runpy.py | python | run_path | (path_name, init_globals=None, run_name=None) | Execute code located at the specified filesystem location
Returns the resulting top level namespace dictionary
The file path may refer directly to a Python script (i.e.
one that could be directly executed with execfile) or else
it may refer to a zipfile or directory containing a top
level __main__.py script. | Execute code located at the specified filesystem location | [
"Execute",
"code",
"located",
"at",
"the",
"specified",
"filesystem",
"location"
] | def run_path(path_name, init_globals=None, run_name=None):
"""Execute code located at the specified filesystem location
Returns the resulting top level namespace dictionary
The file path may refer directly to a Python script (i.e.
one that could be directly executed with execfile) or else
it may refer to a zipfile or directory containing a top
level __main__.py script.
"""
if run_name is None:
run_name = "<run_path>"
importer = _get_importer(path_name)
if isinstance(importer, imp.NullImporter):
# Not a valid sys.path entry, so run the code directly
# execfile() doesn't help as we want to allow compiled files
code = _get_code_from_file(path_name)
return _run_module_code(code, init_globals, run_name, path_name)
else:
# Importer is defined for path, so add it to
# the start of sys.path
sys.path.insert(0, path_name)
try:
# Here's where things are a little different from the run_module
# case. There, we only had to replace the module in sys while the
# code was running and doing so was somewhat optional. Here, we
# have no choice and we have to remove it even while we read the
# code. If we don't do this, a __loader__ attribute in the
# existing __main__ module may prevent location of the new module.
main_name = "__main__"
saved_main = sys.modules[main_name]
del sys.modules[main_name]
try:
mod_name, loader, code, fname = _get_main_module_details()
finally:
sys.modules[main_name] = saved_main
pkg_name = ""
with _TempModule(run_name) as temp_module, \
_ModifiedArgv0(path_name):
mod_globals = temp_module.module.__dict__
return _run_code(code, mod_globals, init_globals,
run_name, fname, loader, pkg_name).copy()
finally:
try:
sys.path.remove(path_name)
except ValueError:
pass | [
"def",
"run_path",
"(",
"path_name",
",",
"init_globals",
"=",
"None",
",",
"run_name",
"=",
"None",
")",
":",
"if",
"run_name",
"is",
"None",
":",
"run_name",
"=",
"\"<run_path>\"",
"importer",
"=",
"_get_importer",
"(",
"path_name",
")",
"if",
"isinstance"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/runpy.py#L223-L269 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextBuffer.BeginFont | (*args, **kwargs) | return _richtext.RichTextBuffer_BeginFont(*args, **kwargs) | BeginFont(self, Font font) -> bool | BeginFont(self, Font font) -> bool | [
"BeginFont",
"(",
"self",
"Font",
"font",
")",
"-",
">",
"bool"
] | def BeginFont(*args, **kwargs):
"""BeginFont(self, Font font) -> bool"""
return _richtext.RichTextBuffer_BeginFont(*args, **kwargs) | [
"def",
"BeginFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_BeginFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2365-L2367 | |
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | support/cpplint.py | python | _ClassifyInclude | (fileinfo, include, is_system) | return _OTHER_HEADER | Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER | Figures out what kind of header 'include' is. | [
"Figures",
"out",
"what",
"kind",
"of",
"header",
"include",
"is",
"."
] | def _ClassifyInclude(fileinfo, include, is_system):
"""Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER
"""
# This is a list of all standard c++ header files, except
# those already checked for above.
is_cpp_h = include in _CPP_HEADERS
if is_system:
if is_cpp_h:
return _CPP_SYS_HEADER
else:
return _C_SYS_HEADER
# If the target file and the include we're checking share a
# basename when we drop common extensions, and the include
# lives in . , then it's likely to be owned by the target file.
target_dir, target_base = (
os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
if target_base == include_base and (
include_dir == target_dir or
include_dir == os.path.normpath(target_dir + '/../public')):
return _LIKELY_MY_HEADER
# If the target and include share some initial basename
# component, it's possible the target is implementing the
# include, so it's allowed to be first, but we'll never
# complain if it's not there.
target_first_component = _RE_FIRST_COMPONENT.match(target_base)
include_first_component = _RE_FIRST_COMPONENT.match(include_base)
if (target_first_component and include_first_component and
target_first_component.group(0) ==
include_first_component.group(0)):
return _POSSIBLE_MY_HEADER
return _OTHER_HEADER | [
"def",
"_ClassifyInclude",
"(",
"fileinfo",
",",
"include",
",",
"is_system",
")",
":",
"# This is a list of all standard c++ header files, except",
"# those already checked for above.",
"is_cpp_h",
"=",
"include",
"in",
"_CPP_HEADERS",
"if",
"is_system",
":",
"if",
"is_cpp... | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L4466-L4522 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/setup.py | python | find_classifiers | (docs) | return [] | Determine classifiers from CLASSIFIERS
:return: List of classifiers (``['classifier', ...]``)
:rtype: ``list`` | Determine classifiers from CLASSIFIERS | [
"Determine",
"classifiers",
"from",
"CLASSIFIERS"
] | def find_classifiers(docs):
"""
Determine classifiers from CLASSIFIERS
:return: List of classifiers (``['classifier', ...]``)
:rtype: ``list``
"""
filename = docs.get('meta.classifiers', 'CLASSIFIERS').strip()
if filename and _os.path.isfile(filename):
fp = open(filename, encoding='utf-8')
try:
content = fp.read()
finally:
fp.close()
content = [item.strip() for item in content.splitlines()]
return [item for item in content if item and not item.startswith('#')]
return [] | [
"def",
"find_classifiers",
"(",
"docs",
")",
":",
"filename",
"=",
"docs",
".",
"get",
"(",
"'meta.classifiers'",
",",
"'CLASSIFIERS'",
")",
".",
"strip",
"(",
")",
"if",
"filename",
"and",
"_os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/setup.py#L120-L136 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xpathParserContext.xpathFalseFunction | (self, nargs) | Implement the false() XPath function boolean false() | Implement the false() XPath function boolean false() | [
"Implement",
"the",
"false",
"()",
"XPath",
"function",
"boolean",
"false",
"()"
] | def xpathFalseFunction(self, nargs):
"""Implement the false() XPath function boolean false() """
libxml2mod.xmlXPathFalseFunction(self._o, nargs) | [
"def",
"xpathFalseFunction",
"(",
"self",
",",
"nargs",
")",
":",
"libxml2mod",
".",
"xmlXPathFalseFunction",
"(",
"self",
".",
"_o",
",",
"nargs",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L7510-L7512 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/tools/transformers/fusion_embedlayer.py | python | FusionEmbedLayerNoMask.fuse_distilbert | (self, layernorm, add_before_layernorm, input_name_to_nodes, output_name_to_node) | return True | Fuse embedding layer for DistilBert
Args:
layernorm (NodeProto): node of LayerNormalization or SkipLayerNormalization
add_before_layernorm (NodeProto): the Add node before LayerNormalization, or the SkipLayerNormalization itself
input_name_to_nodes (Dict[str, List[NodeProto]]): map from input name to nodes
output_name_to_node (Dict[str, List[NodeProto]]): map from output name to nodes | Fuse embedding layer for DistilBert
Args:
layernorm (NodeProto): node of LayerNormalization or SkipLayerNormalization
add_before_layernorm (NodeProto): the Add node before LayerNormalization, or the SkipLayerNormalization itself
input_name_to_nodes (Dict[str, List[NodeProto]]): map from input name to nodes
output_name_to_node (Dict[str, List[NodeProto]]): map from output name to nodes | [
"Fuse",
"embedding",
"layer",
"for",
"DistilBert",
"Args",
":",
"layernorm",
"(",
"NodeProto",
")",
":",
"node",
"of",
"LayerNormalization",
"or",
"SkipLayerNormalization",
"add_before_layernorm",
"(",
"NodeProto",
")",
":",
"the",
"Add",
"node",
"before",
"LayerN... | def fuse_distilbert(self, layernorm, add_before_layernorm, input_name_to_nodes, output_name_to_node):
"""Fuse embedding layer for DistilBert
Args:
layernorm (NodeProto): node of LayerNormalization or SkipLayerNormalization
add_before_layernorm (NodeProto): the Add node before LayerNormalization, or the SkipLayerNormalization itself
input_name_to_nodes (Dict[str, List[NodeProto]]): map from input name to nodes
output_name_to_node (Dict[str, List[NodeProto]]): map from output name to nodes
"""
# DistilBert has no segment embedding, subgraph pattern is like
# input_ids
# | \
# | (position_embedding_subgraph)
# | |
# Gather Gather
# \ /
# Add
# |
# LayerNormalization
two_gather = self.match_two_gather(add_before_layernorm)
if two_gather is None:
return False
word_embedding_gather, position_embedding_gather = two_gather
input_ids = word_embedding_gather.input[1]
if not self.check_attention_subgraph(layernorm, input_name_to_nodes, is_distil_bert=True):
return False
if not self.match_position_embedding(position_embedding_gather, input_ids, output_name_to_node):
return False
if not self.check_embedding(word_embedding_gather, None, position_embedding_gather):
return False
embed_node = self.create_fused_node(input_ids, layernorm, word_embedding_gather, position_embedding_gather,
None)
self.finish_fusion(layernorm, embed_node)
return True | [
"def",
"fuse_distilbert",
"(",
"self",
",",
"layernorm",
",",
"add_before_layernorm",
",",
"input_name_to_nodes",
",",
"output_name_to_node",
")",
":",
"# DistilBert has no segment embedding, subgraph pattern is like",
"# input_ids",
"# | \\",
"# | (pos... | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/transformers/fusion_embedlayer.py#L497-L535 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/msvs.py | python | msvs_generator.get_enabled_vs_configurations | (self, platforms_list, enabled_specs) | return list(sorted(vs_configurations)) | Base on the enabled specs, build up a list of all the configurations | Base on the enabled specs, build up a list of all the configurations | [
"Base",
"on",
"the",
"enabled",
"specs",
"build",
"up",
"a",
"list",
"of",
"all",
"the",
"configurations"
] | def get_enabled_vs_configurations(self, platforms_list, enabled_specs):
"""
Base on the enabled specs, build up a list of all the configurations
"""
# Go through each of platforms and collect the common configurations
platform_configurations_set = set()
for platform in platforms_list:
platform_config_details = platform.get_configuration_details()
for platform_config_detail in platform_config_details:
platform_configurations_set.add((platform_config_detail.config_name(), platform_config_detail))
platform_configurations_list = list(platform_configurations_set)
platform_configurations_list.sort(key=lambda plat: plat[0])
vs_configurations = set()
# Each VS configuration is based on the spec at the top level
for waf_spec in enabled_specs:
vs_spec_name = self.convert_waf_spec_to_vs_spec(waf_spec)
restricted_configurations_for_spec = self.preprocess_target_configuration_list(None, None,
self.spec_configurations(
waf_spec))
exclude_test_configurations = self.spec_exclude_test_configurations(waf_spec)
exclude_monolithic_configurations = self.spec_exclude_monolithic_configurations(waf_spec)
for platform_config in platform_configurations_list:
if restricted_configurations_for_spec and platform_config[0] not in restricted_configurations_for_spec:
continue
if exclude_test_configurations and platform_config[1].is_test:
continue
if exclude_monolithic_configurations and platform_config[1].settings.is_monolithic:
continue
vs_config = VS_Configuration(vs_spec_name, waf_spec, platform_config[0])
# TODO: Make sure that there is at least one module that is defined for the platform and configuration
vs_configurations.add(vs_config)
return list(sorted(vs_configurations)) | [
"def",
"get_enabled_vs_configurations",
"(",
"self",
",",
"platforms_list",
",",
"enabled_specs",
")",
":",
"# Go through each of platforms and collect the common configurations",
"platform_configurations_set",
"=",
"set",
"(",
")",
"for",
"platform",
"in",
"platforms_list",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/msvs.py#L1828-L1865 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/jax/utils.py | python | tree_conj | (t: PyTree) | return jax.tree_map(lambda x: jax.lax.conj(x) if jnp.iscomplexobj(x) else x, t) | r"""
Conjugate all complex leaves. The real leaves are left untouched.
Args:
t: pytree | r"""
Conjugate all complex leaves. The real leaves are left untouched.
Args:
t: pytree | [
"r",
"Conjugate",
"all",
"complex",
"leaves",
".",
"The",
"real",
"leaves",
"are",
"left",
"untouched",
".",
"Args",
":",
"t",
":",
"pytree"
] | def tree_conj(t: PyTree) -> PyTree:
r"""
Conjugate all complex leaves. The real leaves are left untouched.
Args:
t: pytree
"""
return jax.tree_map(lambda x: jax.lax.conj(x) if jnp.iscomplexobj(x) else x, t) | [
"def",
"tree_conj",
"(",
"t",
":",
"PyTree",
")",
"->",
"PyTree",
":",
"return",
"jax",
".",
"tree_map",
"(",
"lambda",
"x",
":",
"jax",
".",
"lax",
".",
"conj",
"(",
"x",
")",
"if",
"jnp",
".",
"iscomplexobj",
"(",
"x",
")",
"else",
"x",
",",
... | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/jax/utils.py#L172-L178 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Node/__init__.py | python | Node.GetTag | (self, key) | return self._tags.get(key, None) | Return a user-defined tag. | Return a user-defined tag. | [
"Return",
"a",
"user",
"-",
"defined",
"tag",
"."
] | def GetTag(self, key):
""" Return a user-defined tag. """
if not self._tags:
return None
return self._tags.get(key, None) | [
"def",
"GetTag",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"self",
".",
"_tags",
":",
"return",
"None",
"return",
"self",
".",
"_tags",
".",
"get",
"(",
"key",
",",
"None",
")"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/__init__.py#L1441-L1445 | |
ucbrise/clipper | 9f25e3fc7f8edc891615e81c5b80d3d8aed72608 | clipper_admin/clipper_admin/deployers/mxnet.py | python | create_endpoint | (clipper_conn,
name,
input_type,
func,
mxnet_model,
mxnet_data_shapes,
default_output="None",
version=1,
slo_micros=3000000,
labels=None,
registry=None,
base_image="default",
num_replicas=1,
batch_size=-1,
pkgs_to_install=None) | Registers an app and deploys the provided predict function with MXNet model as
a Clipper model.
Parameters
----------
clipper_conn : :py:meth:`clipper_admin.ClipperConnection`
A ``ClipperConnection`` object connected to a running Clipper cluster.
name : str
The name to be assigned to both the registered application and deployed model.
input_type : str
The input_type to be associated with the registered app and deployed model.
One of "integers", "floats", "doubles", "bytes", or "strings".
func : function
The prediction function. Any state associated with the function will be
captured via closure capture and pickled with Cloudpickle.
mxnet_model : mxnet model object
The MXNet model to save.
the shape of the data used to train the model.
mxnet_data_shapes : list of DataDesc objects
List of DataDesc objects representing the name, shape, type and layout information
of data used for model prediction.
Required because loading serialized MXNet models involves binding, which requires
https://mxnet.incubator.apache.org/api/python/module.html#mxnet.module.BaseModule.bind
default_output : str, optional
The default output for the application. The default output will be returned whenever
an application is unable to receive a response from a model within the specified
query latency SLO (service level objective). The reason the default output was returned
is always provided as part of the prediction response object. Defaults to "None".
version : str, optional
The version to assign this model. Versions must be unique on a per-model
basis, but may be re-used across different models.
slo_micros : int, optional
The query latency objective for the application in microseconds.
This is the processing latency between Clipper receiving a request
and sending a response. It does not account for network latencies
before a request is received or after a response is sent.
If Clipper cannot process a query within the latency objective,
the default output is returned. Therefore, it is recommended that
the SLO not be set aggressively low unless absolutely necessary.
100000 (100ms) is a good starting value, but the optimal latency objective
will vary depending on the application.
labels : list(str), optional
A list of strings annotating the model. These are ignored by Clipper
and used purely for user annotations.
registry : str, optional
The Docker container registry to push the freshly built model to. Note
that if you are running Clipper on Kubernetes, this registry must be accesible
to the Kubernetes cluster in order to fetch the container from the registry.
base_image : str, optional
The base Docker image to build the new model image from. This
image should contain all code necessary to run a Clipper model
container RPC client.
num_replicas : int, optional
The number of replicas of the model to create. The number of replicas
for a model can be changed at any time with
:py:meth:`clipper.ClipperConnection.set_num_replicas`.
batch_size : int, optional
The user-defined query batch size for the model. Replicas of the model will attempt
to process at most `batch_size` queries simultaneously. They may process smaller
batches if `batch_size` queries are not immediately available.
If the default value of -1 is used, Clipper will adaptively calculate the batch size for
individual replicas of this model.
pkgs_to_install : list (of strings), optional
A list of the names of packages to install, using pip, in the container.
The names must be strings.
Note
----
Regarding `mxnet_data_shapes` parameter:
Clipper may provide the model with variable size input batches. Because MXNet can't
handle variable size input batches, we recommend setting batch size for input data
to 1, or dynamically reshaping the model with every prediction based on the current
input batch size.
More information regarding a DataDesc object can be found here:
https://mxnet.incubator.apache.org/versions/0.11.0/api/python/io.html#mxnet.io.DataDesc | Registers an app and deploys the provided predict function with MXNet model as
a Clipper model. | [
"Registers",
"an",
"app",
"and",
"deploys",
"the",
"provided",
"predict",
"function",
"with",
"MXNet",
"model",
"as",
"a",
"Clipper",
"model",
"."
] | def create_endpoint(clipper_conn,
name,
input_type,
func,
mxnet_model,
mxnet_data_shapes,
default_output="None",
version=1,
slo_micros=3000000,
labels=None,
registry=None,
base_image="default",
num_replicas=1,
batch_size=-1,
pkgs_to_install=None):
"""Registers an app and deploys the provided predict function with MXNet model as
a Clipper model.
Parameters
----------
clipper_conn : :py:meth:`clipper_admin.ClipperConnection`
A ``ClipperConnection`` object connected to a running Clipper cluster.
name : str
The name to be assigned to both the registered application and deployed model.
input_type : str
The input_type to be associated with the registered app and deployed model.
One of "integers", "floats", "doubles", "bytes", or "strings".
func : function
The prediction function. Any state associated with the function will be
captured via closure capture and pickled with Cloudpickle.
mxnet_model : mxnet model object
The MXNet model to save.
the shape of the data used to train the model.
mxnet_data_shapes : list of DataDesc objects
List of DataDesc objects representing the name, shape, type and layout information
of data used for model prediction.
Required because loading serialized MXNet models involves binding, which requires
https://mxnet.incubator.apache.org/api/python/module.html#mxnet.module.BaseModule.bind
default_output : str, optional
The default output for the application. The default output will be returned whenever
an application is unable to receive a response from a model within the specified
query latency SLO (service level objective). The reason the default output was returned
is always provided as part of the prediction response object. Defaults to "None".
version : str, optional
The version to assign this model. Versions must be unique on a per-model
basis, but may be re-used across different models.
slo_micros : int, optional
The query latency objective for the application in microseconds.
This is the processing latency between Clipper receiving a request
and sending a response. It does not account for network latencies
before a request is received or after a response is sent.
If Clipper cannot process a query within the latency objective,
the default output is returned. Therefore, it is recommended that
the SLO not be set aggressively low unless absolutely necessary.
100000 (100ms) is a good starting value, but the optimal latency objective
will vary depending on the application.
labels : list(str), optional
A list of strings annotating the model. These are ignored by Clipper
and used purely for user annotations.
registry : str, optional
The Docker container registry to push the freshly built model to. Note
that if you are running Clipper on Kubernetes, this registry must be accesible
to the Kubernetes cluster in order to fetch the container from the registry.
base_image : str, optional
The base Docker image to build the new model image from. This
image should contain all code necessary to run a Clipper model
container RPC client.
num_replicas : int, optional
The number of replicas of the model to create. The number of replicas
for a model can be changed at any time with
:py:meth:`clipper.ClipperConnection.set_num_replicas`.
batch_size : int, optional
The user-defined query batch size for the model. Replicas of the model will attempt
to process at most `batch_size` queries simultaneously. They may process smaller
batches if `batch_size` queries are not immediately available.
If the default value of -1 is used, Clipper will adaptively calculate the batch size for
individual replicas of this model.
pkgs_to_install : list (of strings), optional
A list of the names of packages to install, using pip, in the container.
The names must be strings.
Note
----
Regarding `mxnet_data_shapes` parameter:
Clipper may provide the model with variable size input batches. Because MXNet can't
handle variable size input batches, we recommend setting batch size for input data
to 1, or dynamically reshaping the model with every prediction based on the current
input batch size.
More information regarding a DataDesc object can be found here:
https://mxnet.incubator.apache.org/versions/0.11.0/api/python/io.html#mxnet.io.DataDesc
"""
clipper_conn.register_application(name, input_type, default_output,
slo_micros)
deploy_mxnet_model(clipper_conn, name, version, input_type, func,
mxnet_model, mxnet_data_shapes, base_image, labels,
registry, num_replicas, batch_size, pkgs_to_install)
clipper_conn.link_model_to_app(name, name) | [
"def",
"create_endpoint",
"(",
"clipper_conn",
",",
"name",
",",
"input_type",
",",
"func",
",",
"mxnet_model",
",",
"mxnet_data_shapes",
",",
"default_output",
"=",
"\"None\"",
",",
"version",
"=",
"1",
",",
"slo_micros",
"=",
"3000000",
",",
"labels",
"=",
... | https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/deployers/mxnet.py#L17-L115 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/crf/python/ops/crf.py | python | crf_decode | (potentials, transition_params, sequence_length) | return decode_tags, best_score | Decode the highest scoring sequence of tags in TensorFlow.
This is a function for tensor.
Args:
potentials: A [batch_size, max_seq_len, num_tags] tensor, matrix of
unary potentials.
transition_params: A [num_tags, num_tags] tensor, matrix of
binary potentials.
sequence_length: A [batch_size] tensor, containing sequence lengths.
Returns:
decode_tags: A [batch_size, max_seq_len] tensor, with dtype tf.int32.
Contains the highest scoring tag indicies.
best_score: A [batch_size] tensor, containing the score of decode_tags. | Decode the highest scoring sequence of tags in TensorFlow. | [
"Decode",
"the",
"highest",
"scoring",
"sequence",
"of",
"tags",
"in",
"TensorFlow",
"."
] | def crf_decode(potentials, transition_params, sequence_length):
"""Decode the highest scoring sequence of tags in TensorFlow.
This is a function for tensor.
Args:
potentials: A [batch_size, max_seq_len, num_tags] tensor, matrix of
unary potentials.
transition_params: A [num_tags, num_tags] tensor, matrix of
binary potentials.
sequence_length: A [batch_size] tensor, containing sequence lengths.
Returns:
decode_tags: A [batch_size, max_seq_len] tensor, with dtype tf.int32.
Contains the highest scoring tag indicies.
best_score: A [batch_size] tensor, containing the score of decode_tags.
"""
# For simplicity, in shape comments, denote:
# 'batch_size' by 'B', 'max_seq_len' by 'T' , 'num_tags' by 'O' (output).
num_tags = potentials.get_shape()[2].value
# Computes forward decoding. Get last score and backpointers.
crf_fwd_cell = CrfDecodeForwardRnnCell(transition_params)
initial_state = array_ops.slice(potentials, [0, 0, 0], [-1, 1, -1])
initial_state = array_ops.squeeze(initial_state, axis=[1]) # [B, O]
inputs = array_ops.slice(potentials, [0, 1, 0], [-1, -1, -1]) # [B, T-1, O]
backpointers, last_score = rnn.dynamic_rnn(
crf_fwd_cell,
inputs=inputs,
sequence_length=sequence_length - 1,
initial_state=initial_state,
time_major=False,
dtype=dtypes.int32) # [B, T - 1, O], [B, O]
backpointers = gen_array_ops.reverse_sequence(
backpointers, sequence_length - 1, seq_dim=1) # [B, T-1, O]
# Computes backward decoding. Extract tag indices from backpointers.
crf_bwd_cell = CrfDecodeBackwardRnnCell(num_tags)
initial_state = math_ops.cast(math_ops.argmax(last_score, axis=1),
dtype=dtypes.int32) # [B]
initial_state = array_ops.expand_dims(initial_state, axis=-1) # [B, 1]
decode_tags, _ = rnn.dynamic_rnn(
crf_bwd_cell,
inputs=backpointers,
sequence_length=sequence_length - 1,
initial_state=initial_state,
time_major=False,
dtype=dtypes.int32) # [B, T - 1, 1]
decode_tags = array_ops.squeeze(decode_tags, axis=[2]) # [B, T - 1]
decode_tags = array_ops.concat([initial_state, decode_tags], axis=1) # [B, T]
decode_tags = gen_array_ops.reverse_sequence(
decode_tags, sequence_length, seq_dim=1) # [B, T]
best_score = math_ops.reduce_max(last_score, axis=1) # [B]
return decode_tags, best_score | [
"def",
"crf_decode",
"(",
"potentials",
",",
"transition_params",
",",
"sequence_length",
")",
":",
"# For simplicity, in shape comments, denote:",
"# 'batch_size' by 'B', 'max_seq_len' by 'T' , 'num_tags' by 'O' (output).",
"num_tags",
"=",
"potentials",
".",
"get_shape",
"(",
"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/crf/python/ops/crf.py#L423-L477 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | PointCloud.setDepthImage_d | (self, intrinsics: "double const [4]", np_array2: "double *", depth_scale: "double") | return _robotsim.PointCloud_setDepthImage_d(self, intrinsics, np_array2, depth_scale) | r"""
setDepthImage_d(PointCloud self, double const [4] intrinsics, double * np_array2, double depth_scale)
Sets a structured point cloud from a depth image. [fx,fy,cx,cy] are the
intrinsics parameters. The depth is given as a size hxw array, top to bottom. | r"""
setDepthImage_d(PointCloud self, double const [4] intrinsics, double * np_array2, double depth_scale) | [
"r",
"setDepthImage_d",
"(",
"PointCloud",
"self",
"double",
"const",
"[",
"4",
"]",
"intrinsics",
"double",
"*",
"np_array2",
"double",
"depth_scale",
")"
] | def setDepthImage_d(self, intrinsics: "double const [4]", np_array2: "double *", depth_scale: "double") -> "void":
r"""
setDepthImage_d(PointCloud self, double const [4] intrinsics, double * np_array2, double depth_scale)
Sets a structured point cloud from a depth image. [fx,fy,cx,cy] are the
intrinsics parameters. The depth is given as a size hxw array, top to bottom.
"""
return _robotsim.PointCloud_setDepthImage_d(self, intrinsics, np_array2, depth_scale) | [
"def",
"setDepthImage_d",
"(",
"self",
",",
"intrinsics",
":",
"\"double const [4]\"",
",",
"np_array2",
":",
"\"double *\"",
",",
"depth_scale",
":",
"\"double\"",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"PointCloud_setDepthImage_d",
"(",
"self",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L1379-L1388 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/base/executioners.py | python | ParallelBarrier._target | (self, nodes, barrier, page_attributes, read, tokenize, render, write) | Target function for multiprocessing.Process() calls. | Target function for multiprocessing.Process() calls. | [
"Target",
"function",
"for",
"multiprocessing",
".",
"Process",
"()",
"calls",
"."
] | def _target(self, nodes, barrier, page_attributes, read, tokenize, render, write):
"""Target function for multiprocessing.Process() calls."""
if read:
for node in nodes:
self._page_content[node.uid] = self.read(node)
page_attributes[node.uid] = node.attributes
barrier.wait()
self._updateAttributes(page_attributes)
if tokenize:
for node in nodes:
mooseutils.recursive_update(node.attributes, page_attributes[node.uid])
self._page_ast[node.uid] = self.tokenize(node, self._page_content[node.uid])
page_attributes[node.uid] = node.attributes
barrier.wait()
self._updateAttributes(page_attributes)
if render:
for node in nodes:
mooseutils.recursive_update(node.attributes, page_attributes[node.uid])
self._page_result[node.uid] = self.render(node, self._page_ast[node.uid])
page_attributes[node.uid] = node.attributes
barrier.wait()
self._updateAttributes(page_attributes)
if write:
for node in nodes:
mooseutils.recursive_update(node.attributes, page_attributes[node.uid])
self.write(node, self._page_result[node.uid]) | [
"def",
"_target",
"(",
"self",
",",
"nodes",
",",
"barrier",
",",
"page_attributes",
",",
"read",
",",
"tokenize",
",",
"render",
",",
"write",
")",
":",
"if",
"read",
":",
"for",
"node",
"in",
"nodes",
":",
"self",
".",
"_page_content",
"[",
"node",
... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/base/executioners.py#L562-L594 | ||
microsoft/AirSim | 8057725712c0cd46979135396381784075ffc0f3 | PythonClient/airsim/client.py | python | VehicleClient.getLidarData | (self, lidar_name = '', vehicle_name = '') | return LidarData.from_msgpack(self.client.call('getLidarData', lidar_name, vehicle_name)) | Args:
lidar_name (str, optional): Name of Lidar to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to
Returns:
LidarData: | Args:
lidar_name (str, optional): Name of Lidar to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to | [
"Args",
":",
"lidar_name",
"(",
"str",
"optional",
")",
":",
"Name",
"of",
"Lidar",
"to",
"get",
"data",
"from",
"specified",
"in",
"settings",
".",
"json",
"vehicle_name",
"(",
"str",
"optional",
")",
":",
"Name",
"of",
"vehicle",
"to",
"which",
"the",
... | def getLidarData(self, lidar_name = '', vehicle_name = ''):
"""
Args:
lidar_name (str, optional): Name of Lidar to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to
Returns:
LidarData:
"""
return LidarData.from_msgpack(self.client.call('getLidarData', lidar_name, vehicle_name)) | [
"def",
"getLidarData",
"(",
"self",
",",
"lidar_name",
"=",
"''",
",",
"vehicle_name",
"=",
"''",
")",
":",
"return",
"LidarData",
".",
"from_msgpack",
"(",
"self",
".",
"client",
".",
"call",
"(",
"'getLidarData'",
",",
"lidar_name",
",",
"vehicle_name",
... | https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/airsim/client.py#L894-L903 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/environment.py | python | Environment._generate | (self, source, name, filename, defer_init=False) | return generate(source, self, name, filename, defer_init=defer_init,
optimized=self.optimized) | Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5 | Internal hook that can be overridden to hook a different generate
method in. | [
"Internal",
"hook",
"that",
"can",
"be",
"overridden",
"to",
"hook",
"a",
"different",
"generate",
"method",
"in",
"."
] | def _generate(self, source, name, filename, defer_init=False):
"""Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5
"""
return generate(source, self, name, filename, defer_init=defer_init,
optimized=self.optimized) | [
"def",
"_generate",
"(",
"self",
",",
"source",
",",
"name",
",",
"filename",
",",
"defer_init",
"=",
"False",
")",
":",
"return",
"generate",
"(",
"source",
",",
"self",
",",
"name",
",",
"filename",
",",
"defer_init",
"=",
"defer_init",
",",
"optimized... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/environment.py#L536-L543 | |
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py | python | FindStartOfExpressionInLine | (line, endpos, depth, startchar, endchar) | return (-1, depth) | Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line) | Find position at the matching startchar. | [
"Find",
"position",
"at",
"the",
"matching",
"startchar",
"."
] | def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar):
"""Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line)
"""
for i in xrange(endpos, -1, -1):
if line[i] == endchar:
depth += 1
elif line[i] == startchar:
depth -= 1
if depth == 0:
return (i, 0)
return (-1, depth) | [
"def",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"endpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"endpos",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"endch... | https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py#L1300-L1324 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py | python | Connection.sock_shutdown | (self, *args, **kwargs) | return self._socket.shutdown(*args, **kwargs) | Call the :meth:`shutdown` method of the underlying socket.
See :manpage:`shutdown(2)`.
:return: What the socket's shutdown() method returns | Call the :meth:`shutdown` method of the underlying socket.
See :manpage:`shutdown(2)`. | [
"Call",
"the",
":",
"meth",
":",
"shutdown",
"method",
"of",
"the",
"underlying",
"socket",
".",
"See",
":",
"manpage",
":",
"shutdown",
"(",
"2",
")",
"."
] | def sock_shutdown(self, *args, **kwargs):
"""
Call the :meth:`shutdown` method of the underlying socket.
See :manpage:`shutdown(2)`.
:return: What the socket's shutdown() method returns
"""
return self._socket.shutdown(*args, **kwargs) | [
"def",
"sock_shutdown",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_socket",
".",
"shutdown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py#L2197-L2204 | |
tkn-tub/ns3-gym | 19bfe0a583e641142609939a090a09dfc63a095f | utils/grid.py | python | GraphicRenderer.get_selection_rectangle | (self) | return(x_start, y_start, x_end - x_start, y_height) | ! Get Selection Rectangle
@param self this object
@return rectangle | ! Get Selection Rectangle | [
"!",
"Get",
"Selection",
"Rectangle"
] | def get_selection_rectangle(self):
"""! Get Selection Rectangle
@param self this object
@return rectangle
"""
y_start = self.__top_legend.get_height() + self.__data.get_height() + self.__mid_scale.get_height() + 20
y_height = self.__bot_scale.get_height() + 20
x_start = self.__bot_scale.get_position(self.__r_start)
x_end = self.__bot_scale.get_position(self.__r_end)
return(x_start, y_start, x_end - x_start, y_height) | [
"def",
"get_selection_rectangle",
"(",
"self",
")",
":",
"y_start",
"=",
"self",
".",
"__top_legend",
".",
"get_height",
"(",
")",
"+",
"self",
".",
"__data",
".",
"get_height",
"(",
")",
"+",
"self",
".",
"__mid_scale",
".",
"get_height",
"(",
")",
"+",... | https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/utils/grid.py#L1052-L1061 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/dinner-plate-stacks.py | python | DinnerPlates.pop | (self) | return self.__stks[-1].pop() | :rtype: int | :rtype: int | [
":",
"rtype",
":",
"int"
] | def pop(self):
"""
:rtype: int
"""
while self.__stks and not self.__stks[-1]:
self.__stks.pop()
if not self.__stks:
return -1
return self.__stks[-1].pop() | [
"def",
"pop",
"(",
"self",
")",
":",
"while",
"self",
".",
"__stks",
"and",
"not",
"self",
".",
"__stks",
"[",
"-",
"1",
"]",
":",
"self",
".",
"__stks",
".",
"pop",
"(",
")",
"if",
"not",
"self",
".",
"__stks",
":",
"return",
"-",
"1",
"return... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/dinner-plate-stacks.py#L34-L42 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | Frame.SetMenuBar | (*args, **kwargs) | return _windows_.Frame_SetMenuBar(*args, **kwargs) | SetMenuBar(self, MenuBar menubar) | SetMenuBar(self, MenuBar menubar) | [
"SetMenuBar",
"(",
"self",
"MenuBar",
"menubar",
")"
] | def SetMenuBar(*args, **kwargs):
"""SetMenuBar(self, MenuBar menubar)"""
return _windows_.Frame_SetMenuBar(*args, **kwargs) | [
"def",
"SetMenuBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"Frame_SetMenuBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L591-L593 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/handlers.py | python | SysLogHandler.__init__ | (self, address=('localhost', SYSLOG_UDP_PORT),
facility=LOG_USER, socktype=None) | Initialize a handler.
If address is specified as a string, a UNIX socket is used. To log to a
local syslogd, "SysLogHandler(address="/dev/log")" can be used.
If facility is not specified, LOG_USER is used. If socktype is
specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
socket type will be used. For Unix sockets, you can also specify a
socktype of None, in which case socket.SOCK_DGRAM will be used, falling
back to socket.SOCK_STREAM. | Initialize a handler. | [
"Initialize",
"a",
"handler",
"."
] | def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
facility=LOG_USER, socktype=None):
"""
Initialize a handler.
If address is specified as a string, a UNIX socket is used. To log to a
local syslogd, "SysLogHandler(address="/dev/log")" can be used.
If facility is not specified, LOG_USER is used. If socktype is
specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
socket type will be used. For Unix sockets, you can also specify a
socktype of None, in which case socket.SOCK_DGRAM will be used, falling
back to socket.SOCK_STREAM.
"""
logging.Handler.__init__(self)
self.address = address
self.facility = facility
self.socktype = socktype
if isinstance(address, basestring):
self.unixsocket = 1
self._connect_unixsocket(address)
else:
self.unixsocket = 0
if socktype is None:
socktype = socket.SOCK_DGRAM
self.socket = socket.socket(socket.AF_INET, socktype)
if socktype == socket.SOCK_STREAM:
self.socket.connect(address)
self.socktype = socktype
self.formatter = None | [
"def",
"__init__",
"(",
"self",
",",
"address",
"=",
"(",
"'localhost'",
",",
"SYSLOG_UDP_PORT",
")",
",",
"facility",
"=",
"LOG_USER",
",",
"socktype",
"=",
"None",
")",
":",
"logging",
".",
"Handler",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/handlers.py#L739-L769 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/credentials.py | python | RefreshableCredentials.get_frozen_credentials | (self) | return self._frozen_credentials | Return immutable credentials.
The ``access_key``, ``secret_key``, and ``token`` properties
on this class will always check and refresh credentials if
needed before returning the particular credentials.
This has an edge case where you can get inconsistent
credentials. Imagine this:
# Current creds are "t1"
tmp.access_key ---> expired? no, so return t1.access_key
# ---- time is now expired, creds need refreshing to "t2" ----
tmp.secret_key ---> expired? yes, refresh and return t2.secret_key
This means we're using the access key from t1 with the secret key
from t2. To fix this issue, you can request a frozen credential object
which is guaranteed not to change.
The frozen credentials returned from this method should be used
immediately and then discarded. The typical usage pattern would
be::
creds = RefreshableCredentials(...)
some_code = SomeSignerObject()
# I'm about to sign the request.
# The frozen credentials are only used for the
# duration of generate_presigned_url and will be
# immediately thrown away.
request = some_code.sign_some_request(
with_credentials=creds.get_frozen_credentials())
print("Signed request:", request) | Return immutable credentials. | [
"Return",
"immutable",
"credentials",
"."
] | def get_frozen_credentials(self):
"""Return immutable credentials.
The ``access_key``, ``secret_key``, and ``token`` properties
on this class will always check and refresh credentials if
needed before returning the particular credentials.
This has an edge case where you can get inconsistent
credentials. Imagine this:
# Current creds are "t1"
tmp.access_key ---> expired? no, so return t1.access_key
# ---- time is now expired, creds need refreshing to "t2" ----
tmp.secret_key ---> expired? yes, refresh and return t2.secret_key
This means we're using the access key from t1 with the secret key
from t2. To fix this issue, you can request a frozen credential object
which is guaranteed not to change.
The frozen credentials returned from this method should be used
immediately and then discarded. The typical usage pattern would
be::
creds = RefreshableCredentials(...)
some_code = SomeSignerObject()
# I'm about to sign the request.
# The frozen credentials are only used for the
# duration of generate_presigned_url and will be
# immediately thrown away.
request = some_code.sign_some_request(
with_credentials=creds.get_frozen_credentials())
print("Signed request:", request)
"""
self._refresh()
return self._frozen_credentials | [
"def",
"get_frozen_credentials",
"(",
"self",
")",
":",
"self",
".",
"_refresh",
"(",
")",
"return",
"self",
".",
"_frozen_credentials"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/credentials.py#L557-L592 | |
google/usd_from_gltf | 6d288cce8b68744494a226574ae1d7ba6a9c46eb | tools/ufgbatch/ufgcommon/util.py | python | enable_ansi_colors | () | Enable ANSI text colorization. | Enable ANSI text colorization. | [
"Enable",
"ANSI",
"text",
"colorization",
"."
] | def enable_ansi_colors():
"""Enable ANSI text colorization."""
# On Windows this is done via SetConsoleMode, but rather than go through the
# hassle of importing the function from a system DLL, just call the 'color'
# console command to do it for us.
if platform.system() == 'Windows':
os.system('color') | [
"def",
"enable_ansi_colors",
"(",
")",
":",
"# On Windows this is done via SetConsoleMode, but rather than go through the",
"# hassle of importing the function from a system DLL, just call the 'color'",
"# console command to do it for us.",
"if",
"platform",
".",
"system",
"(",
")",
"=="... | https://github.com/google/usd_from_gltf/blob/6d288cce8b68744494a226574ae1d7ba6a9c46eb/tools/ufgbatch/ufgcommon/util.py#L58-L64 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/value/summarizable.py | python | SummarizableValue.__init__ | (self, page, name, units, important, description, tir_label,
improvement_direction, grouping_keys) | A summarizable value result from a test. | A summarizable value result from a test. | [
"A",
"summarizable",
"value",
"result",
"from",
"a",
"test",
"."
] | def __init__(self, page, name, units, important, description, tir_label,
improvement_direction, grouping_keys):
"""A summarizable value result from a test."""
super(SummarizableValue, self).__init__(
page, name, units, important, description, tir_label, grouping_keys)
# TODO(eakuefner): uncomment this assert after Telemetry clients are fixed.
# Note: Telemetry unittests satisfy this assert.
# assert improvement_direction_module.IsValid(improvement_direction)
self._improvement_direction = improvement_direction | [
"def",
"__init__",
"(",
"self",
",",
"page",
",",
"name",
",",
"units",
",",
"important",
",",
"description",
",",
"tir_label",
",",
"improvement_direction",
",",
"grouping_keys",
")",
":",
"super",
"(",
"SummarizableValue",
",",
"self",
")",
".",
"__init__"... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/value/summarizable.py#L11-L19 | ||
sofa-framework/sofa | 70628e35a44fcc258cf8250109b5e4eba8c5abe9 | applications/plugins/PSL/python/pslparserhjson.py | python | mlscanstring | (s, end) | return (('m', str(r[0])), r[1]) | Transform the returned string from the scanner into a string tuple encoding
the type of string for further processin.
This function scans multiline string and returns ('m', "value") | Transform the returned string from the scanner into a string tuple encoding
the type of string for further processin.
This function scans multiline string and returns ('m', "value") | [
"Transform",
"the",
"returned",
"string",
"from",
"the",
"scanner",
"into",
"a",
"string",
"tuple",
"encoding",
"the",
"type",
"of",
"string",
"for",
"further",
"processin",
".",
"This",
"function",
"scans",
"multiline",
"string",
"and",
"returns",
"(",
"m",
... | def mlscanstring(s, end):
'''Transform the returned string from the scanner into a string tuple encoding
the type of string for further processin.
This function scans multiline string and returns ('m', "value")
'''
r=decoder.mlscanstring(s,end)
return (('m', str(r[0])), r[1]) | [
"def",
"mlscanstring",
"(",
"s",
",",
"end",
")",
":",
"r",
"=",
"decoder",
".",
"mlscanstring",
"(",
"s",
",",
"end",
")",
"return",
"(",
"(",
"'m'",
",",
"str",
"(",
"r",
"[",
"0",
"]",
")",
")",
",",
"r",
"[",
"1",
"]",
")"
] | https://github.com/sofa-framework/sofa/blob/70628e35a44fcc258cf8250109b5e4eba8c5abe9/applications/plugins/PSL/python/pslparserhjson.py#L144-L150 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/panelbox.py | python | PanelBoxItem.__DoLayout | (self) | Layout the control | Layout the control | [
"Layout",
"the",
"control"
] | def __DoLayout(self):
"""Layout the control"""
vsizer = wx.BoxSizer(wx.VERTICAL)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
hsizer.Add((8, 8), 0)
if self._bmp is not None:
self._bmp = wx.StaticBitmap(self, bitmap=self._bmp)
hsizer.Add(self._bmp, 0, wx.ALIGN_CENTER_VERTICAL)
hsizer.Add((5, 5), 0)
# Add Label Text
isizer = wx.BoxSizer(wx.VERTICAL)
self._label = wx.StaticText(self, label=self._label)
isizer.Add(self._label, 0, wx.ALIGN_LEFT)
if self._sub is not None:
isizer.Add((3, 3), 0)
# Add Subwindow if one is defined
if self._sub is not None:
self._sub.Reparent(self)
s_sizer = wx.BoxSizer(wx.HORIZONTAL)
s_sizer.Add(self._sub, 1, wx.EXPAND)
isizer.Add(s_sizer, 1, wx.EXPAND)
hsizer.Add(isizer, 1, wx.ALIGN_CENTER_VERTICAL)
hsizer.Add((8, 8), 0)
vsizer.AddMany([((8, 8), 0), (hsizer, 0, wx.EXPAND), ((8, 8), 0)])
self.SetSizer(vsizer) | [
"def",
"__DoLayout",
"(",
"self",
")",
":",
"vsizer",
"=",
"wx",
".",
"BoxSizer",
"(",
"wx",
".",
"VERTICAL",
")",
"hsizer",
"=",
"wx",
".",
"BoxSizer",
"(",
"wx",
".",
"HORIZONTAL",
")",
"hsizer",
".",
"Add",
"(",
"(",
"8",
",",
"8",
")",
",",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/panelbox.py#L392-L420 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/nn_ops.py | python | _LRNGradShape | (op) | return [in_grads_shape.merge_with(in_image_shape).merge_with(out_image_shape)] | Shape function for LRNGrad op. | Shape function for LRNGrad op. | [
"Shape",
"function",
"for",
"LRNGrad",
"op",
"."
] | def _LRNGradShape(op):
"""Shape function for LRNGrad op."""
in_grads_shape = op.inputs[0].get_shape().with_rank(4)
in_image_shape = op.inputs[1].get_shape().with_rank(4)
out_image_shape = op.inputs[2].get_shape().with_rank(4)
return [in_grads_shape.merge_with(in_image_shape).merge_with(out_image_shape)] | [
"def",
"_LRNGradShape",
"(",
"op",
")",
":",
"in_grads_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"4",
")",
"in_image_shape",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
".",
"get_shape",
"(",
"... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/nn_ops.py#L698-L703 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Tools/msvc.py | python | setup_msvc | (conf, versiondict) | Checks installed compilers and targets and returns the first combination from the user's
options, env, or the global supported lists that checks.
:param versiondict: dict(platform -> dict(architecture -> configuration))
:type versiondict: dict(string -> dict(string -> target_compiler)
:return: the compiler, revision, path, include dirs, library paths and target architecture
:rtype: tuple of strings | Checks installed compilers and targets and returns the first combination from the user's
options, env, or the global supported lists that checks. | [
"Checks",
"installed",
"compilers",
"and",
"targets",
"and",
"returns",
"the",
"first",
"combination",
"from",
"the",
"user",
"s",
"options",
"env",
"or",
"the",
"global",
"supported",
"lists",
"that",
"checks",
"."
] | def setup_msvc(conf, versiondict):
"""
Checks installed compilers and targets and returns the first combination from the user's
options, env, or the global supported lists that checks.
:param versiondict: dict(platform -> dict(architecture -> configuration))
:type versiondict: dict(string -> dict(string -> target_compiler)
:return: the compiler, revision, path, include dirs, library paths and target architecture
:rtype: tuple of strings
"""
platforms = getattr(Options.options, 'msvc_targets', '').split(',')
if platforms == ['']:
platforms=Utils.to_list(conf.env.MSVC_TARGETS) or [i for i,j in all_msvc_platforms+all_icl_platforms+all_wince_platforms]
desired_versions = getattr(Options.options, 'msvc_version', '').split(',')
if desired_versions == ['']:
desired_versions = conf.env.MSVC_VERSIONS or list(reversed(sorted(versiondict.keys())))
# Override lazy detection by evaluating after the fact.
lazy_detect = getattr(Options.options, 'msvc_lazy', True)
if conf.env.MSVC_LAZY_AUTODETECT is False:
lazy_detect = False
if not lazy_detect:
for val in versiondict.values():
for arch in list(val.keys()):
cfg = val[arch]
cfg.evaluate()
if not cfg.is_valid:
del val[arch]
conf.env.MSVC_INSTALLED_VERSIONS = versiondict
for version in desired_versions:
Logs.debug('msvc: detecting %r - %r', version, desired_versions)
try:
targets = versiondict[version]
except KeyError:
continue
seen = set()
for arch in platforms:
if arch in seen:
continue
else:
seen.add(arch)
try:
cfg = targets[arch]
except KeyError:
continue
cfg.evaluate()
if cfg.is_valid:
compiler,revision = version.rsplit(' ', 1)
return compiler,revision,cfg.bindirs,cfg.incdirs,cfg.libdirs,cfg.cpu
conf.fatal('msvc: Impossible to find a valid architecture for building %r - %r' % (desired_versions, list(versiondict.keys()))) | [
"def",
"setup_msvc",
"(",
"conf",
",",
"versiondict",
")",
":",
"platforms",
"=",
"getattr",
"(",
"Options",
".",
"options",
",",
"'msvc_targets'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
"if",
"platforms",
"==",
"[",
"''",
"]",
":",
"platforms"... | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/msvc.py#L107-L160 | ||
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/BASIC/basparse.py | python | p_command_data | (p) | command : DATA numlist | command : DATA numlist | [
"command",
":",
"DATA",
"numlist"
] | def p_command_data(p):
'''command : DATA numlist'''
p[0] = ('DATA',p[2]) | [
"def",
"p_command_data",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"'DATA'",
",",
"p",
"[",
"2",
"]",
")"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/BASIC/basparse.py#L103-L105 | ||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/text_format.py | python | _Tokenizer.ConsumeBool | (self) | return result | Consumes a boolean value.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed. | Consumes a boolean value. | [
"Consumes",
"a",
"boolean",
"value",
"."
] | def ConsumeBool(self):
"""Consumes a boolean value.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
try:
result = ParseBool(self.token)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result | [
"def",
"ConsumeBool",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"ParseBool",
"(",
"self",
".",
"token",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"self",
".",
"_ParseError",
"(",
"str",
"(",
"e",
")",
")",
"self",
".",
"NextToken",... | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/text_format.py#L475-L489 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/fusion/portableglobe/servers/file_search.py | python | JsonPlacemark.GetPlacemark | (self, row, results) | Write json for next placemark. | Write json for next placemark. | [
"Write",
"json",
"for",
"next",
"placemark",
"."
] | def GetPlacemark(self, row, results):
"""Write json for next placemark."""
if len(row) < 3:
return ""
elif len(row) == 3:
return (json_placemark_template % (row[-2], row[-1],
row[0], "", results))
else:
return (json_placemark_template % (row[-2], row[-1],
row[0], row[1], results)) | [
"def",
"GetPlacemark",
"(",
"self",
",",
"row",
",",
"results",
")",
":",
"if",
"len",
"(",
"row",
")",
"<",
"3",
":",
"return",
"\"\"",
"elif",
"len",
"(",
"row",
")",
"==",
"3",
":",
"return",
"(",
"json_placemark_template",
"%",
"(",
"row",
"[",... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/file_search.py#L118-L127 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/sparse/coo.py | python | coo_matrix.tocsr | (self, copy=False) | Convert this matrix to Compressed Sparse Row format
Duplicate entries will be summed together.
Examples
--------
>>> from numpy import array
>>> from scipy.sparse import coo_matrix
>>> row = array([0, 0, 1, 3, 1, 0, 0])
>>> col = array([0, 2, 1, 3, 1, 0, 0])
>>> data = array([1, 1, 1, 1, 1, 1, 1])
>>> A = coo_matrix((data, (row, col)), shape=(4, 4)).tocsr()
>>> A.toarray()
array([[3, 0, 1, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1]]) | Convert this matrix to Compressed Sparse Row format | [
"Convert",
"this",
"matrix",
"to",
"Compressed",
"Sparse",
"Row",
"format"
] | def tocsr(self, copy=False):
"""Convert this matrix to Compressed Sparse Row format
Duplicate entries will be summed together.
Examples
--------
>>> from numpy import array
>>> from scipy.sparse import coo_matrix
>>> row = array([0, 0, 1, 3, 1, 0, 0])
>>> col = array([0, 2, 1, 3, 1, 0, 0])
>>> data = array([1, 1, 1, 1, 1, 1, 1])
>>> A = coo_matrix((data, (row, col)), shape=(4, 4)).tocsr()
>>> A.toarray()
array([[3, 0, 1, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1]])
"""
from .csr import csr_matrix
if self.nnz == 0:
return csr_matrix(self.shape, dtype=self.dtype)
else:
M,N = self.shape
idx_dtype = get_index_dtype((self.row, self.col),
maxval=max(self.nnz, N))
row = self.row.astype(idx_dtype, copy=False)
col = self.col.astype(idx_dtype, copy=False)
indptr = np.empty(M + 1, dtype=idx_dtype)
indices = np.empty_like(col, dtype=idx_dtype)
data = np.empty_like(self.data, dtype=upcast(self.dtype))
coo_tocsr(M, N, self.nnz, row, col, self.data,
indptr, indices, data)
x = csr_matrix((data, indices, indptr), shape=self.shape)
if not self.has_canonical_format:
x.sum_duplicates()
return x | [
"def",
"tocsr",
"(",
"self",
",",
"copy",
"=",
"False",
")",
":",
"from",
".",
"csr",
"import",
"csr_matrix",
"if",
"self",
".",
"nnz",
"==",
"0",
":",
"return",
"csr_matrix",
"(",
"self",
".",
"shape",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/coo.py#L368-L408 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/compiler_d.py | python | options | (opt) | Restrict the compiler detection from the command-line::
$ waf configure --check-d-compiler=dmd | Restrict the compiler detection from the command-line:: | [
"Restrict",
"the",
"compiler",
"detection",
"from",
"the",
"command",
"-",
"line",
"::"
] | def options(opt):
"""
Restrict the compiler detection from the command-line::
$ waf configure --check-d-compiler=dmd
"""
d_compiler_opts = opt.add_option_group('D Compiler Options')
d_compiler_opts.add_option('--check-d-compiler', default='gdc,dmd,ldc2', action='store',
help='check for the compiler [Default:gdc,dmd,ldc2]', dest='dcheck')
for d_compiler in ['gdc', 'dmd', 'ldc2']:
opt.load('%s' % d_compiler) | [
"def",
"options",
"(",
"opt",
")",
":",
"d_compiler_opts",
"=",
"opt",
".",
"add_option_group",
"(",
"'D Compiler Options'",
")",
"d_compiler_opts",
".",
"add_option",
"(",
"'--check-d-compiler'",
",",
"default",
"=",
"'gdc,dmd,ldc2'",
",",
"action",
"=",
"'store'... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/compiler_d.py#L48-L58 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/multiprocessing/util.py | python | log_to_stderr | (level=None) | return _logger | Turn on logging and add a handler which prints to stderr | Turn on logging and add a handler which prints to stderr | [
"Turn",
"on",
"logging",
"and",
"add",
"a",
"handler",
"which",
"prints",
"to",
"stderr"
] | def log_to_stderr(level=None):
'''
Turn on logging and add a handler which prints to stderr
'''
global _log_to_stderr
import logging
logger = get_logger()
formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
if level:
logger.setLevel(level)
_log_to_stderr = True
return _logger | [
"def",
"log_to_stderr",
"(",
"level",
"=",
"None",
")",
":",
"global",
"_log_to_stderr",
"import",
"logging",
"logger",
"=",
"get_logger",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"DEFAULT_LOGGING_FORMAT",
")",
"handler",
"=",
"logging",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/multiprocessing/util.py#L113-L129 | |
bigtreetech/BIGTREETECH-SKR-mini-E3 | 221247c12502ff92d071c701ea63cf3aa9bb3b29 | firmware/V1.0/Marlin-2.0.7.2-SKR-mini-E3-V1.0/buildroot/share/scripts/createTemperatureLookupMarlin.py | python | Thermistor.resol | (self, adc) | return res | Convert ADC reading into a resolution | Convert ADC reading into a resolution | [
"Convert",
"ADC",
"reading",
"into",
"a",
"resolution"
] | def resol(self, adc):
"Convert ADC reading into a resolution"
res = self.temp(adc)-self.temp(adc+1)
return res | [
"def",
"resol",
"(",
"self",
",",
"adc",
")",
":",
"res",
"=",
"self",
".",
"temp",
"(",
"adc",
")",
"-",
"self",
".",
"temp",
"(",
"adc",
"+",
"1",
")",
"return",
"res"
] | https://github.com/bigtreetech/BIGTREETECH-SKR-mini-E3/blob/221247c12502ff92d071c701ea63cf3aa9bb3b29/firmware/V1.0/Marlin-2.0.7.2-SKR-mini-E3-V1.0/buildroot/share/scripts/createTemperatureLookupMarlin.py#L62-L65 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/operations/build/wheel_legacy.py | python | format_command_result | (
command_args, # type: List[str]
command_output, # type: str
) | return text | Format command information for logging. | Format command information for logging. | [
"Format",
"command",
"information",
"for",
"logging",
"."
] | def format_command_result(
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> str
"""Format command information for logging."""
command_desc = format_command_args(command_args)
text = f'Command arguments: {command_desc}\n'
if not command_output:
text += 'Command output: None'
elif logger.getEffectiveLevel() > logging.DEBUG:
text += 'Command output: [use --verbose to show]'
else:
if not command_output.endswith('\n'):
command_output += '\n'
text += f'Command output:\n{command_output}{LOG_DIVIDER}'
return text | [
"def",
"format_command_result",
"(",
"command_args",
",",
"# type: List[str]",
"command_output",
",",
"# type: str",
")",
":",
"# type: (...) -> str",
"command_desc",
"=",
"format_command_args",
"(",
"command_args",
")",
"text",
"=",
"f'Command arguments: {command_desc}\\n'",... | 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/_internal/operations/build/wheel_legacy.py#L19-L37 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/opset8/ops.py | python | gather | (
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
) | return _get_node_factory_opset8().create("Gather", inputs, attributes) | Return a node which performs Gather with support of negative indices.
@param data: N-D tensor with data for gathering
@param indices: N-D tensor with indices by which data is gathered. Negative indices
indicate reverse indexing from the end
@param axis: axis along which elements are gathered
@param batch_dims: number of batch dimensions
@return: The new node which performs Gather | Return a node which performs Gather with support of negative indices. | [
"Return",
"a",
"node",
"which",
"performs",
"Gather",
"with",
"support",
"of",
"negative",
"indices",
"."
] | def gather(
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
) -> Node:
"""Return a node which performs Gather with support of negative indices.
@param data: N-D tensor with data for gathering
@param indices: N-D tensor with indices by which data is gathered. Negative indices
indicate reverse indexing from the end
@param axis: axis along which elements are gathered
@param batch_dims: number of batch dimensions
@return: The new node which performs Gather
"""
inputs = as_nodes(data, indices, axis)
attributes = {
"batch_dims": batch_dims
}
return _get_node_factory_opset8().create("Gather", inputs, attributes) | [
"def",
"gather",
"(",
"data",
":",
"NodeInput",
",",
"indices",
":",
"NodeInput",
",",
"axis",
":",
"NodeInput",
",",
"batch_dims",
":",
"Optional",
"[",
"int",
"]",
"=",
"0",
",",
")",
"->",
"Node",
":",
"inputs",
"=",
"as_nodes",
"(",
"data",
",",
... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset8/ops.py#L247-L266 | |
zeakey/DeepSkeleton | dc70170f8fd2ec8ca1157484ce66129981104486 | python/caffe/io.py | python | arraylist_to_blobprotovecor_str | (arraylist) | return vec.SerializeToString() | Converts a list of arrays to a serialized blobprotovec, which could be
then passed to a network for processing. | Converts a list of arrays to a serialized blobprotovec, which could be
then passed to a network for processing. | [
"Converts",
"a",
"list",
"of",
"arrays",
"to",
"a",
"serialized",
"blobprotovec",
"which",
"could",
"be",
"then",
"passed",
"to",
"a",
"network",
"for",
"processing",
"."
] | def arraylist_to_blobprotovecor_str(arraylist):
"""Converts a list of arrays to a serialized blobprotovec, which could be
then passed to a network for processing.
"""
vec = caffe_pb2.BlobProtoVector()
vec.blobs.extend([array_to_blobproto(arr) for arr in arraylist])
return vec.SerializeToString() | [
"def",
"arraylist_to_blobprotovecor_str",
"(",
"arraylist",
")",
":",
"vec",
"=",
"caffe_pb2",
".",
"BlobProtoVector",
"(",
")",
"vec",
".",
"blobs",
".",
"extend",
"(",
"[",
"array_to_blobproto",
"(",
"arr",
")",
"for",
"arr",
"in",
"arraylist",
"]",
")",
... | https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/python/caffe/io.py#L46-L52 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/pystache/common.py | python | is_string | (obj) | return isinstance(obj, _STRING_TYPES) | Return whether the given object is a bytes or string | Return whether the given object is a bytes or string | [
"Return",
"whether",
"the",
"given",
"object",
"is",
"a",
"bytes",
"or",
"string"
] | def is_string(obj):
"""
Return whether the given object is a bytes or string
"""
return isinstance(obj, _STRING_TYPES) | [
"def",
"is_string",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"_STRING_TYPES",
")"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/pystache/common.py#L14-L19 | |
alibaba/graph-learn | 54cafee9db3054dc310a28b856be7f97c7d5aee9 | graphlearn/python/nn/tf/layers/ego_gin_conv.py | python | EgoGINConv.forward | (self, x, neighbor, expand) | return self.output.forward(x + agg) | Compute node embeddings based on GIN.
```x_i = W * [(1 + eps) * x_i + sum(x_j) for x_j in N_i]```,
where ```N_i``` is the neighbor set of ```x_i```.
Args:
x: A float tensor with shape = [batch_size, in_dim].
neighbor: A float tensor with shape = [batch_size * expand, in_dim].
expand: An integer, the neighbor count.
Return:
A float tensor with shape=[batch_size, out_dim]. | Compute node embeddings based on GIN.
```x_i = W * [(1 + eps) * x_i + sum(x_j) for x_j in N_i]```,
where ```N_i``` is the neighbor set of ```x_i```. | [
"Compute",
"node",
"embeddings",
"based",
"on",
"GIN",
".",
"x_i",
"=",
"W",
"*",
"[",
"(",
"1",
"+",
"eps",
")",
"*",
"x_i",
"+",
"sum",
"(",
"x_j",
")",
"for",
"x_j",
"in",
"N_i",
"]",
"where",
"N_i",
"is",
"the",
"neighbor",
"set",
"of",
"x_... | def forward(self, x, neighbor, expand):
""" Compute node embeddings based on GIN.
```x_i = W * [(1 + eps) * x_i + sum(x_j) for x_j in N_i]```,
where ```N_i``` is the neighbor set of ```x_i```.
Args:
x: A float tensor with shape = [batch_size, in_dim].
neighbor: A float tensor with shape = [batch_size * expand, in_dim].
expand: An integer, the neighbor count.
Return:
A float tensor with shape=[batch_size, out_dim].
"""
nbr = tf.reshape(neighbor, [-1, expand, self._in_dim[1]])
agg = tf.math.reduce_sum(nbr, axis=1)
if self.trans:
x = self.trans[0].forward((1.0 + self._eps) * x)
agg = self.trans[1].forward(agg)
return self.output.forward(x + agg) | [
"def",
"forward",
"(",
"self",
",",
"x",
",",
"neighbor",
",",
"expand",
")",
":",
"nbr",
"=",
"tf",
".",
"reshape",
"(",
"neighbor",
",",
"[",
"-",
"1",
",",
"expand",
",",
"self",
".",
"_in_dim",
"[",
"1",
"]",
"]",
")",
"agg",
"=",
"tf",
"... | https://github.com/alibaba/graph-learn/blob/54cafee9db3054dc310a28b856be7f97c7d5aee9/graphlearn/python/nn/tf/layers/ego_gin_conv.py#L75-L95 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/decimal.py | python | Decimal.__truediv__ | (self, other, context=None) | return ans._fix(context) | Return self / other. | Return self / other. | [
"Return",
"self",
"/",
"other",
"."
] | def __truediv__(self, other, context=None):
"""Return self / other."""
other = _convert_other(other)
if other is NotImplemented:
return NotImplemented
if context is None:
context = getcontext()
sign = self._sign ^ other._sign
if self._is_special or other._is_special:
ans = self._check_nans(other, context)
if ans:
return ans
if self._isinfinity() and other._isinfinity():
return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
if self._isinfinity():
return _SignedInfinity[sign]
if other._isinfinity():
context._raise_error(Clamped, 'Division by infinity')
return _dec_from_triple(sign, '0', context.Etiny())
# Special cases for zeroes
if not other:
if not self:
return context._raise_error(DivisionUndefined, '0 / 0')
return context._raise_error(DivisionByZero, 'x / 0', sign)
if not self:
exp = self._exp - other._exp
coeff = 0
else:
# OK, so neither = 0, INF or NaN
shift = len(other._int) - len(self._int) + context.prec + 1
exp = self._exp - other._exp - shift
op1 = _WorkRep(self)
op2 = _WorkRep(other)
if shift >= 0:
coeff, remainder = divmod(op1.int * 10**shift, op2.int)
else:
coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
if remainder:
# result is not exact; adjust to ensure correct rounding
if coeff % 5 == 0:
coeff += 1
else:
# result is exact; get as close to ideal exponent as possible
ideal_exp = self._exp - other._exp
while exp < ideal_exp and coeff % 10 == 0:
coeff //= 10
exp += 1
ans = _dec_from_triple(sign, str(coeff), exp)
return ans._fix(context) | [
"def",
"__truediv__",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
")",
"if",
"other",
"is",
"NotImplemented",
":",
"return",
"NotImplemented",
"if",
"context",
"is",
"None",
":",
"context"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L1291-L1348 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/random.py | python | Random.weibullvariate | (self, alpha, beta) | return alpha * pow(-_log(u), 1.0/beta) | Weibull distribution.
alpha is the scale parameter and beta is the shape parameter. | Weibull distribution. | [
"Weibull",
"distribution",
"."
] | def weibullvariate(self, alpha, beta):
"""Weibull distribution.
alpha is the scale parameter and beta is the shape parameter.
"""
# Jain, pg. 499; bug fix courtesy Bill Arms
u = 1.0 - self.random()
return alpha * pow(-_log(u), 1.0/beta) | [
"def",
"weibullvariate",
"(",
"self",
",",
"alpha",
",",
"beta",
")",
":",
"# Jain, pg. 499; bug fix courtesy Bill Arms",
"u",
"=",
"1.0",
"-",
"self",
".",
"random",
"(",
")",
"return",
"alpha",
"*",
"pow",
"(",
"-",
"_log",
"(",
"u",
")",
",",
"1.0",
... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/random.py#L630-L639 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/poplib.py | python | POP3.dele | (self, which) | return self._shortcmd('DELE %s' % which) | Delete message number 'which'.
Result is 'response'. | Delete message number 'which'. | [
"Delete",
"message",
"number",
"which",
"."
] | def dele(self, which):
"""Delete message number 'which'.
Result is 'response'.
"""
return self._shortcmd('DELE %s' % which) | [
"def",
"dele",
"(",
"self",
",",
"which",
")",
":",
"return",
"self",
".",
"_shortcmd",
"(",
"'DELE %s'",
"%",
"which",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/poplib.py#L251-L256 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANS/SANSBeamCentreFinder.py | python | SANSBeamCentreFinder._validate_workspaces | (workspaces) | return workspaces | This method checks if any of the workspaces to plot contain NaN values.
:param workspaces: A list of workspace names
:return: A list of workspaces (used in matplotlib plotting). Raises if NaN values present. | This method checks if any of the workspaces to plot contain NaN values.
:param workspaces: A list of workspace names
:return: A list of workspaces (used in matplotlib plotting). Raises if NaN values present. | [
"This",
"method",
"checks",
"if",
"any",
"of",
"the",
"workspaces",
"to",
"plot",
"contain",
"NaN",
"values",
".",
":",
"param",
"workspaces",
":",
"A",
"list",
"of",
"workspace",
"names",
":",
"return",
":",
"A",
"list",
"of",
"workspaces",
"(",
"used",... | def _validate_workspaces(workspaces):
"""
This method checks if any of the workspaces to plot contain NaN values.
:param workspaces: A list of workspace names
:return: A list of workspaces (used in matplotlib plotting). Raises if NaN values present.
"""
workspaces = AnalysisDataService.Instance().retrieveWorkspaces(workspaces, unrollGroups=True)
for ws in workspaces:
if np.isnan(ws.readY(0)).any():
# All data can be NaN if bounds are too close together
# this makes the data unplottable
raise ValueError("Workspace contains NaN values.")
return workspaces | [
"def",
"_validate_workspaces",
"(",
"workspaces",
")",
":",
"workspaces",
"=",
"AnalysisDataService",
".",
"Instance",
"(",
")",
".",
"retrieveWorkspaces",
"(",
"workspaces",
",",
"unrollGroups",
"=",
"True",
")",
"for",
"ws",
"in",
"workspaces",
":",
"if",
"n... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANS/SANSBeamCentreFinder.py#L296-L308 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/valgrind/tsan_analyze.py | python | TsanAnalyzer.ParseReportFile | (self, filename) | return ret | Parses a report file and returns a list of ThreadSanitizer reports.
Args:
filename: report filename.
Returns:
list of (list of (str iff self._use_gdb, _StackTraceLine otherwise)). | Parses a report file and returns a list of ThreadSanitizer reports. | [
"Parses",
"a",
"report",
"file",
"and",
"returns",
"a",
"list",
"of",
"ThreadSanitizer",
"reports",
"."
] | def ParseReportFile(self, filename):
'''Parses a report file and returns a list of ThreadSanitizer reports.
Args:
filename: report filename.
Returns:
list of (list of (str iff self._use_gdb, _StackTraceLine otherwise)).
'''
ret = []
self.cur_fd_ = open(filename, 'r')
while True:
# Read ThreadSanitizer reports.
self.ReadLine()
if not self.line_:
break
while True:
tmp = []
while re.search(TsanAnalyzer.RACE_VERIFIER_LINE, self.line_):
tmp.append(self.line_)
self.ReadLine()
while re.search(TsanAnalyzer.THREAD_CREATION_STR, self.line_):
tmp.extend(self.ReadSection())
if re.search(TsanAnalyzer.TSAN_RACE_DESCRIPTION, self.line_):
tmp.extend(self.ReadSection())
ret.append(tmp) # includes RaceVerifier and thread creation stacks
elif (re.search(TsanAnalyzer.TSAN_WARNING_DESCRIPTION, self.line_) and
not common.IsWindows()): # workaround for http://crbug.com/53198
tmp.extend(self.ReadSection())
ret.append(tmp)
else:
break
tmp = []
if re.search(TsanAnalyzer.TSAN_ASSERTION, self.line_):
tmp.extend(self.ReadTillTheEnd())
ret.append(tmp)
break
match = re.search("used_suppression:\s+([0-9]+)\s(.*)", self.line_)
if match:
count, supp_name = match.groups()
count = int(count)
self.used_suppressions[supp_name] += count
self.cur_fd_.close()
return ret | [
"def",
"ParseReportFile",
"(",
"self",
",",
"filename",
")",
":",
"ret",
"=",
"[",
"]",
"self",
".",
"cur_fd_",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"while",
"True",
":",
"# Read ThreadSanitizer reports.",
"self",
".",
"ReadLine",
"(",
")",
"if... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/valgrind/tsan_analyze.py#L148-L195 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | SizerFlags.ReserveSpaceEvenIfHidden | (*args, **kwargs) | return _core_.SizerFlags_ReserveSpaceEvenIfHidden(*args, **kwargs) | ReserveSpaceEvenIfHidden(self) -> SizerFlags
Makes the item ignore window's visibility status | ReserveSpaceEvenIfHidden(self) -> SizerFlags | [
"ReserveSpaceEvenIfHidden",
"(",
"self",
")",
"-",
">",
"SizerFlags"
] | def ReserveSpaceEvenIfHidden(*args, **kwargs):
"""
ReserveSpaceEvenIfHidden(self) -> SizerFlags
Makes the item ignore window's visibility status
"""
return _core_.SizerFlags_ReserveSpaceEvenIfHidden(*args, **kwargs) | [
"def",
"ReserveSpaceEvenIfHidden",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerFlags_ReserveSpaceEvenIfHidden",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13866-L13872 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py | python | Treeview.detach | (self, *items) | Unlinks all of the specified items from the tree.
The items and all of their descendants are still present, and may
be reinserted at another point in the tree, but will not be
displayed. The root item may not be detached. | Unlinks all of the specified items from the tree. | [
"Unlinks",
"all",
"of",
"the",
"specified",
"items",
"from",
"the",
"tree",
"."
] | def detach(self, *items):
"""Unlinks all of the specified items from the tree.
The items and all of their descendants are still present, and may
be reinserted at another point in the tree, but will not be
displayed. The root item may not be detached."""
self.tk.call(self._w, "detach", items) | [
"def",
"detach",
"(",
"self",
",",
"*",
"items",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"\"detach\"",
",",
"items",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/ttk.py#L1220-L1226 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/polynomial.py | python | polyval2d | (x, y, c) | return c | Evaluate a 2-D polynomial at points (x, y).
This function returns the value
.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars and they
must have the same shape after conversion. In either case, either `x`
and `y` or their elements must support multiplication and addition both
with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points `(x, y)`,
where `x` and `y` must have the same shape. If `x` or `y` is a list
or tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term
of multi-degree i,j is contained in `c[i,j]`. If `c` has
dimension greater than two the remaining indices enumerate multiple
sets of coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points formed with
pairs of corresponding values from `x` and `y`.
See Also
--------
polyval, polygrid2d, polyval3d, polygrid3d
Notes
-----
.. versionadded::1.7.0 | Evaluate a 2-D polynomial at points (x, y). | [
"Evaluate",
"a",
"2",
"-",
"D",
"polynomial",
"at",
"points",
"(",
"x",
"y",
")",
"."
] | def polyval2d(x, y, c):
"""
Evaluate a 2-D polynomial at points (x, y).
This function returns the value
.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars and they
must have the same shape after conversion. In either case, either `x`
and `y` or their elements must support multiplication and addition both
with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points `(x, y)`,
where `x` and `y` must have the same shape. If `x` or `y` is a list
or tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term
of multi-degree i,j is contained in `c[i,j]`. If `c` has
dimension greater than two the remaining indices enumerate multiple
sets of coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points formed with
pairs of corresponding values from `x` and `y`.
See Also
--------
polyval, polygrid2d, polyval3d, polygrid3d
Notes
-----
.. versionadded::1.7.0
"""
try:
x, y = np.array((x, y), copy=0)
except:
raise ValueError('x, y are incompatible')
c = polyval(x, c)
c = polyval(y, c, tensor=False)
return c | [
"def",
"polyval2d",
"(",
"x",
",",
"y",
",",
"c",
")",
":",
"try",
":",
"x",
",",
"y",
"=",
"np",
".",
"array",
"(",
"(",
"x",
",",
"y",
")",
",",
"copy",
"=",
"0",
")",
"except",
":",
"raise",
"ValueError",
"(",
"'x, y are incompatible'",
")",... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/polynomial.py#L782-L836 | |
irods/irods | ed6328646cee87182098d569919004049bf4ce21 | scripts/irods/pyparsing.py | python | ParserElement.enablePackrat | () | Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method C{ParserElement.enablePackrat()}. If
your program uses C{psyco} to "compile as you go", you must call
C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
Python will crash. For best results, call C{enablePackrat()} immediately
after importing pyparsing. | Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions. | [
"Enables",
"packrat",
"parsing",
"which",
"adds",
"memoizing",
"to",
"the",
"parsing",
"logic",
".",
"Repeated",
"parse",
"attempts",
"at",
"the",
"same",
"string",
"location",
"(",
"which",
"happens",
"often",
"in",
"many",
"complex",
"grammars",
")",
"can",
... | def enablePackrat():
"""Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method C{ParserElement.enablePackrat()}. If
your program uses C{psyco} to "compile as you go", you must call
C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
Python will crash. For best results, call C{enablePackrat()} immediately
after importing pyparsing.
"""
if not ParserElement._packratEnabled:
ParserElement._packratEnabled = True
ParserElement._parse = ParserElement._parseCache | [
"def",
"enablePackrat",
"(",
")",
":",
"if",
"not",
"ParserElement",
".",
"_packratEnabled",
":",
"ParserElement",
".",
"_packratEnabled",
"=",
"True",
"ParserElement",
".",
"_parse",
"=",
"ParserElement",
".",
"_parseCache"
] | https://github.com/irods/irods/blob/ed6328646cee87182098d569919004049bf4ce21/scripts/irods/pyparsing.py#L1101-L1119 | ||
nodejs/nan | 8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62 | cpplint.py | python | NestingState.InNamespaceBody | (self) | return self.stack and isinstance(self.stack[-1], _NamespaceInfo) | Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise. | Check if we are currently one level inside a namespace body. | [
"Check",
"if",
"we",
"are",
"currently",
"one",
"level",
"inside",
"a",
"namespace",
"body",
"."
] | def InNamespaceBody(self):
"""Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _NamespaceInfo) | [
"def",
"InNamespaceBody",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"and",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_NamespaceInfo",
")"
] | https://github.com/nodejs/nan/blob/8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62/cpplint.py#L2673-L2679 | |
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/commands/kvstore.py | python | KvKeyValsCmd.print_kvstore_values | (
self,
resp: kvstore_types.Publication,
area: Optional[str] = None,
) | print values from raw publication from KvStore | print values from raw publication from KvStore | [
"print",
"values",
"from",
"raw",
"publication",
"from",
"KvStore"
] | def print_kvstore_values(
self,
resp: kvstore_types.Publication,
area: Optional[str] = None,
) -> None:
"""print values from raw publication from KvStore"""
rows = []
for key, value in sorted(resp.keyVals.items(), key=lambda x: x[0]):
val = self.deserialize_kvstore_publication(key, value)
if not val:
if isinstance(value.value, Iterable) and all(
isinstance(c, str) and c in string.printable for c in value.value
):
val = value.value
else:
val = hexdump.hexdump(value.value, "return")
ttl = "INF" if value.ttl == Consts.CONST_TTL_INF else value.ttl
rows.append(
[
"key: {}\n version: {}\n originatorId: {}\n "
"ttl: {}\n ttlVersion: {}\n value:\n {}".format(
key,
value.version,
value.originatorId,
ttl,
value.ttlVersion,
val,
)
]
)
area = f"in area {area}" if area is not None else ""
caption = f"Dump key-value pairs in KvStore {area}"
print(printing.render_vertical_table(rows, caption=caption)) | [
"def",
"print_kvstore_values",
"(",
"self",
",",
"resp",
":",
"kvstore_types",
".",
"Publication",
",",
"area",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"rows",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"sort... | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/commands/kvstore.py#L363-L398 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/utils.py | python | unquote_unreserved | (uri) | return ''.join(parts) | Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
:rtype: str | Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded. | [
"Un",
"-",
"escape",
"any",
"percent",
"-",
"escape",
"sequences",
"in",
"a",
"URI",
"that",
"are",
"unreserved",
"characters",
".",
"This",
"leaves",
"all",
"reserved",
"illegal",
"and",
"non",
"-",
"ASCII",
"bytes",
"encoded",
"."
] | def unquote_unreserved(uri):
"""Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
:rtype: str
"""
parts = uri.split('%')
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
if c in UNRESERVED_SET:
parts[i] = c + parts[i][2:]
else:
parts[i] = '%' + parts[i]
else:
parts[i] = '%' + parts[i]
return ''.join(parts) | [
"def",
"unquote_unreserved",
"(",
"uri",
")",
":",
"parts",
"=",
"uri",
".",
"split",
"(",
"'%'",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"parts",
")",
")",
":",
"h",
"=",
"parts",
"[",
"i",
"]",
"[",
"0",
":",
"2",
"]",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/utils.py#L570-L591 | |
acado/acado | b4e28f3131f79cadfd1a001e9fff061f361d3a0f | misc/cpplint.py | python | CleanseComments | (line) | return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed. | Removes //-comments and single-line C-style /* */ comments. | [
"Removes",
"//",
"-",
"comments",
"and",
"single",
"-",
"line",
"C",
"-",
"style",
"/",
"*",
"*",
"/",
"comments",
"."
] | def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | [
"def",
"CleanseComments",
"(",
"line",
")",
":",
"commentpos",
"=",
"line",
".",
"find",
"(",
"'//'",
")",
"if",
"commentpos",
"!=",
"-",
"1",
"and",
"not",
"IsCppString",
"(",
"line",
"[",
":",
"commentpos",
"]",
")",
":",
"line",
"=",
"line",
"[",
... | https://github.com/acado/acado/blob/b4e28f3131f79cadfd1a001e9fff061f361d3a0f/misc/cpplint.py#L1159-L1172 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/gluon/trainer.py | python | Trainer.load_states | (self, fname) | Loads trainer states (e.g. optimizer, momentum) from a file.
Parameters
----------
fname : str
Path to input states file. | Loads trainer states (e.g. optimizer, momentum) from a file. | [
"Loads",
"trainer",
"states",
"(",
"e",
".",
"g",
".",
"optimizer",
"momentum",
")",
"from",
"a",
"file",
"."
] | def load_states(self, fname):
"""Loads trainer states (e.g. optimizer, momentum) from a file.
Parameters
----------
fname : str
Path to input states file.
"""
if self._update_on_kvstore:
self._kvstore.load_optimizer_states(fname)
self._optimizer = self._kvstore._updater.optimizer
else:
with open(fname, 'rb') as f:
states = f.read()
for updater in self._updaters:
updater.set_states(states)
updater.optimizer = self._updaters[0].optimizer
self._optimizer = self._updaters[0].optimizer | [
"def",
"load_states",
"(",
"self",
",",
"fname",
")",
":",
"if",
"self",
".",
"_update_on_kvstore",
":",
"self",
".",
"_kvstore",
".",
"load_optimizer_states",
"(",
"fname",
")",
"self",
".",
"_optimizer",
"=",
"self",
".",
"_kvstore",
".",
"_updater",
"."... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/gluon/trainer.py#L218-L235 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | GCP.__init__ | (self, *args) | r"""__init__(GCP self, double x=0.0, double y=0.0, double z=0.0, double pixel=0.0, double line=0.0, char const * info="", char const * id="") -> GCP | r"""__init__(GCP self, double x=0.0, double y=0.0, double z=0.0, double pixel=0.0, double line=0.0, char const * info="", char const * id="") -> GCP | [
"r",
"__init__",
"(",
"GCP",
"self",
"double",
"x",
"=",
"0",
".",
"0",
"double",
"y",
"=",
"0",
".",
"0",
"double",
"z",
"=",
"0",
".",
"0",
"double",
"pixel",
"=",
"0",
".",
"0",
"double",
"line",
"=",
"0",
".",
"0",
"char",
"const",
"*",
... | def __init__(self, *args):
r"""__init__(GCP self, double x=0.0, double y=0.0, double z=0.0, double pixel=0.0, double line=0.0, char const * info="", char const * id="") -> GCP"""
_gdal.GCP_swiginit(self, _gdal.new_GCP(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_gdal",
".",
"GCP_swiginit",
"(",
"self",
",",
"_gdal",
".",
"new_GCP",
"(",
"*",
"args",
")",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L1979-L1981 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/jinja2/lexer.py | python | Lexer.tokenize | (self, source, name=None, filename=None, state=None) | return TokenStream(self.wrap(stream, name, filename), name, filename) | Calls tokeniter + tokenize and wraps it in a token stream. | Calls tokeniter + tokenize and wraps it in a token stream. | [
"Calls",
"tokeniter",
"+",
"tokenize",
"and",
"wraps",
"it",
"in",
"a",
"token",
"stream",
"."
] | def tokenize(self, source, name=None, filename=None, state=None):
"""Calls tokeniter + tokenize and wraps it in a token stream.
"""
stream = self.tokeniter(source, name, filename, state)
return TokenStream(self.wrap(stream, name, filename), name, filename) | [
"def",
"tokenize",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"stream",
"=",
"self",
".",
"tokeniter",
"(",
"source",
",",
"name",
",",
"filename",
",",
"state",
")",
"re... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/lexer.py#L552-L556 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py | python | WhileContext.pivot | (self) | return self._pivot | The boolean tensor representing the loop termination condition. | The boolean tensor representing the loop termination condition. | [
"The",
"boolean",
"tensor",
"representing",
"the",
"loop",
"termination",
"condition",
"."
] | def pivot(self):
"""The boolean tensor representing the loop termination condition."""
return self._pivot | [
"def",
"pivot",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pivot"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L1415-L1417 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/detail/extract_selection.py | python | maskarray_is_valid | (maskArray) | return maskArray is dsa.NoneArray or \
isinstance(maskArray, dsa.VTKArray) or \
isinstance(maskArray, dsa.VTKCompositeDataArray) | Validates that the maskArray is either a VTKArray or a
VTKCompositeDataArrays or a NoneArray other returns false. | Validates that the maskArray is either a VTKArray or a
VTKCompositeDataArrays or a NoneArray other returns false. | [
"Validates",
"that",
"the",
"maskArray",
"is",
"either",
"a",
"VTKArray",
"or",
"a",
"VTKCompositeDataArrays",
"or",
"a",
"NoneArray",
"other",
"returns",
"false",
"."
] | def maskarray_is_valid(maskArray):
"""Validates that the maskArray is either a VTKArray or a
VTKCompositeDataArrays or a NoneArray other returns false."""
return maskArray is dsa.NoneArray or \
isinstance(maskArray, dsa.VTKArray) or \
isinstance(maskArray, dsa.VTKCompositeDataArray) | [
"def",
"maskarray_is_valid",
"(",
"maskArray",
")",
":",
"return",
"maskArray",
"is",
"dsa",
".",
"NoneArray",
"or",
"isinstance",
"(",
"maskArray",
",",
"dsa",
".",
"VTKArray",
")",
"or",
"isinstance",
"(",
"maskArray",
",",
"dsa",
".",
"VTKCompositeDataArray... | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/detail/extract_selection.py#L38-L43 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | RobotModelLink.setTransform | (self, R, t) | return _robotsim.RobotModelLink_setTransform(self, R, t) | setTransform(RobotModelLink self, double const [9] R, double const [3] t)
Sets the link's current transformation (R,t) to the world frame.
Note:
This does NOT perform inverse kinematics. The transform is
overwritten when the robot's setConfig() method is called. | setTransform(RobotModelLink self, double const [9] R, double const [3] t) | [
"setTransform",
"(",
"RobotModelLink",
"self",
"double",
"const",
"[",
"9",
"]",
"R",
"double",
"const",
"[",
"3",
"]",
"t",
")"
] | def setTransform(self, R, t):
"""
setTransform(RobotModelLink self, double const [9] R, double const [3] t)
Sets the link's current transformation (R,t) to the world frame.
Note:
This does NOT perform inverse kinematics. The transform is
overwritten when the robot's setConfig() method is called.
"""
return _robotsim.RobotModelLink_setTransform(self, R, t) | [
"def",
"setTransform",
"(",
"self",
",",
"R",
",",
"t",
")",
":",
"return",
"_robotsim",
".",
"RobotModelLink_setTransform",
"(",
"self",
",",
"R",
",",
"t",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L3993-L4007 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py | python | _Stream.__init__ | (self, name, mode, comptype, fileobj, bufsize) | Construct a _Stream object. | Construct a _Stream object. | [
"Construct",
"a",
"_Stream",
"object",
"."
] | def __init__(self, name, mode, comptype, fileobj, bufsize):
"""Construct a _Stream object.
"""
self._extfileobj = True
if fileobj is None:
fileobj = _LowLevelFile(name, mode)
self._extfileobj = False
if comptype == '*':
# Enable transparent compression detection for the
# stream interface
fileobj = _StreamProxy(fileobj)
comptype = fileobj.getcomptype()
self.name = name or ""
self.mode = mode
self.comptype = comptype
self.fileobj = fileobj
self.bufsize = bufsize
self.buf = b""
self.pos = 0
self.closed = False
try:
if comptype == "gz":
try:
import zlib
except ImportError:
raise CompressionError("zlib module is not available")
self.zlib = zlib
self.crc = zlib.crc32(b"")
if mode == "r":
self._init_read_gz()
else:
self._init_write_gz()
if comptype == "bz2":
try:
import bz2
except ImportError:
raise CompressionError("bz2 module is not available")
if mode == "r":
self.dbuf = b""
self.cmp = bz2.BZ2Decompressor()
else:
self.cmp = bz2.BZ2Compressor()
except:
if not self._extfileobj:
self.fileobj.close()
self.closed = True
raise | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"mode",
",",
"comptype",
",",
"fileobj",
",",
"bufsize",
")",
":",
"self",
".",
"_extfileobj",
"=",
"True",
"if",
"fileobj",
"is",
"None",
":",
"fileobj",
"=",
"_LowLevelFile",
"(",
"name",
",",
"mode",... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py#L399-L449 | ||
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/operators/cast.py | python | FloatToHalf | (inputs, **kwargs) | return output | Cast the type of tensor from ``float32`` to ``float16``.
Parameters
----------
inputs : Tensor
The ``float32`` tensor.
Returns
-------
Tensor
The ``float16`` tensor. | Cast the type of tensor from ``float32`` to ``float16``. | [
"Cast",
"the",
"type",
"of",
"tensor",
"from",
"float32",
"to",
"float16",
"."
] | def FloatToHalf(inputs, **kwargs):
"""Cast the type of tensor from ``float32`` to ``float16``.
Parameters
----------
inputs : Tensor
The ``float32`` tensor.
Returns
-------
Tensor
The ``float16`` tensor.
"""
CheckInputs(inputs, 1)
arguments = ParseArguments(locals())
output = Tensor.CreateOperator(nout=1, op_type='FloatToHalf', **arguments)
if inputs.shape is not None:
output.shape = inputs.shape[:]
return output | [
"def",
"FloatToHalf",
"(",
"inputs",
",",
"*",
"*",
"kwargs",
")",
":",
"CheckInputs",
"(",
"inputs",
",",
"1",
")",
"arguments",
"=",
"ParseArguments",
"(",
"locals",
"(",
")",
")",
"output",
"=",
"Tensor",
".",
"CreateOperator",
"(",
"nout",
"=",
"1"... | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/operators/cast.py#L14-L36 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchComponent.py | python | addToComponent | (compobject,addobject,mod=None) | Add an object to a component's properties.
Does not run if the addobject already exists in the component's properties.
Adds the object to the first property found of Base, Group, or Hosts.
If mod is provided, adds the object to that property instead.
Parameters
----------
compobject: <ArchComponent.Component>
The component object to add the object to.
addobject: <App::DocumentObject>
The object to add to the component.
mod: str, optional
The property to add the object to. | Add an object to a component's properties. | [
"Add",
"an",
"object",
"to",
"a",
"component",
"s",
"properties",
"."
] | def addToComponent(compobject,addobject,mod=None):
"""Add an object to a component's properties.
Does not run if the addobject already exists in the component's properties.
Adds the object to the first property found of Base, Group, or Hosts.
If mod is provided, adds the object to that property instead.
Parameters
----------
compobject: <ArchComponent.Component>
The component object to add the object to.
addobject: <App::DocumentObject>
The object to add to the component.
mod: str, optional
The property to add the object to.
"""
import Draft
if compobject == addobject: return
# first check zis already there
found = False
attribs = ["Additions","Objects","Components","Subtractions","Base","Group","Hosts"]
for a in attribs:
if hasattr(compobject,a):
if a == "Base":
if addobject == getattr(compobject,a):
found = True
else:
if addobject in getattr(compobject,a):
found = True
if not found:
if mod:
if hasattr(compobject,mod):
if mod == "Base":
setattr(compobject,mod,addobject)
addobject.ViewObject.hide()
elif mod == "Axes":
if Draft.getType(addobject) == "Axis":
l = getattr(compobject,mod)
l.append(addobject)
setattr(compobject,mod,l)
else:
l = getattr(compobject,mod)
l.append(addobject)
setattr(compobject,mod,l)
if mod != "Objects":
addobject.ViewObject.hide()
if Draft.getType(compobject) == "PanelSheet":
addobject.Placement.move(compobject.Placement.Base.negative())
else:
for a in attribs[:3]:
if hasattr(compobject,a):
l = getattr(compobject,a)
l.append(addobject)
setattr(compobject,a,l)
addobject.ViewObject.hide()
break | [
"def",
"addToComponent",
"(",
"compobject",
",",
"addobject",
",",
"mod",
"=",
"None",
")",
":",
"import",
"Draft",
"if",
"compobject",
"==",
"addobject",
":",
"return",
"# first check zis already there",
"found",
"=",
"False",
"attribs",
"=",
"[",
"\"Additions\... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchComponent.py#L55-L112 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py | python | _ZipDecrypter._GenerateCRCTable | () | return table | Generate a CRC-32 table.
ZIP encryption uses the CRC32 one-byte primitive for scrambling some
internal keys. We noticed that a direct implementation is faster than
relying on binascii.crc32(). | Generate a CRC-32 table. | [
"Generate",
"a",
"CRC",
"-",
"32",
"table",
"."
] | def _GenerateCRCTable():
"""Generate a CRC-32 table.
ZIP encryption uses the CRC32 one-byte primitive for scrambling some
internal keys. We noticed that a direct implementation is faster than
relying on binascii.crc32().
"""
poly = 0xedb88320
table = [0] * 256
for i in range(256):
crc = i
for j in range(8):
if crc & 1:
crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly
else:
crc = ((crc >> 1) & 0x7FFFFFFF)
table[i] = crc
return table | [
"def",
"_GenerateCRCTable",
"(",
")",
":",
"poly",
"=",
"0xedb88320",
"table",
"=",
"[",
"0",
"]",
"*",
"256",
"for",
"i",
"in",
"range",
"(",
"256",
")",
":",
"crc",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"8",
")",
":",
"if",
"crc",
"&",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py#L433-L450 | |
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/ansic/cparse.py | python | p_struct_declarator_3 | (t) | struct_declarator : COLON constant_expression | struct_declarator : COLON constant_expression | [
"struct_declarator",
":",
"COLON",
"constant_expression"
] | def p_struct_declarator_3(t):
'struct_declarator : COLON constant_expression'
pass | [
"def",
"p_struct_declarator_3",
"(",
"t",
")",
":",
"pass"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L225-L227 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/connectionpool.py | python | _normalize_host | (host, scheme) | return host | Normalize hosts for comparisons and use with sockets. | Normalize hosts for comparisons and use with sockets. | [
"Normalize",
"hosts",
"for",
"comparisons",
"and",
"use",
"with",
"sockets",
"."
] | def _normalize_host(host, scheme):
"""
Normalize hosts for comparisons and use with sockets.
"""
host = normalize_host(host, scheme)
# httplib doesn't like it when we include brackets in IPv6 addresses
# Specifically, if we include brackets but also pass the port then
# httplib crazily doubles up the square brackets on the Host header.
# Instead, we need to make sure we never pass ``None`` as the port.
# However, for backward compatibility reasons we can't actually
# *assert* that. See http://bugs.python.org/issue28539
if host.startswith("[") and host.endswith("]"):
host = host[1:-1]
return host | [
"def",
"_normalize_host",
"(",
"host",
",",
"scheme",
")",
":",
"host",
"=",
"normalize_host",
"(",
"host",
",",
"scheme",
")",
"# httplib doesn't like it when we include brackets in IPv6 addresses",
"# Specifically, if we include brackets but also pass the port then",
"# httplib... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/connectionpool.py#L1036-L1051 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/spatialite/connector.py | python | SpatiaLiteDBConnector._checkSpatial | (self) | return self.has_spatial | check if it's a valid SpatiaLite db | check if it's a valid SpatiaLite db | [
"check",
"if",
"it",
"s",
"a",
"valid",
"SpatiaLite",
"db"
] | def _checkSpatial(self):
""" check if it's a valid SpatiaLite db """
self.has_spatial = self._checkGeometryColumnsTable()
return self.has_spatial | [
"def",
"_checkSpatial",
"(",
"self",
")",
":",
"self",
".",
"has_spatial",
"=",
"self",
".",
"_checkGeometryColumnsTable",
"(",
")",
"return",
"self",
".",
"has_spatial"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/spatialite/connector.py#L90-L93 | |
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | tools/extra/resize_and_crop_images.py | python | OpenCVResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256) | Takes an image name, resize it and crop the center square | Takes an image name, resize it and crop the center square | [
"Takes",
"an",
"image",
"name",
"resize",
"it",
"and",
"crop",
"the",
"center",
"square"
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256):
'''Takes an image name, resize it and crop the center square
'''
img = cv2.imread(input_file)
height, width, depth = img.shape
new_height = output_side_length
new_width = output_side_length
if height > width:
new_height = output_side_length * height / width
else:
new_width = output_side_length * width / height
resized_img = cv2.resize(img, (new_width, new_height))
height_offset = (new_height - output_side_length) / 2
width_offset = (new_width - output_side_length) / 2
cropped_img = resized_img[height_offset:height_offset + output_side_length,
width_offset:width_offset + output_side_length]
cv2.imwrite(output_file, cropped_img) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"input_file",
")",
"height",
",",
"width",
",",
"depth",
"=",
"img",
".",
"shape",
... | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/tools/extra/resize_and_crop_images.py#L20-L36 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/executor.py | python | Executor.output_dict | (self) | return self._output_dict | Get dictionary representation of output arrays.
Returns
-------
output_dict : dict of str to NDArray
The dictionary that maps name of output names to NDArrays.
Raises
------
ValueError : if there are duplicated names in the outputs. | Get dictionary representation of output arrays. | [
"Get",
"dictionary",
"representation",
"of",
"output",
"arrays",
"."
] | def output_dict(self):
"""Get dictionary representation of output arrays.
Returns
-------
output_dict : dict of str to NDArray
The dictionary that maps name of output names to NDArrays.
Raises
------
ValueError : if there are duplicated names in the outputs.
"""
if self._output_dict is None:
self._output_dict = Executor._get_dict(
self._symbol.list_outputs(), self.outputs)
return self._output_dict | [
"def",
"output_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"_output_dict",
"is",
"None",
":",
"self",
".",
"_output_dict",
"=",
"Executor",
".",
"_get_dict",
"(",
"self",
".",
"_symbol",
".",
"list_outputs",
"(",
")",
",",
"self",
".",
"outputs",
... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/executor.py#L309-L324 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | PreTreeCtrl | (*args, **kwargs) | return val | PreTreeCtrl() -> TreeCtrl | PreTreeCtrl() -> TreeCtrl | [
"PreTreeCtrl",
"()",
"-",
">",
"TreeCtrl"
] | def PreTreeCtrl(*args, **kwargs):
"""PreTreeCtrl() -> TreeCtrl"""
val = _controls_.new_PreTreeCtrl(*args, **kwargs)
return val | [
"def",
"PreTreeCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_controls_",
".",
"new_PreTreeCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5604-L5607 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/retrying.py | python | Retrying.stop_after_delay | (self, previous_attempt_number, delay_since_first_attempt_ms) | return delay_since_first_attempt_ms >= self._stop_max_delay | Stop after the time from the first attempt >= stop_max_delay. | Stop after the time from the first attempt >= stop_max_delay. | [
"Stop",
"after",
"the",
"time",
"from",
"the",
"first",
"attempt",
">",
"=",
"stop_max_delay",
"."
] | def stop_after_delay(self, previous_attempt_number, delay_since_first_attempt_ms):
"""Stop after the time from the first attempt >= stop_max_delay."""
return delay_since_first_attempt_ms >= self._stop_max_delay | [
"def",
"stop_after_delay",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"return",
"delay_since_first_attempt_ms",
">=",
"self",
".",
"_stop_max_delay"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/retrying.py#L145-L147 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/compiler.py | python | CodeGenerator.fail | (self, msg, lineno) | Fail with a :exc:`TemplateAssertionError`. | Fail with a :exc:`TemplateAssertionError`. | [
"Fail",
"with",
"a",
":",
"exc",
":",
"TemplateAssertionError",
"."
] | def fail(self, msg, lineno):
"""Fail with a :exc:`TemplateAssertionError`."""
raise TemplateAssertionError(msg, lineno, self.name, self.filename) | [
"def",
"fail",
"(",
"self",
",",
"msg",
",",
"lineno",
")",
":",
"raise",
"TemplateAssertionError",
"(",
"msg",
",",
"lineno",
",",
"self",
".",
"name",
",",
"self",
".",
"filename",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/compiler.py#L313-L315 | ||
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | libcxx/utils/libcxx/sym_check/util.py | python | read_syms_from_list | (slist) | return [ast.literal_eval(l) for l in slist] | Read a list of symbols from a list of strings.
Each string is one symbol. | Read a list of symbols from a list of strings.
Each string is one symbol. | [
"Read",
"a",
"list",
"of",
"symbols",
"from",
"a",
"list",
"of",
"strings",
".",
"Each",
"string",
"is",
"one",
"symbol",
"."
] | def read_syms_from_list(slist):
"""
Read a list of symbols from a list of strings.
Each string is one symbol.
"""
return [ast.literal_eval(l) for l in slist] | [
"def",
"read_syms_from_list",
"(",
"slist",
")",
":",
"return",
"[",
"ast",
".",
"literal_eval",
"(",
"l",
")",
"for",
"l",
"in",
"slist",
"]"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/libcxx/utils/libcxx/sym_check/util.py#L17-L22 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/common.py | python | GetEnvironFallback | (var_list, default) | return default | Look up a key in the environment, with fallback to secondary keys
and finally falling back to a default value. | Look up a key in the environment, with fallback to secondary keys
and finally falling back to a default value. | [
"Look",
"up",
"a",
"key",
"in",
"the",
"environment",
"with",
"fallback",
"to",
"secondary",
"keys",
"and",
"finally",
"falling",
"back",
"to",
"a",
"default",
"value",
"."
] | def GetEnvironFallback(var_list, default):
"""Look up a key in the environment, with fallback to secondary keys
and finally falling back to a default value."""
for var in var_list:
if var in os.environ:
return os.environ[var]
return default | [
"def",
"GetEnvironFallback",
"(",
"var_list",
",",
"default",
")",
":",
"for",
"var",
"in",
"var_list",
":",
"if",
"var",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"environ",
"[",
"var",
"]",
"return",
"default"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/common.py#L114-L120 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/tensorboard/backend/handler.py | python | TensorboardHandler._send_json_response | (self, obj, code=200) | Writes out the given object as JSON using the given HTTP status code.
This also replaces special float values with stringified versions.
Args:
obj: The object to respond with.
code: The numeric HTTP status code to use. | Writes out the given object as JSON using the given HTTP status code. | [
"Writes",
"out",
"the",
"given",
"object",
"as",
"JSON",
"using",
"the",
"given",
"HTTP",
"status",
"code",
"."
] | def _send_json_response(self, obj, code=200):
"""Writes out the given object as JSON using the given HTTP status code.
This also replaces special float values with stringified versions.
Args:
obj: The object to respond with.
code: The numeric HTTP status code to use.
"""
content = json.dumps(json_util.WrapSpecialFloats(obj))
self._respond(content, 'application/json', code) | [
"def",
"_send_json_response",
"(",
"self",
",",
"obj",
",",
"code",
"=",
"200",
")",
":",
"content",
"=",
"json",
".",
"dumps",
"(",
"json_util",
".",
"WrapSpecialFloats",
"(",
"obj",
")",
")",
"self",
".",
"_respond",
"(",
"content",
",",
"'application/... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/tensorboard/backend/handler.py#L225-L235 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | bindings/pyroot_legacy/JupyROOT/helpers/cppcompleter.py | python | CppCompleter.complete | (self, ip, event) | return self._completeImpl(event.line) | Autocomplete interfacing to TTabCom. If an accessor of a scope is
present in the line, the suggestions are prepended with the line.
That's how completers work. For example:
myGraph.Set<tab> will return "myGraph.Set+suggestion in the list of
suggestions. | Autocomplete interfacing to TTabCom. If an accessor of a scope is
present in the line, the suggestions are prepended with the line.
That's how completers work. For example:
myGraph.Set<tab> will return "myGraph.Set+suggestion in the list of
suggestions. | [
"Autocomplete",
"interfacing",
"to",
"TTabCom",
".",
"If",
"an",
"accessor",
"of",
"a",
"scope",
"is",
"present",
"in",
"the",
"line",
"the",
"suggestions",
"are",
"prepended",
"with",
"the",
"line",
".",
"That",
"s",
"how",
"completers",
"work",
".",
"For... | def complete(self, ip, event) :
'''
Autocomplete interfacing to TTabCom. If an accessor of a scope is
present in the line, the suggestions are prepended with the line.
That's how completers work. For example:
myGraph.Set<tab> will return "myGraph.Set+suggestion in the list of
suggestions.
'''
return self._completeImpl(event.line) | [
"def",
"complete",
"(",
"self",
",",
"ip",
",",
"event",
")",
":",
"return",
"self",
".",
"_completeImpl",
"(",
"event",
".",
"line",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/pyroot_legacy/JupyROOT/helpers/cppcompleter.py#L169-L177 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/nodes.py | python | Expr.as_const | (self, eval_ctx=None) | Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, if none is given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added. | Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible. | [
"Return",
"the",
"value",
"of",
"the",
"expression",
"as",
"constant",
"or",
"raise",
":",
"exc",
":",
"Impossible",
"if",
"this",
"was",
"not",
"possible",
"."
] | def as_const(self, eval_ctx=None):
"""Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, if none is given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added.
"""
raise Impossible() | [
"def",
"as_const",
"(",
"self",
",",
"eval_ctx",
"=",
"None",
")",
":",
"raise",
"Impossible",
"(",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/nodes.py#L397-L408 | ||
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/MetaSearch/dialogs/maindialog.py | python | _get_field_value | (field) | return value | convenience function to return field value integer | convenience function to return field value integer | [
"convenience",
"function",
"to",
"return",
"field",
"value",
"integer"
] | def _get_field_value(field):
"""convenience function to return field value integer"""
value = 0
if field == 'identifier':
value = 0
if field == 'link':
value = 1
return value | [
"def",
"_get_field_value",
"(",
"field",
")",
":",
"value",
"=",
"0",
"if",
"field",
"==",
"'identifier'",
":",
"value",
"=",
"0",
"if",
"field",
"==",
"'link'",
":",
"value",
"=",
"1",
"return",
"value"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/MetaSearch/dialogs/maindialog.py#L1015-L1025 | |
webmproject/libwebm | ee0bab576c338c9807249b99588e352b7268cb62 | PRESUBMIT.py | python | _RunCmdOnCheckedFiles | (input_api, output_api, run_cmd, files_to_check) | return results | Ensure that libwebm/ files are clean. | Ensure that libwebm/ files are clean. | [
"Ensure",
"that",
"libwebm",
"/",
"files",
"are",
"clean",
"."
] | def _RunCmdOnCheckedFiles(input_api, output_api, run_cmd, files_to_check):
"""Ensure that libwebm/ files are clean."""
file_filter = lambda x: input_api.FilterSourceFile(
x, files_to_check=files_to_check, files_to_skip=None)
affected_files = input_api.change.AffectedFiles(file_filter=file_filter)
results = [
run_cmd(input_api, output_api, f.AbsoluteLocalPath())
for f in affected_files
]
return results | [
"def",
"_RunCmdOnCheckedFiles",
"(",
"input_api",
",",
"output_api",
",",
"run_cmd",
",",
"files_to_check",
")",
":",
"file_filter",
"=",
"lambda",
"x",
":",
"input_api",
".",
"FilterSourceFile",
"(",
"x",
",",
"files_to_check",
"=",
"files_to_check",
",",
"file... | https://github.com/webmproject/libwebm/blob/ee0bab576c338c9807249b99588e352b7268cb62/PRESUBMIT.py#L122-L132 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.