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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
|
python
|
TarFile.extractfile
|
(self, member)
|
Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell()
|
Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell()
|
[
"Extract",
"a",
"member",
"from",
"the",
"archive",
"as",
"a",
"file",
"object",
".",
"member",
"may",
"be",
"a",
"filename",
"or",
"a",
"TarInfo",
"object",
".",
"If",
"member",
"is",
"a",
"regular",
"file",
"a",
"file",
"-",
"like",
"object",
"is",
"returned",
".",
"If",
"member",
"is",
"a",
"link",
"a",
"file",
"-",
"like",
"object",
"is",
"constructed",
"from",
"the",
"link",
"s",
"target",
".",
"If",
"member",
"is",
"none",
"of",
"the",
"above",
"None",
"is",
"returned",
".",
"The",
"file",
"-",
"like",
"object",
"is",
"read",
"-",
"only",
"and",
"provides",
"the",
"following",
"methods",
":",
"read",
"()",
"readline",
"()",
"readlines",
"()",
"seek",
"()",
"and",
"tell",
"()"
] |
def extractfile(self, member):
"""Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above, None is returned.
The file-like object is read-only and provides the following
methods: read(), readline(), readlines(), seek() and tell()
"""
self._check("r")
if isinstance(member, str):
tarinfo = self.getmember(member)
else:
tarinfo = member
if tarinfo.isreg():
return self.fileobject(self, tarinfo)
elif tarinfo.type not in SUPPORTED_TYPES:
# If a member's type is unknown, it is treated as a
# regular file.
return self.fileobject(self, tarinfo)
elif tarinfo.islnk() or tarinfo.issym():
if isinstance(self.fileobj, _Stream):
# A small but ugly workaround for the case that someone tries
# to extract a (sym)link as a file-object from a non-seekable
# stream of tar blocks.
raise StreamError("cannot extract (sym)link as file object")
else:
# A (sym)link's file object is its target's file object.
return self.extractfile(self._find_link_target(tarinfo))
else:
# If there's no data associated with the member (directory, chrdev,
# blkdev, etc.), return None instead of a file object.
return None
|
[
"def",
"extractfile",
"(",
"self",
",",
"member",
")",
":",
"self",
".",
"_check",
"(",
"\"r\"",
")",
"if",
"isinstance",
"(",
"member",
",",
"str",
")",
":",
"tarinfo",
"=",
"self",
".",
"getmember",
"(",
"member",
")",
"else",
":",
"tarinfo",
"=",
"member",
"if",
"tarinfo",
".",
"isreg",
"(",
")",
":",
"return",
"self",
".",
"fileobject",
"(",
"self",
",",
"tarinfo",
")",
"elif",
"tarinfo",
".",
"type",
"not",
"in",
"SUPPORTED_TYPES",
":",
"# If a member's type is unknown, it is treated as a",
"# regular file.",
"return",
"self",
".",
"fileobject",
"(",
"self",
",",
"tarinfo",
")",
"elif",
"tarinfo",
".",
"islnk",
"(",
")",
"or",
"tarinfo",
".",
"issym",
"(",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"fileobj",
",",
"_Stream",
")",
":",
"# A small but ugly workaround for the case that someone tries",
"# to extract a (sym)link as a file-object from a non-seekable",
"# stream of tar blocks.",
"raise",
"StreamError",
"(",
"\"cannot extract (sym)link as file object\"",
")",
"else",
":",
"# A (sym)link's file object is its target's file object.",
"return",
"self",
".",
"extractfile",
"(",
"self",
".",
"_find_link_target",
"(",
"tarinfo",
")",
")",
"else",
":",
"# If there's no data associated with the member (directory, chrdev,",
"# blkdev, etc.), return None instead of a file object.",
"return",
"None"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2199-L2235
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/_core.py
|
python
|
RealPoint.Get
|
(*args, **kwargs)
|
return _core_.RealPoint_Get(*args, **kwargs)
|
Get() -> (x,y)
Return the x and y properties as a tuple.
|
Get() -> (x,y)
|
[
"Get",
"()",
"-",
">",
"(",
"x",
"y",
")"
] |
def Get(*args, **kwargs):
"""
Get() -> (x,y)
Return the x and y properties as a tuple.
"""
return _core_.RealPoint_Get(*args, **kwargs)
|
[
"def",
"Get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"RealPoint_Get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1135-L1141
|
|
apple/swift-lldb
|
d74be846ef3e62de946df343e8c234bde93a8912
|
scripts/Python/static-binding/lldb.py
|
python
|
SBQueueItem.SetAddress
|
(self, addr)
|
return _lldb.SBQueueItem_SetAddress(self, addr)
|
SetAddress(SBQueueItem self, SBAddress addr)
|
SetAddress(SBQueueItem self, SBAddress addr)
|
[
"SetAddress",
"(",
"SBQueueItem",
"self",
"SBAddress",
"addr",
")"
] |
def SetAddress(self, addr):
"""SetAddress(SBQueueItem self, SBAddress addr)"""
return _lldb.SBQueueItem_SetAddress(self, addr)
|
[
"def",
"SetAddress",
"(",
"self",
",",
"addr",
")",
":",
"return",
"_lldb",
".",
"SBQueueItem_SetAddress",
"(",
"self",
",",
"addr",
")"
] |
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L9186-L9188
|
|
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
Framework/PythonInterface/plugins/algorithms/CalculateEfficiencyCorrection.py
|
python
|
CalculateEfficiencyCorrection._calculate_area_density_from_efficiency
|
(self)
|
Calculates area density (atom/cm^2) using efficiency
|
Calculates area density (atom/cm^2) using efficiency
|
[
"Calculates",
"area",
"density",
"(",
"atom",
"/",
"cm^2",
")",
"using",
"efficiency"
] |
def _calculate_area_density_from_efficiency(self):
"""Calculates area density (atom/cm^2) using efficiency"""
material = self._output_ws.sample().getMaterial()
ref_absXS = material.absorbXSection()
xs_term = ref_absXS * self._efficiency_wavelength / TABULATED_WAVELENGTH
if self._xsection_type == "TotalXSection":
xs_term += material.totalScatterXSection()
self._area_density = - np.log(1.0 - self._efficiency) / xs_term
|
[
"def",
"_calculate_area_density_from_efficiency",
"(",
"self",
")",
":",
"material",
"=",
"self",
".",
"_output_ws",
".",
"sample",
"(",
")",
".",
"getMaterial",
"(",
")",
"ref_absXS",
"=",
"material",
".",
"absorbXSection",
"(",
")",
"xs_term",
"=",
"ref_absXS",
"*",
"self",
".",
"_efficiency_wavelength",
"/",
"TABULATED_WAVELENGTH",
"if",
"self",
".",
"_xsection_type",
"==",
"\"TotalXSection\"",
":",
"xs_term",
"+=",
"material",
".",
"totalScatterXSection",
"(",
")",
"self",
".",
"_area_density",
"=",
"-",
"np",
".",
"log",
"(",
"1.0",
"-",
"self",
".",
"_efficiency",
")",
"/",
"xs_term"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/CalculateEfficiencyCorrection.py#L221-L228
|
||
moflow/moflow
|
2dfb27c799c90c6caf1477508eca3eec616ef7d2
|
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py
|
python
|
_ExtensionDict._FindExtensionByName
|
(self, name)
|
return self._extended_message._extensions_by_name.get(name, None)
|
Tries to find a known extension with the specified name.
Args:
name: Extension full name.
Returns:
Extension field descriptor.
|
Tries to find a known extension with the specified name.
|
[
"Tries",
"to",
"find",
"a",
"known",
"extension",
"with",
"the",
"specified",
"name",
"."
] |
def _FindExtensionByName(self, name):
"""Tries to find a known extension with the specified name.
Args:
name: Extension full name.
Returns:
Extension field descriptor.
"""
return self._extended_message._extensions_by_name.get(name, None)
|
[
"def",
"_FindExtensionByName",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_extended_message",
".",
"_extensions_by_name",
".",
"get",
"(",
"name",
",",
"None",
")"
] |
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py#L1141-L1150
|
|
OSGeo/gdal
|
3748fc4ba4fba727492774b2b908a2130c864a83
|
swig/python/osgeo/gdal.py
|
python
|
Dataset.ResetReading
|
(self, *args)
|
return _gdal.Dataset_ResetReading(self, *args)
|
r"""ResetReading(Dataset self)
|
r"""ResetReading(Dataset self)
|
[
"r",
"ResetReading",
"(",
"Dataset",
"self",
")"
] |
def ResetReading(self, *args):
r"""ResetReading(Dataset self)"""
return _gdal.Dataset_ResetReading(self, *args)
|
[
"def",
"ResetReading",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"Dataset_ResetReading",
"(",
"self",
",",
"*",
"args",
")"
] |
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L2269-L2271
|
|
lballabio/quantlib-old
|
136336947ed4fea9ecc1da6edad188700e821739
|
gensrc/gensrc/serialization/exceptions.py
|
python
|
SerializationParseException.__init__
|
(self, xmlDocumentName)
|
Initialize the SerializationParseException object.
|
Initialize the SerializationParseException object.
|
[
"Initialize",
"the",
"SerializationParseException",
"object",
"."
] |
def __init__(self, xmlDocumentName):
"""Initialize the SerializationParseException object."""
errorClass, errorObject, traceBack = sys.exc_info()
self.value_ = SerializationParseException.PARSE_ERROR % {
'xmlDocumentName' : xmlDocumentName,
'parseError' : str(errorObject) }
|
[
"def",
"__init__",
"(",
"self",
",",
"xmlDocumentName",
")",
":",
"errorClass",
",",
"errorObject",
",",
"traceBack",
"=",
"sys",
".",
"exc_info",
"(",
")",
"self",
".",
"value_",
"=",
"SerializationParseException",
".",
"PARSE_ERROR",
"%",
"{",
"'xmlDocumentName'",
":",
"xmlDocumentName",
",",
"'parseError'",
":",
"str",
"(",
"errorObject",
")",
"}"
] |
https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/serialization/exceptions.py#L46-L51
|
||
benoitsteiner/tensorflow-opencl
|
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
|
tensorflow/contrib/distributions/python/ops/geometric.py
|
python
|
Geometric.logits
|
(self)
|
return self._logits
|
Log-odds of a `1` outcome (vs `0`).
|
Log-odds of a `1` outcome (vs `0`).
|
[
"Log",
"-",
"odds",
"of",
"a",
"1",
"outcome",
"(",
"vs",
"0",
")",
"."
] |
def logits(self):
"""Log-odds of a `1` outcome (vs `0`)."""
return self._logits
|
[
"def",
"logits",
"(",
"self",
")",
":",
"return",
"self",
".",
"_logits"
] |
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/geometric.py#L107-L109
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/index/collector.py
|
python
|
LinkCollector.collect_links
|
(self, project_name)
|
return CollectedLinks(
files=file_links,
find_links=find_link_links,
project_urls=url_locations,
)
|
Find all available links for the given project name.
:return: All the Link objects (unfiltered), as a CollectedLinks object.
|
Find all available links for the given project name.
|
[
"Find",
"all",
"available",
"links",
"for",
"the",
"given",
"project",
"name",
"."
] |
def collect_links(self, project_name):
# type: (str) -> CollectedLinks
"""Find all available links for the given project name.
:return: All the Link objects (unfiltered), as a CollectedLinks object.
"""
search_scope = self.search_scope
index_locations = search_scope.get_index_urls_locations(project_name)
index_file_loc, index_url_loc = group_locations(index_locations)
fl_file_loc, fl_url_loc = group_locations(
self.find_links, expand_dir=True,
)
file_links = [
Link(url) for url in itertools.chain(index_file_loc, fl_file_loc)
]
# We trust every directly linked archive in find_links
find_link_links = [Link(url, '-f') for url in self.find_links]
# We trust every url that the user has given us whether it was given
# via --index-url or --find-links.
# We want to filter out anything that does not have a secure origin.
url_locations = [
link for link in itertools.chain(
# Mark PyPI indices as "cache_link_parsing == False" -- this
# will avoid caching the result of parsing the page for links.
(Link(url, cache_link_parsing=False) for url in index_url_loc),
(Link(url) for url in fl_url_loc),
)
if self.session.is_secure_origin(link)
]
url_locations = _remove_duplicate_links(url_locations)
lines = [
'{} location(s) to search for versions of {}:'.format(
len(url_locations), project_name,
),
]
for link in url_locations:
lines.append(f'* {link}')
logger.debug('\n'.join(lines))
return CollectedLinks(
files=file_links,
find_links=find_link_links,
project_urls=url_locations,
)
|
[
"def",
"collect_links",
"(",
"self",
",",
"project_name",
")",
":",
"# type: (str) -> CollectedLinks",
"search_scope",
"=",
"self",
".",
"search_scope",
"index_locations",
"=",
"search_scope",
".",
"get_index_urls_locations",
"(",
"project_name",
")",
"index_file_loc",
",",
"index_url_loc",
"=",
"group_locations",
"(",
"index_locations",
")",
"fl_file_loc",
",",
"fl_url_loc",
"=",
"group_locations",
"(",
"self",
".",
"find_links",
",",
"expand_dir",
"=",
"True",
",",
")",
"file_links",
"=",
"[",
"Link",
"(",
"url",
")",
"for",
"url",
"in",
"itertools",
".",
"chain",
"(",
"index_file_loc",
",",
"fl_file_loc",
")",
"]",
"# We trust every directly linked archive in find_links",
"find_link_links",
"=",
"[",
"Link",
"(",
"url",
",",
"'-f'",
")",
"for",
"url",
"in",
"self",
".",
"find_links",
"]",
"# We trust every url that the user has given us whether it was given",
"# via --index-url or --find-links.",
"# We want to filter out anything that does not have a secure origin.",
"url_locations",
"=",
"[",
"link",
"for",
"link",
"in",
"itertools",
".",
"chain",
"(",
"# Mark PyPI indices as \"cache_link_parsing == False\" -- this",
"# will avoid caching the result of parsing the page for links.",
"(",
"Link",
"(",
"url",
",",
"cache_link_parsing",
"=",
"False",
")",
"for",
"url",
"in",
"index_url_loc",
")",
",",
"(",
"Link",
"(",
"url",
")",
"for",
"url",
"in",
"fl_url_loc",
")",
",",
")",
"if",
"self",
".",
"session",
".",
"is_secure_origin",
"(",
"link",
")",
"]",
"url_locations",
"=",
"_remove_duplicate_links",
"(",
"url_locations",
")",
"lines",
"=",
"[",
"'{} location(s) to search for versions of {}:'",
".",
"format",
"(",
"len",
"(",
"url_locations",
")",
",",
"project_name",
",",
")",
",",
"]",
"for",
"link",
"in",
"url_locations",
":",
"lines",
".",
"append",
"(",
"f'* {link}'",
")",
"logger",
".",
"debug",
"(",
"'\\n'",
".",
"join",
"(",
"lines",
")",
")",
"return",
"CollectedLinks",
"(",
"files",
"=",
"file_links",
",",
"find_links",
"=",
"find_link_links",
",",
"project_urls",
"=",
"url_locations",
",",
")"
] |
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/index/collector.py#L619-L666
|
|
apple/swift-clang
|
d7403439fc6641751840b723e7165fb02f52db95
|
bindings/python/clang/cindex.py
|
python
|
Type.translation_unit
|
(self)
|
return self._tu
|
The TranslationUnit to which this Type is associated.
|
The TranslationUnit to which this Type is associated.
|
[
"The",
"TranslationUnit",
"to",
"which",
"this",
"Type",
"is",
"associated",
"."
] |
def translation_unit(self):
"""The TranslationUnit to which this Type is associated."""
# If this triggers an AttributeError, the instance was not properly
# instantiated.
return self._tu
|
[
"def",
"translation_unit",
"(",
"self",
")",
":",
"# If this triggers an AttributeError, the instance was not properly",
"# instantiated.",
"return",
"self",
".",
"_tu"
] |
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L2256-L2260
|
|
abforce/xposed_art_n
|
ec3fbe417d74d4664cec053d91dd4e3881176374
|
tools/cpplint.py
|
python
|
CheckForNonStandardConstructs
|
(filename, clean_lines, linenum,
nesting_state, error)
|
Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
|
Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
|
[
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] |
def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args and
args.group(1) != 'void' and
not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname),
args.group(1).strip())):
error(filename, linenum, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.')
|
[
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"3",
",",
"'%q in format strings is deprecated. Use %ll instead.'",
")",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%\\d+\\$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"2",
",",
"'%N$ formats are unconventional. Try rewriting to avoid them.'",
")",
"# Remove escaped backslashes before looking for undefined escapes.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"Search",
"(",
"r'(\"|\\').*\\\\(%|\\[|\\(|{)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/printf_format'",
",",
"3",
",",
"'%, [, (, and { are undefined character escapes. Unescape them.'",
")",
"# For the rest, work with both comments and strings removed.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\b(const|volatile|void|char|short|int|long'",
"r'|float|double|signed|unsigned'",
"r'|schar|u?int8|u?int16|u?int32|u?int64)'",
"r'\\s+(register|static|extern|typedef)\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/storage_class'",
",",
"5",
",",
"'Storage class (static, extern, typedef, etc) should be first.'",
")",
"if",
"Match",
"(",
"r'\\s*#\\s*endif\\s*[^/\\s]+'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/endif_comment'",
",",
"5",
",",
"'Uncommented text after #endif is non-standard. Use a comment.'",
")",
"if",
"Match",
"(",
"r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/forward_decl'",
",",
"5",
",",
"'Inner-style forward declarations are invalid. Remove this line.'",
")",
"if",
"Search",
"(",
"r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/deprecated'",
",",
"3",
",",
"'>? and <? (max and min) operators are non-standard and deprecated.'",
")",
"if",
"Search",
"(",
"r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'",
",",
"line",
")",
":",
"# TODO(unknown): Could it be expanded safely to arbitrary references,",
"# without triggering too many false positives? The first",
"# attempt triggered 5 warnings for mostly benign code in the regtest, hence",
"# the restriction.",
"# Here's the original regexp, for the reference:",
"# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'",
"# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/member_string_references'",
",",
"2",
",",
"'const string& members are dangerous. It is much better to use '",
"'alternatives, such as pointers or simple constants.'",
")",
"# Everything else in this function operates on class declarations.",
"# Return early if the top of the nesting stack is not a class, or if",
"# the class head is not completed yet.",
"classinfo",
"=",
"nesting_state",
".",
"InnermostClass",
"(",
")",
"if",
"not",
"classinfo",
"or",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"return",
"# The class may have been declared with namespace or classname qualifiers.",
"# The constructor and destructor will not have those qualifiers.",
"base_classname",
"=",
"classinfo",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
"# Look for single-argument constructors that aren't marked explicit.",
"# Technically a valid construct, but against style.",
"args",
"=",
"Match",
"(",
"r'\\s+(?:inline\\s+)?%s\\s*\\(([^,()]+)\\)'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"line",
")",
"if",
"(",
"args",
"and",
"args",
".",
"group",
"(",
"1",
")",
"!=",
"'void'",
"and",
"not",
"Match",
"(",
"r'(const\\s+)?%s\\s*(?:<\\w+>\\s*)?&'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"args",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Single-argument constructors should be marked explicit.'",
")"
] |
https://github.com/abforce/xposed_art_n/blob/ec3fbe417d74d4664cec053d91dd4e3881176374/tools/cpplint.py#L1783-L1887
|
||
Floydlang/floyd
|
b7070c73d58d3caf15bbcedf3d4f882db893917b
|
compiler/libs/benchmark/tools/gbench/report.py
|
python
|
partition_benchmarks
|
(json1, json2)
|
return partitions
|
While preserving the ordering, find benchmarks with the same names in
both of the inputs, and group them.
(i.e. partition/filter into groups with common name)
|
While preserving the ordering, find benchmarks with the same names in
both of the inputs, and group them.
(i.e. partition/filter into groups with common name)
|
[
"While",
"preserving",
"the",
"ordering",
"find",
"benchmarks",
"with",
"the",
"same",
"names",
"in",
"both",
"of",
"the",
"inputs",
"and",
"group",
"them",
".",
"(",
"i",
".",
"e",
".",
"partition",
"/",
"filter",
"into",
"groups",
"with",
"common",
"name",
")"
] |
def partition_benchmarks(json1, json2):
"""
While preserving the ordering, find benchmarks with the same names in
both of the inputs, and group them.
(i.e. partition/filter into groups with common name)
"""
json1_unique_names = get_unique_benchmark_names(json1)
json2_unique_names = get_unique_benchmark_names(json2)
names = intersect(json1_unique_names, json2_unique_names)
partitions = []
for name in names:
# Pick the time unit from the first entry of the lhs benchmark.
time_unit = (x['time_unit']
for x in json1['benchmarks'] if x['name'] == name).next()
# Filter by name and time unit.
lhs = [x for x in json1['benchmarks'] if x['name'] == name and
x['time_unit'] == time_unit]
rhs = [x for x in json2['benchmarks'] if x['name'] == name and
x['time_unit'] == time_unit]
partitions.append([lhs, rhs])
return partitions
|
[
"def",
"partition_benchmarks",
"(",
"json1",
",",
"json2",
")",
":",
"json1_unique_names",
"=",
"get_unique_benchmark_names",
"(",
"json1",
")",
"json2_unique_names",
"=",
"get_unique_benchmark_names",
"(",
"json2",
")",
"names",
"=",
"intersect",
"(",
"json1_unique_names",
",",
"json2_unique_names",
")",
"partitions",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"# Pick the time unit from the first entry of the lhs benchmark.",
"time_unit",
"=",
"(",
"x",
"[",
"'time_unit'",
"]",
"for",
"x",
"in",
"json1",
"[",
"'benchmarks'",
"]",
"if",
"x",
"[",
"'name'",
"]",
"==",
"name",
")",
".",
"next",
"(",
")",
"# Filter by name and time unit.",
"lhs",
"=",
"[",
"x",
"for",
"x",
"in",
"json1",
"[",
"'benchmarks'",
"]",
"if",
"x",
"[",
"'name'",
"]",
"==",
"name",
"and",
"x",
"[",
"'time_unit'",
"]",
"==",
"time_unit",
"]",
"rhs",
"=",
"[",
"x",
"for",
"x",
"in",
"json2",
"[",
"'benchmarks'",
"]",
"if",
"x",
"[",
"'name'",
"]",
"==",
"name",
"and",
"x",
"[",
"'time_unit'",
"]",
"==",
"time_unit",
"]",
"partitions",
".",
"append",
"(",
"[",
"lhs",
",",
"rhs",
"]",
")",
"return",
"partitions"
] |
https://github.com/Floydlang/floyd/blob/b7070c73d58d3caf15bbcedf3d4f882db893917b/compiler/libs/benchmark/tools/gbench/report.py#L117-L137
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/_core.py
|
python
|
GBSizerItemList_iterator.next
|
(*args, **kwargs)
|
return _core_.GBSizerItemList_iterator_next(*args, **kwargs)
|
next(self) -> GBSizerItem
|
next(self) -> GBSizerItem
|
[
"next",
"(",
"self",
")",
"-",
">",
"GBSizerItem"
] |
def next(*args, **kwargs):
"""next(self) -> GBSizerItem"""
return _core_.GBSizerItemList_iterator_next(*args, **kwargs)
|
[
"def",
"next",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"GBSizerItemList_iterator_next",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L15862-L15864
|
|
GoSSIP-SJTU/Armariris
|
ad5d868482956b2194a77b39c8d543c7c2318200
|
tools/clang/bindings/python/clang/cindex.py
|
python
|
register_functions
|
(lib, ignore_errors)
|
Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library.
|
Register function prototypes with a libclang library instance.
|
[
"Register",
"function",
"prototypes",
"with",
"a",
"libclang",
"library",
"instance",
"."
] |
def register_functions(lib, ignore_errors):
"""Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library.
"""
def register(item):
return register_function(lib, item, ignore_errors)
map(register, functionList)
|
[
"def",
"register_functions",
"(",
"lib",
",",
"ignore_errors",
")",
":",
"def",
"register",
"(",
"item",
")",
":",
"return",
"register_function",
"(",
"lib",
",",
"item",
",",
"ignore_errors",
")",
"map",
"(",
"register",
",",
"functionList",
")"
] |
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L3614-L3624
|
||
PixarAnimationStudios/USD
|
faed18ce62c8736b02413635b584a2f637156bad
|
pxr/usdImaging/usdviewq/appController.py
|
python
|
Blocker.__enter__
|
(self)
|
Enter the 'blocked' state until the context is exited.
|
Enter the 'blocked' state until the context is exited.
|
[
"Enter",
"the",
"blocked",
"state",
"until",
"the",
"context",
"is",
"exited",
"."
] |
def __enter__(self):
"""Enter the 'blocked' state until the context is exited."""
self._count += 1
|
[
"def",
"__enter__",
"(",
"self",
")",
":",
"self",
".",
"_count",
"+=",
"1"
] |
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L252-L255
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py
|
python
|
WorkingSet.find
|
(self, req)
|
return dist
|
Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is raised.
If there is no active distribution for the requested project, ``None``
is returned.
|
Find a distribution matching requirement `req`
|
[
"Find",
"a",
"distribution",
"matching",
"requirement",
"req"
] |
def find(self, req):
"""Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is raised.
If there is no active distribution for the requested project, ``None``
is returned.
"""
dist = self.by_key.get(req.key)
if dist is not None and dist not in req:
# XXX add more info
raise VersionConflict(dist, req)
return dist
|
[
"def",
"find",
"(",
"self",
",",
"req",
")",
":",
"dist",
"=",
"self",
".",
"by_key",
".",
"get",
"(",
"req",
".",
"key",
")",
"if",
"dist",
"is",
"not",
"None",
"and",
"dist",
"not",
"in",
"req",
":",
"# XXX add more info",
"raise",
"VersionConflict",
"(",
"dist",
",",
"req",
")",
"return",
"dist"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L630-L644
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/compiler.py
|
python
|
_unpack_argument
|
(ty, val, kernelargs, retr)
|
Convert arguments to ctypes and append to kernelargs
|
Convert arguments to ctypes and append to kernelargs
|
[
"Convert",
"arguments",
"to",
"ctypes",
"and",
"append",
"to",
"kernelargs"
] |
def _unpack_argument(ty, val, kernelargs, retr):
"""
Convert arguments to ctypes and append to kernelargs
"""
if isinstance(ty, types.Array):
c_intp = ctypes.c_ssize_t
# if a dgpu is present, move the data to the device.
if dgpu_present:
devary, conv = devicearray.auto_device(val, devices.get_context())
if conv:
retr.append(lambda: devary.copy_to_host(val))
data = devary.device_ctypes_pointer
else:
data = ctypes.c_void_p(val.ctypes.data)
meminfo = parent = ctypes.c_void_p(0)
nitems = c_intp(val.size)
itemsize = c_intp(val.dtype.itemsize)
kernelargs.append(meminfo)
kernelargs.append(parent)
kernelargs.append(nitems)
kernelargs.append(itemsize)
kernelargs.append(data)
for ax in range(val.ndim):
kernelargs.append(c_intp(val.shape[ax]))
for ax in range(val.ndim):
kernelargs.append(c_intp(val.strides[ax]))
elif isinstance(ty, types.Integer):
cval = getattr(ctypes, "c_%s" % ty)(val)
kernelargs.append(cval)
elif ty == types.float64:
cval = ctypes.c_double(val)
kernelargs.append(cval)
elif ty == types.float32:
cval = ctypes.c_float(val)
kernelargs.append(cval)
elif ty == types.boolean:
cval = ctypes.c_uint8(int(val))
kernelargs.append(cval)
elif ty == types.complex64:
kernelargs.append(ctypes.c_float(val.real))
kernelargs.append(ctypes.c_float(val.imag))
elif ty == types.complex128:
kernelargs.append(ctypes.c_double(val.real))
kernelargs.append(ctypes.c_double(val.imag))
else:
raise NotImplementedError(ty, val)
|
[
"def",
"_unpack_argument",
"(",
"ty",
",",
"val",
",",
"kernelargs",
",",
"retr",
")",
":",
"if",
"isinstance",
"(",
"ty",
",",
"types",
".",
"Array",
")",
":",
"c_intp",
"=",
"ctypes",
".",
"c_ssize_t",
"# if a dgpu is present, move the data to the device.",
"if",
"dgpu_present",
":",
"devary",
",",
"conv",
"=",
"devicearray",
".",
"auto_device",
"(",
"val",
",",
"devices",
".",
"get_context",
"(",
")",
")",
"if",
"conv",
":",
"retr",
".",
"append",
"(",
"lambda",
":",
"devary",
".",
"copy_to_host",
"(",
"val",
")",
")",
"data",
"=",
"devary",
".",
"device_ctypes_pointer",
"else",
":",
"data",
"=",
"ctypes",
".",
"c_void_p",
"(",
"val",
".",
"ctypes",
".",
"data",
")",
"meminfo",
"=",
"parent",
"=",
"ctypes",
".",
"c_void_p",
"(",
"0",
")",
"nitems",
"=",
"c_intp",
"(",
"val",
".",
"size",
")",
"itemsize",
"=",
"c_intp",
"(",
"val",
".",
"dtype",
".",
"itemsize",
")",
"kernelargs",
".",
"append",
"(",
"meminfo",
")",
"kernelargs",
".",
"append",
"(",
"parent",
")",
"kernelargs",
".",
"append",
"(",
"nitems",
")",
"kernelargs",
".",
"append",
"(",
"itemsize",
")",
"kernelargs",
".",
"append",
"(",
"data",
")",
"for",
"ax",
"in",
"range",
"(",
"val",
".",
"ndim",
")",
":",
"kernelargs",
".",
"append",
"(",
"c_intp",
"(",
"val",
".",
"shape",
"[",
"ax",
"]",
")",
")",
"for",
"ax",
"in",
"range",
"(",
"val",
".",
"ndim",
")",
":",
"kernelargs",
".",
"append",
"(",
"c_intp",
"(",
"val",
".",
"strides",
"[",
"ax",
"]",
")",
")",
"elif",
"isinstance",
"(",
"ty",
",",
"types",
".",
"Integer",
")",
":",
"cval",
"=",
"getattr",
"(",
"ctypes",
",",
"\"c_%s\"",
"%",
"ty",
")",
"(",
"val",
")",
"kernelargs",
".",
"append",
"(",
"cval",
")",
"elif",
"ty",
"==",
"types",
".",
"float64",
":",
"cval",
"=",
"ctypes",
".",
"c_double",
"(",
"val",
")",
"kernelargs",
".",
"append",
"(",
"cval",
")",
"elif",
"ty",
"==",
"types",
".",
"float32",
":",
"cval",
"=",
"ctypes",
".",
"c_float",
"(",
"val",
")",
"kernelargs",
".",
"append",
"(",
"cval",
")",
"elif",
"ty",
"==",
"types",
".",
"boolean",
":",
"cval",
"=",
"ctypes",
".",
"c_uint8",
"(",
"int",
"(",
"val",
")",
")",
"kernelargs",
".",
"append",
"(",
"cval",
")",
"elif",
"ty",
"==",
"types",
".",
"complex64",
":",
"kernelargs",
".",
"append",
"(",
"ctypes",
".",
"c_float",
"(",
"val",
".",
"real",
")",
")",
"kernelargs",
".",
"append",
"(",
"ctypes",
".",
"c_float",
"(",
"val",
".",
"imag",
")",
")",
"elif",
"ty",
"==",
"types",
".",
"complex128",
":",
"kernelargs",
".",
"append",
"(",
"ctypes",
".",
"c_double",
"(",
"val",
".",
"real",
")",
")",
"kernelargs",
".",
"append",
"(",
"ctypes",
".",
"c_double",
"(",
"val",
".",
"imag",
")",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"ty",
",",
"val",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/compiler.py#L374-L428
|
||
hughperkins/tf-coriander
|
970d3df6c11400ad68405f22b0c42a52374e94ca
|
tensorflow/python/ops/control_flow_ops.py
|
python
|
WhileContext.AddBackPropLoopCounter
|
(self, count, outer_grad_state)
|
return next_count
|
Add the backprop loop that controls the iterations.
This is added to the backprop loop. It is used to control the loop
termination of the backprop loop. Called in the outer context of
this grad context.
The pseudocode is:
`n = count; while (n >= 1) { n--; }`
Note that a control dependency is added to `final_zero` to ensure the
correct execution order of stack pop ops.
Args:
count: The number of iterations for backprop.
outer_grad_state: The outer grad state. None if not nested.
Returns:
The loop index.
|
Add the backprop loop that controls the iterations.
|
[
"Add",
"the",
"backprop",
"loop",
"that",
"controls",
"the",
"iterations",
"."
] |
def AddBackPropLoopCounter(self, count, outer_grad_state):
"""Add the backprop loop that controls the iterations.
This is added to the backprop loop. It is used to control the loop
termination of the backprop loop. Called in the outer context of
this grad context.
The pseudocode is:
`n = count; while (n >= 1) { n--; }`
Note that a control dependency is added to `final_zero` to ensure the
correct execution order of stack pop ops.
Args:
count: The number of iterations for backprop.
outer_grad_state: The outer grad state. None if not nested.
Returns:
The loop index.
"""
one = constant_op.constant(1, name="b_count")
self.Enter()
self.AddName(count.name)
enter_count = _Enter(count, self._name, is_constant=False,
parallel_iterations=self._parallel_iterations,
name="b_count")
merge_count = merge([enter_count, enter_count])[0]
self._pivot_for_pred = merge_count
cond = math_ops.greater_equal(merge_count, one)
self._pivot = loop_cond(cond, name="b_count")
switch_count = switch(merge_count, self._pivot)
index = math_ops.sub(switch_count[1], one)
self._pivot_for_body = index
next_count = _NextIteration(index)
merge_count.op._update_input(1, next_count)
final_zero = exit(switch_count[0], name="b_count")
if outer_grad_state is not None:
# Force the stack pops of i-th execution of an inner loop to be ordered
# before the pops of (i+1)-th execution of the same inner loop.
# pylint: disable=protected-access
outer_grad_state.grad_sync._add_control_input(final_zero.op)
# pylint: enable=protected-access
self.ExitResult([final_zero])
self.Exit()
return next_count
|
[
"def",
"AddBackPropLoopCounter",
"(",
"self",
",",
"count",
",",
"outer_grad_state",
")",
":",
"one",
"=",
"constant_op",
".",
"constant",
"(",
"1",
",",
"name",
"=",
"\"b_count\"",
")",
"self",
".",
"Enter",
"(",
")",
"self",
".",
"AddName",
"(",
"count",
".",
"name",
")",
"enter_count",
"=",
"_Enter",
"(",
"count",
",",
"self",
".",
"_name",
",",
"is_constant",
"=",
"False",
",",
"parallel_iterations",
"=",
"self",
".",
"_parallel_iterations",
",",
"name",
"=",
"\"b_count\"",
")",
"merge_count",
"=",
"merge",
"(",
"[",
"enter_count",
",",
"enter_count",
"]",
")",
"[",
"0",
"]",
"self",
".",
"_pivot_for_pred",
"=",
"merge_count",
"cond",
"=",
"math_ops",
".",
"greater_equal",
"(",
"merge_count",
",",
"one",
")",
"self",
".",
"_pivot",
"=",
"loop_cond",
"(",
"cond",
",",
"name",
"=",
"\"b_count\"",
")",
"switch_count",
"=",
"switch",
"(",
"merge_count",
",",
"self",
".",
"_pivot",
")",
"index",
"=",
"math_ops",
".",
"sub",
"(",
"switch_count",
"[",
"1",
"]",
",",
"one",
")",
"self",
".",
"_pivot_for_body",
"=",
"index",
"next_count",
"=",
"_NextIteration",
"(",
"index",
")",
"merge_count",
".",
"op",
".",
"_update_input",
"(",
"1",
",",
"next_count",
")",
"final_zero",
"=",
"exit",
"(",
"switch_count",
"[",
"0",
"]",
",",
"name",
"=",
"\"b_count\"",
")",
"if",
"outer_grad_state",
"is",
"not",
"None",
":",
"# Force the stack pops of i-th execution of an inner loop to be ordered",
"# before the pops of (i+1)-th execution of the same inner loop.",
"# pylint: disable=protected-access",
"outer_grad_state",
".",
"grad_sync",
".",
"_add_control_input",
"(",
"final_zero",
".",
"op",
")",
"# pylint: enable=protected-access",
"self",
".",
"ExitResult",
"(",
"[",
"final_zero",
"]",
")",
"self",
".",
"Exit",
"(",
")",
"return",
"next_count"
] |
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/control_flow_ops.py#L2060-L2109
|
|
turi-code/SFrame
|
796b9bdfb2fa1b881d82080754643c7e68629cd2
|
oss_src/unity/python/sframe/toolkits/_model.py
|
python
|
CustomModel.__init__
|
(self, proxy = None)
|
Construct a dummy object from its proxy object and class name. The
proxy contains a location to the pickle-file where the real object
is stored.
Parameters
----------
proxy : object
Returns
-------
Returns an object of type _class with a path to the pickle archive
saved in proxy.temp_file.
|
Construct a dummy object from its proxy object and class name. The
proxy contains a location to the pickle-file where the real object
is stored.
|
[
"Construct",
"a",
"dummy",
"object",
"from",
"its",
"proxy",
"object",
"and",
"class",
"name",
".",
"The",
"proxy",
"contains",
"a",
"location",
"to",
"the",
"pickle",
"-",
"file",
"where",
"the",
"real",
"object",
"is",
"stored",
"."
] |
def __init__(self, proxy = None):
"""
Construct a dummy object from its proxy object and class name. The
proxy contains a location to the pickle-file where the real object
is stored.
Parameters
----------
proxy : object
Returns
-------
Returns an object of type _class with a path to the pickle archive
saved in proxy.temp_file.
"""
self.__proxy__ = None
|
[
"def",
"__init__",
"(",
"self",
",",
"proxy",
"=",
"None",
")",
":",
"self",
".",
"__proxy__",
"=",
"None"
] |
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/toolkits/_model.py#L232-L248
|
||
blackberry/Boost
|
fc90c3fde129c62565c023f091eddc4a7ed9902b
|
tools/build/v2/tools/common.py
|
python
|
reset
|
()
|
Clear the module state. This is mainly for testing purposes.
Note that this must be called _after_ resetting the module 'feature'.
|
Clear the module state. This is mainly for testing purposes.
Note that this must be called _after_ resetting the module 'feature'.
|
[
"Clear",
"the",
"module",
"state",
".",
"This",
"is",
"mainly",
"for",
"testing",
"purposes",
".",
"Note",
"that",
"this",
"must",
"be",
"called",
"_after_",
"resetting",
"the",
"module",
"feature",
"."
] |
def reset ():
""" Clear the module state. This is mainly for testing purposes.
Note that this must be called _after_ resetting the module 'feature'.
"""
global __had_unspecified_value, __had_value, __declared_subfeature
global __init_loc
global __all_signatures, __debug_configuration, __show_configuration
# Stores toolsets without specified initialization values.
__had_unspecified_value = {}
# Stores toolsets with specified initialization values.
__had_value = {}
# Stores toolsets with declared subfeatures.
__declared_subfeature = {}
# Stores all signatures of the toolsets.
__all_signatures = {}
# Stores the initialization locations of each toolset
__init_loc = {}
__debug_configuration = '--debug-configuration' in bjam.variable('ARGV')
__show_configuration = '--show-configuration' in bjam.variable('ARGV')
global __executable_path_variable
OS = bjam.call("peek", [], "OS")[0]
if OS == "NT":
# On Windows the case and capitalization of PATH is not always predictable, so
# let's find out what variable name was really set.
for n in os.environ:
if n.lower() == "path":
__executable_path_variable = n
break
else:
__executable_path_variable = "PATH"
m = {"NT": __executable_path_variable,
"CYGWIN": "PATH",
"MACOSX": "DYLD_LIBRARY_PATH",
"AIX": "LIBPATH"}
global __shared_library_path_variable
__shared_library_path_variable = m.get(OS, "LD_LIBRARY_PATH")
|
[
"def",
"reset",
"(",
")",
":",
"global",
"__had_unspecified_value",
",",
"__had_value",
",",
"__declared_subfeature",
"global",
"__init_loc",
"global",
"__all_signatures",
",",
"__debug_configuration",
",",
"__show_configuration",
"# Stores toolsets without specified initialization values.",
"__had_unspecified_value",
"=",
"{",
"}",
"# Stores toolsets with specified initialization values.",
"__had_value",
"=",
"{",
"}",
"# Stores toolsets with declared subfeatures.",
"__declared_subfeature",
"=",
"{",
"}",
"# Stores all signatures of the toolsets.",
"__all_signatures",
"=",
"{",
"}",
"# Stores the initialization locations of each toolset",
"__init_loc",
"=",
"{",
"}",
"__debug_configuration",
"=",
"'--debug-configuration'",
"in",
"bjam",
".",
"variable",
"(",
"'ARGV'",
")",
"__show_configuration",
"=",
"'--show-configuration'",
"in",
"bjam",
".",
"variable",
"(",
"'ARGV'",
")",
"global",
"__executable_path_variable",
"OS",
"=",
"bjam",
".",
"call",
"(",
"\"peek\"",
",",
"[",
"]",
",",
"\"OS\"",
")",
"[",
"0",
"]",
"if",
"OS",
"==",
"\"NT\"",
":",
"# On Windows the case and capitalization of PATH is not always predictable, so",
"# let's find out what variable name was really set.",
"for",
"n",
"in",
"os",
".",
"environ",
":",
"if",
"n",
".",
"lower",
"(",
")",
"==",
"\"path\"",
":",
"__executable_path_variable",
"=",
"n",
"break",
"else",
":",
"__executable_path_variable",
"=",
"\"PATH\"",
"m",
"=",
"{",
"\"NT\"",
":",
"__executable_path_variable",
",",
"\"CYGWIN\"",
":",
"\"PATH\"",
",",
"\"MACOSX\"",
":",
"\"DYLD_LIBRARY_PATH\"",
",",
"\"AIX\"",
":",
"\"LIBPATH\"",
"}",
"global",
"__shared_library_path_variable",
"__shared_library_path_variable",
"=",
"m",
".",
"get",
"(",
"OS",
",",
"\"LD_LIBRARY_PATH\"",
")"
] |
https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/tools/common.py#L25-L68
|
||
BlzFans/wke
|
b0fa21158312e40c5fbd84682d643022b6c34a93
|
cygwin/lib/python2.6/cgitb.py
|
python
|
lookup
|
(name, frame, locals)
|
return None, __UNDEF__
|
Find the value for a given name in the given environment.
|
Find the value for a given name in the given environment.
|
[
"Find",
"the",
"value",
"for",
"a",
"given",
"name",
"in",
"the",
"given",
"environment",
"."
] |
def lookup(name, frame, locals):
"""Find the value for a given name in the given environment."""
if name in locals:
return 'local', locals[name]
if name in frame.f_globals:
return 'global', frame.f_globals[name]
if '__builtins__' in frame.f_globals:
builtins = frame.f_globals['__builtins__']
if type(builtins) is type({}):
if name in builtins:
return 'builtin', builtins[name]
else:
if hasattr(builtins, name):
return 'builtin', getattr(builtins, name)
return None, __UNDEF__
|
[
"def",
"lookup",
"(",
"name",
",",
"frame",
",",
"locals",
")",
":",
"if",
"name",
"in",
"locals",
":",
"return",
"'local'",
",",
"locals",
"[",
"name",
"]",
"if",
"name",
"in",
"frame",
".",
"f_globals",
":",
"return",
"'global'",
",",
"frame",
".",
"f_globals",
"[",
"name",
"]",
"if",
"'__builtins__'",
"in",
"frame",
".",
"f_globals",
":",
"builtins",
"=",
"frame",
".",
"f_globals",
"[",
"'__builtins__'",
"]",
"if",
"type",
"(",
"builtins",
")",
"is",
"type",
"(",
"{",
"}",
")",
":",
"if",
"name",
"in",
"builtins",
":",
"return",
"'builtin'",
",",
"builtins",
"[",
"name",
"]",
"else",
":",
"if",
"hasattr",
"(",
"builtins",
",",
"name",
")",
":",
"return",
"'builtin'",
",",
"getattr",
"(",
"builtins",
",",
"name",
")",
"return",
"None",
",",
"__UNDEF__"
] |
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/cgitb.py#L59-L73
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pkgutil.py
|
python
|
find_loader
|
(fullname)
|
return spec.loader if spec is not None else None
|
Find a "loader" object for fullname
This is a backwards compatibility wrapper around
importlib.util.find_spec that converts most failures to ImportError
and only returns the loader rather than the full spec
|
Find a "loader" object for fullname
|
[
"Find",
"a",
"loader",
"object",
"for",
"fullname"
] |
def find_loader(fullname):
"""Find a "loader" object for fullname
This is a backwards compatibility wrapper around
importlib.util.find_spec that converts most failures to ImportError
and only returns the loader rather than the full spec
"""
if fullname.startswith('.'):
msg = "Relative module name {!r} not supported".format(fullname)
raise ImportError(msg)
try:
spec = importlib.util.find_spec(fullname)
except (ImportError, AttributeError, TypeError, ValueError) as ex:
# This hack fixes an impedance mismatch between pkgutil and
# importlib, where the latter raises other errors for cases where
# pkgutil previously raised ImportError
msg = "Error while finding loader for {!r} ({}: {})"
raise ImportError(msg.format(fullname, type(ex), ex)) from ex
return spec.loader if spec is not None else None
|
[
"def",
"find_loader",
"(",
"fullname",
")",
":",
"if",
"fullname",
".",
"startswith",
"(",
"'.'",
")",
":",
"msg",
"=",
"\"Relative module name {!r} not supported\"",
".",
"format",
"(",
"fullname",
")",
"raise",
"ImportError",
"(",
"msg",
")",
"try",
":",
"spec",
"=",
"importlib",
".",
"util",
".",
"find_spec",
"(",
"fullname",
")",
"except",
"(",
"ImportError",
",",
"AttributeError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"ex",
":",
"# This hack fixes an impedance mismatch between pkgutil and",
"# importlib, where the latter raises other errors for cases where",
"# pkgutil previously raised ImportError",
"msg",
"=",
"\"Error while finding loader for {!r} ({}: {})\"",
"raise",
"ImportError",
"(",
"msg",
".",
"format",
"(",
"fullname",
",",
"type",
"(",
"ex",
")",
",",
"ex",
")",
")",
"from",
"ex",
"return",
"spec",
".",
"loader",
"if",
"spec",
"is",
"not",
"None",
"else",
"None"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pkgutil.py#L482-L500
|
|
chromiumembedded/cef
|
80caf947f3fe2210e5344713c5281d8af9bdc295
|
tools/yapf/yapf/yapflib/format_decision_state.py
|
python
|
FormatDecisionState.MustSplit
|
(self)
|
return False
|
Returns True if the line must split before the next token.
|
Returns True if the line must split before the next token.
|
[
"Returns",
"True",
"if",
"the",
"line",
"must",
"split",
"before",
"the",
"next",
"token",
"."
] |
def MustSplit(self):
"""Returns True if the line must split before the next token."""
current = self.next_token
previous = current.previous_token
if current.is_pseudo_paren:
return False
if current.must_break_before:
return True
if not previous:
return False
if self.stack[-1].split_before_closing_bracket and current.value in '}]':
# Split before the closing bracket if we can.
return current.node_split_penalty != split_penalty.UNBREAKABLE
# Prevent splitting before the first argument in compound statements
# with the exception of function declarations.
if (style.Get('SPLIT_BEFORE_FIRST_ARGUMENT') and
self.line.first.value != 'def' and
self.line.first.value in _COMPOUND_STMTS):
return False
###########################################################################
# List Splitting
if (style.Get('DEDENT_CLOSING_BRACKETS') or
style.Get('SPLIT_BEFORE_FIRST_ARGUMENT')):
bracket = current if current.ClosesScope() else previous
if format_token.Subtype.SUBSCRIPT_BRACKET not in bracket.subtypes:
if bracket.OpensScope():
if style.Get('COALESCE_BRACKETS'):
if current.OpensScope():
# Prefer to keep all opening brackets together.
return False
if (not _IsLastScopeInLine(bracket) or
unwrapped_line.IsSurroundedByBrackets(bracket)):
last_token = bracket.matching_bracket
else:
last_token = _LastTokenInLine(bracket.matching_bracket)
if not self._FitsOnLine(bracket, last_token):
# Split before the first element if the whole list can't fit on a
# single line.
self.stack[-1].split_before_closing_bracket = True
return True
elif style.Get('DEDENT_CLOSING_BRACKETS') and current.ClosesScope():
# Split before and dedent the closing bracket.
return self.stack[-1].split_before_closing_bracket
if (current.is_name or current.is_string) and previous.value == ',':
# If the list has function calls in it and the full list itself cannot
# fit on the line, then we want to split. Otherwise, we'll get something
# like this:
#
# X = [
# Bar(xxx='some string',
# yyy='another long string',
# zzz='a third long string'), Bar(
# xxx='some string',
# yyy='another long string',
# zzz='a third long string')
# ]
#
# or when a string formatting syntax.
func_call_or_string_format = False
if current.is_name:
tok = current.next_token
while tok and (tok.is_name or tok.value == '.'):
tok = tok.next_token
func_call_or_string_format = tok and tok.value == '('
elif current.is_string:
tok = current.next_token
while tok and tok.is_string:
tok = tok.next_token
func_call_or_string_format = tok and tok.value == '%'
if func_call_or_string_format:
open_bracket = unwrapped_line.IsSurroundedByBrackets(current)
if open_bracket and open_bracket.value in '[{':
if not self._FitsOnLine(open_bracket, open_bracket.matching_bracket):
return True
###########################################################################
# Dict/Set Splitting
if (style.Get('EACH_DICT_ENTRY_ON_SEPARATE_LINE') and
format_token.Subtype.DICTIONARY_KEY in current.subtypes and
not current.is_comment):
# Place each dictionary entry onto its own line.
if previous.value == '{' and previous.previous_token:
opening = _GetOpeningBracket(previous.previous_token)
if (opening and opening.value == '(' and opening.previous_token and
opening.previous_token.is_name):
# This is a dictionary that's an argument to a function.
if self._FitsOnLine(previous, previous.matching_bracket):
return False
return True
if (style.Get('SPLIT_BEFORE_DICT_SET_GENERATOR') and
format_token.Subtype.DICT_SET_GENERATOR in current.subtypes):
# Split before a dict/set generator.
return True
if (format_token.Subtype.DICTIONARY_VALUE in current.subtypes or
(previous.is_pseudo_paren and previous.value == '(' and
not current.is_comment)):
# Split before the dictionary value if we can't fit every dictionary
# entry on its own line.
if not current.OpensScope():
opening = _GetOpeningBracket(current)
if not self._EachDictEntryFitsOnOneLine(opening):
return True
if previous.value == '{':
# Split if the dict/set cannot fit on one line and ends in a comma.
closing = previous.matching_bracket
if (not self._FitsOnLine(previous, closing) and
closing.previous_token.value == ','):
self.stack[-1].split_before_closing_bracket = True
return True
###########################################################################
# Argument List Splitting
if (style.Get('SPLIT_BEFORE_NAMED_ASSIGNS') and not current.is_comment and
format_token.Subtype.DEFAULT_OR_NAMED_ASSIGN_ARG_LIST in
current.subtypes):
if (previous.value not in {'=', ':', '*', '**'} and
current.value not in ':=,)' and not _IsFunctionDefinition(previous)):
# If we're going to split the lines because of named arguments, then we
# want to split after the opening bracket as well. But not when this is
# part of a function definition.
if previous.value == '(':
# Make sure we don't split after the opening bracket if the
# continuation indent is greater than the opening bracket:
#
# a(
# b=1,
# c=2)
if (self._FitsOnLine(previous, previous.matching_bracket) and
unwrapped_line.IsSurroundedByBrackets(previous)):
# An argument to a function is a function call with named
# assigns.
return False
column = self.column - self.stack[-1].last_space
return column > style.Get('CONTINUATION_INDENT_WIDTH')
opening = _GetOpeningBracket(current)
if opening:
arglist_length = (opening.matching_bracket.total_length -
opening.total_length + self.stack[-1].indent)
return arglist_length > self.column_limit
if style.Get('SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED'):
# Split before arguments in a function call or definition if the
# arguments are terminated by a comma.
opening = _GetOpeningBracket(current)
if opening and opening.previous_token and opening.previous_token.is_name:
if previous.value in '(,':
if opening.matching_bracket.previous_token.value == ',':
return True
if ((current.is_name or current.value in {'*', '**'}) and
previous.value == ','):
# If we have a function call within an argument list and it won't fit on
# the remaining line, but it will fit on a line by itself, then go ahead
# and split before the call.
opening = _GetOpeningBracket(current)
if (opening and opening.value == '(' and opening.previous_token and
(opening.previous_token.is_name or
opening.previous_token.value in {'*', '**'})):
is_func_call = False
token = current
while token:
if token.value == '(':
is_func_call = True
break
if (not (token.is_name or token.value in {'*', '**'}) and
token.value != '.'):
break
token = token.next_token
if is_func_call:
if not self._FitsOnLine(current, opening.matching_bracket):
return True
pprevious = previous.previous_token
if (current.is_name and pprevious and pprevious.is_name and
previous.value == '('):
if (not self._FitsOnLine(previous, previous.matching_bracket) and
_IsFunctionCallWithArguments(current)):
# There is a function call, with more than 1 argument, where the first
# argument is itself a function call with arguments. In this specific
# case, if we split after the first argument's opening '(', then the
# formatting will look bad for the rest of the arguments. E.g.:
#
# outer_function_call(inner_function_call(
# inner_arg1, inner_arg2),
# outer_arg1, outer_arg2)
#
# Instead, enforce a split before that argument to keep things looking
# good.
return True
if (previous.OpensScope() and not current.OpensScope() and
format_token.Subtype.SUBSCRIPT_BRACKET not in previous.subtypes):
if not current.is_comment:
if pprevious and not pprevious.is_keyword and not pprevious.is_name:
# We want to split if there's a comment in the container.
token = current
while token != previous.matching_bracket:
if token.is_comment:
return True
token = token.next_token
if previous.value == '(':
pptoken = previous.previous_token
if not pptoken or not pptoken.is_name:
# Split after the opening of a tuple if it doesn't fit on the current
# line and it's not a function call.
if self._FitsOnLine(previous, previous.matching_bracket):
return False
elif not self._FitsOnLine(previous, previous.matching_bracket):
if (self.column_limit - self.column) / float(self.column_limit) < 0.3:
# Try not to squish all of the arguments off to the right.
return current.next_token != previous.matching_bracket
else:
# Split after the opening of a container if it doesn't fit on the
# current line or if it has a comment.
if not self._FitsOnLine(previous, previous.matching_bracket):
return True
###########################################################################
# List Comprehension Splitting
if (format_token.Subtype.COMP_FOR in current.subtypes and
format_token.Subtype.COMP_FOR not in previous.subtypes):
# Split at the beginning of a list comprehension.
length = _GetLengthOfSubtype(current, format_token.Subtype.COMP_FOR,
format_token.Subtype.COMP_IF)
if length + self.column > self.column_limit:
return True
if (format_token.Subtype.COMP_IF in current.subtypes and
format_token.Subtype.COMP_IF not in previous.subtypes):
# Split at the beginning of an if expression.
length = _GetLengthOfSubtype(current, format_token.Subtype.COMP_IF)
if length + self.column > self.column_limit:
return True
###########################################################################
# Original Formatting Splitting
# These checks rely upon the original formatting. This is in order to
# attempt to keep hand-written code in the same condition as it was before.
# However, this may cause the formatter to fail to be idempotent.
if (style.Get('SPLIT_BEFORE_BITWISE_OPERATOR') and current.value in '&|' and
previous.lineno < current.lineno):
# Retain the split before a bitwise operator.
return True
if (current.is_comment and
previous.lineno < current.lineno - current.value.count('\n')):
# If a comment comes in the middle of an unwrapped line (like an if
# conditional with comments interspersed), then we want to split if the
# original comments were on a separate line.
return True
return False
|
[
"def",
"MustSplit",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"next_token",
"previous",
"=",
"current",
".",
"previous_token",
"if",
"current",
".",
"is_pseudo_paren",
":",
"return",
"False",
"if",
"current",
".",
"must_break_before",
":",
"return",
"True",
"if",
"not",
"previous",
":",
"return",
"False",
"if",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"split_before_closing_bracket",
"and",
"current",
".",
"value",
"in",
"'}]'",
":",
"# Split before the closing bracket if we can.",
"return",
"current",
".",
"node_split_penalty",
"!=",
"split_penalty",
".",
"UNBREAKABLE",
"# Prevent splitting before the first argument in compound statements",
"# with the exception of function declarations.",
"if",
"(",
"style",
".",
"Get",
"(",
"'SPLIT_BEFORE_FIRST_ARGUMENT'",
")",
"and",
"self",
".",
"line",
".",
"first",
".",
"value",
"!=",
"'def'",
"and",
"self",
".",
"line",
".",
"first",
".",
"value",
"in",
"_COMPOUND_STMTS",
")",
":",
"return",
"False",
"###########################################################################",
"# List Splitting",
"if",
"(",
"style",
".",
"Get",
"(",
"'DEDENT_CLOSING_BRACKETS'",
")",
"or",
"style",
".",
"Get",
"(",
"'SPLIT_BEFORE_FIRST_ARGUMENT'",
")",
")",
":",
"bracket",
"=",
"current",
"if",
"current",
".",
"ClosesScope",
"(",
")",
"else",
"previous",
"if",
"format_token",
".",
"Subtype",
".",
"SUBSCRIPT_BRACKET",
"not",
"in",
"bracket",
".",
"subtypes",
":",
"if",
"bracket",
".",
"OpensScope",
"(",
")",
":",
"if",
"style",
".",
"Get",
"(",
"'COALESCE_BRACKETS'",
")",
":",
"if",
"current",
".",
"OpensScope",
"(",
")",
":",
"# Prefer to keep all opening brackets together.",
"return",
"False",
"if",
"(",
"not",
"_IsLastScopeInLine",
"(",
"bracket",
")",
"or",
"unwrapped_line",
".",
"IsSurroundedByBrackets",
"(",
"bracket",
")",
")",
":",
"last_token",
"=",
"bracket",
".",
"matching_bracket",
"else",
":",
"last_token",
"=",
"_LastTokenInLine",
"(",
"bracket",
".",
"matching_bracket",
")",
"if",
"not",
"self",
".",
"_FitsOnLine",
"(",
"bracket",
",",
"last_token",
")",
":",
"# Split before the first element if the whole list can't fit on a",
"# single line.",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"split_before_closing_bracket",
"=",
"True",
"return",
"True",
"elif",
"style",
".",
"Get",
"(",
"'DEDENT_CLOSING_BRACKETS'",
")",
"and",
"current",
".",
"ClosesScope",
"(",
")",
":",
"# Split before and dedent the closing bracket.",
"return",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"split_before_closing_bracket",
"if",
"(",
"current",
".",
"is_name",
"or",
"current",
".",
"is_string",
")",
"and",
"previous",
".",
"value",
"==",
"','",
":",
"# If the list has function calls in it and the full list itself cannot",
"# fit on the line, then we want to split. Otherwise, we'll get something",
"# like this:",
"#",
"# X = [",
"# Bar(xxx='some string',",
"# yyy='another long string',",
"# zzz='a third long string'), Bar(",
"# xxx='some string',",
"# yyy='another long string',",
"# zzz='a third long string')",
"# ]",
"#",
"# or when a string formatting syntax.",
"func_call_or_string_format",
"=",
"False",
"if",
"current",
".",
"is_name",
":",
"tok",
"=",
"current",
".",
"next_token",
"while",
"tok",
"and",
"(",
"tok",
".",
"is_name",
"or",
"tok",
".",
"value",
"==",
"'.'",
")",
":",
"tok",
"=",
"tok",
".",
"next_token",
"func_call_or_string_format",
"=",
"tok",
"and",
"tok",
".",
"value",
"==",
"'('",
"elif",
"current",
".",
"is_string",
":",
"tok",
"=",
"current",
".",
"next_token",
"while",
"tok",
"and",
"tok",
".",
"is_string",
":",
"tok",
"=",
"tok",
".",
"next_token",
"func_call_or_string_format",
"=",
"tok",
"and",
"tok",
".",
"value",
"==",
"'%'",
"if",
"func_call_or_string_format",
":",
"open_bracket",
"=",
"unwrapped_line",
".",
"IsSurroundedByBrackets",
"(",
"current",
")",
"if",
"open_bracket",
"and",
"open_bracket",
".",
"value",
"in",
"'[{'",
":",
"if",
"not",
"self",
".",
"_FitsOnLine",
"(",
"open_bracket",
",",
"open_bracket",
".",
"matching_bracket",
")",
":",
"return",
"True",
"###########################################################################",
"# Dict/Set Splitting",
"if",
"(",
"style",
".",
"Get",
"(",
"'EACH_DICT_ENTRY_ON_SEPARATE_LINE'",
")",
"and",
"format_token",
".",
"Subtype",
".",
"DICTIONARY_KEY",
"in",
"current",
".",
"subtypes",
"and",
"not",
"current",
".",
"is_comment",
")",
":",
"# Place each dictionary entry onto its own line.",
"if",
"previous",
".",
"value",
"==",
"'{'",
"and",
"previous",
".",
"previous_token",
":",
"opening",
"=",
"_GetOpeningBracket",
"(",
"previous",
".",
"previous_token",
")",
"if",
"(",
"opening",
"and",
"opening",
".",
"value",
"==",
"'('",
"and",
"opening",
".",
"previous_token",
"and",
"opening",
".",
"previous_token",
".",
"is_name",
")",
":",
"# This is a dictionary that's an argument to a function.",
"if",
"self",
".",
"_FitsOnLine",
"(",
"previous",
",",
"previous",
".",
"matching_bracket",
")",
":",
"return",
"False",
"return",
"True",
"if",
"(",
"style",
".",
"Get",
"(",
"'SPLIT_BEFORE_DICT_SET_GENERATOR'",
")",
"and",
"format_token",
".",
"Subtype",
".",
"DICT_SET_GENERATOR",
"in",
"current",
".",
"subtypes",
")",
":",
"# Split before a dict/set generator.",
"return",
"True",
"if",
"(",
"format_token",
".",
"Subtype",
".",
"DICTIONARY_VALUE",
"in",
"current",
".",
"subtypes",
"or",
"(",
"previous",
".",
"is_pseudo_paren",
"and",
"previous",
".",
"value",
"==",
"'('",
"and",
"not",
"current",
".",
"is_comment",
")",
")",
":",
"# Split before the dictionary value if we can't fit every dictionary",
"# entry on its own line.",
"if",
"not",
"current",
".",
"OpensScope",
"(",
")",
":",
"opening",
"=",
"_GetOpeningBracket",
"(",
"current",
")",
"if",
"not",
"self",
".",
"_EachDictEntryFitsOnOneLine",
"(",
"opening",
")",
":",
"return",
"True",
"if",
"previous",
".",
"value",
"==",
"'{'",
":",
"# Split if the dict/set cannot fit on one line and ends in a comma.",
"closing",
"=",
"previous",
".",
"matching_bracket",
"if",
"(",
"not",
"self",
".",
"_FitsOnLine",
"(",
"previous",
",",
"closing",
")",
"and",
"closing",
".",
"previous_token",
".",
"value",
"==",
"','",
")",
":",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"split_before_closing_bracket",
"=",
"True",
"return",
"True",
"###########################################################################",
"# Argument List Splitting",
"if",
"(",
"style",
".",
"Get",
"(",
"'SPLIT_BEFORE_NAMED_ASSIGNS'",
")",
"and",
"not",
"current",
".",
"is_comment",
"and",
"format_token",
".",
"Subtype",
".",
"DEFAULT_OR_NAMED_ASSIGN_ARG_LIST",
"in",
"current",
".",
"subtypes",
")",
":",
"if",
"(",
"previous",
".",
"value",
"not",
"in",
"{",
"'='",
",",
"':'",
",",
"'*'",
",",
"'**'",
"}",
"and",
"current",
".",
"value",
"not",
"in",
"':=,)'",
"and",
"not",
"_IsFunctionDefinition",
"(",
"previous",
")",
")",
":",
"# If we're going to split the lines because of named arguments, then we",
"# want to split after the opening bracket as well. But not when this is",
"# part of a function definition.",
"if",
"previous",
".",
"value",
"==",
"'('",
":",
"# Make sure we don't split after the opening bracket if the",
"# continuation indent is greater than the opening bracket:",
"#",
"# a(",
"# b=1,",
"# c=2)",
"if",
"(",
"self",
".",
"_FitsOnLine",
"(",
"previous",
",",
"previous",
".",
"matching_bracket",
")",
"and",
"unwrapped_line",
".",
"IsSurroundedByBrackets",
"(",
"previous",
")",
")",
":",
"# An argument to a function is a function call with named",
"# assigns.",
"return",
"False",
"column",
"=",
"self",
".",
"column",
"-",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"last_space",
"return",
"column",
">",
"style",
".",
"Get",
"(",
"'CONTINUATION_INDENT_WIDTH'",
")",
"opening",
"=",
"_GetOpeningBracket",
"(",
"current",
")",
"if",
"opening",
":",
"arglist_length",
"=",
"(",
"opening",
".",
"matching_bracket",
".",
"total_length",
"-",
"opening",
".",
"total_length",
"+",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"indent",
")",
"return",
"arglist_length",
">",
"self",
".",
"column_limit",
"if",
"style",
".",
"Get",
"(",
"'SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED'",
")",
":",
"# Split before arguments in a function call or definition if the",
"# arguments are terminated by a comma.",
"opening",
"=",
"_GetOpeningBracket",
"(",
"current",
")",
"if",
"opening",
"and",
"opening",
".",
"previous_token",
"and",
"opening",
".",
"previous_token",
".",
"is_name",
":",
"if",
"previous",
".",
"value",
"in",
"'(,'",
":",
"if",
"opening",
".",
"matching_bracket",
".",
"previous_token",
".",
"value",
"==",
"','",
":",
"return",
"True",
"if",
"(",
"(",
"current",
".",
"is_name",
"or",
"current",
".",
"value",
"in",
"{",
"'*'",
",",
"'**'",
"}",
")",
"and",
"previous",
".",
"value",
"==",
"','",
")",
":",
"# If we have a function call within an argument list and it won't fit on",
"# the remaining line, but it will fit on a line by itself, then go ahead",
"# and split before the call.",
"opening",
"=",
"_GetOpeningBracket",
"(",
"current",
")",
"if",
"(",
"opening",
"and",
"opening",
".",
"value",
"==",
"'('",
"and",
"opening",
".",
"previous_token",
"and",
"(",
"opening",
".",
"previous_token",
".",
"is_name",
"or",
"opening",
".",
"previous_token",
".",
"value",
"in",
"{",
"'*'",
",",
"'**'",
"}",
")",
")",
":",
"is_func_call",
"=",
"False",
"token",
"=",
"current",
"while",
"token",
":",
"if",
"token",
".",
"value",
"==",
"'('",
":",
"is_func_call",
"=",
"True",
"break",
"if",
"(",
"not",
"(",
"token",
".",
"is_name",
"or",
"token",
".",
"value",
"in",
"{",
"'*'",
",",
"'**'",
"}",
")",
"and",
"token",
".",
"value",
"!=",
"'.'",
")",
":",
"break",
"token",
"=",
"token",
".",
"next_token",
"if",
"is_func_call",
":",
"if",
"not",
"self",
".",
"_FitsOnLine",
"(",
"current",
",",
"opening",
".",
"matching_bracket",
")",
":",
"return",
"True",
"pprevious",
"=",
"previous",
".",
"previous_token",
"if",
"(",
"current",
".",
"is_name",
"and",
"pprevious",
"and",
"pprevious",
".",
"is_name",
"and",
"previous",
".",
"value",
"==",
"'('",
")",
":",
"if",
"(",
"not",
"self",
".",
"_FitsOnLine",
"(",
"previous",
",",
"previous",
".",
"matching_bracket",
")",
"and",
"_IsFunctionCallWithArguments",
"(",
"current",
")",
")",
":",
"# There is a function call, with more than 1 argument, where the first",
"# argument is itself a function call with arguments. In this specific",
"# case, if we split after the first argument's opening '(', then the",
"# formatting will look bad for the rest of the arguments. E.g.:",
"#",
"# outer_function_call(inner_function_call(",
"# inner_arg1, inner_arg2),",
"# outer_arg1, outer_arg2)",
"#",
"# Instead, enforce a split before that argument to keep things looking",
"# good.",
"return",
"True",
"if",
"(",
"previous",
".",
"OpensScope",
"(",
")",
"and",
"not",
"current",
".",
"OpensScope",
"(",
")",
"and",
"format_token",
".",
"Subtype",
".",
"SUBSCRIPT_BRACKET",
"not",
"in",
"previous",
".",
"subtypes",
")",
":",
"if",
"not",
"current",
".",
"is_comment",
":",
"if",
"pprevious",
"and",
"not",
"pprevious",
".",
"is_keyword",
"and",
"not",
"pprevious",
".",
"is_name",
":",
"# We want to split if there's a comment in the container.",
"token",
"=",
"current",
"while",
"token",
"!=",
"previous",
".",
"matching_bracket",
":",
"if",
"token",
".",
"is_comment",
":",
"return",
"True",
"token",
"=",
"token",
".",
"next_token",
"if",
"previous",
".",
"value",
"==",
"'('",
":",
"pptoken",
"=",
"previous",
".",
"previous_token",
"if",
"not",
"pptoken",
"or",
"not",
"pptoken",
".",
"is_name",
":",
"# Split after the opening of a tuple if it doesn't fit on the current",
"# line and it's not a function call.",
"if",
"self",
".",
"_FitsOnLine",
"(",
"previous",
",",
"previous",
".",
"matching_bracket",
")",
":",
"return",
"False",
"elif",
"not",
"self",
".",
"_FitsOnLine",
"(",
"previous",
",",
"previous",
".",
"matching_bracket",
")",
":",
"if",
"(",
"self",
".",
"column_limit",
"-",
"self",
".",
"column",
")",
"/",
"float",
"(",
"self",
".",
"column_limit",
")",
"<",
"0.3",
":",
"# Try not to squish all of the arguments off to the right.",
"return",
"current",
".",
"next_token",
"!=",
"previous",
".",
"matching_bracket",
"else",
":",
"# Split after the opening of a container if it doesn't fit on the",
"# current line or if it has a comment.",
"if",
"not",
"self",
".",
"_FitsOnLine",
"(",
"previous",
",",
"previous",
".",
"matching_bracket",
")",
":",
"return",
"True",
"###########################################################################",
"# List Comprehension Splitting",
"if",
"(",
"format_token",
".",
"Subtype",
".",
"COMP_FOR",
"in",
"current",
".",
"subtypes",
"and",
"format_token",
".",
"Subtype",
".",
"COMP_FOR",
"not",
"in",
"previous",
".",
"subtypes",
")",
":",
"# Split at the beginning of a list comprehension.",
"length",
"=",
"_GetLengthOfSubtype",
"(",
"current",
",",
"format_token",
".",
"Subtype",
".",
"COMP_FOR",
",",
"format_token",
".",
"Subtype",
".",
"COMP_IF",
")",
"if",
"length",
"+",
"self",
".",
"column",
">",
"self",
".",
"column_limit",
":",
"return",
"True",
"if",
"(",
"format_token",
".",
"Subtype",
".",
"COMP_IF",
"in",
"current",
".",
"subtypes",
"and",
"format_token",
".",
"Subtype",
".",
"COMP_IF",
"not",
"in",
"previous",
".",
"subtypes",
")",
":",
"# Split at the beginning of an if expression.",
"length",
"=",
"_GetLengthOfSubtype",
"(",
"current",
",",
"format_token",
".",
"Subtype",
".",
"COMP_IF",
")",
"if",
"length",
"+",
"self",
".",
"column",
">",
"self",
".",
"column_limit",
":",
"return",
"True",
"###########################################################################",
"# Original Formatting Splitting",
"# These checks rely upon the original formatting. This is in order to",
"# attempt to keep hand-written code in the same condition as it was before.",
"# However, this may cause the formatter to fail to be idempotent.",
"if",
"(",
"style",
".",
"Get",
"(",
"'SPLIT_BEFORE_BITWISE_OPERATOR'",
")",
"and",
"current",
".",
"value",
"in",
"'&|'",
"and",
"previous",
".",
"lineno",
"<",
"current",
".",
"lineno",
")",
":",
"# Retain the split before a bitwise operator.",
"return",
"True",
"if",
"(",
"current",
".",
"is_comment",
"and",
"previous",
".",
"lineno",
"<",
"current",
".",
"lineno",
"-",
"current",
".",
"value",
".",
"count",
"(",
"'\\n'",
")",
")",
":",
"# If a comment comes in the middle of an unwrapped line (like an if",
"# conditional with comments interspersed), then we want to split if the",
"# original comments were on a separate line.",
"return",
"True",
"return",
"False"
] |
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/yapf/yapf/yapflib/format_decision_state.py#L146-L414
|
|
PaddlePaddle/Paddle
|
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
|
python/paddle/utils/cpp_extension/extension_utils.py
|
python
|
log_v
|
(info, verbose=True)
|
Print log information on stdout.
|
Print log information on stdout.
|
[
"Print",
"log",
"information",
"on",
"stdout",
"."
] |
def log_v(info, verbose=True):
"""
Print log information on stdout.
"""
if verbose:
logger.info(info)
|
[
"def",
"log_v",
"(",
"info",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"verbose",
":",
"logger",
".",
"info",
"(",
"info",
")"
] |
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/utils/cpp_extension/extension_utils.py#L1211-L1216
|
||
microsoft/checkedc-clang
|
a173fefde5d7877b7750e7ce96dd08cf18baebf2
|
clang/bindings/python/clang/cindex.py
|
python
|
Diagnostic.category_name
|
(self)
|
return conf.lib.clang_getDiagnosticCategoryText(self)
|
The string name of the category for this diagnostic.
|
The string name of the category for this diagnostic.
|
[
"The",
"string",
"name",
"of",
"the",
"category",
"for",
"this",
"diagnostic",
"."
] |
def category_name(self):
"""The string name of the category for this diagnostic."""
return conf.lib.clang_getDiagnosticCategoryText(self)
|
[
"def",
"category_name",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getDiagnosticCategoryText",
"(",
"self",
")"
] |
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L465-L467
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/hermite.py
|
python
|
hermmulx
|
(c)
|
return prd
|
Multiply a Hermite series by x.
Multiply the Hermite series `c` by x, where x is the independent
variable.
Parameters
----------
c : array_like
1-D array of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the result of the multiplication.
See Also
--------
hermadd, hermsub, hermmul, hermdiv, hermpow
Notes
-----
The multiplication uses the recursion relationship for Hermite
polynomials in the form
.. math::
xP_i(x) = (P_{i + 1}(x)/2 + i*P_{i - 1}(x))
Examples
--------
>>> from numpy.polynomial.hermite import hermmulx
>>> hermmulx([1, 2, 3])
array([2. , 6.5, 1. , 1.5])
|
Multiply a Hermite series by x.
|
[
"Multiply",
"a",
"Hermite",
"series",
"by",
"x",
"."
] |
def hermmulx(c):
"""Multiply a Hermite series by x.
Multiply the Hermite series `c` by x, where x is the independent
variable.
Parameters
----------
c : array_like
1-D array of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the result of the multiplication.
See Also
--------
hermadd, hermsub, hermmul, hermdiv, hermpow
Notes
-----
The multiplication uses the recursion relationship for Hermite
polynomials in the form
.. math::
xP_i(x) = (P_{i + 1}(x)/2 + i*P_{i - 1}(x))
Examples
--------
>>> from numpy.polynomial.hermite import hermmulx
>>> hermmulx([1, 2, 3])
array([2. , 6.5, 1. , 1.5])
"""
# c is a trimmed copy
[c] = pu.as_series([c])
# The zero series needs special treatment
if len(c) == 1 and c[0] == 0:
return c
prd = np.empty(len(c) + 1, dtype=c.dtype)
prd[0] = c[0]*0
prd[1] = c[0]/2
for i in range(1, len(c)):
prd[i + 1] = c[i]/2
prd[i - 1] += c[i]*i
return prd
|
[
"def",
"hermmulx",
"(",
"c",
")",
":",
"# c is a trimmed copy",
"[",
"c",
"]",
"=",
"pu",
".",
"as_series",
"(",
"[",
"c",
"]",
")",
"# The zero series needs special treatment",
"if",
"len",
"(",
"c",
")",
"==",
"1",
"and",
"c",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"c",
"prd",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"c",
")",
"+",
"1",
",",
"dtype",
"=",
"c",
".",
"dtype",
")",
"prd",
"[",
"0",
"]",
"=",
"c",
"[",
"0",
"]",
"*",
"0",
"prd",
"[",
"1",
"]",
"=",
"c",
"[",
"0",
"]",
"/",
"2",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"c",
")",
")",
":",
"prd",
"[",
"i",
"+",
"1",
"]",
"=",
"c",
"[",
"i",
"]",
"/",
"2",
"prd",
"[",
"i",
"-",
"1",
"]",
"+=",
"c",
"[",
"i",
"]",
"*",
"i",
"return",
"prd"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/hermite.py#L371-L421
|
|
microsoft/TSS.MSR
|
0f2516fca2cd9929c31d5450e39301c9bde43688
|
TSS.Py/src/TpmTypes.py
|
python
|
TPML_TAGGED_POLICY.toTpm
|
(self, buf)
|
TpmMarshaller method
|
TpmMarshaller method
|
[
"TpmMarshaller",
"method"
] |
def toTpm(self, buf):
""" TpmMarshaller method """
buf.writeObjArr(self.policies)
|
[
"def",
"toTpm",
"(",
"self",
",",
"buf",
")",
":",
"buf",
".",
"writeObjArr",
"(",
"self",
".",
"policies",
")"
] |
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4863-L4865
|
||
mindspore-ai/mindspore
|
fb8fd3338605bb34fa5cea054e535a8b1d753fab
|
mindspore/python/mindspore/ops/composite/multitype_ops/sub_impl.py
|
python
|
_tensor_sub_list
|
(x, y)
|
return F.tensor_sub(x, y)
|
Returns x - y where x is a tensor and y is a list.
|
Returns x - y where x is a tensor and y is a list.
|
[
"Returns",
"x",
"-",
"y",
"where",
"x",
"is",
"a",
"tensor",
"and",
"y",
"is",
"a",
"list",
"."
] |
def _tensor_sub_list(x, y):
"""Returns x - y where x is a tensor and y is a list. """
y = utils.sequence_to_tensor(y, x.dtype)
return F.tensor_sub(x, y)
|
[
"def",
"_tensor_sub_list",
"(",
"x",
",",
"y",
")",
":",
"y",
"=",
"utils",
".",
"sequence_to_tensor",
"(",
"y",
",",
"x",
".",
"dtype",
")",
"return",
"F",
".",
"tensor_sub",
"(",
"x",
",",
"y",
")"
] |
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/sub_impl.py#L76-L79
|
|
OpenChemistry/tomviz
|
0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a
|
tomviz/python/Recon_DFT_constraint.py
|
python
|
ReconConstrintedDFMOperator.transform
|
(self, dataset, Niter=None, Niter_update_support=None,
supportSigma=None, supportThreshold=None)
|
return returnValues
|
3D Reconstruct from a tilt series using constraint-based Direct Fourier
Method
|
3D Reconstruct from a tilt series using constraint-based Direct Fourier
Method
|
[
"3D",
"Reconstruct",
"from",
"a",
"tilt",
"series",
"using",
"constraint",
"-",
"based",
"Direct",
"Fourier",
"Method"
] |
def transform(self, dataset, Niter=None, Niter_update_support=None,
supportSigma=None, supportThreshold=None):
"""
3D Reconstruct from a tilt series using constraint-based Direct Fourier
Method
"""
self.progress.maximum = 1
import numpy as np
supportThreshold = supportThreshold / 100.0
nonnegativeVoxels = True
tiltAngles = dataset.tilt_angles #Get Tilt angles
tiltSeries = dataset.active_scalars
if tiltSeries is None:
raise RuntimeError("No scalars found!")
self.progress.message = 'Initialization'
#Direct Fourier recon without constraints
(recon, recon_F) \
= dfm3(tiltSeries, tiltAngles, np.size(tiltSeries, 1) * 2)
kr_cutoffs = np.linspace(0.05, 0.5, 10)
#average Fourier magnitude of tilt series as a function of kr
I_data = radial_average(tiltSeries, kr_cutoffs)
(Nx, Ny, Nz) = recon_F.shape
#Note: Nz = np.int(Ny/2+1)
Ntot = Nx * Ny * Ny
f = pyfftw.n_byte_align_empty((Nx, Ny, Nz), 16, dtype=np.complex64)
r = pyfftw.n_byte_align_empty((Nx, Ny, Ny), 16, dtype=np.float32)
fft_forward = pyfftw.FFTW(r, f, axes=(0, 1, 2))
fft_inverse = pyfftw.FFTW(
f, r, direction='FFTW_BACKWARD', axes=(0, 1, 2))
kx = np.fft.fftfreq(Nx)
ky = np.fft.fftfreq(Ny)
kz = ky[0:Nz]
kX, kY, kZ = np.meshgrid(ky, kx, kz)
kR = np.sqrt(kY**2 + kX**2 + kZ**2)
sigma = 0.5 * supportSigma
G = np.exp(-kR**2 / (2 * sigma**2))
#create initial support using sw
f = (recon_F * G).astype(np.complex64)
fft_inverse.update_arrays(f, r)
fft_inverse.execute()
cutoff = np.amax(r) * supportThreshold
support = r >= cutoff
recon_F[kR > kr_cutoffs[-1]] = 0
x = np.random.rand(Nx, Ny, Ny).astype(np.float32) #initial solution
self.progress.maximum = Niter
step = 0
t0 = time.time()
counter = 1
etcMessage = 'Estimated time to complete: n/a'
for i in range(Niter):
if self.canceled:
return
self.progress.message = 'Iteration No.%d/%d. ' % (
i + 1, Niter) + etcMessage
#image space projection
y1 = x.copy()
if nonnegativeVoxels:
y1[y1 < 0] = 0 #non-negative constraint
y1[np.logical_not(support)] = 0 #support constraint
#Fourier space projection
y2 = 2 * y1 - x
r = y2.copy().astype(np.float32)
fft_forward.update_arrays(r, f)
fft_forward.execute()
f[kR > kr_cutoffs[-1]] = 0 #apply low pass filter
f[recon_F != 0] = recon_F[recon_F != 0] #data constraint
#Fourier magnitude constraint
#leave the inner shell unchanged
for j in range(1, kr_cutoffs.size):
shell = np.logical_and(
kR > kr_cutoffs[j - 1], kR <= kr_cutoffs[j])
shell[recon_F != 0] = False
I = np.sum(np.absolute(f[shell]))
if I != 0:
I = I / np.sum(shell)
# lower magnitude for high frequency information to reduce
# artifacts
f[shell] = f[shell] / I * I_data[j] * 0.5
fft_inverse.update_arrays(f, r)
fft_inverse.execute()
y2 = r.copy() / Ntot
#update
x = x + y2 - y1
#update support
if (i < Niter and np.mod(i, Niter_update_support) == 0):
recon[:] = (y2 + y1) / 2
r = recon.copy()
fft_forward.update_arrays(r, f)
fft_forward.execute()
f = (f * G).astype(np.complex64)
fft_inverse.update_arrays(f, r)
fft_inverse.execute()
cutoff = np.amax(r) * supportThreshold
support = r >= cutoff
step += 1
self.progress.value = step
timeLeft = (time.time() - t0) / counter * (Niter - counter)
counter += 1
timeLeftMin, timeLeftSec = divmod(timeLeft, 60)
timeLeftHour, timeLeftMin = divmod(timeLeftMin, 60)
etcMessage = 'Estimated time to complete: %02d:%02d:%02d' % (
timeLeftHour, timeLeftMin, timeLeftSec)
recon[:] = (y2 + y1) / 2
recon[:] = np.fft.fftshift(recon)
child = dataset.create_child_dataset()
child.active_scalars = recon
returnValues = {}
returnValues["reconstruction"] = child
return returnValues
|
[
"def",
"transform",
"(",
"self",
",",
"dataset",
",",
"Niter",
"=",
"None",
",",
"Niter_update_support",
"=",
"None",
",",
"supportSigma",
"=",
"None",
",",
"supportThreshold",
"=",
"None",
")",
":",
"self",
".",
"progress",
".",
"maximum",
"=",
"1",
"import",
"numpy",
"as",
"np",
"supportThreshold",
"=",
"supportThreshold",
"/",
"100.0",
"nonnegativeVoxels",
"=",
"True",
"tiltAngles",
"=",
"dataset",
".",
"tilt_angles",
"#Get Tilt angles",
"tiltSeries",
"=",
"dataset",
".",
"active_scalars",
"if",
"tiltSeries",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"No scalars found!\"",
")",
"self",
".",
"progress",
".",
"message",
"=",
"'Initialization'",
"#Direct Fourier recon without constraints",
"(",
"recon",
",",
"recon_F",
")",
"=",
"dfm3",
"(",
"tiltSeries",
",",
"tiltAngles",
",",
"np",
".",
"size",
"(",
"tiltSeries",
",",
"1",
")",
"*",
"2",
")",
"kr_cutoffs",
"=",
"np",
".",
"linspace",
"(",
"0.05",
",",
"0.5",
",",
"10",
")",
"#average Fourier magnitude of tilt series as a function of kr",
"I_data",
"=",
"radial_average",
"(",
"tiltSeries",
",",
"kr_cutoffs",
")",
"(",
"Nx",
",",
"Ny",
",",
"Nz",
")",
"=",
"recon_F",
".",
"shape",
"#Note: Nz = np.int(Ny/2+1)",
"Ntot",
"=",
"Nx",
"*",
"Ny",
"*",
"Ny",
"f",
"=",
"pyfftw",
".",
"n_byte_align_empty",
"(",
"(",
"Nx",
",",
"Ny",
",",
"Nz",
")",
",",
"16",
",",
"dtype",
"=",
"np",
".",
"complex64",
")",
"r",
"=",
"pyfftw",
".",
"n_byte_align_empty",
"(",
"(",
"Nx",
",",
"Ny",
",",
"Ny",
")",
",",
"16",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"fft_forward",
"=",
"pyfftw",
".",
"FFTW",
"(",
"r",
",",
"f",
",",
"axes",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
")",
"fft_inverse",
"=",
"pyfftw",
".",
"FFTW",
"(",
"f",
",",
"r",
",",
"direction",
"=",
"'FFTW_BACKWARD'",
",",
"axes",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
")",
"kx",
"=",
"np",
".",
"fft",
".",
"fftfreq",
"(",
"Nx",
")",
"ky",
"=",
"np",
".",
"fft",
".",
"fftfreq",
"(",
"Ny",
")",
"kz",
"=",
"ky",
"[",
"0",
":",
"Nz",
"]",
"kX",
",",
"kY",
",",
"kZ",
"=",
"np",
".",
"meshgrid",
"(",
"ky",
",",
"kx",
",",
"kz",
")",
"kR",
"=",
"np",
".",
"sqrt",
"(",
"kY",
"**",
"2",
"+",
"kX",
"**",
"2",
"+",
"kZ",
"**",
"2",
")",
"sigma",
"=",
"0.5",
"*",
"supportSigma",
"G",
"=",
"np",
".",
"exp",
"(",
"-",
"kR",
"**",
"2",
"/",
"(",
"2",
"*",
"sigma",
"**",
"2",
")",
")",
"#create initial support using sw",
"f",
"=",
"(",
"recon_F",
"*",
"G",
")",
".",
"astype",
"(",
"np",
".",
"complex64",
")",
"fft_inverse",
".",
"update_arrays",
"(",
"f",
",",
"r",
")",
"fft_inverse",
".",
"execute",
"(",
")",
"cutoff",
"=",
"np",
".",
"amax",
"(",
"r",
")",
"*",
"supportThreshold",
"support",
"=",
"r",
">=",
"cutoff",
"recon_F",
"[",
"kR",
">",
"kr_cutoffs",
"[",
"-",
"1",
"]",
"]",
"=",
"0",
"x",
"=",
"np",
".",
"random",
".",
"rand",
"(",
"Nx",
",",
"Ny",
",",
"Ny",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"#initial solution",
"self",
".",
"progress",
".",
"maximum",
"=",
"Niter",
"step",
"=",
"0",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"counter",
"=",
"1",
"etcMessage",
"=",
"'Estimated time to complete: n/a'",
"for",
"i",
"in",
"range",
"(",
"Niter",
")",
":",
"if",
"self",
".",
"canceled",
":",
"return",
"self",
".",
"progress",
".",
"message",
"=",
"'Iteration No.%d/%d. '",
"%",
"(",
"i",
"+",
"1",
",",
"Niter",
")",
"+",
"etcMessage",
"#image space projection",
"y1",
"=",
"x",
".",
"copy",
"(",
")",
"if",
"nonnegativeVoxels",
":",
"y1",
"[",
"y1",
"<",
"0",
"]",
"=",
"0",
"#non-negative constraint",
"y1",
"[",
"np",
".",
"logical_not",
"(",
"support",
")",
"]",
"=",
"0",
"#support constraint",
"#Fourier space projection",
"y2",
"=",
"2",
"*",
"y1",
"-",
"x",
"r",
"=",
"y2",
".",
"copy",
"(",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"fft_forward",
".",
"update_arrays",
"(",
"r",
",",
"f",
")",
"fft_forward",
".",
"execute",
"(",
")",
"f",
"[",
"kR",
">",
"kr_cutoffs",
"[",
"-",
"1",
"]",
"]",
"=",
"0",
"#apply low pass filter",
"f",
"[",
"recon_F",
"!=",
"0",
"]",
"=",
"recon_F",
"[",
"recon_F",
"!=",
"0",
"]",
"#data constraint",
"#Fourier magnitude constraint",
"#leave the inner shell unchanged",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"kr_cutoffs",
".",
"size",
")",
":",
"shell",
"=",
"np",
".",
"logical_and",
"(",
"kR",
">",
"kr_cutoffs",
"[",
"j",
"-",
"1",
"]",
",",
"kR",
"<=",
"kr_cutoffs",
"[",
"j",
"]",
")",
"shell",
"[",
"recon_F",
"!=",
"0",
"]",
"=",
"False",
"I",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"absolute",
"(",
"f",
"[",
"shell",
"]",
")",
")",
"if",
"I",
"!=",
"0",
":",
"I",
"=",
"I",
"/",
"np",
".",
"sum",
"(",
"shell",
")",
"# lower magnitude for high frequency information to reduce",
"# artifacts",
"f",
"[",
"shell",
"]",
"=",
"f",
"[",
"shell",
"]",
"/",
"I",
"*",
"I_data",
"[",
"j",
"]",
"*",
"0.5",
"fft_inverse",
".",
"update_arrays",
"(",
"f",
",",
"r",
")",
"fft_inverse",
".",
"execute",
"(",
")",
"y2",
"=",
"r",
".",
"copy",
"(",
")",
"/",
"Ntot",
"#update",
"x",
"=",
"x",
"+",
"y2",
"-",
"y1",
"#update support",
"if",
"(",
"i",
"<",
"Niter",
"and",
"np",
".",
"mod",
"(",
"i",
",",
"Niter_update_support",
")",
"==",
"0",
")",
":",
"recon",
"[",
":",
"]",
"=",
"(",
"y2",
"+",
"y1",
")",
"/",
"2",
"r",
"=",
"recon",
".",
"copy",
"(",
")",
"fft_forward",
".",
"update_arrays",
"(",
"r",
",",
"f",
")",
"fft_forward",
".",
"execute",
"(",
")",
"f",
"=",
"(",
"f",
"*",
"G",
")",
".",
"astype",
"(",
"np",
".",
"complex64",
")",
"fft_inverse",
".",
"update_arrays",
"(",
"f",
",",
"r",
")",
"fft_inverse",
".",
"execute",
"(",
")",
"cutoff",
"=",
"np",
".",
"amax",
"(",
"r",
")",
"*",
"supportThreshold",
"support",
"=",
"r",
">=",
"cutoff",
"step",
"+=",
"1",
"self",
".",
"progress",
".",
"value",
"=",
"step",
"timeLeft",
"=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"t0",
")",
"/",
"counter",
"*",
"(",
"Niter",
"-",
"counter",
")",
"counter",
"+=",
"1",
"timeLeftMin",
",",
"timeLeftSec",
"=",
"divmod",
"(",
"timeLeft",
",",
"60",
")",
"timeLeftHour",
",",
"timeLeftMin",
"=",
"divmod",
"(",
"timeLeftMin",
",",
"60",
")",
"etcMessage",
"=",
"'Estimated time to complete: %02d:%02d:%02d'",
"%",
"(",
"timeLeftHour",
",",
"timeLeftMin",
",",
"timeLeftSec",
")",
"recon",
"[",
":",
"]",
"=",
"(",
"y2",
"+",
"y1",
")",
"/",
"2",
"recon",
"[",
":",
"]",
"=",
"np",
".",
"fft",
".",
"fftshift",
"(",
"recon",
")",
"child",
"=",
"dataset",
".",
"create_child_dataset",
"(",
")",
"child",
".",
"active_scalars",
"=",
"recon",
"returnValues",
"=",
"{",
"}",
"returnValues",
"[",
"\"reconstruction\"",
"]",
"=",
"child",
"return",
"returnValues"
] |
https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/Recon_DFT_constraint.py#L9-L146
|
|
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
third_party/catapult/third_party/python_gflags/gflags.py
|
python
|
_WriteSimpleXMLElement
|
(outfile, name, value, indent)
|
Writes a simple XML element.
Args:
outfile: File object we write the XML element to.
name: A string, the name of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element.
indent: A string, prepended to each line of generated output.
|
Writes a simple XML element.
|
[
"Writes",
"a",
"simple",
"XML",
"element",
"."
] |
def _WriteSimpleXMLElement(outfile, name, value, indent):
"""Writes a simple XML element.
Args:
outfile: File object we write the XML element to.
name: A string, the name of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element.
indent: A string, prepended to each line of generated output.
"""
value_str = _StrOrUnicode(value)
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
value_str = value_str.lower()
safe_value_str = _MakeXMLSafe(value_str)
outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name))
|
[
"def",
"_WriteSimpleXMLElement",
"(",
"outfile",
",",
"name",
",",
"value",
",",
"indent",
")",
":",
"value_str",
"=",
"_StrOrUnicode",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"# Display boolean values as the C++ flag library does: no caps.",
"value_str",
"=",
"value_str",
".",
"lower",
"(",
")",
"safe_value_str",
"=",
"_MakeXMLSafe",
"(",
"value_str",
")",
"outfile",
".",
"write",
"(",
"'%s<%s>%s</%s>\\n'",
"%",
"(",
"indent",
",",
"name",
",",
"safe_value_str",
",",
"name",
")",
")"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags.py#L1789-L1804
|
||
moderngl/moderngl
|
32fe79927e02b0fa893b3603d677bdae39771e14
|
moderngl/texture_array.py
|
python
|
TextureArray.read
|
(self, *, alignment=1)
|
return self.mglo.read(alignment)
|
Read the pixel data as bytes into system memory.
Keyword Args:
alignment (int): The byte alignment of the pixels.
Returns:
bytes
|
Read the pixel data as bytes into system memory.
|
[
"Read",
"the",
"pixel",
"data",
"as",
"bytes",
"into",
"system",
"memory",
"."
] |
def read(self, *, alignment=1) -> bytes:
'''
Read the pixel data as bytes into system memory.
Keyword Args:
alignment (int): The byte alignment of the pixels.
Returns:
bytes
'''
return self.mglo.read(alignment)
|
[
"def",
"read",
"(",
"self",
",",
"*",
",",
"alignment",
"=",
"1",
")",
"->",
"bytes",
":",
"return",
"self",
".",
"mglo",
".",
"read",
"(",
"alignment",
")"
] |
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/texture_array.py#L225-L236
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/iomenu.py
|
python
|
IOBinding._decode
|
(self, two_lines, bytes)
|
return None, False
|
Create a Unicode string.
|
Create a Unicode string.
|
[
"Create",
"a",
"Unicode",
"string",
"."
] |
def _decode(self, two_lines, bytes):
"Create a Unicode string."
chars = None
# Check presence of a UTF-8 signature first
if bytes.startswith(BOM_UTF8):
try:
chars = bytes[3:].decode("utf-8")
except UnicodeDecodeError:
# has UTF-8 signature, but fails to decode...
return None, False
else:
# Indicates that this file originally had a BOM
self.fileencoding = 'BOM'
return chars, False
# Next look for coding specification
try:
enc = coding_spec(two_lines)
except LookupError as name:
tkMessageBox.showerror(
title="Error loading the file",
message="The encoding '%s' is not known to this Python "\
"installation. The file may not display correctly" % name,
parent = self.text)
enc = None
except UnicodeDecodeError:
return None, False
if enc:
try:
chars = str(bytes, enc)
self.fileencoding = enc
return chars, False
except UnicodeDecodeError:
pass
# Try ascii:
try:
chars = str(bytes, 'ascii')
self.fileencoding = None
return chars, False
except UnicodeDecodeError:
pass
# Try utf-8:
try:
chars = str(bytes, 'utf-8')
self.fileencoding = 'utf-8'
return chars, False
except UnicodeDecodeError:
pass
# Finally, try the locale's encoding. This is deprecated;
# the user should declare a non-ASCII encoding
try:
# Wait for the editor window to appear
self.editwin.text.update()
enc = askstring(
"Specify file encoding",
"The file's encoding is invalid for Python 3.x.\n"
"IDLE will convert it to UTF-8.\n"
"What is the current encoding of the file?",
initialvalue = encoding,
parent = self.editwin.text)
if enc:
chars = str(bytes, enc)
self.fileencoding = None
return chars, True
except (UnicodeDecodeError, LookupError):
pass
return None, False
|
[
"def",
"_decode",
"(",
"self",
",",
"two_lines",
",",
"bytes",
")",
":",
"chars",
"=",
"None",
"# Check presence of a UTF-8 signature first",
"if",
"bytes",
".",
"startswith",
"(",
"BOM_UTF8",
")",
":",
"try",
":",
"chars",
"=",
"bytes",
"[",
"3",
":",
"]",
".",
"decode",
"(",
"\"utf-8\"",
")",
"except",
"UnicodeDecodeError",
":",
"# has UTF-8 signature, but fails to decode...",
"return",
"None",
",",
"False",
"else",
":",
"# Indicates that this file originally had a BOM",
"self",
".",
"fileencoding",
"=",
"'BOM'",
"return",
"chars",
",",
"False",
"# Next look for coding specification",
"try",
":",
"enc",
"=",
"coding_spec",
"(",
"two_lines",
")",
"except",
"LookupError",
"as",
"name",
":",
"tkMessageBox",
".",
"showerror",
"(",
"title",
"=",
"\"Error loading the file\"",
",",
"message",
"=",
"\"The encoding '%s' is not known to this Python \"",
"\"installation. The file may not display correctly\"",
"%",
"name",
",",
"parent",
"=",
"self",
".",
"text",
")",
"enc",
"=",
"None",
"except",
"UnicodeDecodeError",
":",
"return",
"None",
",",
"False",
"if",
"enc",
":",
"try",
":",
"chars",
"=",
"str",
"(",
"bytes",
",",
"enc",
")",
"self",
".",
"fileencoding",
"=",
"enc",
"return",
"chars",
",",
"False",
"except",
"UnicodeDecodeError",
":",
"pass",
"# Try ascii:",
"try",
":",
"chars",
"=",
"str",
"(",
"bytes",
",",
"'ascii'",
")",
"self",
".",
"fileencoding",
"=",
"None",
"return",
"chars",
",",
"False",
"except",
"UnicodeDecodeError",
":",
"pass",
"# Try utf-8:",
"try",
":",
"chars",
"=",
"str",
"(",
"bytes",
",",
"'utf-8'",
")",
"self",
".",
"fileencoding",
"=",
"'utf-8'",
"return",
"chars",
",",
"False",
"except",
"UnicodeDecodeError",
":",
"pass",
"# Finally, try the locale's encoding. This is deprecated;",
"# the user should declare a non-ASCII encoding",
"try",
":",
"# Wait for the editor window to appear",
"self",
".",
"editwin",
".",
"text",
".",
"update",
"(",
")",
"enc",
"=",
"askstring",
"(",
"\"Specify file encoding\"",
",",
"\"The file's encoding is invalid for Python 3.x.\\n\"",
"\"IDLE will convert it to UTF-8.\\n\"",
"\"What is the current encoding of the file?\"",
",",
"initialvalue",
"=",
"encoding",
",",
"parent",
"=",
"self",
".",
"editwin",
".",
"text",
")",
"if",
"enc",
":",
"chars",
"=",
"str",
"(",
"bytes",
",",
"enc",
")",
"self",
".",
"fileencoding",
"=",
"None",
"return",
"chars",
",",
"True",
"except",
"(",
"UnicodeDecodeError",
",",
"LookupError",
")",
":",
"pass",
"return",
"None",
",",
"False"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/iomenu.py#L248-L314
|
|
google/shaka-packager
|
e1b0c7c45431327fd3ce193514a5407d07b39b22
|
packager/third_party/libevent/event_rpcgen.py
|
python
|
Parse
|
(file)
|
return entities
|
Parses the input file and returns C code and corresponding header file.
|
Parses the input file and returns C code and corresponding header file.
|
[
"Parses",
"the",
"input",
"file",
"and",
"returns",
"C",
"code",
"and",
"corresponding",
"header",
"file",
"."
] |
def Parse(file):
"""
Parses the input file and returns C code and corresponding header file.
"""
entities = []
while 1:
# Just gets the whole struct nicely formatted
data = GetNextStruct(file)
if not data:
break
entities.extend(ProcessStruct(data))
return entities
|
[
"def",
"Parse",
"(",
"file",
")",
":",
"entities",
"=",
"[",
"]",
"while",
"1",
":",
"# Just gets the whole struct nicely formatted",
"data",
"=",
"GetNextStruct",
"(",
"file",
")",
"if",
"not",
"data",
":",
"break",
"entities",
".",
"extend",
"(",
"ProcessStruct",
"(",
"data",
")",
")",
"return",
"entities"
] |
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/libevent/event_rpcgen.py#L1272-L1288
|
|
krishauser/Klampt
|
972cc83ea5befac3f653c1ba20f80155768ad519
|
Python/klampt/model/sensing.py
|
python
|
camera_to_points_world
|
(camera : SimRobotSensor,
robot : RobotModel,
points_format='numpy',
color_format='channels')
|
return pts
|
Same as :meth:`camera_to_points`, but converts to the world coordinate
system given the robot to which the camera is attached.
Points that have no reading are stripped out.
|
Same as :meth:`camera_to_points`, but converts to the world coordinate
system given the robot to which the camera is attached.
|
[
"Same",
"as",
":",
"meth",
":",
"camera_to_points",
"but",
"converts",
"to",
"the",
"world",
"coordinate",
"system",
"given",
"the",
"robot",
"to",
"which",
"the",
"camera",
"is",
"attached",
"."
] |
def camera_to_points_world(camera : SimRobotSensor,
robot : RobotModel,
points_format='numpy',
color_format='channels') -> Union['ndarray',PointCloud,Geometry3D]:
"""Same as :meth:`camera_to_points`, but converts to the world coordinate
system given the robot to which the camera is attached.
Points that have no reading are stripped out.
"""
assert isinstance(camera,SimRobotSensor),"Must provide a SimRobotSensor instance"
assert camera.type() == 'CameraSensor',"Must provide a camera sensor instance"
link = int(camera.getSetting('link'))
Tsensor = camera.getSetting('Tsensor')
#first 9: row major rotation matrix, last 3: translation
entries = [float(v) for v in Tsensor.split()]
Tworld = get_sensor_xform(camera,robot)
#now get the points
pts = camera_to_points(camera,points_format,all_points=False,color_format=color_format)
if points_format == 'numpy':
Rw = np.array(so3.matrix(Tworld[0]))
tw = np.array(Tworld[1])
pts[:,0:3] = np.dot(pts[:,0:3],Rw.T) + tw
return pts
elif points_format == 'PointCloud' or points_format == 'Geometry3D':
pts.transform(*Tworld)
else:
raise ValueError("Invalid format "+str(points_format))
return pts
|
[
"def",
"camera_to_points_world",
"(",
"camera",
":",
"SimRobotSensor",
",",
"robot",
":",
"RobotModel",
",",
"points_format",
"=",
"'numpy'",
",",
"color_format",
"=",
"'channels'",
")",
"->",
"Union",
"[",
"'ndarray'",
",",
"PointCloud",
",",
"Geometry3D",
"]",
":",
"assert",
"isinstance",
"(",
"camera",
",",
"SimRobotSensor",
")",
",",
"\"Must provide a SimRobotSensor instance\"",
"assert",
"camera",
".",
"type",
"(",
")",
"==",
"'CameraSensor'",
",",
"\"Must provide a camera sensor instance\"",
"link",
"=",
"int",
"(",
"camera",
".",
"getSetting",
"(",
"'link'",
")",
")",
"Tsensor",
"=",
"camera",
".",
"getSetting",
"(",
"'Tsensor'",
")",
"#first 9: row major rotation matrix, last 3: translation",
"entries",
"=",
"[",
"float",
"(",
"v",
")",
"for",
"v",
"in",
"Tsensor",
".",
"split",
"(",
")",
"]",
"Tworld",
"=",
"get_sensor_xform",
"(",
"camera",
",",
"robot",
")",
"#now get the points",
"pts",
"=",
"camera_to_points",
"(",
"camera",
",",
"points_format",
",",
"all_points",
"=",
"False",
",",
"color_format",
"=",
"color_format",
")",
"if",
"points_format",
"==",
"'numpy'",
":",
"Rw",
"=",
"np",
".",
"array",
"(",
"so3",
".",
"matrix",
"(",
"Tworld",
"[",
"0",
"]",
")",
")",
"tw",
"=",
"np",
".",
"array",
"(",
"Tworld",
"[",
"1",
"]",
")",
"pts",
"[",
":",
",",
"0",
":",
"3",
"]",
"=",
"np",
".",
"dot",
"(",
"pts",
"[",
":",
",",
"0",
":",
"3",
"]",
",",
"Rw",
".",
"T",
")",
"+",
"tw",
"return",
"pts",
"elif",
"points_format",
"==",
"'PointCloud'",
"or",
"points_format",
"==",
"'Geometry3D'",
":",
"pts",
".",
"transform",
"(",
"*",
"Tworld",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid format \"",
"+",
"str",
"(",
"points_format",
")",
")",
"return",
"pts"
] |
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/sensing.py#L578-L605
|
|
okex/V3-Open-API-SDK
|
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
|
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py
|
python
|
ParseResults.pprint
|
(self, *args, **kwargs)
|
Pretty-printer for parsed results as a list, using the
`pprint <https://docs.python.org/3/library/pprint.html>`_ module.
Accepts additional positional or keyword args as defined for
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
Example::
ident = Word(alphas, alphanums)
num = Word(nums)
func = Forward()
term = ident | num | Group('(' + func + ')')
func <<= ident + Group(Optional(delimitedList(term)))
result = func.parseString("fna a,b,(fnb c,d,200),100")
result.pprint(width=40)
prints::
['fna',
['a',
'b',
['(', 'fnb', ['c', 'd', '200'], ')'],
'100']]
|
Pretty-printer for parsed results as a list, using the
`pprint <https://docs.python.org/3/library/pprint.html>`_ module.
Accepts additional positional or keyword args as defined for
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
|
[
"Pretty",
"-",
"printer",
"for",
"parsed",
"results",
"as",
"a",
"list",
"using",
"the",
"pprint",
"<https",
":",
"//",
"docs",
".",
"python",
".",
"org",
"/",
"3",
"/",
"library",
"/",
"pprint",
".",
"html",
">",
"_",
"module",
".",
"Accepts",
"additional",
"positional",
"or",
"keyword",
"args",
"as",
"defined",
"for",
"pprint",
".",
"pprint",
"<https",
":",
"//",
"docs",
".",
"python",
".",
"org",
"/",
"3",
"/",
"library",
"/",
"pprint",
".",
"html#pprint",
".",
"pprint",
">",
"_",
"."
] |
def pprint(self, *args, **kwargs):
"""
Pretty-printer for parsed results as a list, using the
`pprint <https://docs.python.org/3/library/pprint.html>`_ module.
Accepts additional positional or keyword args as defined for
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
Example::
ident = Word(alphas, alphanums)
num = Word(nums)
func = Forward()
term = ident | num | Group('(' + func + ')')
func <<= ident + Group(Optional(delimitedList(term)))
result = func.parseString("fna a,b,(fnb c,d,200),100")
result.pprint(width=40)
prints::
['fna',
['a',
'b',
['(', 'fnb', ['c', 'd', '200'], ')'],
'100']]
"""
pprint.pprint(self.asList(), *args, **kwargs)
|
[
"def",
"pprint",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pprint",
".",
"pprint",
"(",
"self",
".",
"asList",
"(",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
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/pyparsing.py#L1042-L1067
|
||
libretro/beetle-psx-libretro
|
05f55acf4ea315bcc16a1cbe0b624696ec6fee35
|
intl/core_option_translation.py
|
python
|
get_struct_type_name
|
(decl: str)
|
Returns relevant parts of the struct declaration:
type, name of the struct and the language appendix, if present.
:param decl: The struct declaration matched by cor.p_type_name.
:return: Tuple, e.g.: ('retro_core_option_definition', 'option_defs_us', '_us')
|
Returns relevant parts of the struct declaration:
type, name of the struct and the language appendix, if present.
:param decl: The struct declaration matched by cor.p_type_name.
:return: Tuple, e.g.: ('retro_core_option_definition', 'option_defs_us', '_us')
|
[
"Returns",
"relevant",
"parts",
"of",
"the",
"struct",
"declaration",
":",
"type",
"name",
"of",
"the",
"struct",
"and",
"the",
"language",
"appendix",
"if",
"present",
".",
":",
"param",
"decl",
":",
"The",
"struct",
"declaration",
"matched",
"by",
"cor",
".",
"p_type_name",
".",
":",
"return",
":",
"Tuple",
"e",
".",
"g",
".",
":",
"(",
"retro_core_option_definition",
"option_defs_us",
"_us",
")"
] |
def get_struct_type_name(decl: str) -> tuple:
""" Returns relevant parts of the struct declaration:
type, name of the struct and the language appendix, if present.
:param decl: The struct declaration matched by cor.p_type_name.
:return: Tuple, e.g.: ('retro_core_option_definition', 'option_defs_us', '_us')
"""
struct_match = cor.p_type_name.search(decl)
if struct_match:
if struct_match.group(3):
struct_type_name = struct_match.group(1, 2, 3)
return struct_type_name
elif struct_match.group(4):
struct_type_name = struct_match.group(1, 2, 4)
return struct_type_name
else:
struct_type_name = struct_match.group(1, 2)
return struct_type_name
else:
raise ValueError(f'No or incomplete struct declaration: {decl}!\n'
'Please make sure all structs are complete, including the type and name declaration.')
|
[
"def",
"get_struct_type_name",
"(",
"decl",
":",
"str",
")",
"->",
"tuple",
":",
"struct_match",
"=",
"cor",
".",
"p_type_name",
".",
"search",
"(",
"decl",
")",
"if",
"struct_match",
":",
"if",
"struct_match",
".",
"group",
"(",
"3",
")",
":",
"struct_type_name",
"=",
"struct_match",
".",
"group",
"(",
"1",
",",
"2",
",",
"3",
")",
"return",
"struct_type_name",
"elif",
"struct_match",
".",
"group",
"(",
"4",
")",
":",
"struct_type_name",
"=",
"struct_match",
".",
"group",
"(",
"1",
",",
"2",
",",
"4",
")",
"return",
"struct_type_name",
"else",
":",
"struct_type_name",
"=",
"struct_match",
".",
"group",
"(",
"1",
",",
"2",
")",
"return",
"struct_type_name",
"else",
":",
"raise",
"ValueError",
"(",
"f'No or incomplete struct declaration: {decl}!\\n'",
"'Please make sure all structs are complete, including the type and name declaration.'",
")"
] |
https://github.com/libretro/beetle-psx-libretro/blob/05f55acf4ea315bcc16a1cbe0b624696ec6fee35/intl/core_option_translation.py#L104-L123
|
||
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py
|
python
|
FitParameters.names
|
(self)
|
return list(self._unique_params.keys())
|
Returns a list of names of parameters. Note that any global parameters are first in the list
|
Returns a list of names of parameters. Note that any global parameters are first in the list
|
[
"Returns",
"a",
"list",
"of",
"names",
"of",
"parameters",
".",
"Note",
"that",
"any",
"global",
"parameters",
"are",
"first",
"in",
"the",
"list"
] |
def names(self):
"""Returns a list of names of parameters. Note that any global parameters are first in the list"""
return list(self._unique_params.keys())
|
[
"def",
"names",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"_unique_params",
".",
"keys",
"(",
")",
")"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py#L159-L161
|
|
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py
|
python
|
TurtleScreen.window_height
|
(self)
|
return self._window_size()[1]
|
Return the height of the turtle window.
Example (for a TurtleScreen instance named screen):
>>> screen.window_height()
480
|
Return the height of the turtle window.
|
[
"Return",
"the",
"height",
"of",
"the",
"turtle",
"window",
"."
] |
def window_height(self):
""" Return the height of the turtle window.
Example (for a TurtleScreen instance named screen):
>>> screen.window_height()
480
"""
return self._window_size()[1]
|
[
"def",
"window_height",
"(",
"self",
")",
":",
"return",
"self",
".",
"_window_size",
"(",
")",
"[",
"1",
"]"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L1264-L1271
|
|
qt/qt
|
0a2f2382541424726168804be2c90b91381608c6
|
src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/make.py
|
python
|
MakefileWriter.WriteMakeRule
|
(self, outputs, inputs, actions=None, comment=None,
order_only=False, force=False, phony=False,
multiple_output_trick=True)
|
Write a Makefile rule, with some extra tricks.
outputs: a list of outputs for the rule (note: this is not directly
supported by make; see comments below)
inputs: a list of inputs for the rule
actions: a list of shell commands to run for the rule
comment: a comment to put in the Makefile above the rule (also useful
for making this Python script's code self-documenting)
order_only: if true, makes the dependency order-only
force: if true, include FORCE_DO_CMD as an order-only dep
phony: if true, the rule does not actually generate the named output, the
output is just a name to run the rule
multiple_output_trick: if true (the default), perform tricks such as dummy
rules to avoid problems with multiple outputs.
|
Write a Makefile rule, with some extra tricks.
|
[
"Write",
"a",
"Makefile",
"rule",
"with",
"some",
"extra",
"tricks",
"."
] |
def WriteMakeRule(self, outputs, inputs, actions=None, comment=None,
order_only=False, force=False, phony=False,
multiple_output_trick=True):
"""Write a Makefile rule, with some extra tricks.
outputs: a list of outputs for the rule (note: this is not directly
supported by make; see comments below)
inputs: a list of inputs for the rule
actions: a list of shell commands to run for the rule
comment: a comment to put in the Makefile above the rule (also useful
for making this Python script's code self-documenting)
order_only: if true, makes the dependency order-only
force: if true, include FORCE_DO_CMD as an order-only dep
phony: if true, the rule does not actually generate the named output, the
output is just a name to run the rule
multiple_output_trick: if true (the default), perform tricks such as dummy
rules to avoid problems with multiple outputs.
"""
if comment:
self.WriteLn('# ' + comment)
if phony:
self.WriteLn('.PHONY: ' + ' '.join(outputs))
# TODO(evanm): just make order_only a list of deps instead of these hacks.
if order_only:
order_insert = '| '
else:
order_insert = ''
if force:
force_append = ' FORCE_DO_CMD'
else:
force_append = ''
if actions:
self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0])
self.WriteLn('%s: %s%s%s' % (outputs[0], order_insert, ' '.join(inputs),
force_append))
if actions:
for action in actions:
self.WriteLn('\t%s' % action)
if multiple_output_trick and len(outputs) > 1:
# If we have more than one output, a rule like
# foo bar: baz
# that for *each* output we must run the action, potentially
# in parallel. That is not what we're trying to write -- what
# we want is that we run the action once and it generates all
# the files.
# http://www.gnu.org/software/hello/manual/automake/Multiple-Outputs.html
# discusses this problem and has this solution:
# 1) Write the naive rule that would produce parallel runs of
# the action.
# 2) Make the outputs seralized on each other, so we won't start
# a parallel run until the first run finishes, at which point
# we'll have generated all the outputs and we're done.
self.WriteLn('%s: %s' % (' '.join(outputs[1:]), outputs[0]))
# Add a dummy command to the "extra outputs" rule, otherwise make seems to
# think these outputs haven't (couldn't have?) changed, and thus doesn't
# flag them as changed (i.e. include in '$?') when evaluating dependent
# rules, which in turn causes do_cmd() to skip running dependent commands.
self.WriteLn('%s: ;' % (' '.join(outputs[1:])))
self.WriteLn()
|
[
"def",
"WriteMakeRule",
"(",
"self",
",",
"outputs",
",",
"inputs",
",",
"actions",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"order_only",
"=",
"False",
",",
"force",
"=",
"False",
",",
"phony",
"=",
"False",
",",
"multiple_output_trick",
"=",
"True",
")",
":",
"if",
"comment",
":",
"self",
".",
"WriteLn",
"(",
"'# '",
"+",
"comment",
")",
"if",
"phony",
":",
"self",
".",
"WriteLn",
"(",
"'.PHONY: '",
"+",
"' '",
".",
"join",
"(",
"outputs",
")",
")",
"# TODO(evanm): just make order_only a list of deps instead of these hacks.",
"if",
"order_only",
":",
"order_insert",
"=",
"'| '",
"else",
":",
"order_insert",
"=",
"''",
"if",
"force",
":",
"force_append",
"=",
"' FORCE_DO_CMD'",
"else",
":",
"force_append",
"=",
"''",
"if",
"actions",
":",
"self",
".",
"WriteLn",
"(",
"\"%s: TOOLSET := $(TOOLSET)\"",
"%",
"outputs",
"[",
"0",
"]",
")",
"self",
".",
"WriteLn",
"(",
"'%s: %s%s%s'",
"%",
"(",
"outputs",
"[",
"0",
"]",
",",
"order_insert",
",",
"' '",
".",
"join",
"(",
"inputs",
")",
",",
"force_append",
")",
")",
"if",
"actions",
":",
"for",
"action",
"in",
"actions",
":",
"self",
".",
"WriteLn",
"(",
"'\\t%s'",
"%",
"action",
")",
"if",
"multiple_output_trick",
"and",
"len",
"(",
"outputs",
")",
">",
"1",
":",
"# If we have more than one output, a rule like",
"# foo bar: baz",
"# that for *each* output we must run the action, potentially",
"# in parallel. That is not what we're trying to write -- what",
"# we want is that we run the action once and it generates all",
"# the files.",
"# http://www.gnu.org/software/hello/manual/automake/Multiple-Outputs.html",
"# discusses this problem and has this solution:",
"# 1) Write the naive rule that would produce parallel runs of",
"# the action.",
"# 2) Make the outputs seralized on each other, so we won't start",
"# a parallel run until the first run finishes, at which point",
"# we'll have generated all the outputs and we're done.",
"self",
".",
"WriteLn",
"(",
"'%s: %s'",
"%",
"(",
"' '",
".",
"join",
"(",
"outputs",
"[",
"1",
":",
"]",
")",
",",
"outputs",
"[",
"0",
"]",
")",
")",
"# Add a dummy command to the \"extra outputs\" rule, otherwise make seems to",
"# think these outputs haven't (couldn't have?) changed, and thus doesn't",
"# flag them as changed (i.e. include in '$?') when evaluating dependent",
"# rules, which in turn causes do_cmd() to skip running dependent commands.",
"self",
".",
"WriteLn",
"(",
"'%s: ;'",
"%",
"(",
"' '",
".",
"join",
"(",
"outputs",
"[",
"1",
":",
"]",
")",
")",
")",
"self",
".",
"WriteLn",
"(",
")"
] |
https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/make.py#L1088-L1146
|
||
thalium/icebox
|
99d147d5b9269222225443ce171b4fd46d8985d4
|
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
|
python
|
initializeDict
|
()
|
return ret
|
Do the dictionary mutex initialization. this function is
deprecated
|
Do the dictionary mutex initialization. this function is
deprecated
|
[
"Do",
"the",
"dictionary",
"mutex",
"initialization",
".",
"this",
"function",
"is",
"deprecated"
] |
def initializeDict():
"""Do the dictionary mutex initialization. this function is
deprecated """
ret = libxml2mod.xmlInitializeDict()
return ret
|
[
"def",
"initializeDict",
"(",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlInitializeDict",
"(",
")",
"return",
"ret"
] |
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L312-L316
|
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py
|
python
|
URLopener.http_error
|
(self, url, fp, errcode, errmsg, headers, data=None)
|
return self.http_error_default(url, fp, errcode, errmsg, headers)
|
Handle http errors.
Derived class can override this, or provide specific handlers
named http_error_DDD where DDD is the 3-digit error code.
|
Handle http errors.
Derived class can override this, or provide specific handlers
named http_error_DDD where DDD is the 3-digit error code.
|
[
"Handle",
"http",
"errors",
".",
"Derived",
"class",
"can",
"override",
"this",
"or",
"provide",
"specific",
"handlers",
"named",
"http_error_DDD",
"where",
"DDD",
"is",
"the",
"3",
"-",
"digit",
"error",
"code",
"."
] |
def http_error(self, url, fp, errcode, errmsg, headers, data=None):
"""Handle http errors.
Derived class can override this, or provide specific handlers
named http_error_DDD where DDD is the 3-digit error code."""
# First check if there's a specific handler for this error
name = 'http_error_%d' % errcode
if hasattr(self, name):
method = getattr(self, name)
if data is None:
result = method(url, fp, errcode, errmsg, headers)
else:
result = method(url, fp, errcode, errmsg, headers, data)
if result: return result
return self.http_error_default(url, fp, errcode, errmsg, headers)
|
[
"def",
"http_error",
"(",
"self",
",",
"url",
",",
"fp",
",",
"errcode",
",",
"errmsg",
",",
"headers",
",",
"data",
"=",
"None",
")",
":",
"# First check if there's a specific handler for this error",
"name",
"=",
"'http_error_%d'",
"%",
"errcode",
"if",
"hasattr",
"(",
"self",
",",
"name",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"if",
"data",
"is",
"None",
":",
"result",
"=",
"method",
"(",
"url",
",",
"fp",
",",
"errcode",
",",
"errmsg",
",",
"headers",
")",
"else",
":",
"result",
"=",
"method",
"(",
"url",
",",
"fp",
",",
"errcode",
",",
"errmsg",
",",
"headers",
",",
"data",
")",
"if",
"result",
":",
"return",
"result",
"return",
"self",
".",
"http_error_default",
"(",
"url",
",",
"fp",
",",
"errcode",
",",
"errmsg",
",",
"headers",
")"
] |
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py#L363-L376
|
|
microsoft/ivy
|
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
|
ivy/ivy_dafny_grammar.py
|
python
|
p_stmt_if_expr_lcb_stmt_rcb_else_LCB_stmt_RCB
|
(p)
|
stmt : IF expr LCB stmts RCB ELSE LCB stmts RCB
|
stmt : IF expr LCB stmts RCB ELSE LCB stmts RCB
|
[
"stmt",
":",
"IF",
"expr",
"LCB",
"stmts",
"RCB",
"ELSE",
"LCB",
"stmts",
"RCB"
] |
def p_stmt_if_expr_lcb_stmt_rcb_else_LCB_stmt_RCB(p):
'stmt : IF expr LCB stmts RCB ELSE LCB stmts RCB'
p[0] = da.IfStmt(p[2],p[4],p[8])
p[0].lineno = p.lineno(1);
|
[
"def",
"p_stmt_if_expr_lcb_stmt_rcb_else_LCB_stmt_RCB",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"da",
".",
"IfStmt",
"(",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"4",
"]",
",",
"p",
"[",
"8",
"]",
")",
"p",
"[",
"0",
"]",
".",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")"
] |
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_dafny_grammar.py#L301-L304
|
||
wlanjie/AndroidFFmpeg
|
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
|
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py
|
python
|
MaildirMessage._explain_to
|
(self, message)
|
Copy Maildir-specific state to message insofar as possible.
|
Copy Maildir-specific state to message insofar as possible.
|
[
"Copy",
"Maildir",
"-",
"specific",
"state",
"to",
"message",
"insofar",
"as",
"possible",
"."
] |
def _explain_to(self, message):
"""Copy Maildir-specific state to message insofar as possible."""
if isinstance(message, MaildirMessage):
message.set_flags(self.get_flags())
message.set_subdir(self.get_subdir())
message.set_date(self.get_date())
elif isinstance(message, _mboxMMDFMessage):
flags = set(self.get_flags())
if 'S' in flags:
message.add_flag('R')
if self.get_subdir() == 'cur':
message.add_flag('O')
if 'T' in flags:
message.add_flag('D')
if 'F' in flags:
message.add_flag('F')
if 'R' in flags:
message.add_flag('A')
message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
elif isinstance(message, MHMessage):
flags = set(self.get_flags())
if 'S' not in flags:
message.add_sequence('unseen')
if 'R' in flags:
message.add_sequence('replied')
if 'F' in flags:
message.add_sequence('flagged')
elif isinstance(message, BabylMessage):
flags = set(self.get_flags())
if 'S' not in flags:
message.add_label('unseen')
if 'T' in flags:
message.add_label('deleted')
if 'R' in flags:
message.add_label('answered')
if 'P' in flags:
message.add_label('forwarded')
elif isinstance(message, Message):
pass
else:
raise TypeError('Cannot convert to specified type: %s' %
type(message))
|
[
"def",
"_explain_to",
"(",
"self",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"MaildirMessage",
")",
":",
"message",
".",
"set_flags",
"(",
"self",
".",
"get_flags",
"(",
")",
")",
"message",
".",
"set_subdir",
"(",
"self",
".",
"get_subdir",
"(",
")",
")",
"message",
".",
"set_date",
"(",
"self",
".",
"get_date",
"(",
")",
")",
"elif",
"isinstance",
"(",
"message",
",",
"_mboxMMDFMessage",
")",
":",
"flags",
"=",
"set",
"(",
"self",
".",
"get_flags",
"(",
")",
")",
"if",
"'S'",
"in",
"flags",
":",
"message",
".",
"add_flag",
"(",
"'R'",
")",
"if",
"self",
".",
"get_subdir",
"(",
")",
"==",
"'cur'",
":",
"message",
".",
"add_flag",
"(",
"'O'",
")",
"if",
"'T'",
"in",
"flags",
":",
"message",
".",
"add_flag",
"(",
"'D'",
")",
"if",
"'F'",
"in",
"flags",
":",
"message",
".",
"add_flag",
"(",
"'F'",
")",
"if",
"'R'",
"in",
"flags",
":",
"message",
".",
"add_flag",
"(",
"'A'",
")",
"message",
".",
"set_from",
"(",
"'MAILER-DAEMON'",
",",
"time",
".",
"gmtime",
"(",
"self",
".",
"get_date",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"message",
",",
"MHMessage",
")",
":",
"flags",
"=",
"set",
"(",
"self",
".",
"get_flags",
"(",
")",
")",
"if",
"'S'",
"not",
"in",
"flags",
":",
"message",
".",
"add_sequence",
"(",
"'unseen'",
")",
"if",
"'R'",
"in",
"flags",
":",
"message",
".",
"add_sequence",
"(",
"'replied'",
")",
"if",
"'F'",
"in",
"flags",
":",
"message",
".",
"add_sequence",
"(",
"'flagged'",
")",
"elif",
"isinstance",
"(",
"message",
",",
"BabylMessage",
")",
":",
"flags",
"=",
"set",
"(",
"self",
".",
"get_flags",
"(",
")",
")",
"if",
"'S'",
"not",
"in",
"flags",
":",
"message",
".",
"add_label",
"(",
"'unseen'",
")",
"if",
"'T'",
"in",
"flags",
":",
"message",
".",
"add_label",
"(",
"'deleted'",
")",
"if",
"'R'",
"in",
"flags",
":",
"message",
".",
"add_label",
"(",
"'answered'",
")",
"if",
"'P'",
"in",
"flags",
":",
"message",
".",
"add_label",
"(",
"'forwarded'",
")",
"elif",
"isinstance",
"(",
"message",
",",
"Message",
")",
":",
"pass",
"else",
":",
"raise",
"TypeError",
"(",
"'Cannot convert to specified type: %s'",
"%",
"type",
"(",
"message",
")",
")"
] |
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py#L1534-L1575
|
||
benoitsteiner/tensorflow-opencl
|
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
|
tensorflow/python/ops/sparse_ops.py
|
python
|
_convert_to_sparse_tensor
|
(sp_input)
|
return sp_input
|
Convert `sp_input` to `SparseTensor` and return it.
Args:
sp_input: `SparseTensor` or `SparseTensorValue`.
Returns:
`sp_input` converted to `SparseTensor`.
Raises:
ValueError: if `sp_input` is neither `SparseTensor` nor `SparseTensorValue`.
|
Convert `sp_input` to `SparseTensor` and return it.
|
[
"Convert",
"sp_input",
"to",
"SparseTensor",
"and",
"return",
"it",
"."
] |
def _convert_to_sparse_tensor(sp_input):
"""Convert `sp_input` to `SparseTensor` and return it.
Args:
sp_input: `SparseTensor` or `SparseTensorValue`.
Returns:
`sp_input` converted to `SparseTensor`.
Raises:
ValueError: if `sp_input` is neither `SparseTensor` nor `SparseTensorValue`.
"""
if isinstance(sp_input, sparse_tensor.SparseTensorValue):
return sparse_tensor.SparseTensor.from_value(sp_input)
if not isinstance(sp_input, sparse_tensor.SparseTensor):
raise TypeError("Input must be a SparseTensor.")
return sp_input
|
[
"def",
"_convert_to_sparse_tensor",
"(",
"sp_input",
")",
":",
"if",
"isinstance",
"(",
"sp_input",
",",
"sparse_tensor",
".",
"SparseTensorValue",
")",
":",
"return",
"sparse_tensor",
".",
"SparseTensor",
".",
"from_value",
"(",
"sp_input",
")",
"if",
"not",
"isinstance",
"(",
"sp_input",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
":",
"raise",
"TypeError",
"(",
"\"Input must be a SparseTensor.\"",
")",
"return",
"sp_input"
] |
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/sparse_ops.py#L70-L86
|
|
macchina-io/macchina.io
|
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
|
platform/JS/V8/v8/third_party/jinja2/compiler.py
|
python
|
Frame.soft
|
(self)
|
return rv
|
Return a soft frame. A soft frame may not be modified as
standalone thing as it shares the resources with the frame it
was created of, but it's not a rootlevel frame any longer.
|
Return a soft frame. A soft frame may not be modified as
standalone thing as it shares the resources with the frame it
was created of, but it's not a rootlevel frame any longer.
|
[
"Return",
"a",
"soft",
"frame",
".",
"A",
"soft",
"frame",
"may",
"not",
"be",
"modified",
"as",
"standalone",
"thing",
"as",
"it",
"shares",
"the",
"resources",
"with",
"the",
"frame",
"it",
"was",
"created",
"of",
"but",
"it",
"s",
"not",
"a",
"rootlevel",
"frame",
"any",
"longer",
"."
] |
def soft(self):
"""Return a soft frame. A soft frame may not be modified as
standalone thing as it shares the resources with the frame it
was created of, but it's not a rootlevel frame any longer.
"""
rv = self.copy()
rv.rootlevel = False
return rv
|
[
"def",
"soft",
"(",
"self",
")",
":",
"rv",
"=",
"self",
".",
"copy",
"(",
")",
"rv",
".",
"rootlevel",
"=",
"False",
"return",
"rv"
] |
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/compiler.py#L215-L222
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
wx/tools/Editra/src/eclib/pstatbar.py
|
python
|
ProgressStatusBar.Stop
|
(self)
|
Stop and hide the progress bar. This method may safely be called
from background threads.
@precondition: Bar is already running
|
Stop and hide the progress bar. This method may safely be called
from background threads.
@precondition: Bar is already running
|
[
"Stop",
"and",
"hide",
"the",
"progress",
"bar",
".",
"This",
"method",
"may",
"safely",
"be",
"called",
"from",
"background",
"threads",
".",
"@precondition",
":",
"Bar",
"is",
"already",
"running"
] |
def Stop(self):
"""Stop and hide the progress bar. This method may safely be called
from background threads.
@precondition: Bar is already running
"""
if wx.Thread_IsMain():
self.DoStop()
else:
self.stop = True # Set flag from non main thread
self.progress = 0
|
[
"def",
"Stop",
"(",
"self",
")",
":",
"if",
"wx",
".",
"Thread_IsMain",
"(",
")",
":",
"self",
".",
"DoStop",
"(",
")",
"else",
":",
"self",
".",
"stop",
"=",
"True",
"# Set flag from non main thread",
"self",
".",
"progress",
"=",
"0"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/pstatbar.py#L281-L291
|
||
ChromiumWebApps/chromium
|
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
|
third_party/jinja2/sandbox.py
|
python
|
SandboxedEnvironment.getitem
|
(self, obj, argument)
|
return self.undefined(obj=obj, name=argument)
|
Subscribe an object from sandboxed code.
|
Subscribe an object from sandboxed code.
|
[
"Subscribe",
"an",
"object",
"from",
"sandboxed",
"code",
"."
] |
def getitem(self, obj, argument):
"""Subscribe an object from sandboxed code."""
try:
return obj[argument]
except (TypeError, LookupError):
if isinstance(argument, string_types):
try:
attr = str(argument)
except Exception:
pass
else:
try:
value = getattr(obj, attr)
except AttributeError:
pass
else:
if self.is_safe_attribute(obj, argument, value):
return value
return self.unsafe_undefined(obj, argument)
return self.undefined(obj=obj, name=argument)
|
[
"def",
"getitem",
"(",
"self",
",",
"obj",
",",
"argument",
")",
":",
"try",
":",
"return",
"obj",
"[",
"argument",
"]",
"except",
"(",
"TypeError",
",",
"LookupError",
")",
":",
"if",
"isinstance",
"(",
"argument",
",",
"string_types",
")",
":",
"try",
":",
"attr",
"=",
"str",
"(",
"argument",
")",
"except",
"Exception",
":",
"pass",
"else",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"attr",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"if",
"self",
".",
"is_safe_attribute",
"(",
"obj",
",",
"argument",
",",
"value",
")",
":",
"return",
"value",
"return",
"self",
".",
"unsafe_undefined",
"(",
"obj",
",",
"argument",
")",
"return",
"self",
".",
"undefined",
"(",
"obj",
"=",
"obj",
",",
"name",
"=",
"argument",
")"
] |
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/sandbox.py#L304-L323
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/_core.py
|
python
|
EvtHandler.GetEvtHandlerEnabled
|
(*args, **kwargs)
|
return _core_.EvtHandler_GetEvtHandlerEnabled(*args, **kwargs)
|
GetEvtHandlerEnabled(self) -> bool
|
GetEvtHandlerEnabled(self) -> bool
|
[
"GetEvtHandlerEnabled",
"(",
"self",
")",
"-",
">",
"bool"
] |
def GetEvtHandlerEnabled(*args, **kwargs):
"""GetEvtHandlerEnabled(self) -> bool"""
return _core_.EvtHandler_GetEvtHandlerEnabled(*args, **kwargs)
|
[
"def",
"GetEvtHandlerEnabled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"EvtHandler_GetEvtHandlerEnabled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L4136-L4138
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/aui.py
|
python
|
AuiPaneInfo.MaximizeButton
|
(*args, **kwargs)
|
return _aui.AuiPaneInfo_MaximizeButton(*args, **kwargs)
|
MaximizeButton(self, bool visible=True) -> AuiPaneInfo
|
MaximizeButton(self, bool visible=True) -> AuiPaneInfo
|
[
"MaximizeButton",
"(",
"self",
"bool",
"visible",
"=",
"True",
")",
"-",
">",
"AuiPaneInfo"
] |
def MaximizeButton(*args, **kwargs):
"""MaximizeButton(self, bool visible=True) -> AuiPaneInfo"""
return _aui.AuiPaneInfo_MaximizeButton(*args, **kwargs)
|
[
"def",
"MaximizeButton",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_MaximizeButton",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L461-L463
|
|
gimli-org/gimli
|
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
|
pygimli/meshtools/mesh.py
|
python
|
readMeshIO
|
(fileName, verbose=False)
|
return mesh
|
Generic mesh read using meshio. (https://github.com/nschloe/meshio)
|
Generic mesh read using meshio. (https://github.com/nschloe/meshio)
|
[
"Generic",
"mesh",
"read",
"using",
"meshio",
".",
"(",
"https",
":",
"//",
"github",
".",
"com",
"/",
"nschloe",
"/",
"meshio",
")"
] |
def readMeshIO(fileName, verbose=False):
"""Generic mesh read using meshio. (https://github.com/nschloe/meshio)
"""
meshio = pg.optImport('meshio')
_t = meshio.read(fileName)
mesh = pg.meshtools.convert(_t)
if verbose is True:
print(mesh)
return mesh
|
[
"def",
"readMeshIO",
"(",
"fileName",
",",
"verbose",
"=",
"False",
")",
":",
"meshio",
"=",
"pg",
".",
"optImport",
"(",
"'meshio'",
")",
"_t",
"=",
"meshio",
".",
"read",
"(",
"fileName",
")",
"mesh",
"=",
"pg",
".",
"meshtools",
".",
"convert",
"(",
"_t",
")",
"if",
"verbose",
"is",
"True",
":",
"print",
"(",
"mesh",
")",
"return",
"mesh"
] |
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/meshtools/mesh.py#L1322-L1330
|
|
thalium/icebox
|
99d147d5b9269222225443ce171b4fd46d8985d4
|
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
|
python
|
xmlDoc.validateDtd
|
(self, ctxt, dtd)
|
return ret
|
Try to validate the document against the dtd instance
Basically it does check all the definitions in the DtD.
Note the the internal subset (if present) is de-coupled
(i.e. not used), which could give problems if ID or IDREF
is present.
|
Try to validate the document against the dtd instance
Basically it does check all the definitions in the DtD.
Note the the internal subset (if present) is de-coupled
(i.e. not used), which could give problems if ID or IDREF
is present.
|
[
"Try",
"to",
"validate",
"the",
"document",
"against",
"the",
"dtd",
"instance",
"Basically",
"it",
"does",
"check",
"all",
"the",
"definitions",
"in",
"the",
"DtD",
".",
"Note",
"the",
"the",
"internal",
"subset",
"(",
"if",
"present",
")",
"is",
"de",
"-",
"coupled",
"(",
"i",
".",
"e",
".",
"not",
"used",
")",
"which",
"could",
"give",
"problems",
"if",
"ID",
"or",
"IDREF",
"is",
"present",
"."
] |
def validateDtd(self, ctxt, dtd):
"""Try to validate the document against the dtd instance
Basically it does check all the definitions in the DtD.
Note the the internal subset (if present) is de-coupled
(i.e. not used), which could give problems if ID or IDREF
is present. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if dtd is None: dtd__o = None
else: dtd__o = dtd._o
ret = libxml2mod.xmlValidateDtd(ctxt__o, self._o, dtd__o)
return ret
|
[
"def",
"validateDtd",
"(",
"self",
",",
"ctxt",
",",
"dtd",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"if",
"dtd",
"is",
"None",
":",
"dtd__o",
"=",
"None",
"else",
":",
"dtd__o",
"=",
"dtd",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidateDtd",
"(",
"ctxt__o",
",",
"self",
".",
"_o",
",",
"dtd__o",
")",
"return",
"ret"
] |
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L4698-L4709
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/grid.py
|
python
|
GridEvent.GetCol
|
(*args, **kwargs)
|
return _grid.GridEvent_GetCol(*args, **kwargs)
|
GetCol(self) -> int
|
GetCol(self) -> int
|
[
"GetCol",
"(",
"self",
")",
"-",
">",
"int"
] |
def GetCol(*args, **kwargs):
"""GetCol(self) -> int"""
return _grid.GridEvent_GetCol(*args, **kwargs)
|
[
"def",
"GetCol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridEvent_GetCol",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2309-L2311
|
|
pmh47/dirt
|
571addc359201b668d9dc450086c6dce6c18d0b6
|
dirt/matrices.py
|
python
|
pad_3x3_to_4x4
|
(matrix, name=None)
|
Pads a 3D transform matrix to a 4D homogeneous transform matrix.
This function converts a batch of 3x3 transform matrices into 4x4 equivalents that operate on
homogeneous coordinates.
To do so, for each matrix in the batch, it appends a column of zeros, a row of zeros, and a single
one at the bottom-right corner.
Args:
matrix: a `Tensor` of shape [*, 3, 3], where * represents arbitrarily many leading (batch) dimensions
name: an optional name for the operation
Returns:
a `Tensor` of shape [*, 4, 4] containing the padded matrices, where * represents the same leading
dimensions as present on `matrix`
|
Pads a 3D transform matrix to a 4D homogeneous transform matrix.
|
[
"Pads",
"a",
"3D",
"transform",
"matrix",
"to",
"a",
"4D",
"homogeneous",
"transform",
"matrix",
"."
] |
def pad_3x3_to_4x4(matrix, name=None):
"""Pads a 3D transform matrix to a 4D homogeneous transform matrix.
This function converts a batch of 3x3 transform matrices into 4x4 equivalents that operate on
homogeneous coordinates.
To do so, for each matrix in the batch, it appends a column of zeros, a row of zeros, and a single
one at the bottom-right corner.
Args:
matrix: a `Tensor` of shape [*, 3, 3], where * represents arbitrarily many leading (batch) dimensions
name: an optional name for the operation
Returns:
a `Tensor` of shape [*, 4, 4] containing the padded matrices, where * represents the same leading
dimensions as present on `matrix`
"""
# matrix is indexed by *, x/y/z (in), x/y/z (out)
# result is indexed by *, x/y/z/w (in), x/y/z/w (out)
with ops.name_scope(name, 'Pad3x3To4x4', [matrix]) as scope:
matrix = tf.convert_to_tensor(matrix, name='matrix')
return tf.concat([
tf.concat([matrix, tf.zeros_like(matrix[..., :, :1])], axis=-1),
tf.concat([tf.zeros_like(matrix[..., :1, :]), tf.ones_like(matrix[..., :1, :1])], axis=-1)
], axis=-2)
|
[
"def",
"pad_3x3_to_4x4",
"(",
"matrix",
",",
"name",
"=",
"None",
")",
":",
"# matrix is indexed by *, x/y/z (in), x/y/z (out)",
"# result is indexed by *, x/y/z/w (in), x/y/z/w (out)",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"'Pad3x3To4x4'",
",",
"[",
"matrix",
"]",
")",
"as",
"scope",
":",
"matrix",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"matrix",
",",
"name",
"=",
"'matrix'",
")",
"return",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"concat",
"(",
"[",
"matrix",
",",
"tf",
".",
"zeros_like",
"(",
"matrix",
"[",
"...",
",",
":",
",",
":",
"1",
"]",
")",
"]",
",",
"axis",
"=",
"-",
"1",
")",
",",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"zeros_like",
"(",
"matrix",
"[",
"...",
",",
":",
"1",
",",
":",
"]",
")",
",",
"tf",
".",
"ones_like",
"(",
"matrix",
"[",
"...",
",",
":",
"1",
",",
":",
"1",
"]",
")",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"]",
",",
"axis",
"=",
"-",
"2",
")"
] |
https://github.com/pmh47/dirt/blob/571addc359201b668d9dc450086c6dce6c18d0b6/dirt/matrices.py#L156-L180
|
||
apple/swift-clang
|
d7403439fc6641751840b723e7165fb02f52db95
|
bindings/python/clang/cindex.py
|
python
|
Type.get_named_type
|
(self)
|
return conf.lib.clang_Type_getNamedType(self)
|
Retrieve the type named by the qualified-id.
|
Retrieve the type named by the qualified-id.
|
[
"Retrieve",
"the",
"type",
"named",
"by",
"the",
"qualified",
"-",
"id",
"."
] |
def get_named_type(self):
"""
Retrieve the type named by the qualified-id.
"""
return conf.lib.clang_Type_getNamedType(self)
|
[
"def",
"get_named_type",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Type_getNamedType",
"(",
"self",
")"
] |
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L2371-L2375
|
|
BlzFans/wke
|
b0fa21158312e40c5fbd84682d643022b6c34a93
|
cygwin/lib/python2.6/multiprocessing/__init__.py
|
python
|
Event
|
()
|
return Event()
|
Returns an event object
|
Returns an event object
|
[
"Returns",
"an",
"event",
"object"
] |
def Event():
'''
Returns an event object
'''
from multiprocessing.synchronize import Event
return Event()
|
[
"def",
"Event",
"(",
")",
":",
"from",
"multiprocessing",
".",
"synchronize",
"import",
"Event",
"return",
"Event",
"(",
")"
] |
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/multiprocessing/__init__.py#L201-L206
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/setuptools/py3/pkg_resources/__init__.py
|
python
|
Environment.__getitem__
|
(self, project_name)
|
return self._distmap.get(distribution_key, [])
|
Return a newest-to-oldest list of distributions for `project_name`
Uses case-insensitive `project_name` comparison, assuming all the
project's distributions use their project's name converted to all
lowercase as their key.
|
Return a newest-to-oldest list of distributions for `project_name`
|
[
"Return",
"a",
"newest",
"-",
"to",
"-",
"oldest",
"list",
"of",
"distributions",
"for",
"project_name"
] |
def __getitem__(self, project_name):
"""Return a newest-to-oldest list of distributions for `project_name`
Uses case-insensitive `project_name` comparison, assuming all the
project's distributions use their project's name converted to all
lowercase as their key.
"""
distribution_key = project_name.lower()
return self._distmap.get(distribution_key, [])
|
[
"def",
"__getitem__",
"(",
"self",
",",
"project_name",
")",
":",
"distribution_key",
"=",
"project_name",
".",
"lower",
"(",
")",
"return",
"self",
".",
"_distmap",
".",
"get",
"(",
"distribution_key",
",",
"[",
"]",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/__init__.py#L1010-L1019
|
|
baidu-research/tensorflow-allreduce
|
66d5b855e90b0949e9fa5cca5599fd729a70e874
|
tensorflow/contrib/specs/python/specs_ops.py
|
python
|
Clstm2
|
(n, *args, **kw)
|
return Cl(n, [3, 3]) | Lstm2(*args, **kw)
|
2D LSTM with 3x3 pre-convolution.
|
2D LSTM with 3x3 pre-convolution.
|
[
"2D",
"LSTM",
"with",
"3x3",
"pre",
"-",
"convolution",
"."
] |
def Clstm2(n, *args, **kw):
"""2D LSTM with 3x3 pre-convolution."""
return Cl(n, [3, 3]) | Lstm2(*args, **kw)
|
[
"def",
"Clstm2",
"(",
"n",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"Cl",
"(",
"n",
",",
"[",
"3",
",",
"3",
"]",
")",
"|",
"Lstm2",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] |
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/specs/python/specs_ops.py#L132-L134
|
|
GoSSIP-SJTU/Armariris
|
ad5d868482956b2194a77b39c8d543c7c2318200
|
bindings/python/llvm/object.py
|
python
|
Symbol.address
|
(self)
|
return lib.LLVMGetSymbolAddress(self)
|
The address of this symbol, in long bytes.
|
The address of this symbol, in long bytes.
|
[
"The",
"address",
"of",
"this",
"symbol",
"in",
"long",
"bytes",
"."
] |
def address(self):
"""The address of this symbol, in long bytes."""
if self.expired:
raise Exception('Symbol instance has expired.')
return lib.LLVMGetSymbolAddress(self)
|
[
"def",
"address",
"(",
"self",
")",
":",
"if",
"self",
".",
"expired",
":",
"raise",
"Exception",
"(",
"'Symbol instance has expired.'",
")",
"return",
"lib",
".",
"LLVMGetSymbolAddress",
"(",
"self",
")"
] |
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/bindings/python/llvm/object.py#L314-L319
|
|
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py
|
python
|
Context.set_session_id
|
(self, buf)
|
Set the session id to *buf* within which a session can be reused for
this Context object. This is needed when doing session resumption,
because there is no way for a stored session to know which Context
object it is associated with.
:param bytes buf: The session id.
:returns: None
|
Set the session id to *buf* within which a session can be reused for
this Context object. This is needed when doing session resumption,
because there is no way for a stored session to know which Context
object it is associated with.
|
[
"Set",
"the",
"session",
"id",
"to",
"*",
"buf",
"*",
"within",
"which",
"a",
"session",
"can",
"be",
"reused",
"for",
"this",
"Context",
"object",
".",
"This",
"is",
"needed",
"when",
"doing",
"session",
"resumption",
"because",
"there",
"is",
"no",
"way",
"for",
"a",
"stored",
"session",
"to",
"know",
"which",
"Context",
"object",
"it",
"is",
"associated",
"with",
"."
] |
def set_session_id(self, buf):
"""
Set the session id to *buf* within which a session can be reused for
this Context object. This is needed when doing session resumption,
because there is no way for a stored session to know which Context
object it is associated with.
:param bytes buf: The session id.
:returns: None
"""
buf = _text_to_bytes_and_warn("buf", buf)
_openssl_assert(
_lib.SSL_CTX_set_session_id_context(
self._context,
buf,
len(buf),
) == 1
)
|
[
"def",
"set_session_id",
"(",
"self",
",",
"buf",
")",
":",
"buf",
"=",
"_text_to_bytes_and_warn",
"(",
"\"buf\"",
",",
"buf",
")",
"_openssl_assert",
"(",
"_lib",
".",
"SSL_CTX_set_session_id_context",
"(",
"self",
".",
"_context",
",",
"buf",
",",
"len",
"(",
"buf",
")",
",",
")",
"==",
"1",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py#L1047-L1065
|
||
benoitsteiner/tensorflow-opencl
|
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
|
tensorflow/python/layers/base.py
|
python
|
Layer.weights
|
(self)
|
return self.trainable_weights + self.non_trainable_weights
|
Returns the list of all layer variables/weights.
Returns:
A list of variables.
|
Returns the list of all layer variables/weights.
|
[
"Returns",
"the",
"list",
"of",
"all",
"layer",
"variables",
"/",
"weights",
"."
] |
def weights(self):
"""Returns the list of all layer variables/weights.
Returns:
A list of variables.
"""
return self.trainable_weights + self.non_trainable_weights
|
[
"def",
"weights",
"(",
"self",
")",
":",
"return",
"self",
".",
"trainable_weights",
"+",
"self",
".",
"non_trainable_weights"
] |
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/layers/base.py#L193-L199
|
|
Kitware/ParaView
|
f760af9124ff4634b23ebbeab95a4f56e0261955
|
Wrapping/Python/paraview/servermanager.py
|
python
|
PropertyIterator.__getattr__
|
(self, name)
|
return getattr(self.SMIterator, name)
|
returns attributes from the vtkSMPropertyIterator.
|
returns attributes from the vtkSMPropertyIterator.
|
[
"returns",
"attributes",
"from",
"the",
"vtkSMPropertyIterator",
"."
] |
def __getattr__(self, name):
"""returns attributes from the vtkSMPropertyIterator."""
return getattr(self.SMIterator, name)
|
[
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"SMIterator",
",",
"name",
")"
] |
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/servermanager.py#L1950-L1952
|
|
SpaceNetChallenge/BuildingDetectors
|
3def3c44b5847c744cd2f3356182892d92496579
|
qinhaifang/src/evalTools/script/spaceNet/geoTools.py
|
python
|
exporttogeojson
|
(geojsonfilename, buildinglist)
|
return geojsonfilename
|
docstring for exporttogeojson
|
docstring for exporttogeojson
|
[
"docstring",
"for",
"exporttogeojson"
] |
def exporttogeojson(geojsonfilename, buildinglist):
"""docstring for exporttogeojson"""
#
# geojsonname should end with .geojson
# building list should be list of dictionaries
# list of Dictionaries {'ImageId': image_id, 'BuildingId': building_id, 'poly': poly}
# image_id is a string,
# BuildingId is an integer,
# poly is a ogr.Geometry Polygon
#
# returns geojsonfilename
driver = ogr.GetDriverByName('geojson')
if os.path.exists(geojsonfilename):
driver.DeleteDataSource(geojsonfilename)
datasource = driver.CreateDataSource(geojsonfilename)
layer = datasource.CreateLayer('buildings', geom_type=ogr.wkbPolygon)
field_name = ogr.FieldDefn("ImageId", ogr.OFTString)
field_name.SetWidth(75)
layer.CreateField(field_name)
layer.CreateField(ogr.FieldDefn("BuildingId", ogr.OFTInteger))
#print('extport buildinglist = {}'.format(buildinglist))
# loop through buildings
for building in buildinglist:
#print('extport building = {}'.format(building))
# create feature
feature = ogr.Feature(layer.GetLayerDefn())
feature.SetField("ImageId", building['ImageId'])
feature.SetField("BuildingId", building['BuildingId'])
#print('extport building poly= {}'.format(building['poly']))
feature.SetGeometry(building['poly'])
# Create the feature in the layer (geojson)
layer.CreateFeature(feature)
# Destroy the feature to free resources
feature.Destroy()
datasource.Destroy()
return geojsonfilename
|
[
"def",
"exporttogeojson",
"(",
"geojsonfilename",
",",
"buildinglist",
")",
":",
"#",
"# geojsonname should end with .geojson",
"# building list should be list of dictionaries",
"# list of Dictionaries {'ImageId': image_id, 'BuildingId': building_id, 'poly': poly}",
"# image_id is a string,",
"# BuildingId is an integer,",
"# poly is a ogr.Geometry Polygon",
"#",
"# returns geojsonfilename",
"driver",
"=",
"ogr",
".",
"GetDriverByName",
"(",
"'geojson'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"geojsonfilename",
")",
":",
"driver",
".",
"DeleteDataSource",
"(",
"geojsonfilename",
")",
"datasource",
"=",
"driver",
".",
"CreateDataSource",
"(",
"geojsonfilename",
")",
"layer",
"=",
"datasource",
".",
"CreateLayer",
"(",
"'buildings'",
",",
"geom_type",
"=",
"ogr",
".",
"wkbPolygon",
")",
"field_name",
"=",
"ogr",
".",
"FieldDefn",
"(",
"\"ImageId\"",
",",
"ogr",
".",
"OFTString",
")",
"field_name",
".",
"SetWidth",
"(",
"75",
")",
"layer",
".",
"CreateField",
"(",
"field_name",
")",
"layer",
".",
"CreateField",
"(",
"ogr",
".",
"FieldDefn",
"(",
"\"BuildingId\"",
",",
"ogr",
".",
"OFTInteger",
")",
")",
"#print('extport buildinglist = {}'.format(buildinglist))",
"# loop through buildings",
"for",
"building",
"in",
"buildinglist",
":",
"#print('extport building = {}'.format(building))",
"# create feature",
"feature",
"=",
"ogr",
".",
"Feature",
"(",
"layer",
".",
"GetLayerDefn",
"(",
")",
")",
"feature",
".",
"SetField",
"(",
"\"ImageId\"",
",",
"building",
"[",
"'ImageId'",
"]",
")",
"feature",
".",
"SetField",
"(",
"\"BuildingId\"",
",",
"building",
"[",
"'BuildingId'",
"]",
")",
"#print('extport building poly= {}'.format(building['poly']))",
"feature",
".",
"SetGeometry",
"(",
"building",
"[",
"'poly'",
"]",
")",
"# Create the feature in the layer (geojson)",
"layer",
".",
"CreateFeature",
"(",
"feature",
")",
"# Destroy the feature to free resources",
"feature",
".",
"Destroy",
"(",
")",
"datasource",
".",
"Destroy",
"(",
")",
"return",
"geojsonfilename"
] |
https://github.com/SpaceNetChallenge/BuildingDetectors/blob/3def3c44b5847c744cd2f3356182892d92496579/qinhaifang/src/evalTools/script/spaceNet/geoTools.py#L81-L120
|
|
qt/qt
|
0a2f2382541424726168804be2c90b91381608c6
|
src/3rdparty/freetype/src/tools/docmaker/sources.py
|
python
|
SourceProcessor.dump
|
( self )
|
print all blocks in a processor
|
print all blocks in a processor
|
[
"print",
"all",
"blocks",
"in",
"a",
"processor"
] |
def dump( self ):
"""print all blocks in a processor"""
for b in self.blocks:
b.dump()
|
[
"def",
"dump",
"(",
"self",
")",
":",
"for",
"b",
"in",
"self",
".",
"blocks",
":",
"b",
".",
"dump",
"(",
")"
] |
https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/freetype/src/tools/docmaker/sources.py#L342-L345
|
||
cmu-db/bustub
|
fe1b9e984bd2967997b52df872c873d80f71cf7d
|
build_support/cpplint.py
|
python
|
RemoveMultiLineComments
|
(filename, lines, error)
|
Removes multiline (c-style) comments from lines.
|
Removes multiline (c-style) comments from lines.
|
[
"Removes",
"multiline",
"(",
"c",
"-",
"style",
")",
"comments",
"from",
"lines",
"."
] |
def RemoveMultiLineComments(filename, lines, error):
"""Removes multiline (c-style) comments from lines."""
lineix = 0
while lineix < len(lines):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if lineix_begin >= len(lines):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if lineix_end >= len(lines):
error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
'Could not find end of multi-line comment')
return
RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
lineix = lineix_end + 1
|
[
"def",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"lineix",
"=",
"0",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"lineix_begin",
"=",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
"if",
"lineix_begin",
">=",
"len",
"(",
"lines",
")",
":",
"return",
"lineix_end",
"=",
"FindNextMultiLineCommentEnd",
"(",
"lines",
",",
"lineix_begin",
")",
"if",
"lineix_end",
">=",
"len",
"(",
"lines",
")",
":",
"error",
"(",
"filename",
",",
"lineix_begin",
"+",
"1",
",",
"'readability/multiline_comment'",
",",
"5",
",",
"'Could not find end of multi-line comment'",
")",
"return",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"lineix_begin",
",",
"lineix_end",
"+",
"1",
")",
"lineix",
"=",
"lineix_end",
"+",
"1"
] |
https://github.com/cmu-db/bustub/blob/fe1b9e984bd2967997b52df872c873d80f71cf7d/build_support/cpplint.py#L1617-L1630
|
||
mantidproject/mantid
|
03deeb89254ec4289edb8771e0188c2090a02f32
|
scripts/SANS/sans/algorithm_detail/centre_finder_new.py
|
python
|
centre_finder_new
|
(state, r_min, r_max, iterations, position_1_start, position_2_start,
tolerance, find_direction, verbose, component)
|
return {"pos1": centre1, "pos2": centre2}
|
Finds the beam centre from a good initial guess.
This function finds the centre of the beam by splitting the workspace up into 4 quadrants and running a reduction on
each. The (left, right) and (up, down) reductions are then compared producing residuals which are minimised through
repeated iteration.
:param state: This is a sans state, to find the beam centre for.
:param r_min: This is the inner radius of the quartile mask.
:param r_max: This is the outer radius of the quartile mask.
:param max_iter: This is the maximum number of iterations.
:param position_1_start: This is the starting position of the search on the x axis.
:param position_2_start: This is the starting position of the search on the y axis.
:param tolerance: This is the tolerance for the search.
:param find_direction: This is an enumerator controlling which axis or both should be searched.
|
Finds the beam centre from a good initial guess.
|
[
"Finds",
"the",
"beam",
"centre",
"from",
"a",
"good",
"initial",
"guess",
"."
] |
def centre_finder_new(state, r_min, r_max, iterations, position_1_start, position_2_start,
tolerance, find_direction, verbose, component):
"""
Finds the beam centre from a good initial guess.
This function finds the centre of the beam by splitting the workspace up into 4 quadrants and running a reduction on
each. The (left, right) and (up, down) reductions are then compared producing residuals which are minimised through
repeated iteration.
:param state: This is a sans state, to find the beam centre for.
:param r_min: This is the inner radius of the quartile mask.
:param r_max: This is the outer radius of the quartile mask.
:param max_iter: This is the maximum number of iterations.
:param position_1_start: This is the starting position of the search on the x axis.
:param position_2_start: This is the starting position of the search on the y axis.
:param tolerance: This is the tolerance for the search.
:param find_direction: This is an enumerator controlling which axis or both should be searched.
"""
# ------------------------------------------------------------------------------------------------------------------
# Load the data
# ------------------------------------------------------------------------------------------------------------------
workspace_to_name = {SANSDataType.SAMPLE_SCATTER: "SampleScatterWorkspace",
SANSDataType.SAMPLE_TRANSMISSION: "SampleTransmissionWorkspace",
SANSDataType.SAMPLE_DIRECT: "SampleDirectWorkspace",
SANSDataType.CAN_SCATTER: "CanScatterWorkspace",
SANSDataType.CAN_TRANSMISSION: "CanTransmissionWorkspace",
SANSDataType.CAN_DIRECT: "CanDirectWorkspace"}
workspace_to_monitor = {SANSDataType.SAMPLE_SCATTER: "SampleScatterMonitorWorkSpace",
SANSDataType.CAN_SCATTER: "CanScatterMonitorWorkspace"}
workspaces, monitors = provide_loaded_data(state, False, workspace_to_name, workspace_to_monitor)
# ------------------------------------------------------------------------------------------------------------------
# Get reduction settings
# Split into individual bundles which can be reduced individually. We split here if we have multiple periods or
# sliced times for example. For the beam centre finder we only use the first period.
# ------------------------------------------------------------------------------------------------------------------
reduction_packages = get_reduction_packages(state, workspaces, monitors)
reduction_package = reduction_packages[0]
# ------------------------------------------------------------------------------------------------------------------
# Setup the beam centre finder algorithm.
# ------------------------------------------------------------------------------------------------------------------
beam_centre_finder = "SANSBeamCentreFinder"
beam_centre_finder_options = {"Iterations": iterations, "RMin": r_min/1000, "RMax": r_max/1000,
"Position1Start": position_1_start, "Position2Start": position_2_start,
"Tolerance": tolerance, "Direction" : find_direction.value,
"Verbose": verbose, "Component": component.value}
beam_centre_alg = create_managed_non_child_algorithm(beam_centre_finder, **beam_centre_finder_options)
beam_centre_alg.setChild(False)
set_properties_for_beam_centre_algorithm(beam_centre_alg, reduction_package,
workspace_to_name, workspace_to_monitor)
# -----------------------------------
# Run the beam centre finder algorithm.
# -----------------------------------
beam_centre_alg.execute()
# -----------------------------------
# Get the outputs
# -----------------------------------
centre1 = beam_centre_alg.getProperty("Centre1").value
centre2 = beam_centre_alg.getProperty("Centre2").value
return {"pos1": centre1, "pos2": centre2}
|
[
"def",
"centre_finder_new",
"(",
"state",
",",
"r_min",
",",
"r_max",
",",
"iterations",
",",
"position_1_start",
",",
"position_2_start",
",",
"tolerance",
",",
"find_direction",
",",
"verbose",
",",
"component",
")",
":",
"# ------------------------------------------------------------------------------------------------------------------",
"# Load the data",
"# ------------------------------------------------------------------------------------------------------------------",
"workspace_to_name",
"=",
"{",
"SANSDataType",
".",
"SAMPLE_SCATTER",
":",
"\"SampleScatterWorkspace\"",
",",
"SANSDataType",
".",
"SAMPLE_TRANSMISSION",
":",
"\"SampleTransmissionWorkspace\"",
",",
"SANSDataType",
".",
"SAMPLE_DIRECT",
":",
"\"SampleDirectWorkspace\"",
",",
"SANSDataType",
".",
"CAN_SCATTER",
":",
"\"CanScatterWorkspace\"",
",",
"SANSDataType",
".",
"CAN_TRANSMISSION",
":",
"\"CanTransmissionWorkspace\"",
",",
"SANSDataType",
".",
"CAN_DIRECT",
":",
"\"CanDirectWorkspace\"",
"}",
"workspace_to_monitor",
"=",
"{",
"SANSDataType",
".",
"SAMPLE_SCATTER",
":",
"\"SampleScatterMonitorWorkSpace\"",
",",
"SANSDataType",
".",
"CAN_SCATTER",
":",
"\"CanScatterMonitorWorkspace\"",
"}",
"workspaces",
",",
"monitors",
"=",
"provide_loaded_data",
"(",
"state",
",",
"False",
",",
"workspace_to_name",
",",
"workspace_to_monitor",
")",
"# ------------------------------------------------------------------------------------------------------------------",
"# Get reduction settings",
"# Split into individual bundles which can be reduced individually. We split here if we have multiple periods or",
"# sliced times for example. For the beam centre finder we only use the first period.",
"# ------------------------------------------------------------------------------------------------------------------",
"reduction_packages",
"=",
"get_reduction_packages",
"(",
"state",
",",
"workspaces",
",",
"monitors",
")",
"reduction_package",
"=",
"reduction_packages",
"[",
"0",
"]",
"# ------------------------------------------------------------------------------------------------------------------",
"# Setup the beam centre finder algorithm.",
"# ------------------------------------------------------------------------------------------------------------------",
"beam_centre_finder",
"=",
"\"SANSBeamCentreFinder\"",
"beam_centre_finder_options",
"=",
"{",
"\"Iterations\"",
":",
"iterations",
",",
"\"RMin\"",
":",
"r_min",
"/",
"1000",
",",
"\"RMax\"",
":",
"r_max",
"/",
"1000",
",",
"\"Position1Start\"",
":",
"position_1_start",
",",
"\"Position2Start\"",
":",
"position_2_start",
",",
"\"Tolerance\"",
":",
"tolerance",
",",
"\"Direction\"",
":",
"find_direction",
".",
"value",
",",
"\"Verbose\"",
":",
"verbose",
",",
"\"Component\"",
":",
"component",
".",
"value",
"}",
"beam_centre_alg",
"=",
"create_managed_non_child_algorithm",
"(",
"beam_centre_finder",
",",
"*",
"*",
"beam_centre_finder_options",
")",
"beam_centre_alg",
".",
"setChild",
"(",
"False",
")",
"set_properties_for_beam_centre_algorithm",
"(",
"beam_centre_alg",
",",
"reduction_package",
",",
"workspace_to_name",
",",
"workspace_to_monitor",
")",
"# -----------------------------------",
"# Run the beam centre finder algorithm.",
"# -----------------------------------",
"beam_centre_alg",
".",
"execute",
"(",
")",
"# -----------------------------------",
"# Get the outputs",
"# -----------------------------------",
"centre1",
"=",
"beam_centre_alg",
".",
"getProperty",
"(",
"\"Centre1\"",
")",
".",
"value",
"centre2",
"=",
"beam_centre_alg",
".",
"getProperty",
"(",
"\"Centre2\"",
")",
".",
"value",
"return",
"{",
"\"pos1\"",
":",
"centre1",
",",
"\"pos2\"",
":",
"centre2",
"}"
] |
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/centre_finder_new.py#L17-L80
|
|
rodeofx/OpenWalter
|
6116fbe3f04f1146c854afbfbdbe944feaee647e
|
walter/common/walterWidgets/walterLayersView.py
|
python
|
LayersModel.executeAction
|
(self, action, index)
|
We are here because user pressed by one of the actions.
|
We are here because user pressed by one of the actions.
|
[
"We",
"are",
"here",
"because",
"user",
"pressed",
"by",
"one",
"of",
"the",
"actions",
"."
] |
def executeAction(self, action, index):
"""We are here because user pressed by one of the actions."""
pass
|
[
"def",
"executeAction",
"(",
"self",
",",
"action",
",",
"index",
")",
":",
"pass"
] |
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/walterLayersView.py#L86-L88
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_carbon/stc.py
|
python
|
StyledTextCtrl.GetStyleBits
|
(*args, **kwargs)
|
return _stc.StyledTextCtrl_GetStyleBits(*args, **kwargs)
|
GetStyleBits(self) -> int
Retrieve number of bits in style bytes used to hold the lexical state.
|
GetStyleBits(self) -> int
|
[
"GetStyleBits",
"(",
"self",
")",
"-",
">",
"int"
] |
def GetStyleBits(*args, **kwargs):
"""
GetStyleBits(self) -> int
Retrieve number of bits in style bytes used to hold the lexical state.
"""
return _stc.StyledTextCtrl_GetStyleBits(*args, **kwargs)
|
[
"def",
"GetStyleBits",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetStyleBits",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L2955-L2961
|
|
cyberbotics/webots
|
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
|
scripts/icon_studio/controllers/icon_creator/icon_creator.py
|
python
|
autocrop
|
(im)
|
Autocrop an image based on its upperleft pixel.
|
Autocrop an image based on its upperleft pixel.
|
[
"Autocrop",
"an",
"image",
"based",
"on",
"its",
"upperleft",
"pixel",
"."
] |
def autocrop(im):
"""Autocrop an image based on its upperleft pixel."""
# reference: https://stackoverflow.com/a/48605963/2210777
rgbImage = im.convert('RGB') # from RGBA, needed since Pillow 7.1.0
bg = Image.new(rgbImage.mode, rgbImage.size, rgbImage.getpixel((0, 0)))
diff = ImageChops.difference(rgbImage, bg)
diff = ImageChops.add(diff, diff, 2.0)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
assert False, "Impossible to crop image"
|
[
"def",
"autocrop",
"(",
"im",
")",
":",
"# reference: https://stackoverflow.com/a/48605963/2210777",
"rgbImage",
"=",
"im",
".",
"convert",
"(",
"'RGB'",
")",
"# from RGBA, needed since Pillow 7.1.0",
"bg",
"=",
"Image",
".",
"new",
"(",
"rgbImage",
".",
"mode",
",",
"rgbImage",
".",
"size",
",",
"rgbImage",
".",
"getpixel",
"(",
"(",
"0",
",",
"0",
")",
")",
")",
"diff",
"=",
"ImageChops",
".",
"difference",
"(",
"rgbImage",
",",
"bg",
")",
"diff",
"=",
"ImageChops",
".",
"add",
"(",
"diff",
",",
"diff",
",",
"2.0",
")",
"bbox",
"=",
"diff",
".",
"getbbox",
"(",
")",
"if",
"bbox",
":",
"return",
"im",
".",
"crop",
"(",
"bbox",
")",
"assert",
"False",
",",
"\"Impossible to crop image\""
] |
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/scripts/icon_studio/controllers/icon_creator/icon_creator.py#L65-L75
|
||
msracver/Deep-Image-Analogy
|
632b9287b42552e32dad64922967c8c9ec7fc4d3
|
scripts/cpp_lint.py
|
python
|
CheckEmptyBlockBody
|
(filename, clean_lines, linenum, error)
|
Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
|
Look for empty loop/conditional body with only a single semicolon.
|
[
"Look",
"for",
"empty",
"loop",
"/",
"conditional",
"body",
"with",
"only",
"a",
"single",
"semicolon",
"."
] |
def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
"""Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" blocks here, since an empty conditional block
# is likely an error.
line = clean_lines.elided[linenum]
matched = Match(r'\s*(for|while|if)\s*\(', line)
if matched:
# Find the end of the conditional expression
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
# Output warning if what follows the condition expression is a semicolon.
# No warning for all other cases, including whitespace or newline, since we
# have a separate check for semicolons preceded by whitespace.
if end_pos >= 0 and Match(r';', end_line[end_pos:]):
if matched.group(1) == 'if':
error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
'Empty conditional bodies should use {}')
else:
error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
'Empty loop bodies should use {} or continue')
|
[
"def",
"CheckEmptyBlockBody",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Search for loop keywords at the beginning of the line. Because only",
"# whitespaces are allowed before the keywords, this will also ignore most",
"# do-while-loops, since those lines should start with closing brace.",
"#",
"# We also check \"if\" blocks here, since an empty conditional block",
"# is likely an error.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"matched",
"=",
"Match",
"(",
"r'\\s*(for|while|if)\\s*\\('",
",",
"line",
")",
"if",
"matched",
":",
"# Find the end of the conditional expression",
"(",
"end_line",
",",
"end_linenum",
",",
"end_pos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"line",
".",
"find",
"(",
"'('",
")",
")",
"# Output warning if what follows the condition expression is a semicolon.",
"# No warning for all other cases, including whitespace or newline, since we",
"# have a separate check for semicolons preceded by whitespace.",
"if",
"end_pos",
">=",
"0",
"and",
"Match",
"(",
"r';'",
",",
"end_line",
"[",
"end_pos",
":",
"]",
")",
":",
"if",
"matched",
".",
"group",
"(",
"1",
")",
"==",
"'if'",
":",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_conditional_body'",
",",
"5",
",",
"'Empty conditional bodies should use {}'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_loop_body'",
",",
"5",
",",
"'Empty loop bodies should use {} or continue'",
")"
] |
https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/cpp_lint.py#L3243-L3275
|
||
BlzFans/wke
|
b0fa21158312e40c5fbd84682d643022b6c34a93
|
cygwin/lib/python2.6/json/encoder.py
|
python
|
encode_basestring
|
(s)
|
return '"' + ESCAPE.sub(replace, s) + '"'
|
Return a JSON representation of a Python string
|
Return a JSON representation of a Python string
|
[
"Return",
"a",
"JSON",
"representation",
"of",
"a",
"Python",
"string"
] |
def encode_basestring(s):
"""Return a JSON representation of a Python string
"""
def replace(match):
return ESCAPE_DCT[match.group(0)]
return '"' + ESCAPE.sub(replace, s) + '"'
|
[
"def",
"encode_basestring",
"(",
"s",
")",
":",
"def",
"replace",
"(",
"match",
")",
":",
"return",
"ESCAPE_DCT",
"[",
"match",
".",
"group",
"(",
"0",
")",
"]",
"return",
"'\"'",
"+",
"ESCAPE",
".",
"sub",
"(",
"replace",
",",
"s",
")",
"+",
"'\"'"
] |
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/json/encoder.py#L52-L58
|
|
krishauser/Klampt
|
972cc83ea5befac3f653c1ba20f80155768ad519
|
Python/python2_version/klampt/math/optimize.py
|
python
|
OptimizationProblemBuilder.setVarValues
|
(self,s)
|
Converts a state into bindings for the optimization variables in the current context.
|
Converts a state into bindings for the optimization variables in the current context.
|
[
"Converts",
"a",
"state",
"into",
"bindings",
"for",
"the",
"optimization",
"variables",
"in",
"the",
"current",
"context",
"."
] |
def setVarValues(self,s):
"""Converts a state into bindings for the optimization variables in the current context."""
for (v,var) in zip(s,self.optimizationVariables):
var.bind(v)
|
[
"def",
"setVarValues",
"(",
"self",
",",
"s",
")",
":",
"for",
"(",
"v",
",",
"var",
")",
"in",
"zip",
"(",
"s",
",",
"self",
".",
"optimizationVariables",
")",
":",
"var",
".",
"bind",
"(",
"v",
")"
] |
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/optimize.py#L874-L877
|
||
yyzybb537/libgo
|
4af17b7c67643c4d54aa354dcc77963ea07847d0
|
third_party/boost.context/tools/build/src/build/generators.py
|
python
|
Generator.convert_to_consumable_types
|
(self, project, name, prop_set, sources, only_one=False)
|
return (consumed, bypassed)
|
Attempts to convert 'source' to the types that this generator can
handle. The intention is to produce the set of targets can should be
used when generator is run.
only_one: convert 'source' to only one of source types
if there's more that one possibility, report an
error.
Returns a pair:
consumed: all targets that can be consumed.
bypassed: all targets that cannot be consumed.
|
Attempts to convert 'source' to the types that this generator can
handle. The intention is to produce the set of targets can should be
used when generator is run.
only_one: convert 'source' to only one of source types
if there's more that one possibility, report an
error.
|
[
"Attempts",
"to",
"convert",
"source",
"to",
"the",
"types",
"that",
"this",
"generator",
"can",
"handle",
".",
"The",
"intention",
"is",
"to",
"produce",
"the",
"set",
"of",
"targets",
"can",
"should",
"be",
"used",
"when",
"generator",
"is",
"run",
".",
"only_one",
":",
"convert",
"source",
"to",
"only",
"one",
"of",
"source",
"types",
"if",
"there",
"s",
"more",
"that",
"one",
"possibility",
"report",
"an",
"error",
"."
] |
def convert_to_consumable_types (self, project, name, prop_set, sources, only_one=False):
""" Attempts to convert 'source' to the types that this generator can
handle. The intention is to produce the set of targets can should be
used when generator is run.
only_one: convert 'source' to only one of source types
if there's more that one possibility, report an
error.
Returns a pair:
consumed: all targets that can be consumed.
bypassed: all targets that cannot be consumed.
"""
if __debug__:
from .targets import ProjectTarget
assert isinstance(name, basestring) or name is None
assert isinstance(project, ProjectTarget)
assert isinstance(prop_set, property_set.PropertySet)
assert is_iterable_typed(sources, virtual_target.VirtualTarget)
assert isinstance(only_one, bool)
consumed = []
bypassed = []
missing_types = []
if len (sources) > 1:
# Don't know how to handle several sources yet. Just try
# to pass the request to other generator
missing_types = self.source_types_
else:
(c, m) = self.consume_directly (sources [0])
consumed += c
missing_types += m
# No need to search for transformation if
# some source type has consumed source and
# no more source types are needed.
if only_one and consumed:
missing_types = []
#TODO: we should check that only one source type
#if create of 'only_one' is true.
# TODO: consider if consuned/bypassed separation should
# be done by 'construct_types'.
if missing_types:
transformed = construct_types (project, name, missing_types, prop_set, sources)
# Add targets of right type to 'consumed'. Add others to
# 'bypassed'. The 'generators.construct' rule has done
# its best to convert everything to the required type.
# There's no need to rerun it on targets of different types.
# NOTE: ignoring usage requirements
for t in transformed[1]:
if t.type() in missing_types:
consumed.append(t)
else:
bypassed.append(t)
consumed = unique(consumed)
bypassed = unique(bypassed)
# remove elements of 'bypassed' that are in 'consumed'
# Suppose the target type of current generator, X is produced from
# X_1 and X_2, which are produced from Y by one generator.
# When creating X_1 from Y, X_2 will be added to 'bypassed'
# Likewise, when creating X_2 from Y, X_1 will be added to 'bypassed'
# But they are also in 'consumed'. We have to remove them from
# bypassed, so that generators up the call stack don't try to convert
# them.
# In this particular case, X_1 instance in 'consumed' and X_1 instance
# in 'bypassed' will be the same: because they have the same source and
# action name, and 'virtual-target.register' won't allow two different
# instances. Therefore, it's OK to use 'set.difference'.
bypassed = set.difference(bypassed, consumed)
return (consumed, bypassed)
|
[
"def",
"convert_to_consumable_types",
"(",
"self",
",",
"project",
",",
"name",
",",
"prop_set",
",",
"sources",
",",
"only_one",
"=",
"False",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"targets",
"import",
"ProjectTarget",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"or",
"name",
"is",
"None",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"assert",
"isinstance",
"(",
"prop_set",
",",
"property_set",
".",
"PropertySet",
")",
"assert",
"is_iterable_typed",
"(",
"sources",
",",
"virtual_target",
".",
"VirtualTarget",
")",
"assert",
"isinstance",
"(",
"only_one",
",",
"bool",
")",
"consumed",
"=",
"[",
"]",
"bypassed",
"=",
"[",
"]",
"missing_types",
"=",
"[",
"]",
"if",
"len",
"(",
"sources",
")",
">",
"1",
":",
"# Don't know how to handle several sources yet. Just try",
"# to pass the request to other generator",
"missing_types",
"=",
"self",
".",
"source_types_",
"else",
":",
"(",
"c",
",",
"m",
")",
"=",
"self",
".",
"consume_directly",
"(",
"sources",
"[",
"0",
"]",
")",
"consumed",
"+=",
"c",
"missing_types",
"+=",
"m",
"# No need to search for transformation if",
"# some source type has consumed source and",
"# no more source types are needed.",
"if",
"only_one",
"and",
"consumed",
":",
"missing_types",
"=",
"[",
"]",
"#TODO: we should check that only one source type",
"#if create of 'only_one' is true.",
"# TODO: consider if consuned/bypassed separation should",
"# be done by 'construct_types'.",
"if",
"missing_types",
":",
"transformed",
"=",
"construct_types",
"(",
"project",
",",
"name",
",",
"missing_types",
",",
"prop_set",
",",
"sources",
")",
"# Add targets of right type to 'consumed'. Add others to",
"# 'bypassed'. The 'generators.construct' rule has done",
"# its best to convert everything to the required type.",
"# There's no need to rerun it on targets of different types.",
"# NOTE: ignoring usage requirements",
"for",
"t",
"in",
"transformed",
"[",
"1",
"]",
":",
"if",
"t",
".",
"type",
"(",
")",
"in",
"missing_types",
":",
"consumed",
".",
"append",
"(",
"t",
")",
"else",
":",
"bypassed",
".",
"append",
"(",
"t",
")",
"consumed",
"=",
"unique",
"(",
"consumed",
")",
"bypassed",
"=",
"unique",
"(",
"bypassed",
")",
"# remove elements of 'bypassed' that are in 'consumed'",
"# Suppose the target type of current generator, X is produced from",
"# X_1 and X_2, which are produced from Y by one generator.",
"# When creating X_1 from Y, X_2 will be added to 'bypassed'",
"# Likewise, when creating X_2 from Y, X_1 will be added to 'bypassed'",
"# But they are also in 'consumed'. We have to remove them from",
"# bypassed, so that generators up the call stack don't try to convert",
"# them.",
"# In this particular case, X_1 instance in 'consumed' and X_1 instance",
"# in 'bypassed' will be the same: because they have the same source and",
"# action name, and 'virtual-target.register' won't allow two different",
"# instances. Therefore, it's OK to use 'set.difference'.",
"bypassed",
"=",
"set",
".",
"difference",
"(",
"bypassed",
",",
"consumed",
")",
"return",
"(",
"consumed",
",",
"bypassed",
")"
] |
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/generators.py#L520-L600
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/msw/_gdi.py
|
python
|
PixelDataBase.GetWidth
|
(*args, **kwargs)
|
return _gdi_.PixelDataBase_GetWidth(*args, **kwargs)
|
GetWidth(self) -> int
|
GetWidth(self) -> int
|
[
"GetWidth",
"(",
"self",
")",
"-",
">",
"int"
] |
def GetWidth(*args, **kwargs):
"""GetWidth(self) -> int"""
return _gdi_.PixelDataBase_GetWidth(*args, **kwargs)
|
[
"def",
"GetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"PixelDataBase_GetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1019-L1021
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/_gdi.py
|
python
|
DC.DrawRoundedRectangleRect
|
(*args, **kwargs)
|
return _gdi_.DC_DrawRoundedRectangleRect(*args, **kwargs)
|
DrawRoundedRectangleRect(self, Rect r, double radius)
Draws a rectangle with the given top left corner, and with the given
size. The corners are quarter-circles using the given radius. The
current pen is used for the outline and the current brush for filling
the shape.
If radius is positive, the value is assumed to be the radius of the
rounded corner. If radius is negative, the absolute value is assumed
to be the proportion of the smallest dimension of the rectangle. This
means that the corner can be a sensible size relative to the size of
the rectangle, and also avoids the strange effects X produces when the
corners are too big for the rectangle.
|
DrawRoundedRectangleRect(self, Rect r, double radius)
|
[
"DrawRoundedRectangleRect",
"(",
"self",
"Rect",
"r",
"double",
"radius",
")"
] |
def DrawRoundedRectangleRect(*args, **kwargs):
"""
DrawRoundedRectangleRect(self, Rect r, double radius)
Draws a rectangle with the given top left corner, and with the given
size. The corners are quarter-circles using the given radius. The
current pen is used for the outline and the current brush for filling
the shape.
If radius is positive, the value is assumed to be the radius of the
rounded corner. If radius is negative, the absolute value is assumed
to be the proportion of the smallest dimension of the rectangle. This
means that the corner can be a sensible size relative to the size of
the rectangle, and also avoids the strange effects X produces when the
corners are too big for the rectangle.
"""
return _gdi_.DC_DrawRoundedRectangleRect(*args, **kwargs)
|
[
"def",
"DrawRoundedRectangleRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_DrawRoundedRectangleRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L3594-L3610
|
|
baoboa/pyqt5
|
11d5f43bc6f213d9d60272f3954a0048569cfc7c
|
examples/mainwindows/separations.py
|
python
|
Viewer.saveImage
|
(self)
|
Provides a dialog window to allow the user to save the image file.
|
Provides a dialog window to allow the user to save the image file.
|
[
"Provides",
"a",
"dialog",
"window",
"to",
"allow",
"the",
"user",
"to",
"save",
"the",
"image",
"file",
"."
] |
def saveImage(self):
""" Provides a dialog window to allow the user to save the image file.
"""
imageFile, _ = QFileDialog.getSaveFileName(self,
"Choose a filename to save the image", "", "Images (*.png)")
info = QFileInfo(imageFile)
if info.baseName() != '':
newImageFile = QFileInfo(info.absoluteDir(),
info.baseName() + '.png').absoluteFilePath()
if not self.finalWidget.pixmap().save(newImageFile, 'PNG'):
QMessageBox.warning(self, "Cannot save file",
"The file could not be saved.",
QMessageBox.Cancel, QMessageBox.NoButton,
QMessageBox.NoButton)
else:
QMessageBox.warning(self, "Cannot save file",
"Please enter a valid filename.", QMessageBox.Cancel,
QMessageBox.NoButton, QMessageBox.NoButton)
|
[
"def",
"saveImage",
"(",
"self",
")",
":",
"imageFile",
",",
"_",
"=",
"QFileDialog",
".",
"getSaveFileName",
"(",
"self",
",",
"\"Choose a filename to save the image\"",
",",
"\"\"",
",",
"\"Images (*.png)\"",
")",
"info",
"=",
"QFileInfo",
"(",
"imageFile",
")",
"if",
"info",
".",
"baseName",
"(",
")",
"!=",
"''",
":",
"newImageFile",
"=",
"QFileInfo",
"(",
"info",
".",
"absoluteDir",
"(",
")",
",",
"info",
".",
"baseName",
"(",
")",
"+",
"'.png'",
")",
".",
"absoluteFilePath",
"(",
")",
"if",
"not",
"self",
".",
"finalWidget",
".",
"pixmap",
"(",
")",
".",
"save",
"(",
"newImageFile",
",",
"'PNG'",
")",
":",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"\"Cannot save file\"",
",",
"\"The file could not be saved.\"",
",",
"QMessageBox",
".",
"Cancel",
",",
"QMessageBox",
".",
"NoButton",
",",
"QMessageBox",
".",
"NoButton",
")",
"else",
":",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"\"Cannot save file\"",
",",
"\"Please enter a valid filename.\"",
",",
"QMessageBox",
".",
"Cancel",
",",
"QMessageBox",
".",
"NoButton",
",",
"QMessageBox",
".",
"NoButton",
")"
] |
https://github.com/baoboa/pyqt5/blob/11d5f43bc6f213d9d60272f3954a0048569cfc7c/examples/mainwindows/separations.py#L456-L476
|
||
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/dataview.py
|
python
|
DataViewCtrl.PrependToggleColumn
|
(*args, **kwargs)
|
return _dataview.DataViewCtrl_PrependToggleColumn(*args, **kwargs)
|
PrependToggleColumn(self, PyObject label_or_bitmap, unsigned int model_column,
int mode=DATAVIEW_CELL_INERT, int width=DVC_TOGGLE_DEFAULT_WIDTH,
int align=ALIGN_CENTER,
int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
|
PrependToggleColumn(self, PyObject label_or_bitmap, unsigned int model_column,
int mode=DATAVIEW_CELL_INERT, int width=DVC_TOGGLE_DEFAULT_WIDTH,
int align=ALIGN_CENTER,
int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
|
[
"PrependToggleColumn",
"(",
"self",
"PyObject",
"label_or_bitmap",
"unsigned",
"int",
"model_column",
"int",
"mode",
"=",
"DATAVIEW_CELL_INERT",
"int",
"width",
"=",
"DVC_TOGGLE_DEFAULT_WIDTH",
"int",
"align",
"=",
"ALIGN_CENTER",
"int",
"flags",
"=",
"DATAVIEW_COL_RESIZABLE",
")",
"-",
">",
"DataViewColumn"
] |
def PrependToggleColumn(*args, **kwargs):
"""
PrependToggleColumn(self, PyObject label_or_bitmap, unsigned int model_column,
int mode=DATAVIEW_CELL_INERT, int width=DVC_TOGGLE_DEFAULT_WIDTH,
int align=ALIGN_CENTER,
int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
"""
return _dataview.DataViewCtrl_PrependToggleColumn(*args, **kwargs)
|
[
"def",
"PrependToggleColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewCtrl_PrependToggleColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L1606-L1613
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python3/src/Lib/email/_header_value_parser.py
|
python
|
_validate_xtext
|
(xtext)
|
If input token contains ASCII non-printables, register a defect.
|
If input token contains ASCII non-printables, register a defect.
|
[
"If",
"input",
"token",
"contains",
"ASCII",
"non",
"-",
"printables",
"register",
"a",
"defect",
"."
] |
def _validate_xtext(xtext):
"""If input token contains ASCII non-printables, register a defect."""
non_printables = _non_printable_finder(xtext)
if non_printables:
xtext.defects.append(errors.NonPrintableDefect(non_printables))
if utils._has_surrogates(xtext):
xtext.defects.append(errors.UndecodableBytesDefect(
"Non-ASCII characters found in header token"))
|
[
"def",
"_validate_xtext",
"(",
"xtext",
")",
":",
"non_printables",
"=",
"_non_printable_finder",
"(",
"xtext",
")",
"if",
"non_printables",
":",
"xtext",
".",
"defects",
".",
"append",
"(",
"errors",
".",
"NonPrintableDefect",
"(",
"non_printables",
")",
")",
"if",
"utils",
".",
"_has_surrogates",
"(",
"xtext",
")",
":",
"xtext",
".",
"defects",
".",
"append",
"(",
"errors",
".",
"UndecodableBytesDefect",
"(",
"\"Non-ASCII characters found in header token\"",
")",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/_header_value_parser.py#L986-L994
|
||
aws/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py
|
python
|
get_module_uses
|
(ctx, target, parent_spec)
|
return _get_module_use(ctx, target)
|
Get all the module uses for a particular module (from the generated module def file)
:param ctx: Context
:param target: Name of the module
:param parent_spec: Name of the parent spec
:return: Set of all modules that this module is dependent on
|
Get all the module uses for a particular module (from the generated module def file)
:param ctx: Context
:param target: Name of the module
:param parent_spec: Name of the parent spec
:return: Set of all modules that this module is dependent on
|
[
"Get",
"all",
"the",
"module",
"uses",
"for",
"a",
"particular",
"module",
"(",
"from",
"the",
"generated",
"module",
"def",
"file",
")",
":",
"param",
"ctx",
":",
"Context",
":",
"param",
"target",
":",
"Name",
"of",
"the",
"module",
":",
"param",
"parent_spec",
":",
"Name",
"of",
"the",
"parent",
"spec",
":",
"return",
":",
"Set",
"of",
"all",
"modules",
"that",
"this",
"module",
"is",
"dependent",
"on"
] |
def get_module_uses(ctx, target, parent_spec):
"""
Get all the module uses for a particular module (from the generated module def file)
:param ctx: Context
:param target: Name of the module
:param parent_spec: Name of the parent spec
:return: Set of all modules that this module is dependent on
"""
visited_modules = set()
def _get_module_use(ctx, target_name):
"""
Determine all of the uses for a module recursivel
:param ctx: Context
:param target_name: Name of the module
:return: Set of all modules that this module is dependent on
"""
module_def_map = _get_module_def(ctx, target_name)
declared_uses = module_def_map.get('uses')[:]
visited_modules.add(target_name)
module_uses = []
for module_use in declared_uses:
if module_use not in module_uses:
module_uses.append(module_use)
# If the module use is non-lumberyard module, it will not be marked as a valid module because it does not
# have a module_def file. Skip these modules to avoid the warning
if module_use in getattr(ctx, 'non_lumberyard_module', {}):
continue
if ctx.is_third_party_uselib_configured(module_use):
# This is a third party uselib, there are no dependencies, so skip
continue
elif module_use in visited_modules:
# This module has been visited, skip
continue
elif not ctx.is_valid_module(module_use):
# This use dependency is an invalid module. Warn and continue
# Special case for 'RAD_TELEMETRY'. This module is only available when both the Gem is enabled and the machine has a valid
# RAD Telemetry license, otherwise references to it should be #ifdef'd out of the code. So if the invalid module is
# RAD Telemetry, we can suppress the warning
if module_use != 'RAD_TELEMETRY':
ctx.warn_once("Module use dependency '{}' for target '{}' refers to an invalid module".format(module_use, target_name))
continue
elif module_use == target:
raise Errors.WafError("Cyclic use-dependency discovered for target '{}'".format(target_name))
else:
child_uses = _get_module_use(ctx, module_use)
for child_use in child_uses:
module_uses.append(child_use)
return module_uses
return _get_module_use(ctx, target)
|
[
"def",
"get_module_uses",
"(",
"ctx",
",",
"target",
",",
"parent_spec",
")",
":",
"visited_modules",
"=",
"set",
"(",
")",
"def",
"_get_module_use",
"(",
"ctx",
",",
"target_name",
")",
":",
"\"\"\"\n Determine all of the uses for a module recursivel\n :param ctx: Context\n :param target_name: Name of the module\n :return: Set of all modules that this module is dependent on\n \"\"\"",
"module_def_map",
"=",
"_get_module_def",
"(",
"ctx",
",",
"target_name",
")",
"declared_uses",
"=",
"module_def_map",
".",
"get",
"(",
"'uses'",
")",
"[",
":",
"]",
"visited_modules",
".",
"add",
"(",
"target_name",
")",
"module_uses",
"=",
"[",
"]",
"for",
"module_use",
"in",
"declared_uses",
":",
"if",
"module_use",
"not",
"in",
"module_uses",
":",
"module_uses",
".",
"append",
"(",
"module_use",
")",
"# If the module use is non-lumberyard module, it will not be marked as a valid module because it does not",
"# have a module_def file. Skip these modules to avoid the warning",
"if",
"module_use",
"in",
"getattr",
"(",
"ctx",
",",
"'non_lumberyard_module'",
",",
"{",
"}",
")",
":",
"continue",
"if",
"ctx",
".",
"is_third_party_uselib_configured",
"(",
"module_use",
")",
":",
"# This is a third party uselib, there are no dependencies, so skip",
"continue",
"elif",
"module_use",
"in",
"visited_modules",
":",
"# This module has been visited, skip",
"continue",
"elif",
"not",
"ctx",
".",
"is_valid_module",
"(",
"module_use",
")",
":",
"# This use dependency is an invalid module. Warn and continue",
"# Special case for 'RAD_TELEMETRY'. This module is only available when both the Gem is enabled and the machine has a valid",
"# RAD Telemetry license, otherwise references to it should be #ifdef'd out of the code. So if the invalid module is",
"# RAD Telemetry, we can suppress the warning",
"if",
"module_use",
"!=",
"'RAD_TELEMETRY'",
":",
"ctx",
".",
"warn_once",
"(",
"\"Module use dependency '{}' for target '{}' refers to an invalid module\"",
".",
"format",
"(",
"module_use",
",",
"target_name",
")",
")",
"continue",
"elif",
"module_use",
"==",
"target",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"\"Cyclic use-dependency discovered for target '{}'\"",
".",
"format",
"(",
"target_name",
")",
")",
"else",
":",
"child_uses",
"=",
"_get_module_use",
"(",
"ctx",
",",
"module_use",
")",
"for",
"child_use",
"in",
"child_uses",
":",
"module_uses",
".",
"append",
"(",
"child_use",
")",
"return",
"module_uses",
"return",
"_get_module_use",
"(",
"ctx",
",",
"target",
")"
] |
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py#L1241-L1296
|
|
trailofbits/llvm-sanitizer-tutorial
|
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
|
llvm/utils/lit/lit/util.py
|
python
|
killProcessAndChildren
|
(pid)
|
This function kills a process with ``pid`` and all its running children
(recursively). It is currently implemented using the psutil module which
provides a simple platform neutral implementation.
TODO: Reimplement this without using psutil so we can remove
our dependency on it.
|
This function kills a process with ``pid`` and all its running children
(recursively). It is currently implemented using the psutil module which
provides a simple platform neutral implementation.
|
[
"This",
"function",
"kills",
"a",
"process",
"with",
"pid",
"and",
"all",
"its",
"running",
"children",
"(",
"recursively",
")",
".",
"It",
"is",
"currently",
"implemented",
"using",
"the",
"psutil",
"module",
"which",
"provides",
"a",
"simple",
"platform",
"neutral",
"implementation",
"."
] |
def killProcessAndChildren(pid):
"""This function kills a process with ``pid`` and all its running children
(recursively). It is currently implemented using the psutil module which
provides a simple platform neutral implementation.
TODO: Reimplement this without using psutil so we can remove
our dependency on it.
"""
import psutil
try:
psutilProc = psutil.Process(pid)
# Handle the different psutil API versions
try:
# psutil >= 2.x
children_iterator = psutilProc.children(recursive=True)
except AttributeError:
# psutil 1.x
children_iterator = psutilProc.get_children(recursive=True)
for child in children_iterator:
try:
child.kill()
except psutil.NoSuchProcess:
pass
psutilProc.kill()
except psutil.NoSuchProcess:
pass
|
[
"def",
"killProcessAndChildren",
"(",
"pid",
")",
":",
"import",
"psutil",
"try",
":",
"psutilProc",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"# Handle the different psutil API versions",
"try",
":",
"# psutil >= 2.x",
"children_iterator",
"=",
"psutilProc",
".",
"children",
"(",
"recursive",
"=",
"True",
")",
"except",
"AttributeError",
":",
"# psutil 1.x",
"children_iterator",
"=",
"psutilProc",
".",
"get_children",
"(",
"recursive",
"=",
"True",
")",
"for",
"child",
"in",
"children_iterator",
":",
"try",
":",
"child",
".",
"kill",
"(",
")",
"except",
"psutil",
".",
"NoSuchProcess",
":",
"pass",
"psutilProc",
".",
"kill",
"(",
")",
"except",
"psutil",
".",
"NoSuchProcess",
":",
"pass"
] |
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/utils/lit/lit/util.py#L400-L426
|
||
miyosuda/TensorFlowAndroidDemo
|
35903e0221aa5f109ea2dbef27f20b52e317f42d
|
jni-build/jni/include/tensorflow/python/ops/nn_ops.py
|
python
|
_MaxPoolWithArgMaxShape
|
(op)
|
return common_shapes.max_pool_shape(op) * 2
|
Shape function for MaxPoolWithArgmax op.
|
Shape function for MaxPoolWithArgmax op.
|
[
"Shape",
"function",
"for",
"MaxPoolWithArgmax",
"op",
"."
] |
def _MaxPoolWithArgMaxShape(op):
"""Shape function for MaxPoolWithArgmax op."""
return common_shapes.max_pool_shape(op) * 2
|
[
"def",
"_MaxPoolWithArgMaxShape",
"(",
"op",
")",
":",
"return",
"common_shapes",
".",
"max_pool_shape",
"(",
"op",
")",
"*",
"2"
] |
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/nn_ops.py#L776-L778
|
|
MythTV/mythtv
|
d282a209cb8be85d036f85a62a8ec971b67d45f4
|
mythtv/programs/scripts/internetcontent/nv_python_libs/mtv/mtv_api.py
|
python
|
Videos.displayTreeView
|
(self)
|
return [[self.channel, dictionaries]]
|
Gather the MTV Genres/Artists/...etc then get a max page of videos meta data in each of them
return array of directories and their video metadata
|
Gather the MTV Genres/Artists/...etc then get a max page of videos meta data in each of them
return array of directories and their video metadata
|
[
"Gather",
"the",
"MTV",
"Genres",
"/",
"Artists",
"/",
"...",
"etc",
"then",
"get",
"a",
"max",
"page",
"of",
"videos",
"meta",
"data",
"in",
"each",
"of",
"them",
"return",
"array",
"of",
"directories",
"and",
"their",
"video",
"metadata"
] |
def displayTreeView(self):
'''Gather the MTV Genres/Artists/...etc then get a max page of videos meta data in each of them
return array of directories and their video metadata
'''
# Channel details and search results
self.channel = {'channel_title': 'MTV', 'channel_link': 'http://www.mtv.com', 'channel_description': "Visit MTV (Music Television) for TV shows, music videos, celebrity photos, news.", 'channel_numresults': 0, 'channel_returned': 1, 'channel_startindex': 0}
if self.config['debug_enabled']:
print(self.config['urls'])
print()
# Set the default videos per page limit for all feeds/categories/... etc
for key in list(self.tree_customize.keys()):
if '__default__' in list(self.tree_customize[key].keys()):
if 'max-results' in list(self.tree_customize[key]['__default__'].keys()):
self.tree_customize[key]['__default__']['max-results'] = str(self.page_limit)
# Get videos within each category
dictionaries = []
# Process the various video feeds/categories/... etc
for key in self.tree_order:
self.tree_key = key
dictionaries = self.getVideos(self.tree_org[key], dictionaries)
return [[self.channel, dictionaries]]
|
[
"def",
"displayTreeView",
"(",
"self",
")",
":",
"# Channel details and search results",
"self",
".",
"channel",
"=",
"{",
"'channel_title'",
":",
"'MTV'",
",",
"'channel_link'",
":",
"'http://www.mtv.com'",
",",
"'channel_description'",
":",
"\"Visit MTV (Music Television) for TV shows, music videos, celebrity photos, news.\"",
",",
"'channel_numresults'",
":",
"0",
",",
"'channel_returned'",
":",
"1",
",",
"'channel_startindex'",
":",
"0",
"}",
"if",
"self",
".",
"config",
"[",
"'debug_enabled'",
"]",
":",
"print",
"(",
"self",
".",
"config",
"[",
"'urls'",
"]",
")",
"print",
"(",
")",
"# Set the default videos per page limit for all feeds/categories/... etc",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"tree_customize",
".",
"keys",
"(",
")",
")",
":",
"if",
"'__default__'",
"in",
"list",
"(",
"self",
".",
"tree_customize",
"[",
"key",
"]",
".",
"keys",
"(",
")",
")",
":",
"if",
"'max-results'",
"in",
"list",
"(",
"self",
".",
"tree_customize",
"[",
"key",
"]",
"[",
"'__default__'",
"]",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"tree_customize",
"[",
"key",
"]",
"[",
"'__default__'",
"]",
"[",
"'max-results'",
"]",
"=",
"str",
"(",
"self",
".",
"page_limit",
")",
"# Get videos within each category",
"dictionaries",
"=",
"[",
"]",
"# Process the various video feeds/categories/... etc",
"for",
"key",
"in",
"self",
".",
"tree_order",
":",
"self",
".",
"tree_key",
"=",
"key",
"dictionaries",
"=",
"self",
".",
"getVideos",
"(",
"self",
".",
"tree_org",
"[",
"key",
"]",
",",
"dictionaries",
")",
"return",
"[",
"[",
"self",
".",
"channel",
",",
"dictionaries",
"]",
"]"
] |
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/mtv/mtv_api.py#L568-L593
|
|
fenderglass/Flye
|
2013acc650356cc934a2a9b82eb90af260c8b52b
|
flye/polishing/bubbles.py
|
python
|
_compute_profile
|
(alignment, ref_sequence)
|
return profile, aln_errors
|
Computes alignment profile
|
Computes alignment profile
|
[
"Computes",
"alignment",
"profile"
] |
def _compute_profile(alignment, ref_sequence):
"""
Computes alignment profile
"""
if len(alignment) == 0:
raise Exception("No alignmemnts!")
genome_len = alignment[0].trg_len
#max_aln_err = cfg.vals["err_modes"][platform]["max_aln_error"]
min_aln_len = cfg.vals["min_polish_aln_len"]
aln_errors = []
#filtered = 0
profile = [ProfileInfo() for _ in range(genome_len)]
for i in range(genome_len):
profile[i].nucl = ref_sequence[i]
for aln in alignment:
#if aln.err_rate > max_aln_err or len(aln.qry_seq) < min_aln_len:
if len(aln.qry_seq) < min_aln_len:
#filtered += 1
continue
aln_errors.append(aln.err_rate)
qry_seq = shift_gaps(aln.trg_seq, aln.qry_seq)
trg_seq = shift_gaps(qry_seq, aln.trg_seq)
trg_pos = aln.trg_start
for trg_nuc, qry_nuc in zip(trg_seq, qry_seq):
if trg_nuc == "-":
trg_pos -= 1
#if trg_pos >= genome_len:
# trg_pos -= genome_len
prof_elem = profile[trg_pos]
if trg_nuc == "-":
prof_elem.insertions[aln.qry_id] += qry_nuc
#prof_elem.num_inserts += 1
else:
#prof_elem.nucl = trg_nuc
prof_elem.coverage += 1
if qry_nuc == "-":
prof_elem.num_deletions += 1
elif trg_nuc != qry_nuc:
prof_elem.num_missmatch += 1
trg_pos += 1
for i in range(genome_len):
for ins_read, ins_str in profile[i].insertions.items():
profile[i].propagated_ins += 1
span = len(ins_str)
for j in range(max(0, i - span), i):
profile[j].propagated_ins += 1
for j in range(i + 1, min(i + span + 1, genome_len)):
profile[j].propagated_ins += 1
#logger.debug("Filtered: {0} out of {1}".format(filtered, len(alignment)))
return profile, aln_errors
|
[
"def",
"_compute_profile",
"(",
"alignment",
",",
"ref_sequence",
")",
":",
"if",
"len",
"(",
"alignment",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"No alignmemnts!\"",
")",
"genome_len",
"=",
"alignment",
"[",
"0",
"]",
".",
"trg_len",
"#max_aln_err = cfg.vals[\"err_modes\"][platform][\"max_aln_error\"]",
"min_aln_len",
"=",
"cfg",
".",
"vals",
"[",
"\"min_polish_aln_len\"",
"]",
"aln_errors",
"=",
"[",
"]",
"#filtered = 0",
"profile",
"=",
"[",
"ProfileInfo",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"genome_len",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"genome_len",
")",
":",
"profile",
"[",
"i",
"]",
".",
"nucl",
"=",
"ref_sequence",
"[",
"i",
"]",
"for",
"aln",
"in",
"alignment",
":",
"#if aln.err_rate > max_aln_err or len(aln.qry_seq) < min_aln_len:",
"if",
"len",
"(",
"aln",
".",
"qry_seq",
")",
"<",
"min_aln_len",
":",
"#filtered += 1",
"continue",
"aln_errors",
".",
"append",
"(",
"aln",
".",
"err_rate",
")",
"qry_seq",
"=",
"shift_gaps",
"(",
"aln",
".",
"trg_seq",
",",
"aln",
".",
"qry_seq",
")",
"trg_seq",
"=",
"shift_gaps",
"(",
"qry_seq",
",",
"aln",
".",
"trg_seq",
")",
"trg_pos",
"=",
"aln",
".",
"trg_start",
"for",
"trg_nuc",
",",
"qry_nuc",
"in",
"zip",
"(",
"trg_seq",
",",
"qry_seq",
")",
":",
"if",
"trg_nuc",
"==",
"\"-\"",
":",
"trg_pos",
"-=",
"1",
"#if trg_pos >= genome_len:",
"# trg_pos -= genome_len",
"prof_elem",
"=",
"profile",
"[",
"trg_pos",
"]",
"if",
"trg_nuc",
"==",
"\"-\"",
":",
"prof_elem",
".",
"insertions",
"[",
"aln",
".",
"qry_id",
"]",
"+=",
"qry_nuc",
"#prof_elem.num_inserts += 1",
"else",
":",
"#prof_elem.nucl = trg_nuc",
"prof_elem",
".",
"coverage",
"+=",
"1",
"if",
"qry_nuc",
"==",
"\"-\"",
":",
"prof_elem",
".",
"num_deletions",
"+=",
"1",
"elif",
"trg_nuc",
"!=",
"qry_nuc",
":",
"prof_elem",
".",
"num_missmatch",
"+=",
"1",
"trg_pos",
"+=",
"1",
"for",
"i",
"in",
"range",
"(",
"genome_len",
")",
":",
"for",
"ins_read",
",",
"ins_str",
"in",
"profile",
"[",
"i",
"]",
".",
"insertions",
".",
"items",
"(",
")",
":",
"profile",
"[",
"i",
"]",
".",
"propagated_ins",
"+=",
"1",
"span",
"=",
"len",
"(",
"ins_str",
")",
"for",
"j",
"in",
"range",
"(",
"max",
"(",
"0",
",",
"i",
"-",
"span",
")",
",",
"i",
")",
":",
"profile",
"[",
"j",
"]",
".",
"propagated_ins",
"+=",
"1",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"min",
"(",
"i",
"+",
"span",
"+",
"1",
",",
"genome_len",
")",
")",
":",
"profile",
"[",
"j",
"]",
".",
"propagated_ins",
"+=",
"1",
"#logger.debug(\"Filtered: {0} out of {1}\".format(filtered, len(alignment)))",
"return",
"profile",
",",
"aln_errors"
] |
https://github.com/fenderglass/Flye/blob/2013acc650356cc934a2a9b82eb90af260c8b52b/flye/polishing/bubbles.py#L320-L381
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/_gdi.py
|
python
|
FontMapper.GetAltForEncoding
|
(*args, **kwargs)
|
return _gdi_.FontMapper_GetAltForEncoding(*args, **kwargs)
|
GetAltForEncoding(self, int encoding, String facename=EmptyString, bool interactive=True) -> PyObject
|
GetAltForEncoding(self, int encoding, String facename=EmptyString, bool interactive=True) -> PyObject
|
[
"GetAltForEncoding",
"(",
"self",
"int",
"encoding",
"String",
"facename",
"=",
"EmptyString",
"bool",
"interactive",
"=",
"True",
")",
"-",
">",
"PyObject"
] |
def GetAltForEncoding(*args, **kwargs):
"""GetAltForEncoding(self, int encoding, String facename=EmptyString, bool interactive=True) -> PyObject"""
return _gdi_.FontMapper_GetAltForEncoding(*args, **kwargs)
|
[
"def",
"GetAltForEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"FontMapper_GetAltForEncoding",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L2058-L2060
|
|
FreeCAD/FreeCAD
|
ba42231b9c6889b89e064d6d563448ed81e376ec
|
src/Mod/Draft/draftguitools/gui_subelements.py
|
python
|
SubelementHighlight.get_selection
|
(self)
|
Get the selection.
|
Get the selection.
|
[
"Get",
"the",
"selection",
"."
] |
def get_selection(self):
"""Get the selection."""
if not Gui.Selection.getSelection() and self.ui:
_msg(translate("draft", "Select an object to edit"))
self.call = self.view.addEventCallback("SoEvent",
gui_tool_utils.selectObject)
else:
self.proceed()
|
[
"def",
"get_selection",
"(",
"self",
")",
":",
"if",
"not",
"Gui",
".",
"Selection",
".",
"getSelection",
"(",
")",
"and",
"self",
".",
"ui",
":",
"_msg",
"(",
"translate",
"(",
"\"draft\"",
",",
"\"Select an object to edit\"",
")",
")",
"self",
".",
"call",
"=",
"self",
".",
"view",
".",
"addEventCallback",
"(",
"\"SoEvent\"",
",",
"gui_tool_utils",
".",
"selectObject",
")",
"else",
":",
"self",
".",
"proceed",
"(",
")"
] |
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_subelements.py#L105-L112
|
||
apiaryio/drafter
|
4634ebd07f6c6f257cc656598ccd535492fdfb55
|
tools/gyp/pylib/gyp/generator/make.py
|
python
|
MakefileWriter.WriteMakeRule
|
(self, outputs, inputs, actions=None, comment=None,
order_only=False, force=False, phony=False, command=None)
|
Write a Makefile rule, with some extra tricks.
outputs: a list of outputs for the rule (note: this is not directly
supported by make; see comments below)
inputs: a list of inputs for the rule
actions: a list of shell commands to run for the rule
comment: a comment to put in the Makefile above the rule (also useful
for making this Python script's code self-documenting)
order_only: if true, makes the dependency order-only
force: if true, include FORCE_DO_CMD as an order-only dep
phony: if true, the rule does not actually generate the named output, the
output is just a name to run the rule
command: (optional) command name to generate unambiguous labels
|
Write a Makefile rule, with some extra tricks.
|
[
"Write",
"a",
"Makefile",
"rule",
"with",
"some",
"extra",
"tricks",
"."
] |
def WriteMakeRule(self, outputs, inputs, actions=None, comment=None,
order_only=False, force=False, phony=False, command=None):
"""Write a Makefile rule, with some extra tricks.
outputs: a list of outputs for the rule (note: this is not directly
supported by make; see comments below)
inputs: a list of inputs for the rule
actions: a list of shell commands to run for the rule
comment: a comment to put in the Makefile above the rule (also useful
for making this Python script's code self-documenting)
order_only: if true, makes the dependency order-only
force: if true, include FORCE_DO_CMD as an order-only dep
phony: if true, the rule does not actually generate the named output, the
output is just a name to run the rule
command: (optional) command name to generate unambiguous labels
"""
outputs = map(QuoteSpaces, outputs)
inputs = map(QuoteSpaces, inputs)
if comment:
self.WriteLn('# ' + comment)
if phony:
self.WriteLn('.PHONY: ' + ' '.join(outputs))
if actions:
self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0])
force_append = ' FORCE_DO_CMD' if force else ''
if order_only:
# Order only rule: Just write a simple rule.
# TODO(evanm): just make order_only a list of deps instead of this hack.
self.WriteLn('%s: | %s%s' %
(' '.join(outputs), ' '.join(inputs), force_append))
elif len(outputs) == 1:
# Regular rule, one output: Just write a simple rule.
self.WriteLn('%s: %s%s' % (outputs[0], ' '.join(inputs), force_append))
else:
# Regular rule, more than one output: Multiple outputs are tricky in
# make. We will write three rules:
# - All outputs depend on an intermediate file.
# - Make .INTERMEDIATE depend on the intermediate.
# - The intermediate file depends on the inputs and executes the
# actual command.
# - The intermediate recipe will 'touch' the intermediate file.
# - The multi-output rule will have an do-nothing recipe.
intermediate = "%s.intermediate" % (command if command else self.target)
self.WriteLn('%s: %s' % (' '.join(outputs), intermediate))
self.WriteLn('\t%s' % '@:');
self.WriteLn('%s: %s' % ('.INTERMEDIATE', intermediate))
self.WriteLn('%s: %s%s' %
(intermediate, ' '.join(inputs), force_append))
actions.insert(0, '$(call do_cmd,touch)')
if actions:
for action in actions:
self.WriteLn('\t%s' % action)
self.WriteLn()
|
[
"def",
"WriteMakeRule",
"(",
"self",
",",
"outputs",
",",
"inputs",
",",
"actions",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"order_only",
"=",
"False",
",",
"force",
"=",
"False",
",",
"phony",
"=",
"False",
",",
"command",
"=",
"None",
")",
":",
"outputs",
"=",
"map",
"(",
"QuoteSpaces",
",",
"outputs",
")",
"inputs",
"=",
"map",
"(",
"QuoteSpaces",
",",
"inputs",
")",
"if",
"comment",
":",
"self",
".",
"WriteLn",
"(",
"'# '",
"+",
"comment",
")",
"if",
"phony",
":",
"self",
".",
"WriteLn",
"(",
"'.PHONY: '",
"+",
"' '",
".",
"join",
"(",
"outputs",
")",
")",
"if",
"actions",
":",
"self",
".",
"WriteLn",
"(",
"\"%s: TOOLSET := $(TOOLSET)\"",
"%",
"outputs",
"[",
"0",
"]",
")",
"force_append",
"=",
"' FORCE_DO_CMD'",
"if",
"force",
"else",
"''",
"if",
"order_only",
":",
"# Order only rule: Just write a simple rule.",
"# TODO(evanm): just make order_only a list of deps instead of this hack.",
"self",
".",
"WriteLn",
"(",
"'%s: | %s%s'",
"%",
"(",
"' '",
".",
"join",
"(",
"outputs",
")",
",",
"' '",
".",
"join",
"(",
"inputs",
")",
",",
"force_append",
")",
")",
"elif",
"len",
"(",
"outputs",
")",
"==",
"1",
":",
"# Regular rule, one output: Just write a simple rule.",
"self",
".",
"WriteLn",
"(",
"'%s: %s%s'",
"%",
"(",
"outputs",
"[",
"0",
"]",
",",
"' '",
".",
"join",
"(",
"inputs",
")",
",",
"force_append",
")",
")",
"else",
":",
"# Regular rule, more than one output: Multiple outputs are tricky in",
"# make. We will write three rules:",
"# - All outputs depend on an intermediate file.",
"# - Make .INTERMEDIATE depend on the intermediate.",
"# - The intermediate file depends on the inputs and executes the",
"# actual command.",
"# - The intermediate recipe will 'touch' the intermediate file.",
"# - The multi-output rule will have an do-nothing recipe.",
"intermediate",
"=",
"\"%s.intermediate\"",
"%",
"(",
"command",
"if",
"command",
"else",
"self",
".",
"target",
")",
"self",
".",
"WriteLn",
"(",
"'%s: %s'",
"%",
"(",
"' '",
".",
"join",
"(",
"outputs",
")",
",",
"intermediate",
")",
")",
"self",
".",
"WriteLn",
"(",
"'\\t%s'",
"%",
"'@:'",
")",
"self",
".",
"WriteLn",
"(",
"'%s: %s'",
"%",
"(",
"'.INTERMEDIATE'",
",",
"intermediate",
")",
")",
"self",
".",
"WriteLn",
"(",
"'%s: %s%s'",
"%",
"(",
"intermediate",
",",
"' '",
".",
"join",
"(",
"inputs",
")",
",",
"force_append",
")",
")",
"actions",
".",
"insert",
"(",
"0",
",",
"'$(call do_cmd,touch)'",
")",
"if",
"actions",
":",
"for",
"action",
"in",
"actions",
":",
"self",
".",
"WriteLn",
"(",
"'\\t%s'",
"%",
"action",
")",
"self",
".",
"WriteLn",
"(",
")"
] |
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/make.py#L1702-L1757
|
||
NVIDIA/TensorRT
|
42805f078052daad1a98bc5965974fcffaad0960
|
demo/Tacotron2/tensorrt/convert_waveglow2onnx.py
|
python
|
convert_convinv_1d_to_2d
|
(convinv)
|
return conv2d
|
Takes an invertible 1x1 1-d convolution and returns a 2-d convolution that does
the inverse
|
Takes an invertible 1x1 1-d convolution and returns a 2-d convolution that does
the inverse
|
[
"Takes",
"an",
"invertible",
"1x1",
"1",
"-",
"d",
"convolution",
"and",
"returns",
"a",
"2",
"-",
"d",
"convolution",
"that",
"does",
"the",
"inverse"
] |
def convert_convinv_1d_to_2d(convinv):
"""
Takes an invertible 1x1 1-d convolution and returns a 2-d convolution that does
the inverse
"""
conv2d = torch.nn.Conv2d(convinv.W_inverse.size(1),
convinv.W_inverse.size(0),
1, bias=False)
conv2d.weight.data[:,:,:,0] = convinv.W_inverse.data
return conv2d
|
[
"def",
"convert_convinv_1d_to_2d",
"(",
"convinv",
")",
":",
"conv2d",
"=",
"torch",
".",
"nn",
".",
"Conv2d",
"(",
"convinv",
".",
"W_inverse",
".",
"size",
"(",
"1",
")",
",",
"convinv",
".",
"W_inverse",
".",
"size",
"(",
"0",
")",
",",
"1",
",",
"bias",
"=",
"False",
")",
"conv2d",
".",
"weight",
".",
"data",
"[",
":",
",",
":",
",",
":",
",",
"0",
"]",
"=",
"convinv",
".",
"W_inverse",
".",
"data",
"return",
"conv2d"
] |
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/Tacotron2/tensorrt/convert_waveglow2onnx.py#L27-L36
|
|
ChromiumWebApps/chromium
|
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
|
tools/telemetry/third_party/websocket-client/websocket.py
|
python
|
create_connection
|
(url, timeout=None, **options)
|
return websock
|
connect to url and return websocket object.
Connect to url and return the WebSocket object.
Passing optional timeout parameter will set the timeout on the socket.
If no timeout is supplied, the global default timeout setting returned by getdefauttimeout() is used.
You can customize using 'options'.
If you set "header" list object, you can set your own custom header.
>>> conn = create_connection("ws://echo.websocket.org/",
... header=["User-Agent: MyProgram",
... "x-custom: header"])
timeout: socket timeout time. This value is integer.
if you set None for this value, it means "use default_timeout value"
options: current support option is only "header".
if you set header as dict value, the custom HTTP headers are added.
|
connect to url and return websocket object.
|
[
"connect",
"to",
"url",
"and",
"return",
"websocket",
"object",
"."
] |
def create_connection(url, timeout=None, **options):
"""
connect to url and return websocket object.
Connect to url and return the WebSocket object.
Passing optional timeout parameter will set the timeout on the socket.
If no timeout is supplied, the global default timeout setting returned by getdefauttimeout() is used.
You can customize using 'options'.
If you set "header" list object, you can set your own custom header.
>>> conn = create_connection("ws://echo.websocket.org/",
... header=["User-Agent: MyProgram",
... "x-custom: header"])
timeout: socket timeout time. This value is integer.
if you set None for this value, it means "use default_timeout value"
options: current support option is only "header".
if you set header as dict value, the custom HTTP headers are added.
"""
sockopt = options.get("sockopt", [])
sslopt = options.get("sslopt", {})
websock = WebSocket(sockopt=sockopt, sslopt=sslopt)
websock.settimeout(timeout if timeout is not None else default_timeout)
websock.connect(url, **options)
return websock
|
[
"def",
"create_connection",
"(",
"url",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"sockopt",
"=",
"options",
".",
"get",
"(",
"\"sockopt\"",
",",
"[",
"]",
")",
"sslopt",
"=",
"options",
".",
"get",
"(",
"\"sslopt\"",
",",
"{",
"}",
")",
"websock",
"=",
"WebSocket",
"(",
"sockopt",
"=",
"sockopt",
",",
"sslopt",
"=",
"sslopt",
")",
"websock",
".",
"settimeout",
"(",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
"else",
"default_timeout",
")",
"websock",
".",
"connect",
"(",
"url",
",",
"*",
"*",
"options",
")",
"return",
"websock"
] |
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/websocket-client/websocket.py#L176-L202
|
|
hanpfei/chromium-net
|
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
|
third_party/catapult/third_party/beautifulsoup4/bs4/element.py
|
python
|
PageElement._attribute_checker
|
(self, operator, attribute, value='')
|
Create a function that performs a CSS selector operation.
Takes an operator, attribute and optional value. Returns a
function that will return True for elements that match that
combination.
|
Create a function that performs a CSS selector operation.
|
[
"Create",
"a",
"function",
"that",
"performs",
"a",
"CSS",
"selector",
"operation",
"."
] |
def _attribute_checker(self, operator, attribute, value=''):
"""Create a function that performs a CSS selector operation.
Takes an operator, attribute and optional value. Returns a
function that will return True for elements that match that
combination.
"""
if operator == '=':
# string representation of `attribute` is equal to `value`
return lambda el: el._attr_value_as_string(attribute) == value
elif operator == '~':
# space-separated list representation of `attribute`
# contains `value`
def _includes_value(element):
attribute_value = element.get(attribute, [])
if not isinstance(attribute_value, list):
attribute_value = attribute_value.split()
return value in attribute_value
return _includes_value
elif operator == '^':
# string representation of `attribute` starts with `value`
return lambda el: el._attr_value_as_string(
attribute, '').startswith(value)
elif operator == '$':
# string represenation of `attribute` ends with `value`
return lambda el: el._attr_value_as_string(
attribute, '').endswith(value)
elif operator == '*':
# string representation of `attribute` contains `value`
return lambda el: value in el._attr_value_as_string(attribute, '')
elif operator == '|':
# string representation of `attribute` is either exactly
# `value` or starts with `value` and then a dash.
def _is_or_starts_with_dash(element):
attribute_value = element._attr_value_as_string(attribute, '')
return (attribute_value == value or attribute_value.startswith(
value + '-'))
return _is_or_starts_with_dash
else:
return lambda el: el.has_attr(attribute)
|
[
"def",
"_attribute_checker",
"(",
"self",
",",
"operator",
",",
"attribute",
",",
"value",
"=",
"''",
")",
":",
"if",
"operator",
"==",
"'='",
":",
"# string representation of `attribute` is equal to `value`",
"return",
"lambda",
"el",
":",
"el",
".",
"_attr_value_as_string",
"(",
"attribute",
")",
"==",
"value",
"elif",
"operator",
"==",
"'~'",
":",
"# space-separated list representation of `attribute`",
"# contains `value`",
"def",
"_includes_value",
"(",
"element",
")",
":",
"attribute_value",
"=",
"element",
".",
"get",
"(",
"attribute",
",",
"[",
"]",
")",
"if",
"not",
"isinstance",
"(",
"attribute_value",
",",
"list",
")",
":",
"attribute_value",
"=",
"attribute_value",
".",
"split",
"(",
")",
"return",
"value",
"in",
"attribute_value",
"return",
"_includes_value",
"elif",
"operator",
"==",
"'^'",
":",
"# string representation of `attribute` starts with `value`",
"return",
"lambda",
"el",
":",
"el",
".",
"_attr_value_as_string",
"(",
"attribute",
",",
"''",
")",
".",
"startswith",
"(",
"value",
")",
"elif",
"operator",
"==",
"'$'",
":",
"# string represenation of `attribute` ends with `value`",
"return",
"lambda",
"el",
":",
"el",
".",
"_attr_value_as_string",
"(",
"attribute",
",",
"''",
")",
".",
"endswith",
"(",
"value",
")",
"elif",
"operator",
"==",
"'*'",
":",
"# string representation of `attribute` contains `value`",
"return",
"lambda",
"el",
":",
"value",
"in",
"el",
".",
"_attr_value_as_string",
"(",
"attribute",
",",
"''",
")",
"elif",
"operator",
"==",
"'|'",
":",
"# string representation of `attribute` is either exactly",
"# `value` or starts with `value` and then a dash.",
"def",
"_is_or_starts_with_dash",
"(",
"element",
")",
":",
"attribute_value",
"=",
"element",
".",
"_attr_value_as_string",
"(",
"attribute",
",",
"''",
")",
"return",
"(",
"attribute_value",
"==",
"value",
"or",
"attribute_value",
".",
"startswith",
"(",
"value",
"+",
"'-'",
")",
")",
"return",
"_is_or_starts_with_dash",
"else",
":",
"return",
"lambda",
"el",
":",
"el",
".",
"has_attr",
"(",
"attribute",
")"
] |
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/beautifulsoup4/bs4/element.py#L584-L623
|
||
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py
|
python
|
withClass
|
(classname, namespace='')
|
return withAttribute(**{classattr : classname})
|
Simplified version of C{L{withAttribute}} when matching on a div class - made
difficult because C{class} is a reserved word in Python.
Example::
html = '''
<div>
Some text
<div class="grid">1 4 0 1 0</div>
<div class="graph">1,3 2,3 1,1</div>
<div>this <div> has no class</div>
</div>
'''
div,div_end = makeHTMLTags("div")
div_grid = div().setParseAction(withClass("grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
|
Simplified version of C{L{withAttribute}} when matching on a div class - made
difficult because C{class} is a reserved word in Python.
|
[
"Simplified",
"version",
"of",
"C",
"{",
"L",
"{",
"withAttribute",
"}}",
"when",
"matching",
"on",
"a",
"div",
"class",
"-",
"made",
"difficult",
"because",
"C",
"{",
"class",
"}",
"is",
"a",
"reserved",
"word",
"in",
"Python",
"."
] |
def withClass(classname, namespace=''):
"""
Simplified version of C{L{withAttribute}} when matching on a div class - made
difficult because C{class} is a reserved word in Python.
Example::
html = '''
<div>
Some text
<div class="grid">1 4 0 1 0</div>
<div class="graph">1,3 2,3 1,1</div>
<div>this <div> has no class</div>
</div>
'''
div,div_end = makeHTMLTags("div")
div_grid = div().setParseAction(withClass("grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
"""
classattr = "%s:class" % namespace if namespace else "class"
return withAttribute(**{classattr : classname})
|
[
"def",
"withClass",
"(",
"classname",
",",
"namespace",
"=",
"''",
")",
":",
"classattr",
"=",
"\"%s:class\"",
"%",
"namespace",
"if",
"namespace",
"else",
"\"class\"",
"return",
"withAttribute",
"(",
"*",
"*",
"{",
"classattr",
":",
"classname",
"}",
")"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L4997-L5030
|
|
microsoft/onnxruntime
|
f92e47e95b13a240e37caf7b36577983544f98fc
|
orttraining/orttraining/python/training/ortmodule/_execution_agent.py
|
python
|
TrainingAgent.__init__
|
(self, path_or_bytes, fw_feed_names, fw_outputs_device_info,
bw_fetches_names, bw_outputs_device_info, session_options=None,
providers=None, provider_options=None)
|
:param path_or_bytes: filename or serialized ONNX or ORT format model in a byte string
:param fw_feed_names: Feed names for foward pass.
:param fw_outputs_device_info: Device info for fetches in forward pass.
:param bw_fetches_names: Fetch names for backward pass.
:param bw_outputs_device_info: Device info for fetches in backward pass.
:param sess_options: session options
:param providers: Optional sequence of providers in order of decreasing
precedence. Values can either be provider names or tuples of
(provider name, options dict). If not provided, then all available
providers are used with the default precedence.
:param provider_options: Optional sequence of options dicts corresponding
to the providers listed in 'providers'.
The model type will be inferred unless explicitly set in the SessionOptions.
To explicitly set:
so = onnxruntime.SessionOptions()
so.add_session_config_entry('session.load_model_format', 'ONNX') or
so.add_session_config_entry('session.load_model_format', 'ORT') or
A file extension of '.ort' will be inferred as an ORT format model.
All other filenames are assumed to be ONNX format models.
'providers' can contain either names or names and options. When any options
are given in 'providers', 'provider_options' should not be used.
The list of providers is ordered by precedence. For example ['CUDAExecutionProvider', 'CPUExecutionProvider']
means execute a node using CUDAExecutionProvider if capable, otherwise execute using CPUExecutionProvider.
|
:param path_or_bytes: filename or serialized ONNX or ORT format model in a byte string
:param fw_feed_names: Feed names for foward pass.
:param fw_outputs_device_info: Device info for fetches in forward pass.
:param bw_fetches_names: Fetch names for backward pass.
:param bw_outputs_device_info: Device info for fetches in backward pass.
:param sess_options: session options
:param providers: Optional sequence of providers in order of decreasing
precedence. Values can either be provider names or tuples of
(provider name, options dict). If not provided, then all available
providers are used with the default precedence.
:param provider_options: Optional sequence of options dicts corresponding
to the providers listed in 'providers'.
|
[
":",
"param",
"path_or_bytes",
":",
"filename",
"or",
"serialized",
"ONNX",
"or",
"ORT",
"format",
"model",
"in",
"a",
"byte",
"string",
":",
"param",
"fw_feed_names",
":",
"Feed",
"names",
"for",
"foward",
"pass",
".",
":",
"param",
"fw_outputs_device_info",
":",
"Device",
"info",
"for",
"fetches",
"in",
"forward",
"pass",
".",
":",
"param",
"bw_fetches_names",
":",
"Fetch",
"names",
"for",
"backward",
"pass",
".",
":",
"param",
"bw_outputs_device_info",
":",
"Device",
"info",
"for",
"fetches",
"in",
"backward",
"pass",
".",
":",
"param",
"sess_options",
":",
"session",
"options",
":",
"param",
"providers",
":",
"Optional",
"sequence",
"of",
"providers",
"in",
"order",
"of",
"decreasing",
"precedence",
".",
"Values",
"can",
"either",
"be",
"provider",
"names",
"or",
"tuples",
"of",
"(",
"provider",
"name",
"options",
"dict",
")",
".",
"If",
"not",
"provided",
"then",
"all",
"available",
"providers",
"are",
"used",
"with",
"the",
"default",
"precedence",
".",
":",
"param",
"provider_options",
":",
"Optional",
"sequence",
"of",
"options",
"dicts",
"corresponding",
"to",
"the",
"providers",
"listed",
"in",
"providers",
"."
] |
def __init__(self, path_or_bytes, fw_feed_names, fw_outputs_device_info,
bw_fetches_names, bw_outputs_device_info, session_options=None,
providers=None, provider_options=None):
"""
:param path_or_bytes: filename or serialized ONNX or ORT format model in a byte string
:param fw_feed_names: Feed names for foward pass.
:param fw_outputs_device_info: Device info for fetches in forward pass.
:param bw_fetches_names: Fetch names for backward pass.
:param bw_outputs_device_info: Device info for fetches in backward pass.
:param sess_options: session options
:param providers: Optional sequence of providers in order of decreasing
precedence. Values can either be provider names or tuples of
(provider name, options dict). If not provided, then all available
providers are used with the default precedence.
:param provider_options: Optional sequence of options dicts corresponding
to the providers listed in 'providers'.
The model type will be inferred unless explicitly set in the SessionOptions.
To explicitly set:
so = onnxruntime.SessionOptions()
so.add_session_config_entry('session.load_model_format', 'ONNX') or
so.add_session_config_entry('session.load_model_format', 'ORT') or
A file extension of '.ort' will be inferred as an ORT format model.
All other filenames are assumed to be ONNX format models.
'providers' can contain either names or names and options. When any options
are given in 'providers', 'provider_options' should not be used.
The list of providers is ordered by precedence. For example ['CUDAExecutionProvider', 'CPUExecutionProvider']
means execute a node using CUDAExecutionProvider if capable, otherwise execute using CPUExecutionProvider.
"""
self._inference_session = onnxruntime.InferenceSession(path_or_bytes, session_options,
providers, provider_options)
self._training_agent = C_TrainingAgent(self._inference_session._sess, fw_feed_names, fw_outputs_device_info,
bw_fetches_names, bw_outputs_device_info)
|
[
"def",
"__init__",
"(",
"self",
",",
"path_or_bytes",
",",
"fw_feed_names",
",",
"fw_outputs_device_info",
",",
"bw_fetches_names",
",",
"bw_outputs_device_info",
",",
"session_options",
"=",
"None",
",",
"providers",
"=",
"None",
",",
"provider_options",
"=",
"None",
")",
":",
"self",
".",
"_inference_session",
"=",
"onnxruntime",
".",
"InferenceSession",
"(",
"path_or_bytes",
",",
"session_options",
",",
"providers",
",",
"provider_options",
")",
"self",
".",
"_training_agent",
"=",
"C_TrainingAgent",
"(",
"self",
".",
"_inference_session",
".",
"_sess",
",",
"fw_feed_names",
",",
"fw_outputs_device_info",
",",
"bw_fetches_names",
",",
"bw_outputs_device_info",
")"
] |
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/ortmodule/_execution_agent.py#L80-L117
|
||
apache/incubator-mxnet
|
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
|
python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py
|
python
|
convert_l2normalization
|
(node, **kwargs)
|
return [l2norm_node]
|
Map MXNet's L2Normalization operator attributes to onnx's LpNormalization operator
and return the created node.
|
Map MXNet's L2Normalization operator attributes to onnx's LpNormalization operator
and return the created node.
|
[
"Map",
"MXNet",
"s",
"L2Normalization",
"operator",
"attributes",
"to",
"onnx",
"s",
"LpNormalization",
"operator",
"and",
"return",
"the",
"created",
"node",
"."
] |
def convert_l2normalization(node, **kwargs):
"""Map MXNet's L2Normalization operator attributes to onnx's LpNormalization operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
mode = attrs.get("mode", "instance")
if mode != "channel":
raise AttributeError("L2Normalization: ONNX currently supports channel mode only")
l2norm_node = onnx.helper.make_node(
"LpNormalization",
input_nodes,
[name],
axis=1, # channel only
name=name
)
return [l2norm_node]
|
[
"def",
"convert_l2normalization",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"mode",
"=",
"attrs",
".",
"get",
"(",
"\"mode\"",
",",
"\"instance\"",
")",
"if",
"mode",
"!=",
"\"channel\"",
":",
"raise",
"AttributeError",
"(",
"\"L2Normalization: ONNX currently supports channel mode only\"",
")",
"l2norm_node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"\"LpNormalization\"",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"axis",
"=",
"1",
",",
"# channel only",
"name",
"=",
"name",
")",
"return",
"[",
"l2norm_node",
"]"
] |
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py#L1132-L1150
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/gtk/stc.py
|
python
|
StyledTextCtrl.GetAnchor
|
(*args, **kwargs)
|
return _stc.StyledTextCtrl_GetAnchor(*args, **kwargs)
|
GetAnchor(self) -> int
Returns the position of the opposite end of the selection to the caret.
|
GetAnchor(self) -> int
|
[
"GetAnchor",
"(",
"self",
")",
"-",
">",
"int"
] |
def GetAnchor(*args, **kwargs):
"""
GetAnchor(self) -> int
Returns the position of the opposite end of the selection to the caret.
"""
return _stc.StyledTextCtrl_GetAnchor(*args, **kwargs)
|
[
"def",
"GetAnchor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetAnchor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L2103-L2109
|
|
apple/swift-lldb
|
d74be846ef3e62de946df343e8c234bde93a8912
|
scripts/Python/static-binding/lldb.py
|
python
|
SBVariablesOptions.GetIncludeRuntimeSupportValues
|
(self)
|
return _lldb.SBVariablesOptions_GetIncludeRuntimeSupportValues(self)
|
GetIncludeRuntimeSupportValues(SBVariablesOptions self) -> bool
|
GetIncludeRuntimeSupportValues(SBVariablesOptions self) -> bool
|
[
"GetIncludeRuntimeSupportValues",
"(",
"SBVariablesOptions",
"self",
")",
"-",
">",
"bool"
] |
def GetIncludeRuntimeSupportValues(self):
"""GetIncludeRuntimeSupportValues(SBVariablesOptions self) -> bool"""
return _lldb.SBVariablesOptions_GetIncludeRuntimeSupportValues(self)
|
[
"def",
"GetIncludeRuntimeSupportValues",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBVariablesOptions_GetIncludeRuntimeSupportValues",
"(",
"self",
")"
] |
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L15098-L15100
|
|
microsoft/checkedc-clang
|
a173fefde5d7877b7750e7ce96dd08cf18baebf2
|
lldb/examples/python/file_extract.py
|
python
|
FileExtract.get_n_uint32
|
(self, n, fail_value=0)
|
Extract "n" uint32_t integers from the binary file at the current file position, returns a list of integers
|
Extract "n" uint32_t integers from the binary file at the current file position, returns a list of integers
|
[
"Extract",
"n",
"uint32_t",
"integers",
"from",
"the",
"binary",
"file",
"at",
"the",
"current",
"file",
"position",
"returns",
"a",
"list",
"of",
"integers"
] |
def get_n_uint32(self, n, fail_value=0):
'''Extract "n" uint32_t integers from the binary file at the current file position, returns a list of integers'''
s = self.read_size(4 * n)
if s:
return struct.unpack(self.byte_order + ("%u" % n) + 'I', s)
else:
return (fail_value,) * n
|
[
"def",
"get_n_uint32",
"(",
"self",
",",
"n",
",",
"fail_value",
"=",
"0",
")",
":",
"s",
"=",
"self",
".",
"read_size",
"(",
"4",
"*",
"n",
")",
"if",
"s",
":",
"return",
"struct",
".",
"unpack",
"(",
"self",
".",
"byte_order",
"+",
"(",
"\"%u\"",
"%",
"n",
")",
"+",
"'I'",
",",
"s",
")",
"else",
":",
"return",
"(",
"fail_value",
",",
")",
"*",
"n"
] |
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/examples/python/file_extract.py#L204-L210
|
||
generalized-intelligence/GAAS
|
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
|
deprecated/demo/tutorial_7/multi_uavs_motion_planning/px4_mavros_run_uav1.py
|
python
|
Px4Controller.start
|
(self)
|
main ROS thread
|
main ROS thread
|
[
"main",
"ROS",
"thread"
] |
def start(self):
rospy.init_node("uav1_offboard_node")
self.cur_target_pose = self.construct_pose_target(x=self.local_pose.pose.position.x, y=self.local_pose.pose.position.y, z=self.takeoff_height)
#print ("self.cur_target_pose:", self.cur_target_pose, type(self.cur_target_pose))
for i in range(20):
self.pose_target_pub.publish(self.cur_target_pose)
self.twist_target_pub.publish(self.cur_target_twist)
self.arm_state = self.arm()
self.offboard_state = self.offboard()
time.sleep(0.2)
if self.takeoff_detection():
print("Vehicle Took Off!")
else:
print("Vehicle Took Off Failed!")
return
'''
main ROS thread
'''
while self.arm_state and self.offboard_state and (rospy.is_shutdown() is False):
if(self.flag==0):
self.pose_target_pub.publish(self.cur_target_pose)
else:
self.twist_target_pub.publish(self.cur_target_twist)
if (self.state is "LAND") and (self.local_pose.pose.position.z < 0.15):
if(self.disarm()):
self.state = "DISARMED"
time.sleep(0.1)
|
[
"def",
"start",
"(",
"self",
")",
":",
"rospy",
".",
"init_node",
"(",
"\"uav1_offboard_node\"",
")",
"self",
".",
"cur_target_pose",
"=",
"self",
".",
"construct_pose_target",
"(",
"x",
"=",
"self",
".",
"local_pose",
".",
"pose",
".",
"position",
".",
"x",
",",
"y",
"=",
"self",
".",
"local_pose",
".",
"pose",
".",
"position",
".",
"y",
",",
"z",
"=",
"self",
".",
"takeoff_height",
")",
"#print (\"self.cur_target_pose:\", self.cur_target_pose, type(self.cur_target_pose))",
"for",
"i",
"in",
"range",
"(",
"20",
")",
":",
"self",
".",
"pose_target_pub",
".",
"publish",
"(",
"self",
".",
"cur_target_pose",
")",
"self",
".",
"twist_target_pub",
".",
"publish",
"(",
"self",
".",
"cur_target_twist",
")",
"self",
".",
"arm_state",
"=",
"self",
".",
"arm",
"(",
")",
"self",
".",
"offboard_state",
"=",
"self",
".",
"offboard",
"(",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"if",
"self",
".",
"takeoff_detection",
"(",
")",
":",
"print",
"(",
"\"Vehicle Took Off!\"",
")",
"else",
":",
"print",
"(",
"\"Vehicle Took Off Failed!\"",
")",
"return",
"while",
"self",
".",
"arm_state",
"and",
"self",
".",
"offboard_state",
"and",
"(",
"rospy",
".",
"is_shutdown",
"(",
")",
"is",
"False",
")",
":",
"if",
"(",
"self",
".",
"flag",
"==",
"0",
")",
":",
"self",
".",
"pose_target_pub",
".",
"publish",
"(",
"self",
".",
"cur_target_pose",
")",
"else",
":",
"self",
".",
"twist_target_pub",
".",
"publish",
"(",
"self",
".",
"cur_target_twist",
")",
"if",
"(",
"self",
".",
"state",
"is",
"\"LAND\"",
")",
"and",
"(",
"self",
".",
"local_pose",
".",
"pose",
".",
"position",
".",
"z",
"<",
"0.15",
")",
":",
"if",
"(",
"self",
".",
"disarm",
"(",
")",
")",
":",
"self",
".",
"state",
"=",
"\"DISARMED\"",
"time",
".",
"sleep",
"(",
"0.1",
")"
] |
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/demo/tutorial_7/multi_uavs_motion_planning/px4_mavros_run_uav1.py#L67-L104
|
||
baidu-research/tensorflow-allreduce
|
66d5b855e90b0949e9fa5cca5599fd729a70e874
|
tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py
|
python
|
setup_predict_data_feeder
|
(x, batch_size=None)
|
return [x]
|
Returns an iterable for feeding into predict step.
Args:
x: numpy, pandas, Dask array or dictionary of aforementioned. Also supports
iterable.
batch_size: Size of batches to split data into. If `None`, returns one
batch of full size.
Returns:
List or iterator (or dictionary thereof) of parts of data to predict on.
Raises:
ValueError: if `batch_size` <= 0.
|
Returns an iterable for feeding into predict step.
|
[
"Returns",
"an",
"iterable",
"for",
"feeding",
"into",
"predict",
"step",
"."
] |
def setup_predict_data_feeder(x, batch_size=None):
"""Returns an iterable for feeding into predict step.
Args:
x: numpy, pandas, Dask array or dictionary of aforementioned. Also supports
iterable.
batch_size: Size of batches to split data into. If `None`, returns one
batch of full size.
Returns:
List or iterator (or dictionary thereof) of parts of data to predict on.
Raises:
ValueError: if `batch_size` <= 0.
"""
if HAS_DASK:
x = extract_dask_data(x)
if HAS_PANDAS:
x = extract_pandas_data(x)
if _is_iterable(x):
return _batch_data(x, batch_size)
if len(x.shape) == 1:
x = np.reshape(x, (-1, 1))
if batch_size is not None:
if batch_size <= 0:
raise ValueError('Invalid batch_size %d.' % batch_size)
n_batches = int(math.ceil(float(len(x)) / batch_size))
return [x[i * batch_size:(i + 1) * batch_size] for i in xrange(n_batches)]
return [x]
|
[
"def",
"setup_predict_data_feeder",
"(",
"x",
",",
"batch_size",
"=",
"None",
")",
":",
"if",
"HAS_DASK",
":",
"x",
"=",
"extract_dask_data",
"(",
"x",
")",
"if",
"HAS_PANDAS",
":",
"x",
"=",
"extract_pandas_data",
"(",
"x",
")",
"if",
"_is_iterable",
"(",
"x",
")",
":",
"return",
"_batch_data",
"(",
"x",
",",
"batch_size",
")",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"1",
":",
"x",
"=",
"np",
".",
"reshape",
"(",
"x",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
"if",
"batch_size",
"is",
"not",
"None",
":",
"if",
"batch_size",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid batch_size %d.'",
"%",
"batch_size",
")",
"n_batches",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"len",
"(",
"x",
")",
")",
"/",
"batch_size",
")",
")",
"return",
"[",
"x",
"[",
"i",
"*",
"batch_size",
":",
"(",
"i",
"+",
"1",
")",
"*",
"batch_size",
"]",
"for",
"i",
"in",
"xrange",
"(",
"n_batches",
")",
"]",
"return",
"[",
"x",
"]"
] |
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py#L191-L219
|
|
catboost/catboost
|
167f64f237114a4d10b2b4ee42adb4569137debe
|
contrib/tools/python3/src/Lib/multiprocessing/context.py
|
python
|
BaseContext.Manager
|
(self)
|
return m
|
Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects.
|
Returns a manager associated with a running server process
|
[
"Returns",
"a",
"manager",
"associated",
"with",
"a",
"running",
"server",
"process"
] |
def Manager(self):
'''Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects.
'''
from .managers import SyncManager
m = SyncManager(ctx=self.get_context())
m.start()
return m
|
[
"def",
"Manager",
"(",
"self",
")",
":",
"from",
".",
"managers",
"import",
"SyncManager",
"m",
"=",
"SyncManager",
"(",
"ctx",
"=",
"self",
".",
"get_context",
"(",
")",
")",
"m",
".",
"start",
"(",
")",
"return",
"m"
] |
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/context.py#L49-L58
|
|
wxWidgets/wxPython-Classic
|
19571e1ae65f1ac445f5491474121998c97a1bf0
|
src/osx_cocoa/stc.py
|
python
|
StyledTextCtrl.GetText
|
(*args, **kwargs)
|
return _stc.StyledTextCtrl_GetText(*args, **kwargs)
|
GetText(self) -> String
Retrieve all the text in the document.
|
GetText(self) -> String
|
[
"GetText",
"(",
"self",
")",
"-",
">",
"String"
] |
def GetText(*args, **kwargs):
"""
GetText(self) -> String
Retrieve all the text in the document.
"""
return _stc.StyledTextCtrl_GetText(*args, **kwargs)
|
[
"def",
"GetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3665-L3671
|
|
KhronosGroup/Vulkan-Headers
|
b32da5329b50e3cb96229aaecba9ded032fe29cc
|
registry/vkconventions.py
|
python
|
VulkanConventions.write_contacts
|
(self)
|
return True
|
Return whether contact list should be written to extension appendices
|
Return whether contact list should be written to extension appendices
|
[
"Return",
"whether",
"contact",
"list",
"should",
"be",
"written",
"to",
"extension",
"appendices"
] |
def write_contacts(self):
"""Return whether contact list should be written to extension appendices"""
return True
|
[
"def",
"write_contacts",
"(",
"self",
")",
":",
"return",
"True"
] |
https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/vkconventions.py#L142-L144
|
|
tfwu/FaceDetection-ConvNet-3D
|
f9251c48eb40c5aec8fba7455115c355466555be
|
python/build/lib.linux-x86_64-2.7/mxnet/ndarray.py
|
python
|
subtract
|
(lhs, rhs)
|
Perform element-wise subtract
Parameters
----------
lhs : Array or float value
left hand side operand
rhs : Array of float value
right hand side operand
Returns
-------
out: Array
result array
|
Perform element-wise subtract
|
[
"Perform",
"element",
"-",
"wise",
"subtract"
] |
def subtract(lhs, rhs):
""" Perform element-wise subtract
Parameters
----------
lhs : Array or float value
left hand side operand
rhs : Array of float value
right hand side operand
Returns
-------
out: Array
result array
"""
# pylint: disable= no-member, protected-access
if isinstance(lhs, numeric_types):
if isinstance(rhs, numeric_types):
return lhs - rhs
elif isinstance(rhs, NDArray):
return NDArray._rminus_scalar(rhs, float(lhs))
else:
raise TypeError('type %s not supported' % str(type(rhs)))
elif isinstance(rhs, numeric_types):
return NDArray._minus_scalar(lhs, float(rhs))
elif isinstance(rhs, NDArray):
lsize = functools.reduce(operator.mul, lhs.shape)
rsize = functools.reduce(operator.mul, rhs.shape)
if lsize < rsize:
lhs = lhs.broadcast_to(rhs.shape)
elif lsize > rsize:
rhs = rhs.broadcast_to(lhs.shape)
return NDArray._minus(lhs, rhs)
else:
raise TypeError('type %s not supported' % str(type(rhs)))
|
[
"def",
"subtract",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"if",
"isinstance",
"(",
"lhs",
",",
"numeric_types",
")",
":",
"if",
"isinstance",
"(",
"rhs",
",",
"numeric_types",
")",
":",
"return",
"lhs",
"-",
"rhs",
"elif",
"isinstance",
"(",
"rhs",
",",
"NDArray",
")",
":",
"return",
"NDArray",
".",
"_rminus_scalar",
"(",
"rhs",
",",
"float",
"(",
"lhs",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'type %s not supported'",
"%",
"str",
"(",
"type",
"(",
"rhs",
")",
")",
")",
"elif",
"isinstance",
"(",
"rhs",
",",
"numeric_types",
")",
":",
"return",
"NDArray",
".",
"_minus_scalar",
"(",
"lhs",
",",
"float",
"(",
"rhs",
")",
")",
"elif",
"isinstance",
"(",
"rhs",
",",
"NDArray",
")",
":",
"lsize",
"=",
"functools",
".",
"reduce",
"(",
"operator",
".",
"mul",
",",
"lhs",
".",
"shape",
")",
"rsize",
"=",
"functools",
".",
"reduce",
"(",
"operator",
".",
"mul",
",",
"rhs",
".",
"shape",
")",
"if",
"lsize",
"<",
"rsize",
":",
"lhs",
"=",
"lhs",
".",
"broadcast_to",
"(",
"rhs",
".",
"shape",
")",
"elif",
"lsize",
">",
"rsize",
":",
"rhs",
"=",
"rhs",
".",
"broadcast_to",
"(",
"lhs",
".",
"shape",
")",
"return",
"NDArray",
".",
"_minus",
"(",
"lhs",
",",
"rhs",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'type %s not supported'",
"%",
"str",
"(",
"type",
"(",
"rhs",
")",
")",
")"
] |
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/ndarray.py#L522-L557
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.