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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/codedeploy/layer1.py | python | CodeDeployConnection.get_application_revision | (self, application_name, revision) | return self.make_request(action='GetApplicationRevision',
body=json.dumps(params)) | Gets information about an application revision.
:type application_name: string
:param application_name: The name of the application that corresponds
to the revision.
:type revision: dict
:param revision: Information about the application revision to get,
including the revision's type and its location. | Gets information about an application revision. | [
"Gets",
"information",
"about",
"an",
"application",
"revision",
"."
] | def get_application_revision(self, application_name, revision):
"""
Gets information about an application revision.
:type application_name: string
:param application_name: The name of the application that corresponds
to the revision.
:type revision: dict
:param revision: Information about the application revision to get,
including the revision's type and its location.
"""
params = {
'applicationName': application_name,
'revision': revision,
}
return self.make_request(action='GetApplicationRevision',
body=json.dumps(params)) | [
"def",
"get_application_revision",
"(",
"self",
",",
"application_name",
",",
"revision",
")",
":",
"params",
"=",
"{",
"'applicationName'",
":",
"application_name",
",",
"'revision'",
":",
"revision",
",",
"}",
"return",
"self",
".",
"make_request",
"(",
"actio... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/codedeploy/layer1.py#L447-L465 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/pyserial/serial/urlhandler/protocol_loop.py | python | LoopbackSerial.getCD | (self) | return True | Read terminal status line: Carrier Detect | Read terminal status line: Carrier Detect | [
"Read",
"terminal",
"status",
"line",
":",
"Carrier",
"Detect"
] | def getCD(self):
"""Read terminal status line: Carrier Detect"""
if not self._isOpen: raise portNotOpenError
if self.logger:
self.logger.info('returning dummy for getCD()')
return True | [
"def",
"getCD",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"portNotOpenError",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'returning dummy for getCD()'",
")",
"return",
"True"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/urlhandler/protocol_loop.py#L228-L233 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.SearchPrev | (*args, **kwargs) | return _stc.StyledTextCtrl_SearchPrev(*args, **kwargs) | SearchPrev(self, int flags, String text) -> int
Find some text starting at the search anchor and moving backwards.
Does not ensure the selection is visible. | SearchPrev(self, int flags, String text) -> int | [
"SearchPrev",
"(",
"self",
"int",
"flags",
"String",
"text",
")",
"-",
">",
"int"
] | def SearchPrev(*args, **kwargs):
"""
SearchPrev(self, int flags, String text) -> int
Find some text starting at the search anchor and moving backwards.
Does not ensure the selection is visible.
"""
return _stc.StyledTextCtrl_SearchPrev(*args, **kwargs) | [
"def",
"SearchPrev",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SearchPrev",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4938-L4945 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/sliceviewer/roi.py | python | extract_matrix_cuts_spectra_axis | (workspace: MatrixWorkspace,
xmin: float,
xmax: float,
ymin: float,
ymax: float,
xcut_name: str,
ycut_name: str,
log_algorithm_calls: bool = True) | Assuming a MatrixWorkspace with vertical spectra axis, extract 1D cuts from the region defined
by the given parameters
:param workspace: A MatrixWorkspace with a vertical SpectraAxis
:param xmin: X min for bounded region
:param xmax: X max for bounded region
:param ymin: Y min for bounded region
:param ymax: Y max for bounded region
:param xcut_name: Name of the X cut. Empty indicates it should be skipped
:param ycut_name: Name of the Y cut. Empty indicates it should be skipped
:param log_algorithm_calls: Log the algorithm call or be silent | Assuming a MatrixWorkspace with vertical spectra axis, extract 1D cuts from the region defined
by the given parameters
:param workspace: A MatrixWorkspace with a vertical SpectraAxis
:param xmin: X min for bounded region
:param xmax: X max for bounded region
:param ymin: Y min for bounded region
:param ymax: Y max for bounded region
:param xcut_name: Name of the X cut. Empty indicates it should be skipped
:param ycut_name: Name of the Y cut. Empty indicates it should be skipped
:param log_algorithm_calls: Log the algorithm call or be silent | [
"Assuming",
"a",
"MatrixWorkspace",
"with",
"vertical",
"spectra",
"axis",
"extract",
"1D",
"cuts",
"from",
"the",
"region",
"defined",
"by",
"the",
"given",
"parameters",
":",
"param",
"workspace",
":",
"A",
"MatrixWorkspace",
"with",
"a",
"vertical",
"SpectraA... | def extract_matrix_cuts_spectra_axis(workspace: MatrixWorkspace,
xmin: float,
xmax: float,
ymin: float,
ymax: float,
xcut_name: str,
ycut_name: str,
log_algorithm_calls: bool = True):
"""
Assuming a MatrixWorkspace with vertical spectra axis, extract 1D cuts from the region defined
by the given parameters
:param workspace: A MatrixWorkspace with a vertical SpectraAxis
:param xmin: X min for bounded region
:param xmax: X max for bounded region
:param ymin: Y min for bounded region
:param ymax: Y max for bounded region
:param xcut_name: Name of the X cut. Empty indicates it should be skipped
:param ycut_name: Name of the Y cut. Empty indicates it should be skipped
:param log_algorithm_calls: Log the algorithm call or be silent
"""
# if the value is half way in a spectrum then include it
tmp_crop_region = '__tmp_sv_region_extract'
roi = _extract_roi_spectra_axis(workspace, xmin, xmax, ymin, ymax, tmp_crop_region,
log_algorithm_calls)
# perform ycut first so xcut can reuse tmp workspace for rebinning if necessary
if ycut_name:
Rebin(
InputWorkspace=roi,
OutputWorkspace=ycut_name,
Params=[xmin, xmax - xmin, xmax],
EnableLogging=log_algorithm_calls)
Transpose(
InputWorkspace=ycut_name, OutputWorkspace=ycut_name, EnableLogging=log_algorithm_calls)
if xcut_name:
if not roi.isCommonBins():
# rebin to a common grid using the resolution from the spectrum
# with the lowest resolution to avoid overbinning
roi = _rebin_to_common_grid(roi, xmin, xmax, log_algorithm_calls)
SumSpectra(InputWorkspace=roi, OutputWorkspace=xcut_name, EnableLogging=log_algorithm_calls)
try:
DeleteWorkspace(tmp_crop_region, EnableLogging=log_algorithm_calls)
except ValueError:
pass | [
"def",
"extract_matrix_cuts_spectra_axis",
"(",
"workspace",
":",
"MatrixWorkspace",
",",
"xmin",
":",
"float",
",",
"xmax",
":",
"float",
",",
"ymin",
":",
"float",
",",
"ymax",
":",
"float",
",",
"xcut_name",
":",
"str",
",",
"ycut_name",
":",
"str",
","... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/roi.py#L36-L80 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/depot_tools/cpplint.py | python | _NamespaceInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Check end of namespace comments. | Check end of namespace comments. | [
"Check",
"end",
"of",
"namespace",
"comments",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
line = clean_lines.raw_lines[linenum]
# Check how many lines is enclosed in this namespace. Don't issue
# warning for missing namespace comments if there aren't enough
# lines. However, do apply checks if there is already an end of
# namespace comment and it's incorrect.
#
# TODO(unknown): We always want to check end of namespace comments
# if a namespace is large, but sometimes we also want to apply the
# check if a short namespace contained nontrivial things (something
# other than forward declarations). There is currently no logic on
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
# preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
# expected namespace.
if self.name:
# Named namespace
if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
re.escape(self.name) + r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
# If "// namespace anonymous" or "// anonymous namespace (more text)",
# mention "// anonymous namespace" as an acceptable form
if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
error(filename, linenum, 'readability/namespace', 5,
'Anonymous namespace should be terminated with "// namespace"'
' or "// anonymous namespace"')
else:
error(filename, linenum, 'readability/namespace', 5,
'Anonymous namespace should be terminated with "// namespace"') | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
"# Check how many lines is enclosed in this namespace. Don't issue",
"# warning for missing n... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/depot_tools/cpplint.py#L2218-L2268 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/py/py/_log/log.py | python | KeywordMapper.setconsumer | (self, keywords, consumer) | set a consumer for a set of keywords. | set a consumer for a set of keywords. | [
"set",
"a",
"consumer",
"for",
"a",
"set",
"of",
"keywords",
"."
] | def setconsumer(self, keywords, consumer):
""" set a consumer for a set of keywords. """
# normalize to tuples
if isinstance(keywords, str):
keywords = tuple(filter(None, keywords.split()))
elif hasattr(keywords, '_keywords'):
keywords = keywords._keywords
elif not isinstance(keywords, tuple):
raise TypeError("key %r is not a string or tuple" % (keywords,))
if consumer is not None and not py.builtin.callable(consumer):
if not hasattr(consumer, 'write'):
raise TypeError(
"%r should be None, callable or file-like" % (consumer,))
consumer = File(consumer)
self.keywords2consumer[keywords] = consumer | [
"def",
"setconsumer",
"(",
"self",
",",
"keywords",
",",
"consumer",
")",
":",
"# normalize to tuples",
"if",
"isinstance",
"(",
"keywords",
",",
"str",
")",
":",
"keywords",
"=",
"tuple",
"(",
"filter",
"(",
"None",
",",
"keywords",
".",
"split",
"(",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_log/log.py#L94-L108 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/coordinator/metric_utils.py | python | get_metric_summary | (metric_name) | return ret | Get summary for the specified metric. | Get summary for the specified metric. | [
"Get",
"summary",
"for",
"the",
"specified",
"metric",
"."
] | def get_metric_summary(metric_name):
"""Get summary for the specified metric."""
metric = _METRICS_MAPPING[metric_name]
histogram_proto = metric.get_cell().value()
ret = dict()
ret['min'] = histogram_proto.min
ret['max'] = histogram_proto.max
ret['num'] = histogram_proto.num
ret['sum'] = histogram_proto.sum
# TODO(haoyuzhang): consider reporting the distribution in buckets.
return ret | [
"def",
"get_metric_summary",
"(",
"metric_name",
")",
":",
"metric",
"=",
"_METRICS_MAPPING",
"[",
"metric_name",
"]",
"histogram_proto",
"=",
"metric",
".",
"get_cell",
"(",
")",
".",
"value",
"(",
")",
"ret",
"=",
"dict",
"(",
")",
"ret",
"[",
"'min'",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/coordinator/metric_utils.py#L75-L85 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | catalogGetPublic | (pubID) | return ret | Try to lookup the catalog reference associated to a public
ID DEPRECATED, use xmlCatalogResolvePublic() | Try to lookup the catalog reference associated to a public
ID DEPRECATED, use xmlCatalogResolvePublic() | [
"Try",
"to",
"lookup",
"the",
"catalog",
"reference",
"associated",
"to",
"a",
"public",
"ID",
"DEPRECATED",
"use",
"xmlCatalogResolvePublic",
"()"
] | def catalogGetPublic(pubID):
"""Try to lookup the catalog reference associated to a public
ID DEPRECATED, use xmlCatalogResolvePublic() """
ret = libxml2mod.xmlCatalogGetPublic(pubID)
return ret | [
"def",
"catalogGetPublic",
"(",
"pubID",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlCatalogGetPublic",
"(",
"pubID",
")",
"return",
"ret"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L871-L875 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/multitype_ops/greater_equal_impl.py | python | _greater_equal_tensor | (x, y) | return F.tensor_ge(x, y) | Determine whether tensor x is greater equal than tensor y elementwise
Args:
x(Tensor): Tensor.
y(Tensor): Tensor.
Returns:
Tensor, return value by operator P.GreaterEqual. | Determine whether tensor x is greater equal than tensor y elementwise | [
"Determine",
"whether",
"tensor",
"x",
"is",
"greater",
"equal",
"than",
"tensor",
"y",
"elementwise"
] | def _greater_equal_tensor(x, y):
"""
Determine whether tensor x is greater equal than tensor y elementwise
Args:
x(Tensor): Tensor.
y(Tensor): Tensor.
Returns:
Tensor, return value by operator P.GreaterEqual.
"""
return F.tensor_ge(x, y) | [
"def",
"_greater_equal_tensor",
"(",
"x",
",",
"y",
")",
":",
"return",
"F",
".",
"tensor_ge",
"(",
"x",
",",
"y",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/greater_equal_impl.py#L43-L54 | |
sofa-framework/sofa | 70628e35a44fcc258cf8250109b5e4eba8c5abe9 | applications/plugins/PSL/python/pslparserhjson.py | python | objectToString | (object, nspace) | return ores | Convert a Sofa object into a hjson string. This function is used during the serialization
process | Convert a Sofa object into a hjson string. This function is used during the serialization
process | [
"Convert",
"a",
"Sofa",
"object",
"into",
"a",
"hjson",
"string",
".",
"This",
"function",
"is",
"used",
"during",
"the",
"serialization",
"process"
] | def objectToString(object, nspace):
'''Convert a Sofa object into a hjson string. This function is used during the serialization
process'''
instanceof = object.getData("psl_instanceof")
if instanceof != None:
instanceof = instanceof.getValue()
if instanceof == "Template":
source = object.psl_source
ores = ""
ores += nspace+instanceof+ " : {"
ores += nspace+" "+source
ores += "}"+"\n"
return ores
res = ""
for datafield in object.getListOfDataFields():
if datafield.isPersistant():
if datafield.hasParent():
res += "\n" + nspace + ' ' + datafield.name + ' : "' + datafield.getParentPath() + '"'
else:
res += "\n" + nspace + " " + datafield.name + " : \"" + datafield.getValueString() + "\""
for link in object.getListOfLinks():
if link.isPersistant():
res += "\n" + nspace + " " + link.name + " : \"" + link.getValueString() + "\""
ores = ""
ores += nspace+object.getClassName() + " : {"
ores += res
if res == "":
ores += "}"+"\n"
else:
ores += "\n" + nspace+"} "+"\n"
return ores | [
"def",
"objectToString",
"(",
"object",
",",
"nspace",
")",
":",
"instanceof",
"=",
"object",
".",
"getData",
"(",
"\"psl_instanceof\"",
")",
"if",
"instanceof",
"!=",
"None",
":",
"instanceof",
"=",
"instanceof",
".",
"getValue",
"(",
")",
"if",
"instanceof... | https://github.com/sofa-framework/sofa/blob/70628e35a44fcc258cf8250109b5e4eba8c5abe9/applications/plugins/PSL/python/pslparserhjson.py#L35-L68 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | ToolBarToolBase.GetKind | (*args, **kwargs) | return _controls_.ToolBarToolBase_GetKind(*args, **kwargs) | GetKind(self) -> int | GetKind(self) -> int | [
"GetKind",
"(",
"self",
")",
"-",
">",
"int"
] | def GetKind(*args, **kwargs):
"""GetKind(self) -> int"""
return _controls_.ToolBarToolBase_GetKind(*args, **kwargs) | [
"def",
"GetKind",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ToolBarToolBase_GetKind",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L3469-L3471 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/completerlib.py | python | get_root_modules | () | return rootmodules | Returns a list containing the names of all the modules available in the
folders of the pythonpath.
ip.db['rootmodules_cache'] maps sys.path entries to list of modules. | Returns a list containing the names of all the modules available in the
folders of the pythonpath. | [
"Returns",
"a",
"list",
"containing",
"the",
"names",
"of",
"all",
"the",
"modules",
"available",
"in",
"the",
"folders",
"of",
"the",
"pythonpath",
"."
] | def get_root_modules():
"""
Returns a list containing the names of all the modules available in the
folders of the pythonpath.
ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
"""
ip = get_ipython()
if ip is None:
# No global shell instance to store cached list of modules.
# Don't try to scan for modules every time.
return list(sys.builtin_module_names)
rootmodules_cache = ip.db.get('rootmodules_cache', {})
rootmodules = list(sys.builtin_module_names)
start_time = time()
store = False
for path in sys.path:
try:
modules = rootmodules_cache[path]
except KeyError:
modules = module_list(path)
try:
modules.remove('__init__')
except ValueError:
pass
if path not in ('', '.'): # cwd modules should not be cached
rootmodules_cache[path] = modules
if time() - start_time > TIMEOUT_STORAGE and not store:
store = True
print("\nCaching the list of root modules, please wait!")
print("(This will only be done once - type '%rehashx' to "
"reset cache!)\n")
sys.stdout.flush()
if time() - start_time > TIMEOUT_GIVEUP:
print("This is taking too long, we give up.\n")
return []
rootmodules.extend(modules)
if store:
ip.db['rootmodules_cache'] = rootmodules_cache
rootmodules = list(set(rootmodules))
return rootmodules | [
"def",
"get_root_modules",
"(",
")",
":",
"ip",
"=",
"get_ipython",
"(",
")",
"if",
"ip",
"is",
"None",
":",
"# No global shell instance to store cached list of modules.",
"# Don't try to scan for modules every time.",
"return",
"list",
"(",
"sys",
".",
"builtin_module_na... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/completerlib.py#L154-L195 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_utils/transformations.py | python | quaternion_multiply | (quaternion1, quaternion0) | return numpy.array((
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
-x1*x0 - y1*y0 - z1*z0 + w1*w0), dtype=numpy.float64) | Return multiplication of two quaternions.
>>> q = quaternion_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
>>> numpy.allclose(q, [-44, -14, 48, 28])
True | Return multiplication of two quaternions. | [
"Return",
"multiplication",
"of",
"two",
"quaternions",
"."
] | def quaternion_multiply(quaternion1, quaternion0):
"""Return multiplication of two quaternions.
>>> q = quaternion_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
>>> numpy.allclose(q, [-44, -14, 48, 28])
True
"""
x0, y0, z0, w0 = quaternion0
x1, y1, z1, w1 = quaternion1
return numpy.array((
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
-x1*x0 - y1*y0 - z1*z0 + w1*w0), dtype=numpy.float64) | [
"def",
"quaternion_multiply",
"(",
"quaternion1",
",",
"quaternion0",
")",
":",
"x0",
",",
"y0",
",",
"z0",
",",
"w0",
"=",
"quaternion0",
"x1",
",",
"y1",
",",
"z1",
",",
"w1",
"=",
"quaternion1",
"return",
"numpy",
".",
"array",
"(",
"(",
"x1",
"*"... | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_utils/transformations.py#L1228-L1242 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ListCtrl.GetTextColour | (*args, **kwargs) | return _controls_.ListCtrl_GetTextColour(*args, **kwargs) | GetTextColour(self) -> Colour | GetTextColour(self) -> Colour | [
"GetTextColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetTextColour(*args, **kwargs):
"""GetTextColour(self) -> Colour"""
return _controls_.ListCtrl_GetTextColour(*args, **kwargs) | [
"def",
"GetTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_GetTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4592-L4594 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/math_ops.py | python | _div_python2 | (x, y, name=None) | Divide two values using Python 2 semantics.
Used for Tensor.__div__.
Args:
x: `Tensor` numerator of real numeric type.
y: `Tensor` denominator of real numeric type.
name: A name for the operation (optional).
Returns:
`x / y` returns the quotient of x and y. | Divide two values using Python 2 semantics. | [
"Divide",
"two",
"values",
"using",
"Python",
"2",
"semantics",
"."
] | def _div_python2(x, y, name=None):
"""Divide two values using Python 2 semantics.
Used for Tensor.__div__.
Args:
x: `Tensor` numerator of real numeric type.
y: `Tensor` denominator of real numeric type.
name: A name for the operation (optional).
Returns:
`x / y` returns the quotient of x and y.
"""
with ops.name_scope(name, "div", [x, y]) as name:
x = ops.convert_to_tensor(x, name="x")
y = ops.convert_to_tensor(y, name="y", dtype=x.dtype.base_dtype)
x_dtype = x.dtype.base_dtype
y_dtype = y.dtype.base_dtype
if x_dtype != y_dtype:
raise TypeError(f"`x` and `y` must have the same dtype, "
f"got {x_dtype!r} != {y_dtype!r}.")
if x_dtype.is_floating or x_dtype.is_complex:
return gen_math_ops.real_div(x, y, name=name)
else:
return gen_math_ops.floor_div(x, y, name=name) | [
"def",
"_div_python2",
"(",
"x",
",",
"y",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"div\"",
",",
"[",
"x",
",",
"y",
"]",
")",
"as",
"name",
":",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_ops.py#L1530-L1555 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PGProperty.GetMaxLength | (*args, **kwargs) | return _propgrid.PGProperty_GetMaxLength(*args, **kwargs) | GetMaxLength(self) -> int | GetMaxLength(self) -> int | [
"GetMaxLength",
"(",
"self",
")",
"-",
">",
"int"
] | def GetMaxLength(*args, **kwargs):
"""GetMaxLength(self) -> int"""
return _propgrid.PGProperty_GetMaxLength(*args, **kwargs) | [
"def",
"GetMaxLength",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_GetMaxLength",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L604-L606 | |
facebookresearch/minirts | 859e747a5e2fab2355bea083daffa6a36820a7f2 | scripts/behavior_clone/module.py | python | CmdEmbedding.forward | (self, ctype, utype) | return torch.cat([ctype_emb, utype_emb], 2) | take cmd_type, produce cmd_repr
ctype: [batch, num_padded_unit],
0 <= ctype < num_ctype, padding cmd should have a valid unit_type | take cmd_type, produce cmd_repr | [
"take",
"cmd_type",
"produce",
"cmd_repr"
] | def forward(self, ctype, utype):
"""take cmd_type, produce cmd_repr
ctype: [batch, num_padded_unit],
0 <= ctype < num_ctype, padding cmd should have a valid unit_type
"""
ctype_emb = self.ctype_emb(ctype)
utype_emb = self.utype_emb(utype)
# print('>>>>', ctype.size())
return torch.cat([ctype_emb, utype_emb], 2) | [
"def",
"forward",
"(",
"self",
",",
"ctype",
",",
"utype",
")",
":",
"ctype_emb",
"=",
"self",
".",
"ctype_emb",
"(",
"ctype",
")",
"utype_emb",
"=",
"self",
".",
"utype_emb",
"(",
"utype",
")",
"# print('>>>>', ctype.size())",
"return",
"torch",
".",
"cat... | https://github.com/facebookresearch/minirts/blob/859e747a5e2fab2355bea083daffa6a36820a7f2/scripts/behavior_clone/module.py#L95-L104 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/displayhook.py | python | DisplayHook.quiet | (self) | Should we silence the display hook because of ';'? | Should we silence the display hook because of ';'? | [
"Should",
"we",
"silence",
"the",
"display",
"hook",
"because",
"of",
";",
"?"
] | def quiet(self):
"""Should we silence the display hook because of ';'?"""
# do not print output if input ends in ';'
try:
cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
except IndexError:
# some uses of ipshellembed may fail here
return False
sio = _io.StringIO(cell)
tokens = list(tokenize.generate_tokens(sio.readline))
for token in reversed(tokens):
if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
continue
if (token[0] == tokenize.OP) and (token[1] == ';'):
return True
else:
return False | [
"def",
"quiet",
"(",
"self",
")",
":",
"# do not print output if input ends in ';'",
"try",
":",
"cell",
"=",
"cast_unicode_py2",
"(",
"self",
".",
"shell",
".",
"history_manager",
".",
"input_hist_parsed",
"[",
"-",
"1",
"]",
")",
"except",
"IndexError",
":",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/displayhook.py#L83-L102 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/utils.py | python | get_environ_proxies | (url, no_proxy=None) | Return a dict of environment proxies.
:rtype: dict | Return a dict of environment proxies. | [
"Return",
"a",
"dict",
"of",
"environment",
"proxies",
"."
] | def get_environ_proxies(url, no_proxy=None):
"""
Return a dict of environment proxies.
:rtype: dict
"""
if should_bypass_proxies(url, no_proxy=no_proxy):
return {}
else:
return getproxies() | [
"def",
"get_environ_proxies",
"(",
"url",
",",
"no_proxy",
"=",
"None",
")",
":",
"if",
"should_bypass_proxies",
"(",
"url",
",",
"no_proxy",
"=",
"no_proxy",
")",
":",
"return",
"{",
"}",
"else",
":",
"return",
"getproxies",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/utils.py#L760-L769 | ||
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/mac_tool.py | python | MacTool._Relink | (self, dest, link) | Creates a symlink to |dest| named |link|. If |link| already exists,
it is overwritten. | Creates a symlink to |dest| named |link|. If |link| already exists,
it is overwritten. | [
"Creates",
"a",
"symlink",
"to",
"|dest|",
"named",
"|link|",
".",
"If",
"|link|",
"already",
"exists",
"it",
"is",
"overwritten",
"."
] | def _Relink(self, dest, link):
"""Creates a symlink to |dest| named |link|. If |link| already exists,
it is overwritten."""
if os.path.lexists(link):
os.remove(link)
os.symlink(dest, link) | [
"def",
"_Relink",
"(",
"self",
",",
"dest",
",",
"link",
")",
":",
"if",
"os",
".",
"path",
".",
"lexists",
"(",
"link",
")",
":",
"os",
".",
"remove",
"(",
"link",
")",
"os",
".",
"symlink",
"(",
"dest",
",",
"link",
")"
] | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/mac_tool.py#L201-L206 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/feature_column/feature_column.py | python | _create_tuple | (shape, value) | return value | Returns a tuple with given shape and filled with value. | Returns a tuple with given shape and filled with value. | [
"Returns",
"a",
"tuple",
"with",
"given",
"shape",
"and",
"filled",
"with",
"value",
"."
] | def _create_tuple(shape, value):
"""Returns a tuple with given shape and filled with value."""
if shape:
return tuple([_create_tuple(shape[1:], value) for _ in range(shape[0])])
return value | [
"def",
"_create_tuple",
"(",
"shape",
",",
"value",
")",
":",
"if",
"shape",
":",
"return",
"tuple",
"(",
"[",
"_create_tuple",
"(",
"shape",
"[",
"1",
":",
"]",
",",
"value",
")",
"for",
"_",
"in",
"range",
"(",
"shape",
"[",
"0",
"]",
")",
"]",... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/feature_column/feature_column.py#L1855-L1859 | |
SGL-UT/GPSTk | 2340ec1cbdbd0b80a204920127798697bc616b30 | swig/doxy2swig.py | python | Doxy2SWIG.parse | (self, node) | Parse a given node. This function in turn calls the
`parse_<nodeType>` functions which handle the respective
nodes. | Parse a given node. This function in turn calls the
`parse_<nodeType>` functions which handle the respective
nodes. | [
"Parse",
"a",
"given",
"node",
".",
"This",
"function",
"in",
"turn",
"calls",
"the",
"parse_<nodeType",
">",
"functions",
"which",
"handle",
"the",
"respective",
"nodes",
"."
] | def parse(self, node):
"""Parse a given node. This function in turn calls the
`parse_<nodeType>` functions which handle the respective
nodes.
"""
pm = getattr(self, "parse_%s"%node.__class__.__name__)
pm(node) | [
"def",
"parse",
"(",
"self",
",",
"node",
")",
":",
"pm",
"=",
"getattr",
"(",
"self",
",",
"\"parse_%s\"",
"%",
"node",
".",
"__class__",
".",
"__name__",
")",
"pm",
"(",
"node",
")"
] | https://github.com/SGL-UT/GPSTk/blob/2340ec1cbdbd0b80a204920127798697bc616b30/swig/doxy2swig.py#L104-L111 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLCollectData.py | python | _applyIncidentEnergyCalibration | (ws, eiWS, wsNames, report, algorithmLogging) | return ws | Update incident energy and wavelength in the sample logs. | Update incident energy and wavelength in the sample logs. | [
"Update",
"incident",
"energy",
"and",
"wavelength",
"in",
"the",
"sample",
"logs",
"."
] | def _applyIncidentEnergyCalibration(ws, eiWS, wsNames, report, algorithmLogging):
"""Update incident energy and wavelength in the sample logs."""
originalEnergy = ws.getRun().getLogData('Ei').value
originalWavelength = ws.getRun().getLogData('wavelength').value
energy = eiWS.readY(0)[0]
wavelength = UnitConversion.run('Energy', 'Wavelength', energy, 0, 0, 0, Direct, 5)
AddSampleLog(Workspace=ws,
LogName='Ei',
LogText=str(energy),
LogType='Number',
NumberType='Double',
LogUnit='meV',
EnableLogging=algorithmLogging)
AddSampleLog(Workspace=ws,
Logname='wavelength',
LogText=str(wavelength),
LogType='Number',
NumberType='Double',
LogUnit='Angstrom',
EnableLogging=algorithmLogging)
report.notice("Applied Ei calibration to '" + str(ws) + "'.")
report.notice('Original Ei: {} new Ei: {}.'.format(originalEnergy, energy))
report.notice('Original wavelength: {} new wavelength {}.'.format(originalWavelength, wavelength))
return ws | [
"def",
"_applyIncidentEnergyCalibration",
"(",
"ws",
",",
"eiWS",
",",
"wsNames",
",",
"report",
",",
"algorithmLogging",
")",
":",
"originalEnergy",
"=",
"ws",
".",
"getRun",
"(",
")",
".",
"getLogData",
"(",
"'Ei'",
")",
".",
"value",
"originalWavelength",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLCollectData.py#L30-L53 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/bayesflow/python/ops/stochastic_graph.py | python | _StochasticValueType.stop_gradient | (self) | Whether the value should be wrapped in stop_gradient.
StochasticTensors must respect this property. | Whether the value should be wrapped in stop_gradient. | [
"Whether",
"the",
"value",
"should",
"be",
"wrapped",
"in",
"stop_gradient",
"."
] | def stop_gradient(self):
"""Whether the value should be wrapped in stop_gradient.
StochasticTensors must respect this property.
"""
pass | [
"def",
"stop_gradient",
"(",
"self",
")",
":",
"pass"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/bayesflow/python/ops/stochastic_graph.py#L144-L149 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/meta_graph.py | python | ops_used_by_graph_def | (graph_def) | return [op for op in used_ops if op not in name_to_function] | Collect the list of ops used by a graph.
Does not validate that the ops are all registered.
Args:
graph_def: A `GraphDef` proto, as from `graph.as_graph_def()`.
Returns:
A list of strings, each naming an op used by the graph. | Collect the list of ops used by a graph. | [
"Collect",
"the",
"list",
"of",
"ops",
"used",
"by",
"a",
"graph",
"."
] | def ops_used_by_graph_def(graph_def):
"""Collect the list of ops used by a graph.
Does not validate that the ops are all registered.
Args:
graph_def: A `GraphDef` proto, as from `graph.as_graph_def()`.
Returns:
A list of strings, each naming an op used by the graph.
"""
# Map function names to definitions
name_to_function = {}
for fun in graph_def.library.function:
name_to_function[fun.signature.name] = fun
# Collect the list of op names. Since functions can reference functions, we
# need a recursive traversal.
used_ops = set() # Includes both primitive ops and functions
functions_to_process = [] # A subset of used_ops
def mark_op_as_used(op):
if op not in used_ops and op in name_to_function:
functions_to_process.append(name_to_function[op])
used_ops.add(op)
for node in graph_def.node:
mark_op_as_used(node.op)
while functions_to_process:
fun = functions_to_process.pop()
for node in fun.node_def:
mark_op_as_used(node.op)
return [op for op in used_ops if op not in name_to_function] | [
"def",
"ops_used_by_graph_def",
"(",
"graph_def",
")",
":",
"# Map function names to definitions",
"name_to_function",
"=",
"{",
"}",
"for",
"fun",
"in",
"graph_def",
".",
"library",
".",
"function",
":",
"name_to_function",
"[",
"fun",
".",
"signature",
".",
"nam... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/meta_graph.py#L130-L163 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py | python | SequenceCategoricalColumn.num_buckets | (self) | return self.categorical_column.num_buckets | Returns number of buckets in this sparse feature. | Returns number of buckets in this sparse feature. | [
"Returns",
"number",
"of",
"buckets",
"in",
"this",
"sparse",
"feature",
"."
] | def num_buckets(self):
"""Returns number of buckets in this sparse feature."""
return self.categorical_column.num_buckets | [
"def",
"num_buckets",
"(",
"self",
")",
":",
"return",
"self",
".",
"categorical_column",
".",
"num_buckets"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L4517-L4519 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/pybind11/pybind11/setup_helpers.py | python | auto_cpp_level | (compiler) | Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows. | Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows. | [
"Return",
"the",
"max",
"supported",
"C",
"++",
"std",
"level",
"(",
"17",
"14",
"or",
"11",
")",
".",
"Returns",
"latest",
"on",
"Windows",
"."
] | def auto_cpp_level(compiler):
"""
Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows.
"""
if WIN:
return "latest"
global cpp_flag_cache
# If this has been previously calculated with the same args, return that
with cpp_cache_lock:
if cpp_flag_cache:
return cpp_flag_cache
levels = [17, 14, 11]
for level in levels:
if has_flag(compiler, STD_TMPL.format(level)):
with cpp_cache_lock:
cpp_flag_cache = level
return level
msg = "Unsupported compiler -- at least C++11 support is needed!"
raise RuntimeError(msg) | [
"def",
"auto_cpp_level",
"(",
"compiler",
")",
":",
"if",
"WIN",
":",
"return",
"\"latest\"",
"global",
"cpp_flag_cache",
"# If this has been previously calculated with the same args, return that",
"with",
"cpp_cache_lock",
":",
"if",
"cpp_flag_cache",
":",
"return",
"cpp_f... | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/pybind11/pybind11/setup_helpers.py#L256-L280 | ||
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/enum_type_wrapper.py | python | EnumTypeWrapper.items | (self) | return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | Return a list of the (name, value) pairs of the enum.
Returns:
A list of (str, int) pairs, in the order they were defined
in the .proto file. | Return a list of the (name, value) pairs of the enum. | [
"Return",
"a",
"list",
"of",
"the",
"(",
"name",
"value",
")",
"pairs",
"of",
"the",
"enum",
"."
] | def items(self):
"""Return a list of the (name, value) pairs of the enum.
Returns:
A list of (str, int) pairs, in the order they were defined
in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"value_descriptor",
".",
"name",
",",
"value_descriptor",
".",
"number",
")",
"for",
"value_descriptor",
"in",
"self",
".",
"_enum_type",
".",
"values",
"]"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/enum_type_wrapper.py#L96-L104 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/GuestHost/OpenGL/glapi_parser/apiutil.py | python | Alias | (funcName) | return d[funcName].alias | Return the function that the named function is an alias of.
Ex: Alias('DrawArraysEXT') = 'DrawArrays'. | Return the function that the named function is an alias of.
Ex: Alias('DrawArraysEXT') = 'DrawArrays'. | [
"Return",
"the",
"function",
"that",
"the",
"named",
"function",
"is",
"an",
"alias",
"of",
".",
"Ex",
":",
"Alias",
"(",
"DrawArraysEXT",
")",
"=",
"DrawArrays",
"."
] | def Alias(funcName):
"""Return the function that the named function is an alias of.
Ex: Alias('DrawArraysEXT') = 'DrawArrays'.
"""
d = GetFunctionDict()
return d[funcName].alias | [
"def",
"Alias",
"(",
"funcName",
")",
":",
"d",
"=",
"GetFunctionDict",
"(",
")",
"return",
"d",
"[",
"funcName",
"]",
".",
"alias"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/GuestHost/OpenGL/glapi_parser/apiutil.py#L332-L337 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/credentials.py | python | AssumeRoleWithWebIdentityCredentialFetcher.__init__ | (self, client_creator, web_identity_token_loader, role_arn,
extra_args=None, cache=None, expiry_window_seconds=None) | :type client_creator: callable
:param client_creator: A callable that creates a client taking
arguments like ``Session.create_client``.
:type web_identity_token_loader: callable
:param web_identity_token_loader: A callable that takes no arguments
and returns a web identity token str.
:type role_arn: str
:param role_arn: The ARN of the role to be assumed.
:type extra_args: dict
:param extra_args: Any additional arguments to add to the assume
role request using the format of the botocore operation.
Possible keys include, but may not be limited to,
DurationSeconds, Policy, SerialNumber, ExternalId and
RoleSessionName.
:type cache: dict
:param cache: An object that supports ``__getitem__``,
``__setitem__``, and ``__contains__``. An example of this is
the ``JSONFileCache`` class in aws-cli.
:type expiry_window_seconds: int
:param expiry_window_seconds: The amount of time, in seconds, | :type client_creator: callable
:param client_creator: A callable that creates a client taking
arguments like ``Session.create_client``. | [
":",
"type",
"client_creator",
":",
"callable",
":",
"param",
"client_creator",
":",
"A",
"callable",
"that",
"creates",
"a",
"client",
"taking",
"arguments",
"like",
"Session",
".",
"create_client",
"."
] | def __init__(self, client_creator, web_identity_token_loader, role_arn,
extra_args=None, cache=None, expiry_window_seconds=None):
"""
:type client_creator: callable
:param client_creator: A callable that creates a client taking
arguments like ``Session.create_client``.
:type web_identity_token_loader: callable
:param web_identity_token_loader: A callable that takes no arguments
and returns a web identity token str.
:type role_arn: str
:param role_arn: The ARN of the role to be assumed.
:type extra_args: dict
:param extra_args: Any additional arguments to add to the assume
role request using the format of the botocore operation.
Possible keys include, but may not be limited to,
DurationSeconds, Policy, SerialNumber, ExternalId and
RoleSessionName.
:type cache: dict
:param cache: An object that supports ``__getitem__``,
``__setitem__``, and ``__contains__``. An example of this is
the ``JSONFileCache`` class in aws-cli.
:type expiry_window_seconds: int
:param expiry_window_seconds: The amount of time, in seconds,
"""
self._web_identity_token_loader = web_identity_token_loader
super(AssumeRoleWithWebIdentityCredentialFetcher, self).__init__(
client_creator, role_arn, extra_args=extra_args,
cache=cache, expiry_window_seconds=expiry_window_seconds
) | [
"def",
"__init__",
"(",
"self",
",",
"client_creator",
",",
"web_identity_token_loader",
",",
"role_arn",
",",
"extra_args",
"=",
"None",
",",
"cache",
"=",
"None",
",",
"expiry_window_seconds",
"=",
"None",
")",
":",
"self",
".",
"_web_identity_token_loader",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/credentials.py#L820-L854 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/SimpleXMLRPCServer.py | python | list_public_methods | (obj) | return [member for member in dir(obj)
if not member.startswith('_') and
hasattr(getattr(obj, member), '__call__')] | Returns a list of attribute strings, found in the specified
object, which represent callable attributes | Returns a list of attribute strings, found in the specified
object, which represent callable attributes | [
"Returns",
"a",
"list",
"of",
"attribute",
"strings",
"found",
"in",
"the",
"specified",
"object",
"which",
"represent",
"callable",
"attributes"
] | def list_public_methods(obj):
"""Returns a list of attribute strings, found in the specified
object, which represent callable attributes"""
return [member for member in dir(obj)
if not member.startswith('_') and
hasattr(getattr(obj, member), '__call__')] | [
"def",
"list_public_methods",
"(",
"obj",
")",
":",
"return",
"[",
"member",
"for",
"member",
"in",
"dir",
"(",
"obj",
")",
"if",
"not",
"member",
".",
"startswith",
"(",
"'_'",
")",
"and",
"hasattr",
"(",
"getattr",
"(",
"obj",
",",
"member",
")",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/SimpleXMLRPCServer.py#L139-L145 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py | python | DebugAnalyzer.list_source | (self, args, screen_info=None) | return output | List Python source files that constructed nodes and tensors. | List Python source files that constructed nodes and tensors. | [
"List",
"Python",
"source",
"files",
"that",
"constructed",
"nodes",
"and",
"tensors",
"."
] | def list_source(self, args, screen_info=None):
"""List Python source files that constructed nodes and tensors."""
del screen_info # Unused.
parsed = self._arg_parsers["list_source"].parse_args(args)
source_list = source_utils.list_source_files_against_dump(
self._debug_dump,
path_regex_whitelist=parsed.path_filter,
node_name_regex_whitelist=parsed.node_name_filter)
top_lines = [
RL("List of source files that created nodes in this run", "bold")]
if parsed.path_filter:
top_lines.append(
RL("File path regex filter: \"%s\"" % parsed.path_filter))
if parsed.node_name_filter:
top_lines.append(
RL("Node name regex filter: \"%s\"" % parsed.node_name_filter))
top_lines.append(RL())
output = debugger_cli_common.rich_text_lines_from_rich_line_list(top_lines)
if not source_list:
output.append("[No source file information.]")
return output
output.extend(self._make_source_table(
[item for item in source_list if not item[1]], False))
output.extend(self._make_source_table(
[item for item in source_list if item[1]], True))
_add_main_menu(output, node_name=None)
return output | [
"def",
"list_source",
"(",
"self",
",",
"args",
",",
"screen_info",
"=",
"None",
")",
":",
"del",
"screen_info",
"# Unused.",
"parsed",
"=",
"self",
".",
"_arg_parsers",
"[",
"\"list_source\"",
"]",
".",
"parse_args",
"(",
"args",
")",
"source_list",
"=",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/cli/analyzer_cli.py#L1242-L1271 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | isChar | (ch) | return ret | This function is DEPRECATED. Use xmlIsChar_ch or xmlIsCharQ
instead | This function is DEPRECATED. Use xmlIsChar_ch or xmlIsCharQ
instead | [
"This",
"function",
"is",
"DEPRECATED",
".",
"Use",
"xmlIsChar_ch",
"or",
"xmlIsCharQ",
"instead"
] | def isChar(ch):
"""This function is DEPRECATED. Use xmlIsChar_ch or xmlIsCharQ
instead """
ret = libxml2mod.xmlIsChar(ch)
return ret | [
"def",
"isChar",
"(",
"ch",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlIsChar",
"(",
"ch",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L251-L255 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/email/message.py | python | Message.set_charset | (self, charset) | Set the charset of the payload to a given character set.
charset can be a Charset instance, a string naming a character set, or
None. If it is a string it will be converted to a Charset instance.
If charset is None, the charset parameter will be removed from the
Content-Type field. Anything else will generate a TypeError.
The message will be assumed to be of type text/* encoded with
charset.input_charset. It will be converted to charset.output_charset
and encoded properly, if needed, when generating the plain text
representation of the message. MIME headers (MIME-Version,
Content-Type, Content-Transfer-Encoding) will be added as needed. | Set the charset of the payload to a given character set. | [
"Set",
"the",
"charset",
"of",
"the",
"payload",
"to",
"a",
"given",
"character",
"set",
"."
] | def set_charset(self, charset):
"""Set the charset of the payload to a given character set.
charset can be a Charset instance, a string naming a character set, or
None. If it is a string it will be converted to a Charset instance.
If charset is None, the charset parameter will be removed from the
Content-Type field. Anything else will generate a TypeError.
The message will be assumed to be of type text/* encoded with
charset.input_charset. It will be converted to charset.output_charset
and encoded properly, if needed, when generating the plain text
representation of the message. MIME headers (MIME-Version,
Content-Type, Content-Transfer-Encoding) will be added as needed.
"""
if charset is None:
self.del_param('charset')
self._charset = None
return
if not isinstance(charset, Charset):
charset = Charset(charset)
self._charset = charset
if 'MIME-Version' not in self:
self.add_header('MIME-Version', '1.0')
if 'Content-Type' not in self:
self.add_header('Content-Type', 'text/plain',
charset=charset.get_output_charset())
else:
self.set_param('charset', charset.get_output_charset())
if charset != charset.get_output_charset():
self._payload = charset.body_encode(self._payload)
if 'Content-Transfer-Encoding' not in self:
cte = charset.get_body_encoding()
try:
cte(self)
except TypeError:
# This 'if' is for backward compatibility, it allows unicode
# through even though that won't work correctly if the
# message is serialized.
payload = self._payload
if payload:
try:
payload = payload.encode('ascii', 'surrogateescape')
except UnicodeError:
payload = payload.encode(charset.output_charset)
self._payload = charset.body_encode(payload)
self.add_header('Content-Transfer-Encoding', cte) | [
"def",
"set_charset",
"(",
"self",
",",
"charset",
")",
":",
"if",
"charset",
"is",
"None",
":",
"self",
".",
"del_param",
"(",
"'charset'",
")",
"self",
".",
"_charset",
"=",
"None",
"return",
"if",
"not",
"isinstance",
"(",
"charset",
",",
"Charset",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/message.py#L323-L368 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | PBXProject.RootGroupsTakeOverOnlyChildren | (self, recurse=False) | Calls TakeOverOnlyChild for all groups in the main group. | Calls TakeOverOnlyChild for all groups in the main group. | [
"Calls",
"TakeOverOnlyChild",
"for",
"all",
"groups",
"in",
"the",
"main",
"group",
"."
] | def RootGroupsTakeOverOnlyChildren(self, recurse=False):
"""Calls TakeOverOnlyChild for all groups in the main group."""
for group in self._properties['mainGroup']._properties['children']:
if isinstance(group, PBXGroup):
group.TakeOverOnlyChild(recurse) | [
"def",
"RootGroupsTakeOverOnlyChildren",
"(",
"self",
",",
"recurse",
"=",
"False",
")",
":",
"for",
"group",
"in",
"self",
".",
"_properties",
"[",
"'mainGroup'",
"]",
".",
"_properties",
"[",
"'children'",
"]",
":",
"if",
"isinstance",
"(",
"group",
",",
... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L2632-L2637 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py | python | _ClassBuilder.build_class | (self) | Finalize class based on the accumulated configuration.
Builder cannot be used after calling this method. | Finalize class based on the accumulated configuration. | [
"Finalize",
"class",
"based",
"on",
"the",
"accumulated",
"configuration",
"."
] | def build_class(self):
"""
Finalize class based on the accumulated configuration.
Builder cannot be used after calling this method.
"""
if self._slots is True:
return self._create_slots_class()
else:
return self._patch_original_class() | [
"def",
"build_class",
"(",
"self",
")",
":",
"if",
"self",
".",
"_slots",
"is",
"True",
":",
"return",
"self",
".",
"_create_slots_class",
"(",
")",
"else",
":",
"return",
"self",
".",
"_patch_original_class",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/attr/_make.py#L489-L498 | ||
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/tools/scan-build-py/libscanbuild/__init__.py | python | run_command | (command, cwd=None) | Run a given command and report the execution.
:param command: array of tokens
:param cwd: the working directory where the command will be executed
:return: output of the command | Run a given command and report the execution. | [
"Run",
"a",
"given",
"command",
"and",
"report",
"the",
"execution",
"."
] | def run_command(command, cwd=None):
""" Run a given command and report the execution.
:param command: array of tokens
:param cwd: the working directory where the command will be executed
:return: output of the command
"""
def decode_when_needed(result):
""" check_output returns bytes or string depend on python version """
return result.decode('utf-8') if isinstance(result, bytes) else result
try:
directory = os.path.abspath(cwd) if cwd else os.getcwd()
logging.debug('exec command %s in %s', command, directory)
output = subprocess.check_output(command,
cwd=directory,
stderr=subprocess.STDOUT)
return decode_when_needed(output).splitlines()
except subprocess.CalledProcessError as ex:
ex.output = decode_when_needed(ex.output).splitlines()
raise ex | [
"def",
"run_command",
"(",
"command",
",",
"cwd",
"=",
"None",
")",
":",
"def",
"decode_when_needed",
"(",
"result",
")",
":",
"\"\"\" check_output returns bytes or string depend on python version \"\"\"",
"return",
"result",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
... | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/tools/scan-build-py/libscanbuild/__init__.py#L59-L79 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/httputil.py | python | HTTPConnection.finish | (self) | Indicates that the last body data has been written. | Indicates that the last body data has been written. | [
"Indicates",
"that",
"the",
"last",
"body",
"data",
"has",
"been",
"written",
"."
] | def finish(self) -> None:
"""Indicates that the last body data has been written.
"""
raise NotImplementedError() | [
"def",
"finish",
"(",
"self",
")",
"->",
"None",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/httputil.py#L604-L607 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/tbb_2020.3/python/tbb/pool.py | python | Pool.apply | (self, func, args=(), kwds=dict()) | return self.apply_async(func, args, kwds).get() | Equivalent of the apply() builtin function. It blocks till
the result is ready. | Equivalent of the apply() builtin function. It blocks till
the result is ready. | [
"Equivalent",
"of",
"the",
"apply",
"()",
"builtin",
"function",
".",
"It",
"blocks",
"till",
"the",
"result",
"is",
"ready",
"."
] | def apply(self, func, args=(), kwds=dict()):
"""Equivalent of the apply() builtin function. It blocks till
the result is ready."""
return self.apply_async(func, args, kwds).get() | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"args",
"=",
"(",
")",
",",
"kwds",
"=",
"dict",
"(",
")",
")",
":",
"return",
"self",
".",
"apply_async",
"(",
"func",
",",
"args",
",",
"kwds",
")",
".",
"get",
"(",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/tbb_2020.3/python/tbb/pool.py#L101-L104 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | PlatformInformation.__eq__ | (*args, **kwargs) | return _misc_.PlatformInformation___eq__(*args, **kwargs) | __eq__(self, PlatformInformation t) -> bool | __eq__(self, PlatformInformation t) -> bool | [
"__eq__",
"(",
"self",
"PlatformInformation",
"t",
")",
"-",
">",
"bool"
] | def __eq__(*args, **kwargs):
"""__eq__(self, PlatformInformation t) -> bool"""
return _misc_.PlatformInformation___eq__(*args, **kwargs) | [
"def",
"__eq__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"PlatformInformation___eq__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1053-L1055 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/image_ops.py | python | convert_image_dtype | (image, dtype, saturate=False, name=None) | Convert `image` to `dtype`, scaling its values if needed.
Images that are represented using floating point values are expected to have
values in the range [0,1). Image data stored in integer data types are
expected to have values in the range `[0,MAX]`, where `MAX` is the largest
positive representable number for the data type.
This op converts between data types, scaling the values appropriately before
casting.
Note that converting from floating point inputs to integer types may lead to
over/underflow problems. Set saturate to `True` to avoid such problem in
problematic conversions. If enabled, saturation will clip the output into the
allowed range before performing a potentially dangerous cast (and only before
performing such a cast, i.e., when casting from a floating point to an integer
type, and when casting from a signed to an unsigned type; `saturate` has no
effect on casts between floats, or on casts that increase the type's range).
Args:
image: An image.
dtype: A `DType` to convert `image` to.
saturate: If `True`, clip the input before casting (if necessary).
name: A name for this operation (optional).
Returns:
`image`, converted to `dtype`. | Convert `image` to `dtype`, scaling its values if needed. | [
"Convert",
"image",
"to",
"dtype",
"scaling",
"its",
"values",
"if",
"needed",
"."
] | def convert_image_dtype(image, dtype, saturate=False, name=None):
"""Convert `image` to `dtype`, scaling its values if needed.
Images that are represented using floating point values are expected to have
values in the range [0,1). Image data stored in integer data types are
expected to have values in the range `[0,MAX]`, where `MAX` is the largest
positive representable number for the data type.
This op converts between data types, scaling the values appropriately before
casting.
Note that converting from floating point inputs to integer types may lead to
over/underflow problems. Set saturate to `True` to avoid such problem in
problematic conversions. If enabled, saturation will clip the output into the
allowed range before performing a potentially dangerous cast (and only before
performing such a cast, i.e., when casting from a floating point to an integer
type, and when casting from a signed to an unsigned type; `saturate` has no
effect on casts between floats, or on casts that increase the type's range).
Args:
image: An image.
dtype: A `DType` to convert `image` to.
saturate: If `True`, clip the input before casting (if necessary).
name: A name for this operation (optional).
Returns:
`image`, converted to `dtype`.
"""
image = ops.convert_to_tensor(image, name='image')
if dtype == image.dtype:
return array_ops.identity(image, name=name)
with ops.op_scope([image], name, 'convert_image') as name:
# Both integer: use integer multiplication in the larger range
if image.dtype.is_integer and dtype.is_integer:
scale_in = image.dtype.max
scale_out = dtype.max
if scale_in > scale_out:
# Scaling down, scale first, then cast. The scaling factor will
# cause in.max to be mapped to above out.max but below out.max+1,
# so that the output is safely in the supported range.
scale = (scale_in + 1) // (scale_out + 1)
scaled = math_ops.div(image, scale)
if saturate:
return math_ops.saturate_cast(scaled, dtype, name=name)
else:
return math_ops.cast(scaled, dtype, name=name)
else:
# Scaling up, cast first, then scale. The scale will not map in.max to
# out.max, but converting back and forth should result in no change.
if saturate:
cast = math_ops.saturate_cast(scaled, dtype)
else:
cast = math_ops.cast(image, dtype)
scale = (scale_out + 1) // (scale_in + 1)
return math_ops.mul(cast, scale, name=name)
elif image.dtype.is_floating and dtype.is_floating:
# Both float: Just cast, no possible overflows in the allowed ranges.
# Note: We're ignoreing float overflows. If your image dynamic range
# exceeds float range you're on your own.
return math_ops.cast(image, dtype, name=name)
else:
if image.dtype.is_integer:
# Converting to float: first cast, then scale. No saturation possible.
cast = math_ops.cast(image, dtype)
scale = 1. / image.dtype.max
return math_ops.mul(cast, scale, name=name)
else:
# Converting from float: first scale, then cast
scale = dtype.max + 0.5 # avoid rounding problems in the cast
scaled = math_ops.mul(image, scale)
if saturate:
return math_ops.saturate_cast(scaled, dtype, name=name)
else:
return math_ops.cast(scaled, dtype, name=name) | [
"def",
"convert_image_dtype",
"(",
"image",
",",
"dtype",
",",
"saturate",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"image",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"image",
",",
"name",
"=",
"'image'",
")",
"if",
"dtype",
"==",
"image",
".... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/image_ops.py#L1048-L1123 | ||
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Node.py | python | Node.isdir | (self) | return os.path.isdir(self.abspath()) | Returns whether the Node represents a folder
:rtype: bool | Returns whether the Node represents a folder | [
"Returns",
"whether",
"the",
"Node",
"represents",
"a",
"folder"
] | def isdir(self):
"""
Returns whether the Node represents a folder
:rtype: bool
"""
return os.path.isdir(self.abspath()) | [
"def",
"isdir",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"abspath",
"(",
")",
")"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Node.py#L274-L280 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/backend.py | python | softmax | (x) | return nn.softmax(x) | Softmax of a tensor.
Arguments:
x: A tensor or variable.
Returns:
A tensor. | Softmax of a tensor. | [
"Softmax",
"of",
"a",
"tensor",
"."
] | def softmax(x):
"""Softmax of a tensor.
Arguments:
x: A tensor or variable.
Returns:
A tensor.
"""
return nn.softmax(x) | [
"def",
"softmax",
"(",
"x",
")",
":",
"return",
"nn",
".",
"softmax",
"(",
"x",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L2841-L2850 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/FeatMaps/FeatMapUtils.py | python | MergeFeatPoints | (fm, mergeMetric=MergeMetric.NoMerge, mergeTol=1.5,
dirMergeMode=DirMergeMode.NoMerge, mergeMethod=MergeMethod.WeightedAverage,
compatFunc=familiesMatch) | return res | NOTE that mergeTol is a max value for merging when using distance-based
merging and a min value when using score-based merging.
returns whether or not any points were actually merged | [] | def MergeFeatPoints(fm, mergeMetric=MergeMetric.NoMerge, mergeTol=1.5,
dirMergeMode=DirMergeMode.NoMerge, mergeMethod=MergeMethod.WeightedAverage,
compatFunc=familiesMatch):
"""
NOTE that mergeTol is a max value for merging when using distance-based
merging and a min value when using score-based merging.
returns whether or not any points were actually merged
"""
MergeMetric.valid(mergeMetric)
MergeMethod.valid(mergeMethod)
DirMergeMode.valid(dirMergeMode)
res = False
if mergeMetric == MergeMetric.NoMerge:
return res
dists = GetFeatFeatDistMatrix(fm, mergeMetric, mergeTol, dirMergeMode, compatFunc)
distOrders = [None] * len(dists)
for i, distV in enumerate(dists):
distOrders[i] = []
for j, dist in enumerate(distV):
if dist < mergeTol:
distOrders[i].append((dist, j))
distOrders[i].sort()
# print('distOrders:')
# print(distOrders)
# we now know the "distances" and have rank-ordered list of
# each point's neighbors. Work with that.
# progressively merge nearest neighbors until there
# are no more points left to merge
featsInPlay = list(range(fm.GetNumFeatures()))
featsToRemove = []
# print '--------------------------------'
while featsInPlay:
# find two features who are mutual nearest neighbors:
fipCopy = featsInPlay[:]
for fi in fipCopy:
# print('>>>',fi,fipCopy,featsInPlay)
# print('\t',distOrders[fi])
mergeThem = False
if not distOrders[fi]:
featsInPlay.remove(fi)
continue
dist, nbr = distOrders[fi][0]
if nbr not in featsInPlay:
continue
if distOrders[nbr][0][1] == fi:
# print 'direct:',fi,nbr
mergeThem = True
else:
# it may be that there are several points at about the same distance,
# check for that now
if feq(distOrders[nbr][0][0], dist):
for distJ, nbrJ in distOrders[nbr][1:]:
if feq(dist, distJ):
if nbrJ == fi:
# print 'indirect: ',fi,nbr
mergeThem = True
break
else:
break
# print ' bottom:',mergeThem
if mergeThem:
break
if mergeThem:
res = True
featI = fm.GetFeature(fi)
nbrFeat = fm.GetFeature(nbr)
if mergeMethod == MergeMethod.WeightedAverage:
newPos = featI.GetPos() * featI.weight + nbrFeat.GetPos() * nbrFeat.weight
newPos /= (featI.weight + nbrFeat.weight)
newWeight = (featI.weight + nbrFeat.weight) / 2
elif mergeMethod == MergeMethod.Average:
newPos = featI.GetPos() + nbrFeat.GetPos()
newPos /= 2
newWeight = (featI.weight + nbrFeat.weight) / 2
elif mergeMethod == MergeMethod.UseLarger:
if featI.weight > nbrFeat.weight:
newPos = featI.GetPos()
newWeight = featI.weight
else:
newPos = nbrFeat.GetPos()
newWeight = nbrFeat.weight
featI.SetPos(newPos)
featI.weight = newWeight
# nbr and fi are no longer valid targets:
# print 'nbr done:',nbr,featsToRemove,featsInPlay
featsToRemove.append(nbr)
featsInPlay.remove(fi)
featsInPlay.remove(nbr)
for nbrList in distOrders:
try:
nbrList.remove(fi)
except ValueError:
pass
try:
nbrList.remove(nbr)
except ValueError:
pass
else:
# print ">>>> Nothing found, abort"
break
featsToRemove.sort()
for i, fIdx in enumerate(featsToRemove):
fm.DropFeature(fIdx - i)
return res | [
"def",
"MergeFeatPoints",
"(",
"fm",
",",
"mergeMetric",
"=",
"MergeMetric",
".",
"NoMerge",
",",
"mergeTol",
"=",
"1.5",
",",
"dirMergeMode",
"=",
"DirMergeMode",
".",
"NoMerge",
",",
"mergeMethod",
"=",
"MergeMethod",
".",
"WeightedAverage",
",",
"compatFunc",... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/FeatMaps/FeatMapUtils.py#L111-L225 | ||
qt/qt | 0a2f2382541424726168804be2c90b91381608c6 | src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/common.py | python | ExceptionAppend | (e, msg) | Append a message to the given exception's message. | Append a message to the given exception's message. | [
"Append",
"a",
"message",
"to",
"the",
"given",
"exception",
"s",
"message",
"."
] | def ExceptionAppend(e, msg):
"""Append a message to the given exception's message."""
if not e.args:
e.args = (msg,)
elif len(e.args) == 1:
e.args = (str(e.args[0]) + ' ' + msg,)
else:
e.args = (str(e.args[0]) + ' ' + msg,) + e.args[1:] | [
"def",
"ExceptionAppend",
"(",
"e",
",",
"msg",
")",
":",
"if",
"not",
"e",
".",
"args",
":",
"e",
".",
"args",
"=",
"(",
"msg",
",",
")",
"elif",
"len",
"(",
"e",
".",
"args",
")",
"==",
"1",
":",
"e",
".",
"args",
"=",
"(",
"str",
"(",
... | https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/common.py#L14-L21 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/optimize_for_inference_lib.py | python | optimize_for_inference | (input_graph_def, input_node_names, output_node_names,
placeholder_type_enum, toco_compatible=False) | return optimized_graph_def | Applies a series of inference optimizations on the input graph.
Args:
input_graph_def: A GraphDef containing a training model.
input_node_names: A list of names of the nodes that are fed inputs during
inference.
output_node_names: A list of names of the nodes that produce the final
results.
placeholder_type_enum: The AttrValue enum for the placeholder data type, or
a list that specifies one value per input node name.
toco_compatible: Boolean, if True, only runs optimizations that result in
TOCO compatible graph operations (default=False).
Returns:
An optimized version of the input graph. | Applies a series of inference optimizations on the input graph. | [
"Applies",
"a",
"series",
"of",
"inference",
"optimizations",
"on",
"the",
"input",
"graph",
"."
] | def optimize_for_inference(input_graph_def, input_node_names, output_node_names,
placeholder_type_enum, toco_compatible=False):
"""Applies a series of inference optimizations on the input graph.
Args:
input_graph_def: A GraphDef containing a training model.
input_node_names: A list of names of the nodes that are fed inputs during
inference.
output_node_names: A list of names of the nodes that produce the final
results.
placeholder_type_enum: The AttrValue enum for the placeholder data type, or
a list that specifies one value per input node name.
toco_compatible: Boolean, if True, only runs optimizations that result in
TOCO compatible graph operations (default=False).
Returns:
An optimized version of the input graph.
"""
ensure_graph_is_valid(input_graph_def)
optimized_graph_def = input_graph_def
optimized_graph_def = strip_unused_lib.strip_unused(
optimized_graph_def, input_node_names, output_node_names,
placeholder_type_enum)
optimized_graph_def = graph_util.remove_training_nodes(
optimized_graph_def, output_node_names)
optimized_graph_def = fold_batch_norms(optimized_graph_def)
if not toco_compatible:
optimized_graph_def = fuse_resize_and_conv(optimized_graph_def,
output_node_names)
ensure_graph_is_valid(optimized_graph_def)
return optimized_graph_def | [
"def",
"optimize_for_inference",
"(",
"input_graph_def",
",",
"input_node_names",
",",
"output_node_names",
",",
"placeholder_type_enum",
",",
"toco_compatible",
"=",
"False",
")",
":",
"ensure_graph_is_valid",
"(",
"input_graph_def",
")",
"optimized_graph_def",
"=",
"inp... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tools/optimize_for_inference_lib.py#L89-L119 | |
bayandin/chromedriver | d40a2092b50f2fca817221eeb5ea093e0e642c10 | log_replay/client_replay.py | python | CommandSequence._IngestRealResponse | (self, response) | Process the actual response from the previously issued command.
Ingests the given response that came from calling the last command on
the running ChromeDriver replay instance. This is the step where the
session and element IDs are matched between |response| and the logged
response.
Args:
response: Python dict of the real response to be analyzed for IDs. | Process the actual response from the previously issued command. | [
"Process",
"the",
"actual",
"response",
"from",
"the",
"previously",
"issued",
"command",
"."
] | def _IngestRealResponse(self, response):
"""Process the actual response from the previously issued command.
Ingests the given response that came from calling the last command on
the running ChromeDriver replay instance. This is the step where the
session and element IDs are matched between |response| and the logged
response.
Args:
response: Python dict of the real response to be analyzed for IDs.
"""
if "value" in response and self._staged_logged_ids:
real_ids = _GetAnyElementIds(response["value"])
if real_ids and self._staged_logged_ids:
for id_old, id_new in zip(self._staged_logged_ids, real_ids):
self._id_map[id_old] = id_new
self._staged_logged_ids = None
# In W3C format, the http response is a single key dict,
# where the value is None, a single value, or another dictionary
# sessionId is contained in the nested dictionary
if (self._staged_logged_session_id
and "value" in response and response["value"]
and isinstance(response["value"], dict)
and "sessionId" in response["value"]):
self._id_map[self._staged_logged_session_id] = (
response["value"]["sessionId"])
self._staged_logged_session_id = None | [
"def",
"_IngestRealResponse",
"(",
"self",
",",
"response",
")",
":",
"if",
"\"value\"",
"in",
"response",
"and",
"self",
".",
"_staged_logged_ids",
":",
"real_ids",
"=",
"_GetAnyElementIds",
"(",
"response",
"[",
"\"value\"",
"]",
")",
"if",
"real_ids",
"and"... | https://github.com/bayandin/chromedriver/blob/d40a2092b50f2fca817221eeb5ea093e0e642c10/log_replay/client_replay.py#L750-L777 | ||
OGRECave/ogre-next | 287307980e6de8910f04f3cc0994451b075071fd | Tools/BlenderExport/ogrepkg/gui.py | python | Size.__init__ | (self, preferredSize=None, minimumSize=None, maximumSize=None) | return | Constructor.
A size hint is a list of integers <code>[width, height]</code>.
@param preferredSize Default <code>[0,0]</code>.
@param minimumSize Default <code>[0,0]</code>.
@param maximumSize Default <code>[Size.INFINITY, Size.INFINITY]</code>. | Constructor.
A size hint is a list of integers <code>[width, height]</code>. | [
"Constructor",
".",
"A",
"size",
"hint",
"is",
"a",
"list",
"of",
"integers",
"<code",
">",
"[",
"width",
"height",
"]",
"<",
"/",
"code",
">",
"."
] | def __init__(self, preferredSize=None, minimumSize=None, maximumSize=None):
"""Constructor.
A size hint is a list of integers <code>[width, height]</code>.
@param preferredSize Default <code>[0,0]</code>.
@param minimumSize Default <code>[0,0]</code>.
@param maximumSize Default <code>[Size.INFINITY, Size.INFINITY]</code>.
"""
self.preferredSize = preferredSize or [0, 0]
if minimumSize:
self.minimumSize = minimumSize
elif ((self.preferredSize[0] < Size.INFINITY) and (self.preferredSize[1] < Size.INFINITY)):
self.minimumSize = self.preferredSize[:]
else:
self.minimumSize = [0, 0]
if preferredSize:
self.maximumSize = maximumSize or self.preferredSize[:]
else:
self.maximumSize = maximumSize or [Size.INFINITY, Size.INFINITY]
return | [
"def",
"__init__",
"(",
"self",
",",
"preferredSize",
"=",
"None",
",",
"minimumSize",
"=",
"None",
",",
"maximumSize",
"=",
"None",
")",
":",
"self",
".",
"preferredSize",
"=",
"preferredSize",
"or",
"[",
"0",
",",
"0",
"]",
"if",
"minimumSize",
":",
... | https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/BlenderExport/ogrepkg/gui.py#L62-L82 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/reveal-cards-in-increasing-order.py | python | Solution.deckRevealedIncreasing | (self, deck) | return list(d) | :type deck: List[int]
:rtype: List[int] | :type deck: List[int]
:rtype: List[int] | [
":",
"type",
"deck",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def deckRevealedIncreasing(self, deck):
"""
:type deck: List[int]
:rtype: List[int]
"""
d = collections.deque()
deck.sort(reverse=True)
for i in deck:
if d:
d.appendleft(d.pop())
d.appendleft(i)
return list(d) | [
"def",
"deckRevealedIncreasing",
"(",
"self",
",",
"deck",
")",
":",
"d",
"=",
"collections",
".",
"deque",
"(",
")",
"deck",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"for",
"i",
"in",
"deck",
":",
"if",
"d",
":",
"d",
".",
"appendleft",
"(",... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/reveal-cards-in-increasing-order.py#L8-L19 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py | python | DescriptorPool.__init__ | (self, descriptor_db=None) | Initializes a Pool of proto buffs.
The descriptor_db argument to the constructor is provided to allow
specialized file descriptor proto lookup code to be triggered on demand. An
example would be an implementation which will read and compile a file
specified in a call to FindFileByName() and not require the call to Add()
at all. Results from this database will be cached internally here as well.
Args:
descriptor_db: A secondary source of file descriptors. | Initializes a Pool of proto buffs. | [
"Initializes",
"a",
"Pool",
"of",
"proto",
"buffs",
"."
] | def __init__(self, descriptor_db=None):
"""Initializes a Pool of proto buffs.
The descriptor_db argument to the constructor is provided to allow
specialized file descriptor proto lookup code to be triggered on demand. An
example would be an implementation which will read and compile a file
specified in a call to FindFileByName() and not require the call to Add()
at all. Results from this database will be cached internally here as well.
Args:
descriptor_db: A secondary source of file descriptors.
"""
self._internal_db = descriptor_database.DescriptorDatabase()
self._descriptor_db = descriptor_db
self._descriptors = {}
self._enum_descriptors = {}
self._service_descriptors = {}
self._file_descriptors = {}
self._toplevel_extensions = {}
# TODO(jieluo): Remove _file_desc_by_toplevel_extension when
# FieldDescriptor.file is added in code gen.
self._file_desc_by_toplevel_extension = {}
# We store extensions in two two-level mappings: The first key is the
# descriptor of the message being extended, the second key is the extension
# full name or its tag number.
self._extensions_by_name = collections.defaultdict(dict)
self._extensions_by_number = collections.defaultdict(dict) | [
"def",
"__init__",
"(",
"self",
",",
"descriptor_db",
"=",
"None",
")",
":",
"self",
".",
"_internal_db",
"=",
"descriptor_database",
".",
"DescriptorDatabase",
"(",
")",
"self",
".",
"_descriptor_db",
"=",
"descriptor_db",
"self",
".",
"_descriptors",
"=",
"{... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/descriptor_pool.py#L110-L137 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/scons/getversion.py | python | _IsGitDescribeFirstParentSupported | () | return False | Checks whether --first-parent parameter is valid for the
version of git available | Checks whether --first-parent parameter is valid for the
version of git available | [
"Checks",
"whether",
"--",
"first",
"-",
"parent",
"parameter",
"is",
"valid",
"for",
"the",
"version",
"of",
"git",
"available"
] | def _IsGitDescribeFirstParentSupported():
"""Checks whether --first-parent parameter is valid for the
version of git available"""
try:
repo = _GetRepository()
repo.git.describe('--first-parent')
return True
except git.exc.GitCommandError:
pass
return False | [
"def",
"_IsGitDescribeFirstParentSupported",
"(",
")",
":",
"try",
":",
"repo",
"=",
"_GetRepository",
"(",
")",
"repo",
".",
"git",
".",
"describe",
"(",
"'--first-parent'",
")",
"return",
"True",
"except",
"git",
".",
"exc",
".",
"GitCommandError",
":",
"p... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/scons/getversion.py#L217-L228 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | third_party/Python/module/pexpect-4.6/pexpect/exceptions.py | python | ExceptionPexpect.get_trace | (self) | return ''.join(tblist) | This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. | This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. | [
"This",
"returns",
"an",
"abbreviated",
"stack",
"trace",
"with",
"lines",
"that",
"only",
"concern",
"the",
"caller",
".",
"In",
"other",
"words",
"the",
"stack",
"trace",
"inside",
"the",
"Pexpect",
"module",
"is",
"not",
"included",
"."
] | def get_trace(self):
'''This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. '''
tblist = traceback.extract_tb(sys.exc_info()[2])
tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
and ('pexpect/expect' not in item[0])]
tblist = traceback.format_list(tblist)
return ''.join(tblist) | [
"def",
"get_trace",
"(",
"self",
")",
":",
"tblist",
"=",
"traceback",
".",
"extract_tb",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
"tblist",
"=",
"[",
"item",
"for",
"item",
"in",
"tblist",
"if",
"(",
"'pexpect/__init__'",
"not",
"i... | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/exceptions.py#L17-L26 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/gluon/trainer.py | python | Trainer._reset_kvstore | (self) | Reset kvstore. | Reset kvstore. | [
"Reset",
"kvstore",
"."
] | def _reset_kvstore(self):
"""Reset kvstore."""
if self._kvstore and 'dist' in self._kvstore.type:
raise RuntimeError("Cannot reset distributed KVStore.")
self._kv_initialized = False
self._kvstore = None
self._distributed = None
self._update_on_kvstore = None
self._params_to_init = [param for param in self._params] | [
"def",
"_reset_kvstore",
"(",
"self",
")",
":",
"if",
"self",
".",
"_kvstore",
"and",
"'dist'",
"in",
"self",
".",
"_kvstore",
".",
"type",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot reset distributed KVStore.\"",
")",
"self",
".",
"_kv_initialized",
"=",
"F... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/gluon/trainer.py#L159-L167 | ||
BDLDev/bdlauncher | d10fb098852ebcf9fb71afb23052a463ee7b5d0a | scripts/cppheaderparser.py | python | Resolver.resolve_type | ( self, string, result ) | keeps track of useful things like: how many pointers, number of typedefs, is fundamental or a class, etc... | keeps track of useful things like: how many pointers, number of typedefs, is fundamental or a class, etc... | [
"keeps",
"track",
"of",
"useful",
"things",
"like",
":",
"how",
"many",
"pointers",
"number",
"of",
"typedefs",
"is",
"fundamental",
"or",
"a",
"class",
"etc",
"..."
] | def resolve_type( self, string, result ): # recursive
'''
keeps track of useful things like: how many pointers, number of typedefs, is fundamental or a class, etc...
'''
## be careful with templates, what is inside <something*> can be a pointer but the overall type is not a pointer
## these come before a template
s = string.split('<')[0]
result[ 'constant' ] += s.split().count('const')
result[ 'static' ] += s.split().count('static')
result[ 'mutable' ] = 'mutable' in s.split()
## these come after a template
s = string.split('>')[-1]
result[ 'pointer' ] += s.count('*')
result[ 'reference' ] += s.count('&')
x = string; alias = False
for a in '* & const static mutable'.split(): x = x.replace(a,'')
for y in x.split():
if y not in self.C_FUNDAMENTAL: alias = y; break
#if alias == 'class':
# result['class'] = result['name'] # forward decl of class
# result['forward_decl'] = True
if alias == '__extension__': result['fundamental_extension'] = True
elif alias:
result['aliases'].append( alias )
if alias in C99_NONSTANDARD:
result['type'] = C99_NONSTANDARD[ alias ]
result['typedef'] = alias
result['typedefs'] += 1
elif alias in self.typedefs:
result['typedefs'] += 1
result['typedef'] = alias
self.resolve_type( self.typedefs[alias], result )
elif alias in self.classes:
klass = self.classes[alias]; result['fundamental'] = False
result['class'] = klass
result['unresolved'] = False
else: result['unresolved'] = True
else:
result['fundamental'] = True
result['unresolved'] = False | [
"def",
"resolve_type",
"(",
"self",
",",
"string",
",",
"result",
")",
":",
"# recursive",
"## be careful with templates, what is inside <something*> can be a pointer but the overall type is not a pointer",
"## these come before a template",
"s",
"=",
"string",
".",
"split",
"(",... | https://github.com/BDLDev/bdlauncher/blob/d10fb098852ebcf9fb71afb23052a463ee7b5d0a/scripts/cppheaderparser.py#L1280-L1323 | ||
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | tools/infer/utility.py | python | get_rotate_crop_image | (img, points) | return dst_img | img_height, img_width = img.shape[0:2]
left = int(np.min(points[:, 0]))
right = int(np.max(points[:, 0]))
top = int(np.min(points[:, 1]))
bottom = int(np.max(points[:, 1]))
img_crop = img[top:bottom, left:right, :].copy()
points[:, 0] = points[:, 0] - left
points[:, 1] = points[:, 1] - top | img_height, img_width = img.shape[0:2]
left = int(np.min(points[:, 0]))
right = int(np.max(points[:, 0]))
top = int(np.min(points[:, 1]))
bottom = int(np.max(points[:, 1]))
img_crop = img[top:bottom, left:right, :].copy()
points[:, 0] = points[:, 0] - left
points[:, 1] = points[:, 1] - top | [
"img_height",
"img_width",
"=",
"img",
".",
"shape",
"[",
"0",
":",
"2",
"]",
"left",
"=",
"int",
"(",
"np",
".",
"min",
"(",
"points",
"[",
":",
"0",
"]",
"))",
"right",
"=",
"int",
"(",
"np",
".",
"max",
"(",
"points",
"[",
":",
"0",
"]",
... | def get_rotate_crop_image(img, points):
'''
img_height, img_width = img.shape[0:2]
left = int(np.min(points[:, 0]))
right = int(np.max(points[:, 0]))
top = int(np.min(points[:, 1]))
bottom = int(np.max(points[:, 1]))
img_crop = img[top:bottom, left:right, :].copy()
points[:, 0] = points[:, 0] - left
points[:, 1] = points[:, 1] - top
'''
assert len(points) == 4, "shape of points must be 4*2"
img_crop_width = int(
max(
np.linalg.norm(points[0] - points[1]),
np.linalg.norm(points[2] - points[3])))
img_crop_height = int(
max(
np.linalg.norm(points[0] - points[3]),
np.linalg.norm(points[1] - points[2])))
pts_std = np.float32([[0, 0], [img_crop_width, 0],
[img_crop_width, img_crop_height],
[0, img_crop_height]])
M = cv2.getPerspectiveTransform(points, pts_std)
dst_img = cv2.warpPerspective(
img,
M, (img_crop_width, img_crop_height),
borderMode=cv2.BORDER_REPLICATE,
flags=cv2.INTER_CUBIC)
dst_img_height, dst_img_width = dst_img.shape[0:2]
if dst_img_height * 1.0 / dst_img_width >= 1.5:
dst_img = np.rot90(dst_img)
return dst_img | [
"def",
"get_rotate_crop_image",
"(",
"img",
",",
"points",
")",
":",
"assert",
"len",
"(",
"points",
")",
"==",
"4",
",",
"\"shape of points must be 4*2\"",
"img_crop_width",
"=",
"int",
"(",
"max",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"points",
"["... | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/tools/infer/utility.py#L581-L613 | |
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/style/filereader.py | python | TextFileReader.process_file | (self, file_path, **kwargs) | Process the given file by calling the processor's process() method.
Args:
file_path: The path of the file to process.
**kwargs: Any additional keyword parameters that should be passed
to the processor's process() method. The process()
method should support these keyword arguments.
Raises:
SystemExit: If no file at file_path exists. | Process the given file by calling the processor's process() method. | [
"Process",
"the",
"given",
"file",
"by",
"calling",
"the",
"processor",
"s",
"process",
"()",
"method",
"."
] | def process_file(self, file_path, **kwargs):
"""Process the given file by calling the processor's process() method.
Args:
file_path: The path of the file to process.
**kwargs: Any additional keyword parameters that should be passed
to the processor's process() method. The process()
method should support these keyword arguments.
Raises:
SystemExit: If no file at file_path exists.
"""
self.file_count += 1
if not self.filesystem.exists(file_path) and file_path != "-":
_log.error("File does not exist: '%s'" % file_path)
raise IOError("File does not exist")
if not self._processor.should_process(file_path):
_log.debug("Skipping file: '%s'" % file_path)
return
_log.debug("Processing file: '%s'" % file_path)
try:
lines = self._read_lines(file_path)
except IOError, err:
message = ("Could not read file. Skipping: '%s'\n %s" % (file_path, err))
_log.warn(message)
return
self._processor.process(lines, file_path, **kwargs) | [
"def",
"process_file",
"(",
"self",
",",
"file_path",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"file_count",
"+=",
"1",
"if",
"not",
"self",
".",
"filesystem",
".",
"exists",
"(",
"file_path",
")",
"and",
"file_path",
"!=",
"\"-\"",
":",
"_log",... | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/style/filereader.py#L93-L124 | ||
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | scripts/cpp_lint.py | python | _CppLintState.SetFilters | (self, filters) | Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" | Sets the error-message filters. | [
"Sets",
"the",
"error",
"-",
"message",
"filters",
"."
] | def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
for filt in filters.split(','):
clean_filt = filt.strip()
if clean_filt:
self.filters.append(clean_filt)
for filt in self.filters:
if not (filt.startswith('+') or filt.startswith('-')):
raise ValueError('Every filter in --filters must start with + or -'
' (%s does not)' % filt) | [
"def",
"SetFilters",
"(",
"self",
",",
"filters",
")",
":",
"# Default filters always have less priority than the flag ones.",
"self",
".",
"filters",
"=",
"_DEFAULT_FILTERS",
"[",
":",
"]",
"for",
"filt",
"in",
"filters",
".",
"split",
"(",
"','",
")",
":",
"cl... | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/cpp_lint.py#L717-L740 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/database.py | python | DependencyGraph.add_missing | (self, distribution, requirement) | Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str`` | Add a missing *requirement* for the given *distribution*. | [
"Add",
"a",
"missing",
"*",
"requirement",
"*",
"for",
"the",
"given",
"*",
"distribution",
"*",
"."
] | def add_missing(self, distribution, requirement):
"""
Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str``
"""
logger.debug('%s missing %r', distribution, requirement)
self.missing.setdefault(distribution, []).append(requirement) | [
"def",
"add_missing",
"(",
"self",
",",
"distribution",
",",
"requirement",
")",
":",
"logger",
".",
"debug",
"(",
"'%s missing %r'",
",",
"distribution",
",",
"requirement",
")",
"self",
".",
"missing",
".",
"setdefault",
"(",
"distribution",
",",
"[",
"]",... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/database.py#L1091-L1100 | ||
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | bindings/python/llvm/object.py | python | Section.cache | (self) | Cache properties of this Section.
This can be called as a workaround to the single active Section
limitation. When called, the properties of the Section are fetched so
they are still available after the Section has been marked inactive. | Cache properties of this Section. | [
"Cache",
"properties",
"of",
"this",
"Section",
"."
] | def cache(self):
"""Cache properties of this Section.
This can be called as a workaround to the single active Section
limitation. When called, the properties of the Section are fetched so
they are still available after the Section has been marked inactive.
"""
getattr(self, 'name')
getattr(self, 'size')
getattr(self, 'contents')
getattr(self, 'address') | [
"def",
"cache",
"(",
"self",
")",
":",
"getattr",
"(",
"self",
",",
"'name'",
")",
"getattr",
"(",
"self",
",",
"'size'",
")",
"getattr",
"(",
"self",
",",
"'contents'",
")",
"getattr",
"(",
"self",
",",
"'address'",
")"
] | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/bindings/python/llvm/object.py#L271-L281 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | RobotModelLink.setTransform | (self, R, t) | return _robotsim.RobotModelLink_setTransform(self, R, t) | setTransform(RobotModelLink self, double const [9] R, double const [3] t)
Sets the link's current transformation (R,t) to the world frame.
Note:
This does NOT perform inverse kinematics. The transform is
overwritten when the robot's setConfig() method is called. | setTransform(RobotModelLink self, double const [9] R, double const [3] t) | [
"setTransform",
"(",
"RobotModelLink",
"self",
"double",
"const",
"[",
"9",
"]",
"R",
"double",
"const",
"[",
"3",
"]",
"t",
")"
] | def setTransform(self, R, t):
"""
setTransform(RobotModelLink self, double const [9] R, double const [3] t)
Sets the link's current transformation (R,t) to the world frame.
Note:
This does NOT perform inverse kinematics. The transform is
overwritten when the robot's setConfig() method is called.
"""
return _robotsim.RobotModelLink_setTransform(self, R, t) | [
"def",
"setTransform",
"(",
"self",
",",
"R",
",",
"t",
")",
":",
"return",
"_robotsim",
".",
"RobotModelLink_setTransform",
"(",
"self",
",",
"R",
",",
"t",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L3993-L4007 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/platform.py | python | Platform._iter_files_in_block_path | (self, path=None, ext='yml') | Iterator for block descriptions and category trees | Iterator for block descriptions and category trees | [
"Iterator",
"for",
"block",
"descriptions",
"and",
"category",
"trees"
] | def _iter_files_in_block_path(self, path=None, ext='yml'):
"""Iterator for block descriptions and category trees"""
for entry in (path or self.config.block_paths):
if os.path.isfile(entry):
yield entry
elif os.path.isdir(entry):
for dirpath, dirnames, filenames in os.walk(entry):
for filename in sorted(filter(lambda f: f.endswith('.' + ext), filenames)):
yield os.path.join(dirpath, filename)
else:
logger.debug('Ignoring invalid path entry %r', entry) | [
"def",
"_iter_files_in_block_path",
"(",
"self",
",",
"path",
"=",
"None",
",",
"ext",
"=",
"'yml'",
")",
":",
"for",
"entry",
"in",
"(",
"path",
"or",
"self",
".",
"config",
".",
"block_paths",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/platform.py#L194-L204 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/message.py | python | _WireReader._get_section | (self, section, count) | Read the next I{count} records from the wire data and add them to
the specified section.
@param section: the section of the message to which to add records
@type section: list of dns.rrset.RRset objects
@param count: the number of records to read
@type count: int | Read the next I{count} records from the wire data and add them to
the specified section. | [
"Read",
"the",
"next",
"I",
"{",
"count",
"}",
"records",
"from",
"the",
"wire",
"data",
"and",
"add",
"them",
"to",
"the",
"specified",
"section",
"."
] | def _get_section(self, section, count):
"""Read the next I{count} records from the wire data and add them to
the specified section.
@param section: the section of the message to which to add records
@type section: list of dns.rrset.RRset objects
@param count: the number of records to read
@type count: int"""
if self.updating or self.one_rr_per_rrset:
force_unique = True
else:
force_unique = False
seen_opt = False
for i in xrange(0, count):
rr_start = self.current
(name, used) = dns.name.from_wire(self.wire, self.current)
absolute_name = name
if not self.message.origin is None:
name = name.relativize(self.message.origin)
self.current = self.current + used
(rdtype, rdclass, ttl, rdlen) = \
struct.unpack('!HHIH',
self.wire[self.current:self.current + 10])
self.current = self.current + 10
if rdtype == dns.rdatatype.OPT:
if not section is self.message.additional or seen_opt:
raise BadEDNS
self.message.payload = rdclass
self.message.ednsflags = ttl
self.message.edns = (ttl & 0xff0000) >> 16
self.message.options = []
current = self.current
optslen = rdlen
while optslen > 0:
(otype, olen) = \
struct.unpack('!HH',
self.wire[current:current + 4])
current = current + 4
opt = dns.edns.option_from_wire(otype, self.wire, current, olen)
self.message.options.append(opt)
current = current + olen
optslen = optslen - 4 - olen
seen_opt = True
elif rdtype == dns.rdatatype.TSIG:
if not (section is self.message.additional and
i == (count - 1)):
raise BadTSIG
if self.message.keyring is None:
raise UnknownTSIGKey('got signed message without keyring')
secret = self.message.keyring.get(absolute_name)
if secret is None:
raise UnknownTSIGKey("key '%s' unknown" % name)
self.message.tsig_ctx = \
dns.tsig.validate(self.wire,
absolute_name,
secret,
int(time.time()),
self.message.request_mac,
rr_start,
self.current,
rdlen,
self.message.tsig_ctx,
self.message.multi,
self.message.first)
self.message.had_tsig = True
else:
if ttl < 0:
ttl = 0
if self.updating and \
(rdclass == dns.rdataclass.ANY or
rdclass == dns.rdataclass.NONE):
deleting = rdclass
rdclass = self.zone_rdclass
else:
deleting = None
if deleting == dns.rdataclass.ANY or \
(deleting == dns.rdataclass.NONE and \
section == self.message.answer):
covers = dns.rdatatype.NONE
rd = None
else:
rd = dns.rdata.from_wire(rdclass, rdtype, self.wire,
self.current, rdlen,
self.message.origin)
covers = rd.covers()
if self.message.xfr and rdtype == dns.rdatatype.SOA:
force_unique = True
rrset = self.message.find_rrset(section, name,
rdclass, rdtype, covers,
deleting, True, force_unique)
if not rd is None:
rrset.add(rd, ttl)
self.current = self.current + rdlen | [
"def",
"_get_section",
"(",
"self",
",",
"section",
",",
"count",
")",
":",
"if",
"self",
".",
"updating",
"or",
"self",
".",
"one_rr_per_rrset",
":",
"force_unique",
"=",
"True",
"else",
":",
"force_unique",
"=",
"False",
"seen_opt",
"=",
"False",
"for",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/message.py#L608-L700 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/common/extensions/docs/server2/api_data_source.py | python | _JSCModel._GetIntroAvailabilityRow | (self) | return {
'title': 'Availability',
'content': [{
'partial': self._template_cache.GetFromFile(
posixpath.join(PRIVATE_TEMPLATES,
'intro_tables',
'%s_message.html' % status)).Get(),
'version': version
}]
} | Generates the 'Availability' row data for an API intro table. | Generates the 'Availability' row data for an API intro table. | [
"Generates",
"the",
"Availability",
"row",
"data",
"for",
"an",
"API",
"intro",
"table",
"."
] | def _GetIntroAvailabilityRow(self):
''' Generates the 'Availability' row data for an API intro table.
'''
if self._IsExperimental():
status = 'experimental'
version = None
else:
availability = self._GetApiAvailability()
status = availability.channel
version = availability.version
return {
'title': 'Availability',
'content': [{
'partial': self._template_cache.GetFromFile(
posixpath.join(PRIVATE_TEMPLATES,
'intro_tables',
'%s_message.html' % status)).Get(),
'version': version
}]
} | [
"def",
"_GetIntroAvailabilityRow",
"(",
"self",
")",
":",
"if",
"self",
".",
"_IsExperimental",
"(",
")",
":",
"status",
"=",
"'experimental'",
"version",
"=",
"None",
"else",
":",
"availability",
"=",
"self",
".",
"_GetApiAvailability",
"(",
")",
"status",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/api_data_source.py#L364-L383 | |
google/mozc | 7329757e1ad30e327c1ae823a8302c79482d6b9c | src/android/vectorgraphics/gen_mozc_drawable.py | python | MozcDrawableConverter._ParseStyle | (self, node, has_shadow, shader_map) | return result | Parses style attribute of the given node. | Parses style attribute of the given node. | [
"Parses",
"style",
"attribute",
"of",
"the",
"given",
"node",
"."
] | def _ParseStyle(self, node, has_shadow, shader_map):
"""Parses style attribute of the given node."""
common_map = {}
# Default fill color is black (SVG's spec)
fill_map = {'style': 'fill', 'color': 0xFF000000, 'shadow': has_shadow}
# Default stroke color is none (SVG's spec)
stroke_map = {'style': 'stroke', 'shadow': has_shadow}
# Special warning for font-size.
# Inkscape often unexpectedly converts from style to font-size attribute.
if node.get('font-size', ''):
logging.warning('font-size attribute is not supported.')
for attr in node.get('style', '').split(';'):
attr = attr.strip()
if not attr:
continue
command, arg = attr.split(':')
if command == 'fill' or command == 'stroke':
paint_map = fill_map if command == 'fill' else stroke_map
if arg == 'none':
paint_map.pop('color', None)
paint_map.pop('shader', None)
continue
shader = self._ParseShader(arg, shader_map)
color = self._ParseColor(arg)
if shader is None and color is None:
if arg != 'none':
logging.critical('Unknown pattern: %s', arg)
sys.exit(1)
continue
paint_map['style'] = command
if shader is not None:
paint_map['shader'] = shader
if color is not None:
paint_map['color'] = color
continue
if command == 'stroke-width':
stroke_map['stroke-width'] = float(arg)
continue
if command == 'stroke-linecap':
stroke_map['stroke-linecap'] = arg
continue
if command == 'stroke-linejoin':
stroke_map['stroke-linejoin'] = arg
continue
# font relating attributes are common to all commands.
if command == 'font-size':
common_map['font-size'] = self._ParsePixel(arg)
if command == 'text-anchor':
common_map['text-anchor'] = arg
if command == 'dominant-baseline':
common_map['dominant-baseline'] = arg
if command == 'font-weight':
common_map['font-weight'] = arg
# 'fill' comes first in order to draw 'fill' first (SVG specification).
result = []
if 'color' in fill_map or 'shader' in fill_map:
fill_map.update(common_map)
result.append(fill_map)
if 'color' in stroke_map or 'shader' in stroke_map:
stroke_map.update(common_map)
result.append(stroke_map)
return result | [
"def",
"_ParseStyle",
"(",
"self",
",",
"node",
",",
"has_shadow",
",",
"shader_map",
")",
":",
"common_map",
"=",
"{",
"}",
"# Default fill color is black (SVG's spec)",
"fill_map",
"=",
"{",
"'style'",
":",
"'fill'",
",",
"'color'",
":",
"0xFF000000",
",",
"... | https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/android/vectorgraphics/gen_mozc_drawable.py#L347-L417 | |
blackberry/Boost | fc90c3fde129c62565c023f091eddc4a7ed9902b | tools/build/v2/build/targets.py | python | generate_from_reference | (target_reference, project, property_set) | return target.generate(rproperties) | Attempts to generate the target given by target reference, which
can refer both to a main target or to a file.
Returns a list consisting of
- usage requirements
- generated virtual targets, if any
target_reference: Target reference
project: Project where the reference is made
property_set: Properties of the main target that makes the reference | Attempts to generate the target given by target reference, which
can refer both to a main target or to a file.
Returns a list consisting of
- usage requirements
- generated virtual targets, if any
target_reference: Target reference
project: Project where the reference is made
property_set: Properties of the main target that makes the reference | [
"Attempts",
"to",
"generate",
"the",
"target",
"given",
"by",
"target",
"reference",
"which",
"can",
"refer",
"both",
"to",
"a",
"main",
"target",
"or",
"to",
"a",
"file",
".",
"Returns",
"a",
"list",
"consisting",
"of",
"-",
"usage",
"requirements",
"-",
... | def generate_from_reference(target_reference, project, property_set):
""" Attempts to generate the target given by target reference, which
can refer both to a main target or to a file.
Returns a list consisting of
- usage requirements
- generated virtual targets, if any
target_reference: Target reference
project: Project where the reference is made
property_set: Properties of the main target that makes the reference
"""
target, sproperties = resolve_reference(target_reference, project)
# Take properties which should be propagated and refine them
# with source-specific requirements.
propagated = property_set.propagated()
rproperties = propagated.refine(sproperties)
return target.generate(rproperties) | [
"def",
"generate_from_reference",
"(",
"target_reference",
",",
"project",
",",
"property_set",
")",
":",
"target",
",",
"sproperties",
"=",
"resolve_reference",
"(",
"target_reference",
",",
"project",
")",
"# Take properties which should be propagated and refine them",
"#... | https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/targets.py#L802-L819 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/strings.py | python | _map_stringarray | (
func: Callable[[str], Any], arr: "StringArray", na_value: Any, dtype: Dtype
) | Map a callable over valid elements of a StringArrray.
Parameters
----------
func : Callable[[str], Any]
Apply to each valid element.
arr : StringArray
na_value : Any
The value to use for missing values. By default, this is
the original value (NA).
dtype : Dtype
The result dtype to use. Specifying this avoids an intermediate
object-dtype allocation.
Returns
-------
ArrayLike
An ExtensionArray for integer or string dtypes, otherwise
an ndarray. | Map a callable over valid elements of a StringArrray. | [
"Map",
"a",
"callable",
"over",
"valid",
"elements",
"of",
"a",
"StringArrray",
"."
] | def _map_stringarray(
func: Callable[[str], Any], arr: "StringArray", na_value: Any, dtype: Dtype
) -> ArrayLike:
"""
Map a callable over valid elements of a StringArrray.
Parameters
----------
func : Callable[[str], Any]
Apply to each valid element.
arr : StringArray
na_value : Any
The value to use for missing values. By default, this is
the original value (NA).
dtype : Dtype
The result dtype to use. Specifying this avoids an intermediate
object-dtype allocation.
Returns
-------
ArrayLike
An ExtensionArray for integer or string dtypes, otherwise
an ndarray.
"""
from pandas.arrays import IntegerArray, StringArray, BooleanArray
mask = isna(arr)
assert isinstance(arr, StringArray)
arr = np.asarray(arr)
if is_integer_dtype(dtype) or is_bool_dtype(dtype):
constructor: Union[Type[IntegerArray], Type[BooleanArray]]
if is_integer_dtype(dtype):
constructor = IntegerArray
else:
constructor = BooleanArray
na_value_is_na = isna(na_value)
if na_value_is_na:
na_value = 1
result = lib.map_infer_mask(
arr,
func,
mask.view("uint8"),
convert=False,
na_value=na_value,
dtype=np.dtype(dtype),
)
if not na_value_is_na:
mask[:] = False
return constructor(result, mask)
elif is_string_dtype(dtype) and not is_object_dtype(dtype):
# i.e. StringDtype
result = lib.map_infer_mask(
arr, func, mask.view("uint8"), convert=False, na_value=na_value
)
return StringArray(result)
else:
# This is when the result type is object. We reach this when
# -> We know the result type is truly object (e.g. .encode returns bytes
# or .findall returns a list).
# -> We don't know the result type. E.g. `.get` can return anything.
return lib.map_infer_mask(arr, func, mask.view("uint8")) | [
"def",
"_map_stringarray",
"(",
"func",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"Any",
"]",
",",
"arr",
":",
"\"StringArray\"",
",",
"na_value",
":",
"Any",
",",
"dtype",
":",
"Dtype",
")",
"->",
"ArrayLike",
":",
"from",
"pandas",
".",
"arrays",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/strings.py#L134-L201 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.get_element_property_value | (self, object_id, name) | return int(propVal) | get element property value (an integer) for a specified element
block and element property name
>>> eprop_val = exo.get_element_property_value(elem_blk_id, eprop_name)
Parameters
----------
elem_blk_id : int
element block *ID* (not *INDEX*)
<string> eprop_name
Returns
-------
<int> eprop_val | get element property value (an integer) for a specified element
block and element property name | [
"get",
"element",
"property",
"value",
"(",
"an",
"integer",
")",
"for",
"a",
"specified",
"element",
"block",
"and",
"element",
"property",
"name"
] | def get_element_property_value(self, object_id, name):
"""
get element property value (an integer) for a specified element
block and element property name
>>> eprop_val = exo.get_element_property_value(elem_blk_id, eprop_name)
Parameters
----------
elem_blk_id : int
element block *ID* (not *INDEX*)
<string> eprop_name
Returns
-------
<int> eprop_val
"""
propVal = self.__ex_get_prop('EX_ELEM_BLOCK', object_id, name)
return int(propVal) | [
"def",
"get_element_property_value",
"(",
"self",
",",
"object_id",
",",
"name",
")",
":",
"propVal",
"=",
"self",
".",
"__ex_get_prop",
"(",
"'EX_ELEM_BLOCK'",
",",
"object_id",
",",
"name",
")",
"return",
"int",
"(",
"propVal",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L3088-L3106 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/engine/cell.py | python | Cell.minimum_distance | (self, atom1, atom2) | return np.dot(self.h, s) | Takes two atoms and tries to find the smallest vector between two
images.
This is only rigorously accurate in the case of a cubic cell,
but gives the correct results as long as the cut-off radius is defined
as smaller than the smallest width between parallel faces even for
triclinic cells.
Args:
atom1: An Atom object.
atom2: An Atom object.
Returns:
An array giving the minimum distance between the positions of atoms
atom1 and atom2 in the minimum image convention. | Takes two atoms and tries to find the smallest vector between two
images. | [
"Takes",
"two",
"atoms",
"and",
"tries",
"to",
"find",
"the",
"smallest",
"vector",
"between",
"two",
"images",
"."
] | def minimum_distance(self, atom1, atom2):
"""Takes two atoms and tries to find the smallest vector between two
images.
This is only rigorously accurate in the case of a cubic cell,
but gives the correct results as long as the cut-off radius is defined
as smaller than the smallest width between parallel faces even for
triclinic cells.
Args:
atom1: An Atom object.
atom2: An Atom object.
Returns:
An array giving the minimum distance between the positions of atoms
atom1 and atom2 in the minimum image convention.
"""
s = np.dot(self.ih,atom1.q-atom2.q)
for i in range(3):
s[i] -= round(s[i])
return np.dot(self.h, s) | [
"def",
"minimum_distance",
"(",
"self",
",",
"atom1",
",",
"atom2",
")",
":",
"s",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"ih",
",",
"atom1",
".",
"q",
"-",
"atom2",
".",
"q",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"s",
"[",
... | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/cell.py#L119-L140 | |
fifengine/fifengine | 4b62c42e85bec19893cef8e63e6855927cff2c47 | engine/python/fife/extensions/pychan/internal.py | python | Manager.createFont | (self, path="", size=0, glyphs="") | return self.hook.create_font(path,size,glyphs) | Creates and returns a GuiFont from the GUI Manager | Creates and returns a GuiFont from the GUI Manager | [
"Creates",
"and",
"returns",
"a",
"GuiFont",
"from",
"the",
"GUI",
"Manager"
] | def createFont(self, path="", size=0, glyphs=""):
"""
Creates and returns a GuiFont from the GUI Manager
"""
return self.hook.create_font(path,size,glyphs) | [
"def",
"createFont",
"(",
"self",
",",
"path",
"=",
"\"\"",
",",
"size",
"=",
"0",
",",
"glyphs",
"=",
"\"\"",
")",
":",
"return",
"self",
".",
"hook",
".",
"create_font",
"(",
"path",
",",
"size",
",",
"glyphs",
")"
] | https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/internal.py#L172-L176 | |
hcdth011/ROS-Hydro-SLAM | 629448eecd2c9a3511158115fa53ea9e4ae41359 | rpg_vikit/vikit_py/src/vikit_py/transformations.py | python | quaternion_from_matrix | (matrix) | return q | Return quaternion from rotation matrix.
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R)
>>> numpy.allclose(q, [0.0164262, 0.0328524, 0.0492786, 0.9981095])
True | Return quaternion from rotation matrix. | [
"Return",
"quaternion",
"from",
"rotation",
"matrix",
"."
] | def quaternion_from_matrix(matrix):
"""Return quaternion from rotation matrix.
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R)
>>> numpy.allclose(q, [0.0164262, 0.0328524, 0.0492786, 0.9981095])
True
"""
q = numpy.empty((4, ), dtype=numpy.float64)
M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:4, :4]
t = numpy.trace(M)
if t > M[3, 3]:
q[3] = t
q[2] = M[1, 0] - M[0, 1]
q[1] = M[0, 2] - M[2, 0]
q[0] = M[2, 1] - M[1, 2]
else:
i, j, k = 0, 1, 2
if M[1, 1] > M[0, 0]:
i, j, k = 1, 2, 0
if M[2, 2] > M[i, i]:
i, j, k = 2, 0, 1
t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
q[i] = t
q[j] = M[i, j] + M[j, i]
q[k] = M[k, i] + M[i, k]
q[3] = M[k, j] - M[j, k]
q *= 0.5 / math.sqrt(t * M[3, 3])
return q | [
"def",
"quaternion_from_matrix",
"(",
"matrix",
")",
":",
"q",
"=",
"numpy",
".",
"empty",
"(",
"(",
"4",
",",
")",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"M",
"=",
"numpy",
".",
"array",
"(",
"matrix",
",",
"dtype",
"=",
"numpy",
".",
... | https://github.com/hcdth011/ROS-Hydro-SLAM/blob/629448eecd2c9a3511158115fa53ea9e4ae41359/rpg_vikit/vikit_py/src/vikit_py/transformations.py#L1200-L1229 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | log | (x, out=None, **kwargs) | return _unary_func_helper(x, _npi.log, _np.log, out=out, **kwargs) | Natural logarithm, element-wise.
The natural logarithm `log` is the inverse of the exponential function,
so that `log(exp(x)) = x`. The natural logarithm is logarithm in base
`e`.
Parameters
----------
x : _Symbol
Input value. Elements must be of real value.
out : _Symbol or None, optional
Dummy parameter to keep the consistency with the ndarray counterpart.
Returns
-------
y : _Symbol
The natural logarithm of `x`, element-wise.
This is a scalar if `x` is a scalar.
Notes
-----
Currently only supports data of real values and ``inf`` as input. Returns data of real value, ``inf``, ``-inf`` and
``nan`` according to the input.
This function differs from the original `numpy.log
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html>`_ in
the following aspects:
- Does not support complex number for now
- Input type does not support Python native iterables(list, tuple, ...). Only ndarray is supported.
- ``out`` param: cannot perform auto braodcasting. ``out`` symbol's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` symbol's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case. | Natural logarithm, element-wise.
The natural logarithm `log` is the inverse of the exponential function,
so that `log(exp(x)) = x`. The natural logarithm is logarithm in base
`e`. | [
"Natural",
"logarithm",
"element",
"-",
"wise",
".",
"The",
"natural",
"logarithm",
"log",
"is",
"the",
"inverse",
"of",
"the",
"exponential",
"function",
"so",
"that",
"log",
"(",
"exp",
"(",
"x",
"))",
"=",
"x",
".",
"The",
"natural",
"logarithm",
"is"... | def log(x, out=None, **kwargs):
"""
Natural logarithm, element-wise.
The natural logarithm `log` is the inverse of the exponential function,
so that `log(exp(x)) = x`. The natural logarithm is logarithm in base
`e`.
Parameters
----------
x : _Symbol
Input value. Elements must be of real value.
out : _Symbol or None, optional
Dummy parameter to keep the consistency with the ndarray counterpart.
Returns
-------
y : _Symbol
The natural logarithm of `x`, element-wise.
This is a scalar if `x` is a scalar.
Notes
-----
Currently only supports data of real values and ``inf`` as input. Returns data of real value, ``inf``, ``-inf`` and
``nan`` according to the input.
This function differs from the original `numpy.log
<https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html>`_ in
the following aspects:
- Does not support complex number for now
- Input type does not support Python native iterables(list, tuple, ...). Only ndarray is supported.
- ``out`` param: cannot perform auto braodcasting. ``out`` symbol's shape must be the same as the expected output.
- ``out`` param: cannot perform auto type cast. ``out`` symbol's dtype must be the same as the expected output.
- ``out`` param does not support scalar input case.
"""
return _unary_func_helper(x, _npi.log, _np.log, out=out, **kwargs) | [
"def",
"log",
"(",
"x",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_unary_func_helper",
"(",
"x",
",",
"_npi",
".",
"log",
",",
"_np",
".",
"log",
",",
"out",
"=",
"out",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L3096-L3129 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/input_lib.py | python | _get_next_as_optional | (iterator, strategy, name=None) | return global_has_value, replicas | Returns an empty dataset indicator and the next input from the iterator. | Returns an empty dataset indicator and the next input from the iterator. | [
"Returns",
"an",
"empty",
"dataset",
"indicator",
"and",
"the",
"next",
"input",
"from",
"the",
"iterator",
"."
] | def _get_next_as_optional(iterator, strategy, name=None):
"""Returns an empty dataset indicator and the next input from the iterator."""
replicas = []
worker_has_values = []
worker_devices = []
for i, worker in enumerate(iterator._input_workers.worker_devices): # pylint: disable=protected-access
if name is not None:
d = tf_device.DeviceSpec.from_string(worker)
new_name = "%s_%s_%d" % (name, d.job, d.task)
else:
new_name = None
with ops.device(worker):
worker_has_value, next_element = (
iterator._iterators[i].get_next_as_list(new_name)) # pylint: disable=protected-access
# Collective all-reduce requires explict devices for inputs.
with ops.device("/cpu:0"):
# Converting to integers for all-reduce.
worker_has_value = math_ops.cast(worker_has_value, dtypes.int32)
worker_devices.append(worker_has_value.device)
worker_has_values.append(worker_has_value)
# Make `replicas` a flat list of values across all replicas.
replicas.append(next_element)
# Run an all-reduce to see whether any worker has values.
# TODO(b/131423105): we should be able to short-cut the all-reduce in some
# cases.
if getattr(strategy.extended, "_support_per_replica_values", True):
worker_has_values = values.PerReplica(
values.WorkerDeviceMap(
worker_devices,
num_replicas_per_worker=len(
strategy.extended._input_workers._input_worker_devices)), # pylint: disable=protected-access
worker_has_values)
global_has_value = strategy.reduce(
reduce_util.ReduceOp.SUM, worker_has_values, axis=None)
else:
assert len(worker_has_values) == 1
global_has_value = worker_has_values[0]
global_has_value = array_ops.reshape(
math_ops.cast(global_has_value, dtypes.bool), [])
return global_has_value, replicas | [
"def",
"_get_next_as_optional",
"(",
"iterator",
",",
"strategy",
",",
"name",
"=",
"None",
")",
":",
"replicas",
"=",
"[",
"]",
"worker_has_values",
"=",
"[",
"]",
"worker_devices",
"=",
"[",
"]",
"for",
"i",
",",
"worker",
"in",
"enumerate",
"(",
"iter... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/input_lib.py#L186-L227 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/xrc.py | python | XmlDocument.GetVersion | (*args, **kwargs) | return _xrc.XmlDocument_GetVersion(*args, **kwargs) | GetVersion(self) -> String | GetVersion(self) -> String | [
"GetVersion",
"(",
"self",
")",
"-",
">",
"String"
] | def GetVersion(*args, **kwargs):
"""GetVersion(self) -> String"""
return _xrc.XmlDocument_GetVersion(*args, **kwargs) | [
"def",
"GetVersion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlDocument_GetVersion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/xrc.py#L539-L541 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Rect2D.IsEmpty | (*args, **kwargs) | return _core_.Rect2D_IsEmpty(*args, **kwargs) | IsEmpty(self) -> bool | IsEmpty(self) -> bool | [
"IsEmpty",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsEmpty(*args, **kwargs):
"""IsEmpty(self) -> bool"""
return _core_.Rect2D_IsEmpty(*args, **kwargs) | [
"def",
"IsEmpty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect2D_IsEmpty",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1975-L1977 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/tools/scan-build-py/libscanbuild/report.py | python | assemble_cover | (args, prefix, fragments) | Put together the fragments into a final report. | Put together the fragments into a final report. | [
"Put",
"together",
"the",
"fragments",
"into",
"a",
"final",
"report",
"."
] | def assemble_cover(args, prefix, fragments):
""" Put together the fragments into a final report. """
import getpass
import socket
if args.html_title is None:
args.html_title = os.path.basename(prefix) + ' - analyzer results'
with open(os.path.join(args.output, 'index.html'), 'w') as handle:
indent = 0
handle.write(reindent("""
|<!DOCTYPE html>
|<html>
| <head>
| <title>{html_title}</title>
| <link type="text/css" rel="stylesheet" href="scanview.css"/>
| <script type='text/javascript' src="sorttable.js"></script>
| <script type='text/javascript' src='selectable.js'></script>
| </head>""", indent).format(html_title=args.html_title))
handle.write(comment('SUMMARYENDHEAD'))
handle.write(reindent("""
| <body>
| <h1>{html_title}</h1>
| <table>
| <tr><th>User:</th><td>{user_name}@{host_name}</td></tr>
| <tr><th>Working Directory:</th><td>{current_dir}</td></tr>
| <tr><th>Command Line:</th><td>{cmd_args}</td></tr>
| <tr><th>Clang Version:</th><td>{clang_version}</td></tr>
| <tr><th>Date:</th><td>{date}</td></tr>
| </table>""", indent).format(html_title=args.html_title,
user_name=getpass.getuser(),
host_name=socket.gethostname(),
current_dir=prefix,
cmd_args=' '.join(sys.argv),
clang_version=get_version(args.clang),
date=datetime.datetime.today(
).strftime('%c')))
for fragment in fragments:
# copy the content of fragments
with open(fragment, 'r') as input_handle:
shutil.copyfileobj(input_handle, handle)
handle.write(reindent("""
| </body>
|</html>""", indent)) | [
"def",
"assemble_cover",
"(",
"args",
",",
"prefix",
",",
"fragments",
")",
":",
"import",
"getpass",
"import",
"socket",
"if",
"args",
".",
"html_title",
"is",
"None",
":",
"args",
".",
"html_title",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"prefix... | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/tools/scan-build-py/libscanbuild/report.py#L63-L107 | ||
dmlc/nnvm | dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38 | python/nnvm/frontend/mxnet.py | python | _convert_symbol | (op_name, inputs, attrs,
identity_list=None,
convert_map=None) | return sym | Convert from mxnet op to nnvm op.
The converter must specify some conversions explicitly to
support gluon format ops such as conv2d...
Parameters
----------
op_name : str
Operator name, such as Convolution, FullyConnected
inputs : list of nnvm.Symbol
List of input symbols.
attrs : dict
Dict of operator attributes
identity_list : list
List of operators that don't require conversion
convert_map : dict
Dict of name : callable, where name is the op's name that
require conversion to nnvm, callable are functions which
take attrs and return (new_op_name, new_attrs)
Returns
-------
sym : nnvm.Symbol
Converted nnvm Symbol | Convert from mxnet op to nnvm op.
The converter must specify some conversions explicitly to
support gluon format ops such as conv2d... | [
"Convert",
"from",
"mxnet",
"op",
"to",
"nnvm",
"op",
".",
"The",
"converter",
"must",
"specify",
"some",
"conversions",
"explicitly",
"to",
"support",
"gluon",
"format",
"ops",
"such",
"as",
"conv2d",
"..."
] | def _convert_symbol(op_name, inputs, attrs,
identity_list=None,
convert_map=None):
"""Convert from mxnet op to nnvm op.
The converter must specify some conversions explicitly to
support gluon format ops such as conv2d...
Parameters
----------
op_name : str
Operator name, such as Convolution, FullyConnected
inputs : list of nnvm.Symbol
List of input symbols.
attrs : dict
Dict of operator attributes
identity_list : list
List of operators that don't require conversion
convert_map : dict
Dict of name : callable, where name is the op's name that
require conversion to nnvm, callable are functions which
take attrs and return (new_op_name, new_attrs)
Returns
-------
sym : nnvm.Symbol
Converted nnvm Symbol
"""
identity_list = identity_list if identity_list else _identity_list
convert_map = convert_map if convert_map else _convert_map
if op_name in identity_list:
op = _get_nnvm_op(op_name)
sym = op(*inputs, **attrs)
elif op_name in convert_map:
sym = convert_map[op_name](inputs, attrs)
else:
_raise_not_supported('Operator: ' + op_name)
return sym | [
"def",
"_convert_symbol",
"(",
"op_name",
",",
"inputs",
",",
"attrs",
",",
"identity_list",
"=",
"None",
",",
"convert_map",
"=",
"None",
")",
":",
"identity_list",
"=",
"identity_list",
"if",
"identity_list",
"else",
"_identity_list",
"convert_map",
"=",
"conv... | https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/frontend/mxnet.py#L260-L296 | |
fifengine/fifengine | 4b62c42e85bec19893cef8e63e6855927cff2c47 | engine/python/fife/extensions/pychan/dialog/filebrowser.py | python | FileBrowser.setDirectory | (self, path) | sets the current directory according to path | sets the current directory according to path | [
"sets",
"the",
"current",
"directory",
"according",
"to",
"path"
] | def setDirectory(self, path):
""" sets the current directory according to path """
path_copy = self.path
self.path = path
if not self._widget: return
def decodeList(list):
fs_encoding = sys.getfilesystemencoding()
if fs_encoding is None: fs_encoding = "ascii"
newList = []
for i in list:
try: newList.append(str(i, fs_encoding))
except:
newList.append(str(i, fs_encoding, 'replace'))
print("WARNING: Could not decode item:", i)
return newList
dir_list_copy = list(self.dir_list)
file_list_copy = list(self.file_list)
self.dir_list = []
self.file_list = []
contents = os.listdir(path)
for content in contents:
if os.path.isdir(os.path.join(path, content)):
self.dir_list.append(content)
elif os.path.isfile(os.path.join(path, content)):
extension = os.path.splitext(content)[1][1:]
if extension in self.extensions:
self.file_list.append(content)
try:
self.dir_list = sorted(decodeList(self.dir_list), key=lambda s: s.lower())
self.dir_list.insert(0, "..")
self.file_list = sorted(decodeList(self.file_list), key=lambda s: s.lower())
except:
self.path = path_copy
self.dir_list = list(dir_list_copy)
self.file_list = list(file_list_copy)
print("WARNING: Tried to browse to directory that is not accessible!")
self._widget.distributeInitialData({
'dirList' : self.dir_list,
'fileList' : self.file_list
})
self._widget.adaptLayout() | [
"def",
"setDirectory",
"(",
"self",
",",
"path",
")",
":",
"path_copy",
"=",
"self",
".",
"path",
"self",
".",
"path",
"=",
"path",
"if",
"not",
"self",
".",
"_widget",
":",
"return",
"def",
"decodeList",
"(",
"list",
")",
":",
"fs_encoding",
"=",
"s... | https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/dialog/filebrowser.py#L117-L165 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/internal/python_message.py | python | _AddSlots | (message_descriptor, dictionary) | Adds a __slots__ entry to dictionary, containing the names of all valid
attributes for this message type.
Args:
message_descriptor: A Descriptor instance describing this message type.
dictionary: Class dictionary to which we'll add a '__slots__' entry. | Adds a __slots__ entry to dictionary, containing the names of all valid
attributes for this message type. | [
"Adds",
"a",
"__slots__",
"entry",
"to",
"dictionary",
"containing",
"the",
"names",
"of",
"all",
"valid",
"attributes",
"for",
"this",
"message",
"type",
"."
] | def _AddSlots(message_descriptor, dictionary):
"""Adds a __slots__ entry to dictionary, containing the names of all valid
attributes for this message type.
Args:
message_descriptor: A Descriptor instance describing this message type.
dictionary: Class dictionary to which we'll add a '__slots__' entry.
"""
dictionary['__slots__'] = ['_cached_byte_size',
'_cached_byte_size_dirty',
'_fields',
'_is_present_in_parent',
'_listener',
'_listener_for_children',
'__weakref__'] | [
"def",
"_AddSlots",
"(",
"message_descriptor",
",",
"dictionary",
")",
":",
"dictionary",
"[",
"'__slots__'",
"]",
"=",
"[",
"'_cached_byte_size'",
",",
"'_cached_byte_size_dirty'",
",",
"'_fields'",
",",
"'_is_present_in_parent'",
",",
"'_listener'",
",",
"'_listener... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/internal/python_message.py#L155-L169 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/finddlg.py | python | FindReplaceDlgBase.SetFindDirectory | (self, path) | Set the directory selection for find in files
@param path: path to set for lookin data | Set the directory selection for find in files
@param path: path to set for lookin data | [
"Set",
"the",
"directory",
"selection",
"for",
"find",
"in",
"files",
"@param",
"path",
":",
"path",
"to",
"set",
"for",
"lookin",
"data"
] | def SetFindDirectory(self, path):
"""Set the directory selection for find in files
@param path: path to set for lookin data
"""
self._panel.SetLookinSelection(path) | [
"def",
"SetFindDirectory",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"_panel",
".",
"SetLookinSelection",
"(",
"path",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/finddlg.py#L560-L565 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/google/protobuf/internal/well_known_types.py | python | _FieldMaskTree.MergeMessage | (
self, source, destination,
replace_message, replace_repeated) | Merge all fields specified by this tree from source to destination. | Merge all fields specified by this tree from source to destination. | [
"Merge",
"all",
"fields",
"specified",
"by",
"this",
"tree",
"from",
"source",
"to",
"destination",
"."
] | def MergeMessage(
self, source, destination,
replace_message, replace_repeated):
"""Merge all fields specified by this tree from source to destination."""
_MergeMessage(
self._root, source, destination, replace_message, replace_repeated) | [
"def",
"MergeMessage",
"(",
"self",
",",
"source",
",",
"destination",
",",
"replace_message",
",",
"replace_repeated",
")",
":",
"_MergeMessage",
"(",
"self",
".",
"_root",
",",
"source",
",",
"destination",
",",
"replace_message",
",",
"replace_repeated",
")"
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L554-L559 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewColumn.__init__ | (self, *args, **kwargs) | __init__(self, PyObject title_or_bitmap, DataViewRenderer renderer,
unsigned int model_column, int width=80, int align=ALIGN_CENTER,
int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn | __init__(self, PyObject title_or_bitmap, DataViewRenderer renderer,
unsigned int model_column, int width=80, int align=ALIGN_CENTER,
int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn | [
"__init__",
"(",
"self",
"PyObject",
"title_or_bitmap",
"DataViewRenderer",
"renderer",
"unsigned",
"int",
"model_column",
"int",
"width",
"=",
"80",
"int",
"align",
"=",
"ALIGN_CENTER",
"int",
"flags",
"=",
"DATAVIEW_COL_RESIZABLE",
")",
"-",
">",
"DataViewColumn"
... | def __init__(self, *args, **kwargs):
"""
__init__(self, PyObject title_or_bitmap, DataViewRenderer renderer,
unsigned int model_column, int width=80, int align=ALIGN_CENTER,
int flags=DATAVIEW_COL_RESIZABLE) -> DataViewColumn
"""
_dataview.DataViewColumn_swiginit(self,_dataview.new_DataViewColumn(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_dataview",
".",
"DataViewColumn_swiginit",
"(",
"self",
",",
"_dataview",
".",
"new_DataViewColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1523-L1529 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/csv.py | python | Sniffer._guess_delimiter | (self, data, delimiters) | return (delim, skipinitialspace) | The delimiter /should/ occur the same number of times on
each row. However, due to malformed data, it may not. We don't want
an all or nothing approach, so we allow for small variations in this
number.
1) build a table of the frequency of each character on every line.
2) build a table of frequencies of this frequency (meta-frequency?),
e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows,
7 times in 2 rows'
3) use the mode of the meta-frequency to determine the /expected/
frequency for that character
4) find out how often the character actually meets that goal
5) the character that best meets its goal is the delimiter
For performance reasons, the data is evaluated in chunks, so it can
try and evaluate the smallest portion of the data possible, evaluating
additional chunks as necessary. | The delimiter /should/ occur the same number of times on
each row. However, due to malformed data, it may not. We don't want
an all or nothing approach, so we allow for small variations in this
number.
1) build a table of the frequency of each character on every line.
2) build a table of frequencies of this frequency (meta-frequency?),
e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows,
7 times in 2 rows'
3) use the mode of the meta-frequency to determine the /expected/
frequency for that character
4) find out how often the character actually meets that goal
5) the character that best meets its goal is the delimiter
For performance reasons, the data is evaluated in chunks, so it can
try and evaluate the smallest portion of the data possible, evaluating
additional chunks as necessary. | [
"The",
"delimiter",
"/",
"should",
"/",
"occur",
"the",
"same",
"number",
"of",
"times",
"on",
"each",
"row",
".",
"However",
"due",
"to",
"malformed",
"data",
"it",
"may",
"not",
".",
"We",
"don",
"t",
"want",
"an",
"all",
"or",
"nothing",
"approach",... | def _guess_delimiter(self, data, delimiters):
"""
The delimiter /should/ occur the same number of times on
each row. However, due to malformed data, it may not. We don't want
an all or nothing approach, so we allow for small variations in this
number.
1) build a table of the frequency of each character on every line.
2) build a table of frequencies of this frequency (meta-frequency?),
e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows,
7 times in 2 rows'
3) use the mode of the meta-frequency to determine the /expected/
frequency for that character
4) find out how often the character actually meets that goal
5) the character that best meets its goal is the delimiter
For performance reasons, the data is evaluated in chunks, so it can
try and evaluate the smallest portion of the data possible, evaluating
additional chunks as necessary.
"""
data = list(filter(None, data.split('\n')))
ascii = [chr(c) for c in range(127)] # 7-bit ASCII
# build frequency tables
chunkLength = min(10, len(data))
iteration = 0
charFrequency = {}
modes = {}
delims = {}
start, end = 0, chunkLength
while start < len(data):
iteration += 1
for line in data[start:end]:
for char in ascii:
metaFrequency = charFrequency.get(char, {})
# must count even if frequency is 0
freq = line.count(char)
# value is the mode
metaFrequency[freq] = metaFrequency.get(freq, 0) + 1
charFrequency[char] = metaFrequency
for char in charFrequency.keys():
items = list(charFrequency[char].items())
if len(items) == 1 and items[0][0] == 0:
continue
# get the mode of the frequencies
if len(items) > 1:
modes[char] = max(items, key=lambda x: x[1])
# adjust the mode - subtract the sum of all
# other frequencies
items.remove(modes[char])
modes[char] = (modes[char][0], modes[char][1]
- sum(item[1] for item in items))
else:
modes[char] = items[0]
# build a list of possible delimiters
modeList = modes.items()
total = float(min(chunkLength * iteration, len(data)))
# (rows of consistent data) / (number of rows) = 100%
consistency = 1.0
# minimum consistency threshold
threshold = 0.9
while len(delims) == 0 and consistency >= threshold:
for k, v in modeList:
if v[0] > 0 and v[1] > 0:
if ((v[1]/total) >= consistency and
(delimiters is None or k in delimiters)):
delims[k] = v
consistency -= 0.01
if len(delims) == 1:
delim = list(delims.keys())[0]
skipinitialspace = (data[0].count(delim) ==
data[0].count("%c " % delim))
return (delim, skipinitialspace)
# analyze another chunkLength lines
start = end
end += chunkLength
if not delims:
return ('', 0)
# if there's more than one, fall back to a 'preferred' list
if len(delims) > 1:
for d in self.preferred:
if d in delims.keys():
skipinitialspace = (data[0].count(d) ==
data[0].count("%c " % d))
return (d, skipinitialspace)
# nothing else indicates a preference, pick the character that
# dominates(?)
items = [(v,k) for (k,v) in delims.items()]
items.sort()
delim = items[-1][1]
skipinitialspace = (data[0].count(delim) ==
data[0].count("%c " % delim))
return (delim, skipinitialspace) | [
"def",
"_guess_delimiter",
"(",
"self",
",",
"data",
",",
"delimiters",
")",
":",
"data",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"data",
".",
"split",
"(",
"'\\n'",
")",
")",
")",
"ascii",
"=",
"[",
"chr",
"(",
"c",
")",
"for",
"c",
"in",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/csv.py#L281-L381 | |
leela-zero/leela-zero | e3ed6310d33d75078ba74c3adf887d18439fc2e3 | training/tf/chunkparser.py | python | ChunkParser.convert_v2_to_tuple | (self, content) | return (planes, probs, winner) | Convert v2 binary training data to packed tensors
v2 struct format is
int32 ver
float probs[19*18+1]
byte planes[19*19*16/8]
byte to_move
byte winner
packed tensor formats are
float32 winner
float32*362 probs
uint8*6498 planes | Convert v2 binary training data to packed tensors | [
"Convert",
"v2",
"binary",
"training",
"data",
"to",
"packed",
"tensors"
] | def convert_v2_to_tuple(self, content):
"""
Convert v2 binary training data to packed tensors
v2 struct format is
int32 ver
float probs[19*18+1]
byte planes[19*19*16/8]
byte to_move
byte winner
packed tensor formats are
float32 winner
float32*362 probs
uint8*6498 planes
"""
(ver, probs, planes, to_move, winner) = self.v2_struct.unpack(content)
# Unpack planes.
planes = np.unpackbits(np.frombuffer(planes, dtype=np.uint8))
assert len(planes) == 19*19*16
# Now we add the two final planes, being the 'color to move' planes.
stm = to_move
assert stm == 0 or stm == 1
# Flattern all planes to a single byte string
planes = planes.tobytes() + self.flat_planes[stm]
assert len(planes) == (18 * 19 * 19), len(planes)
winner = float(winner * 2 - 1)
assert winner == 1.0 or winner == -1.0, winner
winner = struct.pack('f', winner)
return (planes, probs, winner) | [
"def",
"convert_v2_to_tuple",
"(",
"self",
",",
"content",
")",
":",
"(",
"ver",
",",
"probs",
",",
"planes",
",",
"to_move",
",",
"winner",
")",
"=",
"self",
".",
"v2_struct",
".",
"unpack",
"(",
"content",
")",
"# Unpack planes.",
"planes",
"=",
"np",
... | https://github.com/leela-zero/leela-zero/blob/e3ed6310d33d75078ba74c3adf887d18439fc2e3/training/tf/chunkparser.py#L251-L282 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/pipes.py | python | Template.clone | (self) | return t | t.clone() returns a new pipeline template with identical
initial state as the current one. | t.clone() returns a new pipeline template with identical
initial state as the current one. | [
"t",
".",
"clone",
"()",
"returns",
"a",
"new",
"pipeline",
"template",
"with",
"identical",
"initial",
"state",
"as",
"the",
"current",
"one",
"."
] | def clone(self):
"""t.clone() returns a new pipeline template with identical
initial state as the current one."""
t = Template()
t.steps = self.steps[:]
t.debugging = self.debugging
return t | [
"def",
"clone",
"(",
"self",
")",
":",
"t",
"=",
"Template",
"(",
")",
"t",
".",
"steps",
"=",
"self",
".",
"steps",
"[",
":",
"]",
"t",
".",
"debugging",
"=",
"self",
".",
"debugging",
"return",
"t"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pipes.py#L98-L104 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | DC.Blit | (*args, **kwargs) | return _gdi_.DC_Blit(*args, **kwargs) | Blit(self, int xdest, int ydest, int width, int height, DC source,
int xsrc, int ysrc, int rop=COPY, bool useMask=False,
int xsrcMask=-1, int ysrcMask=-1) -> bool
Copy from a source DC to this DC. Parameters specify the destination
coordinates, size of area to copy, source DC, source coordinates,
logical function, whether to use a bitmap mask, and mask source
position. | Blit(self, int xdest, int ydest, int width, int height, DC source,
int xsrc, int ysrc, int rop=COPY, bool useMask=False,
int xsrcMask=-1, int ysrcMask=-1) -> bool | [
"Blit",
"(",
"self",
"int",
"xdest",
"int",
"ydest",
"int",
"width",
"int",
"height",
"DC",
"source",
"int",
"xsrc",
"int",
"ysrc",
"int",
"rop",
"=",
"COPY",
"bool",
"useMask",
"=",
"False",
"int",
"xsrcMask",
"=",
"-",
"1",
"int",
"ysrcMask",
"=",
... | def Blit(*args, **kwargs):
"""
Blit(self, int xdest, int ydest, int width, int height, DC source,
int xsrc, int ysrc, int rop=COPY, bool useMask=False,
int xsrcMask=-1, int ysrcMask=-1) -> bool
Copy from a source DC to this DC. Parameters specify the destination
coordinates, size of area to copy, source DC, source coordinates,
logical function, whether to use a bitmap mask, and mask source
position.
"""
return _gdi_.DC_Blit(*args, **kwargs) | [
"def",
"Blit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_Blit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L3779-L3790 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sframe.py | python | SFrame.__init__ | (self, data=None,
format='auto',
_proxy=None) | __init__(data=list(), format='auto')
Construct a new SFrame from a url or a pandas.DataFrame. | __init__(data=list(), format='auto')
Construct a new SFrame from a url or a pandas.DataFrame. | [
"__init__",
"(",
"data",
"=",
"list",
"()",
"format",
"=",
"auto",
")",
"Construct",
"a",
"new",
"SFrame",
"from",
"a",
"url",
"or",
"a",
"pandas",
".",
"DataFrame",
"."
] | def __init__(self, data=None,
format='auto',
_proxy=None):
"""__init__(data=list(), format='auto')
Construct a new SFrame from a url or a pandas.DataFrame.
"""
# emit metrics for num_rows, num_columns, and type (local://, s3, hdfs, http)
SFrame.__construct_ctr += 1
if SFrame.__construct_ctr % 1000 == 0:
_mt._get_metric_tracker().track('sframe.init1000')
if (_proxy):
self.__proxy__ = _proxy
else:
self.__proxy__ = UnitySFrameProxy(glconnect.get_client())
_format = None
if (format == 'auto'):
if (HAS_PANDAS and isinstance(data, pandas.DataFrame)):
_format = 'dataframe'
_mt._get_metric_tracker().track('sframe.location.memory', value=1)
elif (isinstance(data, str) or
(sys.version_info.major < 3 and isinstance(data, unicode))):
if data.find('://') == -1:
suffix = 'local'
else:
suffix = data.split('://')[0]
if data.endswith(('.csv', '.csv.gz')):
_format = 'csv'
elif data.endswith(('.tsv', '.tsv.gz')):
_format = 'tsv'
elif data.endswith(('.txt', '.txt.gz')):
print("Assuming file is csv. For other delimiters, " + \
"please use `SFrame.read_csv`.")
_format = 'csv'
else:
_format = 'sframe'
elif type(data) == SArray:
_format = 'sarray'
elif isinstance(data, SFrame):
_format = 'sframe_obj'
elif isinstance(data, dict):
_format = 'dict'
elif _is_non_string_iterable(data):
_format = 'array'
elif data is None:
_format = 'empty'
else:
raise ValueError('Cannot infer input type for data ' + str(data))
else:
_format = format
with cython_context():
if (_format == 'dataframe'):
for c in data.columns.values:
self.add_column(SArray(data[c].values), str(c))
elif (_format == 'sframe_obj'):
for col in data.column_names():
self.__proxy__.add_column(data[col].__proxy__, col)
elif (_format == 'sarray'):
self.__proxy__.add_column(data.__proxy__, '')
elif (_format == 'array'):
if len(data) > 0:
unique_types = set([type(x) for x in data if x is not None])
if len(unique_types) == 1 and SArray in unique_types:
for arr in data:
self.add_column(arr)
elif SArray in unique_types:
raise ValueError("Cannot create SFrame from mix of regular values and SArrays")
else:
self.__proxy__.add_column(SArray(data).__proxy__, '')
elif (_format == 'dict'):
# Validate that every column is the same length.
if len(set(len(value) for value in data.values())) > 1:
# probably should be a value error. But we used to raise
# runtime error here...
raise RuntimeError("All column should be of the same length")
# split into SArray values and other iterable values.
# We convert the iterable values in bulk, and then add the sarray values as columns
sarray_keys = sorted(key for key,value in six.iteritems(data) if isinstance(value, SArray))
self.__proxy__.load_from_dataframe({key:value for key,value in six.iteritems(data) if not isinstance(value, SArray)})
for key in sarray_keys:
self.__proxy__.add_column(data[key].__proxy__, key)
elif (_format == 'csv'):
url = data
tmpsf = SFrame.read_csv(url, delimiter=',', header=True)
self.__proxy__ = tmpsf.__proxy__
elif (_format == 'tsv'):
url = data
tmpsf = SFrame.read_csv(url, delimiter='\t', header=True)
self.__proxy__ = tmpsf.__proxy__
elif (_format == 'sframe'):
url = _make_internal_url(data)
self.__proxy__.load_from_sframe_index(url)
elif (_format == 'empty'):
pass
else:
raise ValueError('Unknown input type: ' + format)
sframe_size = -1
if self.__has_size__():
sframe_size = self.num_rows() | [
"def",
"__init__",
"(",
"self",
",",
"data",
"=",
"None",
",",
"format",
"=",
"'auto'",
",",
"_proxy",
"=",
"None",
")",
":",
"# emit metrics for num_rows, num_columns, and type (local://, s3, hdfs, http)",
"SFrame",
".",
"__construct_ctr",
"+=",
"1",
"if",
"SFrame"... | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sframe.py#L852-L957 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | FileType_ExpandCommand | (*args, **kwargs) | return _misc_.FileType_ExpandCommand(*args, **kwargs) | FileType_ExpandCommand(String command, String filename, String mimetype=EmptyString) -> String | FileType_ExpandCommand(String command, String filename, String mimetype=EmptyString) -> String | [
"FileType_ExpandCommand",
"(",
"String",
"command",
"String",
"filename",
"String",
"mimetype",
"=",
"EmptyString",
")",
"-",
">",
"String"
] | def FileType_ExpandCommand(*args, **kwargs):
"""FileType_ExpandCommand(String command, String filename, String mimetype=EmptyString) -> String"""
return _misc_.FileType_ExpandCommand(*args, **kwargs) | [
"def",
"FileType_ExpandCommand",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"FileType_ExpandCommand",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L2645-L2647 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | Gauge.IsVertical | (*args, **kwargs) | return _controls_.Gauge_IsVertical(*args, **kwargs) | IsVertical(self) -> bool | IsVertical(self) -> bool | [
"IsVertical",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsVertical(*args, **kwargs):
"""IsVertical(self) -> bool"""
return _controls_.Gauge_IsVertical(*args, **kwargs) | [
"def",
"IsVertical",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Gauge_IsVertical",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L767-L769 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/dataclasses.py | python | field | (*, default=MISSING, default_factory=MISSING, init=True, repr=True,
hash=None, compare=True, metadata=None) | return Field(default, default_factory, init, repr, hash, compare,
metadata) | Return an object to identify dataclass fields.
default is the default value of the field. default_factory is a
0-argument function called to initialize a field's value. If init
is True, the field will be a parameter to the class's __init__()
function. If repr is True, the field will be included in the
object's repr(). If hash is True, the field will be included in
the object's hash(). If compare is True, the field will be used
in comparison functions. metadata, if specified, must be a
mapping which is stored but not otherwise examined by dataclass.
It is an error to specify both default and default_factory. | Return an object to identify dataclass fields. | [
"Return",
"an",
"object",
"to",
"identify",
"dataclass",
"fields",
"."
] | def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
hash=None, compare=True, metadata=None):
"""Return an object to identify dataclass fields.
default is the default value of the field. default_factory is a
0-argument function called to initialize a field's value. If init
is True, the field will be a parameter to the class's __init__()
function. If repr is True, the field will be included in the
object's repr(). If hash is True, the field will be included in
the object's hash(). If compare is True, the field will be used
in comparison functions. metadata, if specified, must be a
mapping which is stored but not otherwise examined by dataclass.
It is an error to specify both default and default_factory.
"""
if default is not MISSING and default_factory is not MISSING:
raise ValueError('cannot specify both default and default_factory')
return Field(default, default_factory, init, repr, hash, compare,
metadata) | [
"def",
"field",
"(",
"*",
",",
"default",
"=",
"MISSING",
",",
"default_factory",
"=",
"MISSING",
",",
"init",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"hash",
"=",
"None",
",",
"compare",
"=",
"True",
",",
"metadata",
"=",
"None",
")",
":",
"if... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/dataclasses.py#L309-L328 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/all_reduce/python/all_reduce.py | python | _padded_split | (tensor, pieces) | Like split for 1D tensors but pads-out case where len % pieces != 0.
Args:
tensor: T @{tf.Tensor} that must be 1D.
pieces: a positive integer specifying the number of pieces into which
tensor should be split.
Returns:
list of T @{tf.Tensor} of length pieces, which hold the values of
thin input tensor, in order. The final tensor may
be zero-padded on the end to make its size equal to those of all
of the other tensors.
Raises:
ValueError: The input tensor is not 1D. | Like split for 1D tensors but pads-out case where len % pieces != 0. | [
"Like",
"split",
"for",
"1D",
"tensors",
"but",
"pads",
"-",
"out",
"case",
"where",
"len",
"%",
"pieces",
"!",
"=",
"0",
"."
] | def _padded_split(tensor, pieces):
"""Like split for 1D tensors but pads-out case where len % pieces != 0.
Args:
tensor: T @{tf.Tensor} that must be 1D.
pieces: a positive integer specifying the number of pieces into which
tensor should be split.
Returns:
list of T @{tf.Tensor} of length pieces, which hold the values of
thin input tensor, in order. The final tensor may
be zero-padded on the end to make its size equal to those of all
of the other tensors.
Raises:
ValueError: The input tensor is not 1D.
"""
shape = tensor.shape
if 1 != len(shape):
raise ValueError("input tensor must be 1D")
tensor_len = shape[0].value
with ops.colocate_with(tensor):
if tensor_len % pieces != 0:
# pad to an even length
chunk_size = 1 + tensor_len // pieces
if pieces > tensor_len:
# This is an edge case that should not come up in practice,
# i.e. a different reduction algorithm would be better,
# but we'll make it work just for completeness.
pad_len = pieces - tensor_len
extended_whole = array_ops.concat(
[tensor, array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)
parts = array_ops.split(extended_whole, pieces)
return parts, pad_len
elif (pieces - 1) * chunk_size >= tensor_len:
# Another edge case of limited real interest.
pad_len = (pieces * chunk_size) % tensor_len
extended_whole = array_ops.concat(
[tensor, array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)
parts = array_ops.split(extended_whole, pieces)
return parts, pad_len
else:
last_chunk_size = tensor_len - (pieces - 1) * chunk_size
pad_len = chunk_size - last_chunk_size
piece_lens = [chunk_size for _ in range(pieces - 1)] + [last_chunk_size]
parts = array_ops.split(tensor, piece_lens)
parts[-1] = array_ops.concat(
[parts[-1], array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)
return parts, pad_len
else:
return array_ops.split(tensor, pieces), 0 | [
"def",
"_padded_split",
"(",
"tensor",
",",
"pieces",
")",
":",
"shape",
"=",
"tensor",
".",
"shape",
"if",
"1",
"!=",
"len",
"(",
"shape",
")",
":",
"raise",
"ValueError",
"(",
"\"input tensor must be 1D\"",
")",
"tensor_len",
"=",
"shape",
"[",
"0",
"]... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/all_reduce/python/all_reduce.py#L78-L128 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/model_selection/_search.py | python | _CVScoreTuple.__repr__ | (self) | return "mean: {0:.5f}, std: {1:.5f}, params: {2}".format(
self.mean_validation_score,
np.std(self.cv_validation_scores),
self.parameters) | Simple custom repr to summarize the main info | Simple custom repr to summarize the main info | [
"Simple",
"custom",
"repr",
"to",
"summarize",
"the",
"main",
"info"
] | def __repr__(self):
"""Simple custom repr to summarize the main info"""
return "mean: {0:.5f}, std: {1:.5f}, params: {2}".format(
self.mean_validation_score,
np.std(self.cv_validation_scores),
self.parameters) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"mean: {0:.5f}, std: {1:.5f}, params: {2}\"",
".",
"format",
"(",
"self",
".",
"mean_validation_score",
",",
"np",
".",
"std",
"(",
"self",
".",
"cv_validation_scores",
")",
",",
"self",
".",
"parameters",
")... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/model_selection/_search.py#L364-L369 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/util/fileops.py | python | get_file_handle | (path, append_file=False) | return open(path, mode) | Open 'path', truncate it if 'append_file' is False, and return file handle. | Open 'path', truncate it if 'append_file' is False, and return file handle. | [
"Open",
"path",
"truncate",
"it",
"if",
"append_file",
"is",
"False",
"and",
"return",
"file",
"handle",
"."
] | def get_file_handle(path, append_file=False):
"""Open 'path', truncate it if 'append_file' is False, and return file handle."""
mode = "a+" if append_file else "w"
return open(path, mode) | [
"def",
"get_file_handle",
"(",
"path",
",",
"append_file",
"=",
"False",
")",
":",
"mode",
"=",
"\"a+\"",
"if",
"append_file",
"else",
"\"w\"",
"return",
"open",
"(",
"path",
",",
"mode",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/util/fileops.py#L26-L29 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/internals/managers.py | python | BlockManager.as_array | (
self,
transpose: bool = False,
dtype: Dtype | None = None,
copy: bool = False,
na_value=lib.no_default,
) | return arr.transpose() if transpose else arr | Convert the blockmanager data into an numpy array.
Parameters
----------
transpose : bool, default False
If True, transpose the return array.
dtype : object, default None
Data type of the return array.
copy : bool, default False
If True then guarantee that a copy is returned. A value of
False does not guarantee that the underlying data is not
copied.
na_value : object, default lib.no_default
Value to be used as the missing value sentinel.
Returns
-------
arr : ndarray | Convert the blockmanager data into an numpy array. | [
"Convert",
"the",
"blockmanager",
"data",
"into",
"an",
"numpy",
"array",
"."
] | def as_array(
self,
transpose: bool = False,
dtype: Dtype | None = None,
copy: bool = False,
na_value=lib.no_default,
) -> np.ndarray:
"""
Convert the blockmanager data into an numpy array.
Parameters
----------
transpose : bool, default False
If True, transpose the return array.
dtype : object, default None
Data type of the return array.
copy : bool, default False
If True then guarantee that a copy is returned. A value of
False does not guarantee that the underlying data is not
copied.
na_value : object, default lib.no_default
Value to be used as the missing value sentinel.
Returns
-------
arr : ndarray
"""
if len(self.blocks) == 0:
arr = np.empty(self.shape, dtype=float)
return arr.transpose() if transpose else arr
# We want to copy when na_value is provided to avoid
# mutating the original object
copy = copy or na_value is not lib.no_default
if self.is_single_block:
blk = self.blocks[0]
if blk.is_extension:
# Avoid implicit conversion of extension blocks to object
# error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no
# attribute "to_numpy"
arr = blk.values.to_numpy( # type: ignore[union-attr]
dtype=dtype, na_value=na_value
).reshape(blk.shape)
else:
arr = np.asarray(blk.get_values())
if dtype:
# error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has
# incompatible type "Union[ExtensionDtype, str, dtype[Any],
# Type[object]]"; expected "Union[dtype[Any], None, type,
# _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int,
# Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
arr = arr.astype(dtype, copy=False) # type: ignore[arg-type]
else:
arr = self._interleave(dtype=dtype, na_value=na_value)
# The underlying data was copied within _interleave
copy = False
if copy:
arr = arr.copy()
if na_value is not lib.no_default:
arr[isna(arr)] = na_value
return arr.transpose() if transpose else arr | [
"def",
"as_array",
"(",
"self",
",",
"transpose",
":",
"bool",
"=",
"False",
",",
"dtype",
":",
"Dtype",
"|",
"None",
"=",
"None",
",",
"copy",
":",
"bool",
"=",
"False",
",",
"na_value",
"=",
"lib",
".",
"no_default",
",",
")",
"->",
"np",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/managers.py#L1411-L1476 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py | python | UpdateIncludeState | (filename, include_dict, io=codecs) | return True | Fill up the include_dict with new includes found from the file.
Args:
filename: the name of the header to read.
include_dict: a dictionary in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was successfully added. False otherwise. | Fill up the include_dict with new includes found from the file. | [
"Fill",
"up",
"the",
"include_dict",
"with",
"new",
"includes",
"found",
"from",
"the",
"file",
"."
] | def UpdateIncludeState(filename, include_dict, io=codecs):
"""Fill up the include_dict with new includes found from the file.
Args:
filename: the name of the header to read.
include_dict: a dictionary in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was successfully added. False otherwise.
"""
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
include_dict.setdefault(include, linenum)
return True | [
"def",
"UpdateIncludeState",
"(",
"filename",
",",
"include_dict",
",",
"io",
"=",
"codecs",
")",
":",
"headerfile",
"=",
"None",
"try",
":",
"headerfile",
"=",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf8'",
",",
"'replace'",
")",
"except... | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py#L5724-L5748 | |
NVIDIA/MDL-SDK | aa9642b2546ad7b6236b5627385d882c2ed83c5d | src/mdl/jit/llvm/dist/utils/lit/lit/Util.py | python | to_string | (b) | Return the parameter as type 'str', possibly encoding it.
In Python2, the 'str' type is the same as 'bytes'. In Python3, the
'str' type is (essentially) Python2's 'unicode' type, and 'bytes' is
distinct. | Return the parameter as type 'str', possibly encoding it. | [
"Return",
"the",
"parameter",
"as",
"type",
"str",
"possibly",
"encoding",
"it",
"."
] | def to_string(b):
"""Return the parameter as type 'str', possibly encoding it.
In Python2, the 'str' type is the same as 'bytes'. In Python3, the
'str' type is (essentially) Python2's 'unicode' type, and 'bytes' is
distinct.
"""
if isinstance(b, str):
# In Python2, this branch is taken for types 'str' and 'bytes'.
# In Python3, this branch is taken only for 'str'.
return b
if isinstance(b, bytes):
# In Python2, this branch is never taken ('bytes' is handled as 'str').
# In Python3, this is true only for 'bytes'.
try:
return b.decode('utf-8')
except UnicodeDecodeError:
# If the value is not valid Unicode, return the default
# repr-line encoding.
return str(b)
# By this point, here's what we *don't* have:
#
# - In Python2:
# - 'str' or 'bytes' (1st branch above)
# - In Python3:
# - 'str' (1st branch above)
# - 'bytes' (2nd branch above)
#
# The last type we might expect is the Python2 'unicode' type. There is no
# 'unicode' type in Python3 (all the Python3 cases were already handled). In
# order to get a 'str' object, we need to encode the 'unicode' object.
try:
return b.encode('utf-8')
except AttributeError:
raise TypeError('not sure how to convert %s to %s' % (type(b), str)) | [
"def",
"to_string",
"(",
"b",
")",
":",
"if",
"isinstance",
"(",
"b",
",",
"str",
")",
":",
"# In Python2, this branch is taken for types 'str' and 'bytes'.",
"# In Python3, this branch is taken only for 'str'.",
"return",
"b",
"if",
"isinstance",
"(",
"b",
",",
"bytes"... | https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/llvm/dist/utils/lit/lit/Util.py#L64-L100 | ||
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/examples/python/gdbremote.py | python | TerminalColors.strike | (self, on=True) | return '' | Enable or disable strike through depending on the "on" parameter. | Enable or disable strike through depending on the "on" parameter. | [
"Enable",
"or",
"disable",
"strike",
"through",
"depending",
"on",
"the",
"on",
"parameter",
"."
] | def strike(self, on=True):
'''Enable or disable strike through depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[9m"
else:
return "\x1b[29m"
return '' | [
"def",
"strike",
"(",
"self",
",",
"on",
"=",
"True",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"on",
":",
"return",
"\"\\x1b[9m\"",
"else",
":",
"return",
"\"\\x1b[29m\"",
"return",
"''"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/examples/python/gdbremote.py#L92-L99 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/layers/python/layers/target_column.py | python | _TargetColumn.loss | (self, logits, target, features) | Returns loss tensor for this head.
Args:
logits: logits, a float tensor.
target: either a tensor for labels or in multihead case, a dict of string
to target tensor.
features: features dict.
Returns:
Loss tensor. | Returns loss tensor for this head. | [
"Returns",
"loss",
"tensor",
"for",
"this",
"head",
"."
] | def loss(self, logits, target, features):
"""Returns loss tensor for this head.
Args:
logits: logits, a float tensor.
target: either a tensor for labels or in multihead case, a dict of string
to target tensor.
features: features dict.
Returns:
Loss tensor.
"""
target = target[self.name] if isinstance(target, dict) else target
loss_unweighted = self._loss_fn(logits, target)
weight_tensor = self.get_weight_tensor(features)
if weight_tensor is None:
return math_ops.reduce_mean(loss_unweighted, name="loss")
else:
loss_unweighted = array_ops.reshape(loss_unweighted, shape=(-1,))
loss_weighted = math_ops.mul(
loss_unweighted,
array_ops.reshape(weight_tensor, shape=(-1,)))
return math_ops.div(
math_ops.reduce_sum(loss_weighted),
math_ops.to_float(math_ops.reduce_sum(weight_tensor)),
name="loss") | [
"def",
"loss",
"(",
"self",
",",
"logits",
",",
"target",
",",
"features",
")",
":",
"target",
"=",
"target",
"[",
"self",
".",
"name",
"]",
"if",
"isinstance",
"(",
"target",
",",
"dict",
")",
"else",
"target",
"loss_unweighted",
"=",
"self",
".",
"... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/layers/python/layers/target_column.py#L166-L192 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/util.py | python | parse_marker | (marker_string) | return marker(marker_string) | Parse a marker string and return a dictionary containing a marker expression.
The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
the expression grammar, or strings. A string contained in quotes is to be
interpreted as a literal string, and a string not contained in quotes is a
variable (such as os_name). | Parse a marker string and return a dictionary containing a marker expression. | [
"Parse",
"a",
"marker",
"string",
"and",
"return",
"a",
"dictionary",
"containing",
"a",
"marker",
"expression",
"."
] | def parse_marker(marker_string):
"""
Parse a marker string and return a dictionary containing a marker expression.
The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
the expression grammar, or strings. A string contained in quotes is to be
interpreted as a literal string, and a string not contained in quotes is a
variable (such as os_name).
"""
def marker_var(remaining):
# either identifier, or literal string
m = IDENTIFIER.match(remaining)
if m:
result = m.groups()[0]
remaining = remaining[m.end():]
elif not remaining:
raise SyntaxError('unexpected end of input')
else:
q = remaining[0]
if q not in '\'"':
raise SyntaxError('invalid expression: %s' % remaining)
oq = '\'"'.replace(q, '')
remaining = remaining[1:]
parts = [q]
while remaining:
# either a string chunk, or oq, or q to terminate
if remaining[0] == q:
break
elif remaining[0] == oq:
parts.append(oq)
remaining = remaining[1:]
else:
m = STRING_CHUNK.match(remaining)
if not m:
raise SyntaxError('error in string literal: %s' % remaining)
parts.append(m.groups()[0])
remaining = remaining[m.end():]
else:
s = ''.join(parts)
raise SyntaxError('unterminated string: %s' % s)
parts.append(q)
result = ''.join(parts)
remaining = remaining[1:].lstrip() # skip past closing quote
return result, remaining
def marker_expr(remaining):
if remaining and remaining[0] == '(':
result, remaining = marker(remaining[1:].lstrip())
if remaining[0] != ')':
raise SyntaxError('unterminated parenthesis: %s' % remaining)
remaining = remaining[1:].lstrip()
else:
lhs, remaining = marker_var(remaining)
while remaining:
m = MARKER_OP.match(remaining)
if not m:
break
op = m.groups()[0]
remaining = remaining[m.end():]
rhs, remaining = marker_var(remaining)
lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
result = lhs
return result, remaining
def marker_and(remaining):
lhs, remaining = marker_expr(remaining)
while remaining:
m = AND.match(remaining)
if not m:
break
remaining = remaining[m.end():]
rhs, remaining = marker_expr(remaining)
lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
return lhs, remaining
def marker(remaining):
lhs, remaining = marker_and(remaining)
while remaining:
m = OR.match(remaining)
if not m:
break
remaining = remaining[m.end():]
rhs, remaining = marker_and(remaining)
lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
return lhs, remaining
return marker(marker_string) | [
"def",
"parse_marker",
"(",
"marker_string",
")",
":",
"def",
"marker_var",
"(",
"remaining",
")",
":",
"# either identifier, or literal string",
"m",
"=",
"IDENTIFIER",
".",
"match",
"(",
"remaining",
")",
"if",
"m",
":",
"result",
"=",
"m",
".",
"groups",
... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/util.py#L56-L142 | |
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | watering-system/python/iot_watering_system/log.py | python | log | (event) | Publish message to MQTT server and data store. | Publish message to MQTT server and data store. | [
"Publish",
"message",
"to",
"MQTT",
"server",
"and",
"data",
"store",
"."
] | def log(event):
"""
Publish message to MQTT server and data store.
"""
message = "{0} {1}".format(datetime.utcnow().isoformat(), event)
payload = {"value": message}
print(message)
send(payload) | [
"def",
"log",
"(",
"event",
")",
":",
"message",
"=",
"\"{0} {1}\"",
".",
"format",
"(",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
",",
"event",
")",
"payload",
"=",
"{",
"\"value\"",
":",
"message",
"}",
"print",
"(",
"message... | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/watering-system/python/iot_watering_system/log.py#L45-L54 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitored_session.py | python | _as_graph_element | (obj, graph) | return element | Retrieves Graph element. | Retrieves Graph element. | [
"Retrieves",
"Graph",
"element",
"."
] | def _as_graph_element(obj, graph):
"""Retrieves Graph element."""
graph = graph or ops.get_default_graph()
if not isinstance(obj, six.string_types):
if not hasattr(obj, 'graph') or obj.graph != graph:
raise ValueError('Passed %s should have graph attribute that is equal '
'to current graph %s.' % (obj, graph))
return obj
if ':' in obj:
element = graph.as_graph_element(obj)
else:
element = graph.as_graph_element(obj + ':0')
# Check that there is no :1 (e.g. it's single output).
try:
graph.as_graph_element(obj + ':1')
except (KeyError, ValueError):
pass
else:
raise ValueError('Name %s is ambiguous, '
'as this `Operation` has multiple outputs '
'(at least 2).' % obj)
return element | [
"def",
"_as_graph_element",
"(",
"obj",
",",
"graph",
")",
":",
"graph",
"=",
"graph",
"or",
"ops",
".",
"get_default_graph",
"(",
")",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj"... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitored_session.py#L118-L139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.