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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | components/policy/tools/syntax_check_policy_template_json.py | python | PolicyTemplateChecker._CheckPolicyIDs | (self, policy_ids) | Checks a set of policy_ids to make sure it contains a continuous range
of entries (i.e. no holes).
Holes would not be a technical problem, but we want to ensure that nobody
accidentally omits IDs. | Checks a set of policy_ids to make sure it contains a continuous range
of entries (i.e. no holes).
Holes would not be a technical problem, but we want to ensure that nobody
accidentally omits IDs. | [
"Checks",
"a",
"set",
"of",
"policy_ids",
"to",
"make",
"sure",
"it",
"contains",
"a",
"continuous",
"range",
"of",
"entries",
"(",
"i",
".",
"e",
".",
"no",
"holes",
")",
".",
"Holes",
"would",
"not",
"be",
"a",
"technical",
"problem",
"but",
"we",
"want",
"to",
"ensure",
"that",
"nobody",
"accidentally",
"omits",
"IDs",
"."
] | def _CheckPolicyIDs(self, policy_ids):
'''
Checks a set of policy_ids to make sure it contains a continuous range
of entries (i.e. no holes).
Holes would not be a technical problem, but we want to ensure that nobody
accidentally omits IDs.
'''
for i in range(len(policy_ids)):
if (i + 1) not in policy_ids:
self._Error('No policy with id: %s' % (i + 1)) | [
"def",
"_CheckPolicyIDs",
"(",
"self",
",",
"policy_ids",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"policy_ids",
")",
")",
":",
"if",
"(",
"i",
"+",
"1",
")",
"not",
"in",
"policy_ids",
":",
"self",
".",
"_Error",
"(",
"'No policy with id: %s'",
"%",
"(",
"i",
"+",
"1",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/components/policy/tools/syntax_check_policy_template_json.py#L136-L145 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/linalg/decomp.py | python | eigvalsh_tridiagonal | (d, e, select='a', select_range=None,
check_finite=True, tol=0., lapack_driver='auto') | return eigh_tridiagonal(
d, e, eigvals_only=True, select=select, select_range=select_range,
check_finite=check_finite, tol=tol, lapack_driver=lapack_driver) | Solve eigenvalue problem for a real symmetric tridiagonal matrix.
Find eigenvalues `w` of ``a``::
a v[:,i] = w[i] v[:,i]
v.H v = identity
For a real symmetric matrix ``a`` with diagonal elements `d` and
off-diagonal elements `e`.
Parameters
----------
d : ndarray, shape (ndim,)
The diagonal elements of the array.
e : ndarray, shape (ndim-1,)
The off-diagonal elements of the array.
select : {'a', 'v', 'i'}, optional
Which eigenvalues to calculate
====== ========================================
select calculated
====== ========================================
'a' All eigenvalues
'v' Eigenvalues in the interval (min, max]
'i' Eigenvalues with indices min <= i <= max
====== ========================================
select_range : (min, max), optional
Range of selected eigenvalues
check_finite : bool, optional
Whether to check that the input matrix contains only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
tol : float
The absolute tolerance to which each eigenvalue is required
(only used when ``lapack_driver='stebz'``).
An eigenvalue (or cluster) is considered to have converged if it
lies in an interval of this width. If <= 0. (default),
the value ``eps*|a|`` is used where eps is the machine precision,
and ``|a|`` is the 1-norm of the matrix ``a``.
lapack_driver : str
LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf',
or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'``
and 'stebz' otherwise. 'sterf' and 'stev' can only be used when
``select='a'``.
Returns
-------
w : (M,) ndarray
The eigenvalues, in ascending order, each repeated according to its
multiplicity.
Raises
------
LinAlgError
If eigenvalue computation does not converge.
See Also
--------
eigh_tridiagonal : eigenvalues and right eiegenvectors for
symmetric/Hermitian tridiagonal matrices
Examples
--------
>>> from scipy.linalg import eigvalsh_tridiagonal, eigvalsh
>>> d = 3*np.ones(4)
>>> e = -1*np.ones(3)
>>> w = eigvalsh_tridiagonal(d, e)
>>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
>>> w2 = eigvalsh(A) # Verify with other eigenvalue routines
>>> np.allclose(w - w2, np.zeros(4))
True | Solve eigenvalue problem for a real symmetric tridiagonal matrix. | [
"Solve",
"eigenvalue",
"problem",
"for",
"a",
"real",
"symmetric",
"tridiagonal",
"matrix",
"."
] | def eigvalsh_tridiagonal(d, e, select='a', select_range=None,
check_finite=True, tol=0., lapack_driver='auto'):
"""
Solve eigenvalue problem for a real symmetric tridiagonal matrix.
Find eigenvalues `w` of ``a``::
a v[:,i] = w[i] v[:,i]
v.H v = identity
For a real symmetric matrix ``a`` with diagonal elements `d` and
off-diagonal elements `e`.
Parameters
----------
d : ndarray, shape (ndim,)
The diagonal elements of the array.
e : ndarray, shape (ndim-1,)
The off-diagonal elements of the array.
select : {'a', 'v', 'i'}, optional
Which eigenvalues to calculate
====== ========================================
select calculated
====== ========================================
'a' All eigenvalues
'v' Eigenvalues in the interval (min, max]
'i' Eigenvalues with indices min <= i <= max
====== ========================================
select_range : (min, max), optional
Range of selected eigenvalues
check_finite : bool, optional
Whether to check that the input matrix contains only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
tol : float
The absolute tolerance to which each eigenvalue is required
(only used when ``lapack_driver='stebz'``).
An eigenvalue (or cluster) is considered to have converged if it
lies in an interval of this width. If <= 0. (default),
the value ``eps*|a|`` is used where eps is the machine precision,
and ``|a|`` is the 1-norm of the matrix ``a``.
lapack_driver : str
LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf',
or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'``
and 'stebz' otherwise. 'sterf' and 'stev' can only be used when
``select='a'``.
Returns
-------
w : (M,) ndarray
The eigenvalues, in ascending order, each repeated according to its
multiplicity.
Raises
------
LinAlgError
If eigenvalue computation does not converge.
See Also
--------
eigh_tridiagonal : eigenvalues and right eiegenvectors for
symmetric/Hermitian tridiagonal matrices
Examples
--------
>>> from scipy.linalg import eigvalsh_tridiagonal, eigvalsh
>>> d = 3*np.ones(4)
>>> e = -1*np.ones(3)
>>> w = eigvalsh_tridiagonal(d, e)
>>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
>>> w2 = eigvalsh(A) # Verify with other eigenvalue routines
>>> np.allclose(w - w2, np.zeros(4))
True
"""
return eigh_tridiagonal(
d, e, eigvals_only=True, select=select, select_range=select_range,
check_finite=check_finite, tol=tol, lapack_driver=lapack_driver) | [
"def",
"eigvalsh_tridiagonal",
"(",
"d",
",",
"e",
",",
"select",
"=",
"'a'",
",",
"select_range",
"=",
"None",
",",
"check_finite",
"=",
"True",
",",
"tol",
"=",
"0.",
",",
"lapack_driver",
"=",
"'auto'",
")",
":",
"return",
"eigh_tridiagonal",
"(",
"d",
",",
"e",
",",
"eigvals_only",
"=",
"True",
",",
"select",
"=",
"select",
",",
"select_range",
"=",
"select_range",
",",
"check_finite",
"=",
"check_finite",
",",
"tol",
"=",
"tol",
",",
"lapack_driver",
"=",
"lapack_driver",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/decomp.py#L956-L1033 | |
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | python/taichi/ui/gui.py | python | GUI.arrow_field | (self,
direction,
radius=1,
color=0xffffff,
bound=0.5,
**kwargs) | Draw a field of arrows on canvas.
Args:
direction (np.array): The pattern and direction of the field of arrows.
color (Union[int, np.array], optional): The color or colors of arrows.
Default is 0xFFFFFF.
bound (Number, optional): The boundary of the field. Default is 0.5. | Draw a field of arrows on canvas. | [
"Draw",
"a",
"field",
"of",
"arrows",
"on",
"canvas",
"."
] | def arrow_field(self,
direction,
radius=1,
color=0xffffff,
bound=0.5,
**kwargs):
"""Draw a field of arrows on canvas.
Args:
direction (np.array): The pattern and direction of the field of arrows.
color (Union[int, np.array], optional): The color or colors of arrows.
Default is 0xFFFFFF.
bound (Number, optional): The boundary of the field. Default is 0.5.
"""
assert len(direction.shape) == 3
assert direction.shape[2] == 2
base = self._make_field_base(direction.shape[0], direction.shape[1],
bound)
direction = direction.reshape(direction.shape[0] * direction.shape[1],
2)
self.arrows(base, direction, radius=radius, color=color, **kwargs) | [
"def",
"arrow_field",
"(",
"self",
",",
"direction",
",",
"radius",
"=",
"1",
",",
"color",
"=",
"0xffffff",
",",
"bound",
"=",
"0.5",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"len",
"(",
"direction",
".",
"shape",
")",
"==",
"3",
"assert",
"direction",
".",
"shape",
"[",
"2",
"]",
"==",
"2",
"base",
"=",
"self",
".",
"_make_field_base",
"(",
"direction",
".",
"shape",
"[",
"0",
"]",
",",
"direction",
".",
"shape",
"[",
"1",
"]",
",",
"bound",
")",
"direction",
"=",
"direction",
".",
"reshape",
"(",
"direction",
".",
"shape",
"[",
"0",
"]",
"*",
"direction",
".",
"shape",
"[",
"1",
"]",
",",
"2",
")",
"self",
".",
"arrows",
"(",
"base",
",",
"direction",
",",
"radius",
"=",
"radius",
",",
"color",
"=",
"color",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/ui/gui.py#L648-L669 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGrid.GetMarginColour | (*args, **kwargs) | return _propgrid.PropertyGrid_GetMarginColour(*args, **kwargs) | GetMarginColour(self) -> Colour | GetMarginColour(self) -> Colour | [
"GetMarginColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetMarginColour(*args, **kwargs):
"""GetMarginColour(self) -> Colour"""
return _propgrid.PropertyGrid_GetMarginColour(*args, **kwargs) | [
"def",
"GetMarginColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_GetMarginColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L2106-L2108 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/tools/grit/grit/gather/chrome_scaled_image.py | python | _MakeBraceGlob | (strings) | Given ['foo', 'bar'], return '{foo,bar}', for error reporting. | Given ['foo', 'bar'], return '{foo,bar}', for error reporting. | [
"Given",
"[",
"foo",
"bar",
"]",
"return",
"{",
"foo",
"bar",
"}",
"for",
"error",
"reporting",
"."
] | def _MakeBraceGlob(strings):
'''Given ['foo', 'bar'], return '{foo,bar}', for error reporting.
'''
if len(strings) == 1:
return strings[0]
else:
return '{' + ','.join(strings) + '}' | [
"def",
"_MakeBraceGlob",
"(",
"strings",
")",
":",
"if",
"len",
"(",
"strings",
")",
"==",
"1",
":",
"return",
"strings",
"[",
"0",
"]",
"else",
":",
"return",
"'{'",
"+",
"','",
".",
"join",
"(",
"strings",
")",
"+",
"'}'"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/gather/chrome_scaled_image.py#L77-L83 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_view.py | python | GeneralFittingView.set_slot_for_simultaneous_fit_by_specifier_changed | (self, slot) | Connect the slot for the fit specifier combo box being changed. | Connect the slot for the fit specifier combo box being changed. | [
"Connect",
"the",
"slot",
"for",
"the",
"fit",
"specifier",
"combo",
"box",
"being",
"changed",
"."
] | def set_slot_for_simultaneous_fit_by_specifier_changed(self, slot) -> None:
"""Connect the slot for the fit specifier combo box being changed."""
self.general_fitting_options.set_slot_for_simultaneous_fit_by_specifier_changed(slot) | [
"def",
"set_slot_for_simultaneous_fit_by_specifier_changed",
"(",
"self",
",",
"slot",
")",
"->",
"None",
":",
"self",
".",
"general_fitting_options",
".",
"set_slot_for_simultaneous_fit_by_specifier_changed",
"(",
"slot",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/general_fitting/general_fitting_view.py#L38-L40 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBSourceManager.DisplaySourceLinesWithLineNumbers | (self, *args) | return _lldb.SBSourceManager_DisplaySourceLinesWithLineNumbers(self, *args) | DisplaySourceLinesWithLineNumbers(self, SBFileSpec file, uint32_t line, uint32_t context_before,
uint32_t context_after, str current_line_cstr,
SBStream s) -> size_t | DisplaySourceLinesWithLineNumbers(self, SBFileSpec file, uint32_t line, uint32_t context_before,
uint32_t context_after, str current_line_cstr,
SBStream s) -> size_t | [
"DisplaySourceLinesWithLineNumbers",
"(",
"self",
"SBFileSpec",
"file",
"uint32_t",
"line",
"uint32_t",
"context_before",
"uint32_t",
"context_after",
"str",
"current_line_cstr",
"SBStream",
"s",
")",
"-",
">",
"size_t"
] | def DisplaySourceLinesWithLineNumbers(self, *args):
"""
DisplaySourceLinesWithLineNumbers(self, SBFileSpec file, uint32_t line, uint32_t context_before,
uint32_t context_after, str current_line_cstr,
SBStream s) -> size_t
"""
return _lldb.SBSourceManager_DisplaySourceLinesWithLineNumbers(self, *args) | [
"def",
"DisplaySourceLinesWithLineNumbers",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBSourceManager_DisplaySourceLinesWithLineNumbers",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7855-L7861 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.AdjustIncludeDirs | (self, include_dirs, config) | return [self.ConvertVSMacros(p, config=config) for p in includes] | Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar. | Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar. | [
"Updates",
"include_dirs",
"to",
"expand",
"VS",
"specific",
"paths",
"and",
"adds",
"the",
"system",
"include",
"dirs",
"used",
"for",
"platform",
"SDK",
"and",
"similar",
"."
] | def AdjustIncludeDirs(self, include_dirs, config):
"""Updates include_dirs to expand VS specific paths, and adds the system
include dirs used for platform SDK and similar."""
config = self._TargetConfig(config)
includes = include_dirs + self.msvs_system_include_dirs[config]
includes.extend(self._Setting(
('VCCLCompilerTool', 'AdditionalIncludeDirectories'), config, default=[]))
return [self.ConvertVSMacros(p, config=config) for p in includes] | [
"def",
"AdjustIncludeDirs",
"(",
"self",
",",
"include_dirs",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"includes",
"=",
"include_dirs",
"+",
"self",
".",
"msvs_system_include_dirs",
"[",
"config",
"]",
"includes",
".",
"extend",
"(",
"self",
".",
"_Setting",
"(",
"(",
"'VCCLCompilerTool'",
",",
"'AdditionalIncludeDirectories'",
")",
",",
"config",
",",
"default",
"=",
"[",
"]",
")",
")",
"return",
"[",
"self",
".",
"ConvertVSMacros",
"(",
"p",
",",
"config",
"=",
"config",
")",
"for",
"p",
"in",
"includes",
"]"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/msvs_emulation.py#L332-L339 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/protobuf/python/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',
'_unknown_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'",
",",
"'_unknown_fields'",
",",
"'_is_present_in_parent'",
",",
"'_listener'",
",",
"'_listener_for_children'",
",",
"'__weakref__'",
"]"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/protobuf/python/google/protobuf/internal/python_message.py#L164-L179 | ||
greenheartgames/greenworks | 3ea4ab490b56676de3f0a237c74bcfdb17323e60 | deps/cpplint/cpplint.py | python | FileInfo.Split | (self) | return (project,) + os.path.splitext(rest) | Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension). | Splits the file into the directory, basename, and extension. | [
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
"."
] | def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest) | [
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
".",
"splitext",
"(",
"rest",
")"
] | https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L1130-L1142 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/android/sdk/adb_wrapper.py | python | AdbWrapper.Pull | (self, remote, local, timeout=60 * 5, retries=DEFAULT_RETRIES) | Pulls a file from the device to the host.
Args:
remote: Path on the device filesystem.
local: Path on the host filesystem.
timeout: (optional) Timeout per try in seconds.
retries: (optional) Number of retries to attempt. | Pulls a file from the device to the host. | [
"Pulls",
"a",
"file",
"from",
"the",
"device",
"to",
"the",
"host",
"."
] | def Pull(self, remote, local, timeout=60 * 5, retries=DEFAULT_RETRIES):
"""Pulls a file from the device to the host.
Args:
remote: Path on the device filesystem.
local: Path on the host filesystem.
timeout: (optional) Timeout per try in seconds.
retries: (optional) Number of retries to attempt.
"""
cmd = ['pull', remote, local]
self._RunDeviceAdbCmd(cmd, timeout, retries)
try:
VerifyLocalFileExists(local)
except IOError:
raise device_errors.AdbCommandFailedError(
cmd, 'File not found on host: %s' % local, device_serial=str(self)) | [
"def",
"Pull",
"(",
"self",
",",
"remote",
",",
"local",
",",
"timeout",
"=",
"60",
"*",
"5",
",",
"retries",
"=",
"DEFAULT_RETRIES",
")",
":",
"cmd",
"=",
"[",
"'pull'",
",",
"remote",
",",
"local",
"]",
"self",
".",
"_RunDeviceAdbCmd",
"(",
"cmd",
",",
"timeout",
",",
"retries",
")",
"try",
":",
"VerifyLocalFileExists",
"(",
"local",
")",
"except",
"IOError",
":",
"raise",
"device_errors",
".",
"AdbCommandFailedError",
"(",
"cmd",
",",
"'File not found on host: %s'",
"%",
"local",
",",
"device_serial",
"=",
"str",
"(",
"self",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/sdk/adb_wrapper.py#L437-L452 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/google/protobuf/json_format.py | python | _ListValueMessageToJsonObject | (message, unused_including_default=False) | return [_ValueMessageToJsonObject(value)
for value in message.values] | Converts ListValue message according to Proto3 JSON Specification. | Converts ListValue message according to Proto3 JSON Specification. | [
"Converts",
"ListValue",
"message",
"according",
"to",
"Proto3",
"JSON",
"Specification",
"."
] | def _ListValueMessageToJsonObject(message, unused_including_default=False):
"""Converts ListValue message according to Proto3 JSON Specification."""
return [_ValueMessageToJsonObject(value)
for value in message.values] | [
"def",
"_ListValueMessageToJsonObject",
"(",
"message",
",",
"unused_including_default",
"=",
"False",
")",
":",
"return",
"[",
"_ValueMessageToJsonObject",
"(",
"value",
")",
"for",
"value",
"in",
"message",
".",
"values",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/json_format.py#L265-L268 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | tutorials/roofit/rf401_importttreethx.py | python | makeTTree | () | return tree | Create ROOT ROOT.TTree filled with a Gaussian distribution in x and a uniform distribution in y. | Create ROOT ROOT.TTree filled with a Gaussian distribution in x and a uniform distribution in y. | [
"Create",
"ROOT",
"ROOT",
".",
"TTree",
"filled",
"with",
"a",
"Gaussian",
"distribution",
"in",
"x",
"and",
"a",
"uniform",
"distribution",
"in",
"y",
"."
] | def makeTTree():
"""Create ROOT ROOT.TTree filled with a Gaussian distribution in x and a uniform distribution in y."""
tree = ROOT.TTree("tree", "tree")
px = array("d", [0])
py = array("d", [0])
pz = array("d", [0])
pi = array("i", [0])
tree.Branch("x", px, "x/D")
tree.Branch("y", py, "y/D")
tree.Branch("z", pz, "z/D")
tree.Branch("i", pi, "i/I")
for i in range(100):
px[0] = ROOT.gRandom.Gaus(0, 3)
py[0] = ROOT.gRandom.Uniform() * 30 - 15
pz[0] = ROOT.gRandom.Gaus(0, 5)
pi[0] = i % 3
tree.Fill()
return tree | [
"def",
"makeTTree",
"(",
")",
":",
"tree",
"=",
"ROOT",
".",
"TTree",
"(",
"\"tree\"",
",",
"\"tree\"",
")",
"px",
"=",
"array",
"(",
"\"d\"",
",",
"[",
"0",
"]",
")",
"py",
"=",
"array",
"(",
"\"d\"",
",",
"[",
"0",
"]",
")",
"pz",
"=",
"array",
"(",
"\"d\"",
",",
"[",
"0",
"]",
")",
"pi",
"=",
"array",
"(",
"\"i\"",
",",
"[",
"0",
"]",
")",
"tree",
".",
"Branch",
"(",
"\"x\"",
",",
"px",
",",
"\"x/D\"",
")",
"tree",
".",
"Branch",
"(",
"\"y\"",
",",
"py",
",",
"\"y/D\"",
")",
"tree",
".",
"Branch",
"(",
"\"z\"",
",",
"pz",
",",
"\"z/D\"",
")",
"tree",
".",
"Branch",
"(",
"\"i\"",
",",
"pi",
",",
"\"i/I\"",
")",
"for",
"i",
"in",
"range",
"(",
"100",
")",
":",
"px",
"[",
"0",
"]",
"=",
"ROOT",
".",
"gRandom",
".",
"Gaus",
"(",
"0",
",",
"3",
")",
"py",
"[",
"0",
"]",
"=",
"ROOT",
".",
"gRandom",
".",
"Uniform",
"(",
")",
"*",
"30",
"-",
"15",
"pz",
"[",
"0",
"]",
"=",
"ROOT",
".",
"gRandom",
".",
"Gaus",
"(",
"0",
",",
"5",
")",
"pi",
"[",
"0",
"]",
"=",
"i",
"%",
"3",
"tree",
".",
"Fill",
"(",
")",
"return",
"tree"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/tutorials/roofit/rf401_importttreethx.py#L30-L49 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/abseil-cpp/create_lts.py | python | ReplaceStringsInFile | (filename, replacement_dict) | Performs textual replacements in a file.
Rewrites filename with the keys in replacement_dict replaced with
their values. This function assumes the file can fit in memory.
Args:
filename: the filename to perform the replacement on
replacement_dict: a dictionary of key strings to be replaced with their
values
Raises:
Exception: A failure occured | Performs textual replacements in a file. | [
"Performs",
"textual",
"replacements",
"in",
"a",
"file",
"."
] | def ReplaceStringsInFile(filename, replacement_dict):
"""Performs textual replacements in a file.
Rewrites filename with the keys in replacement_dict replaced with
their values. This function assumes the file can fit in memory.
Args:
filename: the filename to perform the replacement on
replacement_dict: a dictionary of key strings to be replaced with their
values
Raises:
Exception: A failure occured
"""
f = open(filename, 'r')
content = f.read()
f.close()
for key, value in replacement_dict.items():
original = content
content = content.replace(key, value)
if content == original:
raise Exception('Failed to find {} in {}'.format(key, filename))
f = open(filename, 'w')
f.write(content)
f.close() | [
"def",
"ReplaceStringsInFile",
"(",
"filename",
",",
"replacement_dict",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"content",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"for",
"key",
",",
"value",
"in",
"replacement_dict",
".",
"items",
"(",
")",
":",
"original",
"=",
"content",
"content",
"=",
"content",
".",
"replace",
"(",
"key",
",",
"value",
")",
"if",
"content",
"==",
"original",
":",
"raise",
"Exception",
"(",
"'Failed to find {} in {}'",
".",
"format",
"(",
"key",
",",
"filename",
")",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"content",
")",
"f",
".",
"close",
"(",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/abseil-cpp/create_lts.py#L24-L50 | ||
assimp/assimp | 97c7e084c2f7f8c9355ea42f73605890481bddc5 | port/PyAssimp/scripts/transformations.py | python | Arcball.matrix | (self) | return quaternion_matrix(self._qnow) | Return homogeneous rotation matrix. | Return homogeneous rotation matrix. | [
"Return",
"homogeneous",
"rotation",
"matrix",
"."
] | def matrix(self):
"""Return homogeneous rotation matrix."""
return quaternion_matrix(self._qnow) | [
"def",
"matrix",
"(",
"self",
")",
":",
"return",
"quaternion_matrix",
"(",
"self",
".",
"_qnow",
")"
] | https://github.com/assimp/assimp/blob/97c7e084c2f7f8c9355ea42f73605890481bddc5/port/PyAssimp/scripts/transformations.py#L1467-L1469 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/html.py | python | HtmlPrintout.CleanUpStatics | (*args, **kwargs) | return _html.HtmlPrintout_CleanUpStatics(*args, **kwargs) | CleanUpStatics() | CleanUpStatics() | [
"CleanUpStatics",
"()"
] | def CleanUpStatics(*args, **kwargs):
"""CleanUpStatics()"""
return _html.HtmlPrintout_CleanUpStatics(*args, **kwargs) | [
"def",
"CleanUpStatics",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlPrintout_CleanUpStatics",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1312-L1314 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/generate_stubs/generate_stubs.py | python | PosixStubWriter.WriteImplementationContents | (self, namespace, outfile) | Given a file handle, write out the stub definitions for this module.
Args:
namespace: The namespace these functions should be in.
outfile: The file handle to populate. | Given a file handle, write out the stub definitions for this module. | [
"Given",
"a",
"file",
"handle",
"write",
"out",
"the",
"stub",
"definitions",
"for",
"this",
"module",
"."
] | def WriteImplementationContents(self, namespace, outfile):
"""Given a file handle, write out the stub definitions for this module.
Args:
namespace: The namespace these functions should be in.
outfile: The file handle to populate.
"""
outfile.write(IMPLEMENTATION_CONTENTS_C_START)
self.WriteFunctionPointers(outfile)
self.WriteStubFunctions(outfile)
outfile.write(IMPLEMENTATION_CONTENTS_C_END)
outfile.write(NAMESPACE_START % namespace)
self.WriteModuleInitializeFunctions(outfile)
outfile.write(NAMESPACE_END % namespace) | [
"def",
"WriteImplementationContents",
"(",
"self",
",",
"namespace",
",",
"outfile",
")",
":",
"outfile",
".",
"write",
"(",
"IMPLEMENTATION_CONTENTS_C_START",
")",
"self",
".",
"WriteFunctionPointers",
"(",
"outfile",
")",
"self",
".",
"WriteStubFunctions",
"(",
"outfile",
")",
"outfile",
".",
"write",
"(",
"IMPLEMENTATION_CONTENTS_C_END",
")",
"outfile",
".",
"write",
"(",
"NAMESPACE_START",
"%",
"namespace",
")",
"self",
".",
"WriteModuleInitializeFunctions",
"(",
"outfile",
")",
"outfile",
".",
"write",
"(",
"NAMESPACE_END",
"%",
"namespace",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/generate_stubs/generate_stubs.py#L765-L779 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/functional/elemwise.py | python | acosh | (x) | return log(x + (x ** 2 - 1) ** 0.5) | r"""Element-wise `inverse hyperbolic cosine`. | r"""Element-wise `inverse hyperbolic cosine`. | [
"r",
"Element",
"-",
"wise",
"inverse",
"hyperbolic",
"cosine",
"."
] | def acosh(x):
r"""Element-wise `inverse hyperbolic cosine`."""
return log(x + (x ** 2 - 1) ** 0.5) | [
"def",
"acosh",
"(",
"x",
")",
":",
"return",
"log",
"(",
"x",
"+",
"(",
"x",
"**",
"2",
"-",
"1",
")",
"**",
"0.5",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/elemwise.py#L391-L393 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | src/python/m5/ext/pyfdt/pyfdt.py | python | FdtPropertyBytes.dtb_represent | (self, string_store, pos=0, version=17) | return (blob, string_store, pos) | Get blob representation | Get blob representation | [
"Get",
"blob",
"representation"
] | def dtb_represent(self, string_store, pos=0, version=17):
"""Get blob representation"""
# print "%x:%s" % (pos, self)
strpos = string_store.find(self.name+'\0')
if strpos < 0:
strpos = len(string_store)
string_store += self.name+'\0'
blob = pack('>III', FDT_PROP, len(self.bytes), strpos)
blob += pack('').join([pack('>b', byte) for byte in self.bytes])
if len(blob) % 4:
blob += pack('b', 0) * (4-(len(blob) % 4))
pos += len(blob)
return (blob, string_store, pos) | [
"def",
"dtb_represent",
"(",
"self",
",",
"string_store",
",",
"pos",
"=",
"0",
",",
"version",
"=",
"17",
")",
":",
"# print \"%x:%s\" % (pos, self)",
"strpos",
"=",
"string_store",
".",
"find",
"(",
"self",
".",
"name",
"+",
"'\\0'",
")",
"if",
"strpos",
"<",
"0",
":",
"strpos",
"=",
"len",
"(",
"string_store",
")",
"string_store",
"+=",
"self",
".",
"name",
"+",
"'\\0'",
"blob",
"=",
"pack",
"(",
"'>III'",
",",
"FDT_PROP",
",",
"len",
"(",
"self",
".",
"bytes",
")",
",",
"strpos",
")",
"blob",
"+=",
"pack",
"(",
"''",
")",
".",
"join",
"(",
"[",
"pack",
"(",
"'>b'",
",",
"byte",
")",
"for",
"byte",
"in",
"self",
".",
"bytes",
"]",
")",
"if",
"len",
"(",
"blob",
")",
"%",
"4",
":",
"blob",
"+=",
"pack",
"(",
"'b'",
",",
"0",
")",
"*",
"(",
"4",
"-",
"(",
"len",
"(",
"blob",
")",
"%",
"4",
")",
")",
"pos",
"+=",
"len",
"(",
"blob",
")",
"return",
"(",
"blob",
",",
"string_store",
",",
"pos",
")"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/m5/ext/pyfdt/pyfdt.py#L350-L362 | |
nginnever/zogminer | 3c2bc925c833d57c758872e747d5d51fd7185611 | share/qt/extract_strings_qt.py | python | parse_po | (text) | return messages | Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples. | Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples. | [
"Parse",
"po",
"format",
"produced",
"by",
"xgettext",
".",
"Return",
"a",
"list",
"of",
"(",
"msgid",
"msgstr",
")",
"tuples",
"."
] | def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples.
"""
messages = []
msgid = []
msgstr = []
in_msgid = False
in_msgstr = False
for line in text.split('\n'):
line = line.rstrip('\r')
if line.startswith('msgid '):
if in_msgstr:
messages.append((msgid, msgstr))
in_msgstr = False
# message start
in_msgid = True
msgid = [line[6:]]
elif line.startswith('msgstr '):
in_msgid = False
in_msgstr = True
msgstr = [line[7:]]
elif line.startswith('"'):
if in_msgid:
msgid.append(line)
if in_msgstr:
msgstr.append(line)
if in_msgstr:
messages.append((msgid, msgstr))
return messages | [
"def",
"parse_po",
"(",
"text",
")",
":",
"messages",
"=",
"[",
"]",
"msgid",
"=",
"[",
"]",
"msgstr",
"=",
"[",
"]",
"in_msgid",
"=",
"False",
"in_msgstr",
"=",
"False",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"'\\n'",
")",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
"'\\r'",
")",
"if",
"line",
".",
"startswith",
"(",
"'msgid '",
")",
":",
"if",
"in_msgstr",
":",
"messages",
".",
"append",
"(",
"(",
"msgid",
",",
"msgstr",
")",
")",
"in_msgstr",
"=",
"False",
"# message start",
"in_msgid",
"=",
"True",
"msgid",
"=",
"[",
"line",
"[",
"6",
":",
"]",
"]",
"elif",
"line",
".",
"startswith",
"(",
"'msgstr '",
")",
":",
"in_msgid",
"=",
"False",
"in_msgstr",
"=",
"True",
"msgstr",
"=",
"[",
"line",
"[",
"7",
":",
"]",
"]",
"elif",
"line",
".",
"startswith",
"(",
"'\"'",
")",
":",
"if",
"in_msgid",
":",
"msgid",
".",
"append",
"(",
"line",
")",
"if",
"in_msgstr",
":",
"msgstr",
".",
"append",
"(",
"line",
")",
"if",
"in_msgstr",
":",
"messages",
".",
"append",
"(",
"(",
"msgid",
",",
"msgstr",
")",
")",
"return",
"messages"
] | https://github.com/nginnever/zogminer/blob/3c2bc925c833d57c758872e747d5d51fd7185611/share/qt/extract_strings_qt.py#L15-L49 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/base.py | python | IndexOpsMixin._reduce | (
self, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds
) | return func(skipna=skipna, **kwds) | perform the reduction type operation if we can | perform the reduction type operation if we can | [
"perform",
"the",
"reduction",
"type",
"operation",
"if",
"we",
"can"
] | def _reduce(
self, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds
):
""" perform the reduction type operation if we can """
func = getattr(self, name, None)
if func is None:
raise TypeError(
f"{type(self).__name__} cannot perform the operation {name}"
)
return func(skipna=skipna, **kwds) | [
"def",
"_reduce",
"(",
"self",
",",
"op",
",",
"name",
",",
"axis",
"=",
"0",
",",
"skipna",
"=",
"True",
",",
"numeric_only",
"=",
"None",
",",
"filter_type",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"name",
",",
"None",
")",
"if",
"func",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"f\"{type(self).__name__} cannot perform the operation {name}\"",
")",
"return",
"func",
"(",
"skipna",
"=",
"skipna",
",",
"*",
"*",
"kwds",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/base.py#L1053-L1062 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/nn_impl.py | python | nce_loss | (weights,
biases,
labels,
inputs,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
remove_accidental_hits=False,
partition_strategy="mod",
name="nce_loss") | return _sum_rows(sampled_losses) | Computes and returns the noise-contrastive estimation training loss.
See [Noise-contrastive estimation: A new estimation principle for
unnormalized statistical
models](http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf).
Also see our [Candidate Sampling Algorithms
Reference](https://www.tensorflow.org/extras/candidate_sampling.pdf)
A common use case is to use this method for training, and calculate the full
sigmoid loss for evaluation or inference. In this case, you must set
`partition_strategy="div"` for the two losses to be consistent, as in the
following example:
```python
if mode == "train":
loss = tf.nn.nce_loss(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
...,
partition_strategy="div")
elif mode == "eval":
logits = tf.matmul(inputs, tf.transpose(weights))
logits = tf.nn.bias_add(logits, biases)
labels_one_hot = tf.one_hot(labels, n_classes)
loss = tf.nn.sigmoid_cross_entropy_with_logits(
labels=labels_one_hot,
logits=logits)
loss = tf.reduce_sum(loss, axis=1)
```
Note: By default this uses a log-uniform (Zipfian) distribution for sampling,
so your labels must be sorted in order of decreasing frequency to achieve
good results. For more details, see
@{tf.nn.log_uniform_candidate_sampler}.
Note: In the case where `num_true` > 1, we assign to each target class
the target probability 1 / `num_true` so that the target probabilities
sum to 1 per-example.
Note: It would be useful to allow a variable number of target classes per
example. We hope to provide this functionality in a future release.
For now, if you have a variable number of target classes, you can pad them
out to a constant number by either repeating them or by padding
with an otherwise unused class.
Args:
weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`
objects whose concatenation along dimension 0 has shape
[num_classes, dim]. The (possibly-partitioned) class embeddings.
biases: A `Tensor` of shape `[num_classes]`. The class biases.
labels: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes.
inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
activations of the input network.
num_sampled: An `int`. The number of classes to randomly sample per batch.
num_classes: An `int`. The number of possible classes.
num_true: An `int`. The number of target classes per training example.
sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
`sampled_expected_count`) returned by a `*_candidate_sampler` function.
(if None, we default to `log_uniform_candidate_sampler`)
remove_accidental_hits: A `bool`. Whether to remove "accidental hits"
where a sampled class equals one of the target classes. If set to
`True`, this is a "Sampled Logistic" loss instead of NCE, and we are
learning to generate log-odds instead of log probabilities. See
our [Candidate Sampling Algorithms Reference]
(https://www.tensorflow.org/extras/candidate_sampling.pdf).
Default is False.
partition_strategy: A string specifying the partitioning strategy, relevant
if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
Default is `"mod"`. See `tf.nn.embedding_lookup` for more details.
name: A name for the operation (optional).
Returns:
A `batch_size` 1-D tensor of per-example NCE losses. | Computes and returns the noise-contrastive estimation training loss. | [
"Computes",
"and",
"returns",
"the",
"noise",
"-",
"contrastive",
"estimation",
"training",
"loss",
"."
] | def nce_loss(weights,
biases,
labels,
inputs,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
remove_accidental_hits=False,
partition_strategy="mod",
name="nce_loss"):
"""Computes and returns the noise-contrastive estimation training loss.
See [Noise-contrastive estimation: A new estimation principle for
unnormalized statistical
models](http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf).
Also see our [Candidate Sampling Algorithms
Reference](https://www.tensorflow.org/extras/candidate_sampling.pdf)
A common use case is to use this method for training, and calculate the full
sigmoid loss for evaluation or inference. In this case, you must set
`partition_strategy="div"` for the two losses to be consistent, as in the
following example:
```python
if mode == "train":
loss = tf.nn.nce_loss(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
...,
partition_strategy="div")
elif mode == "eval":
logits = tf.matmul(inputs, tf.transpose(weights))
logits = tf.nn.bias_add(logits, biases)
labels_one_hot = tf.one_hot(labels, n_classes)
loss = tf.nn.sigmoid_cross_entropy_with_logits(
labels=labels_one_hot,
logits=logits)
loss = tf.reduce_sum(loss, axis=1)
```
Note: By default this uses a log-uniform (Zipfian) distribution for sampling,
so your labels must be sorted in order of decreasing frequency to achieve
good results. For more details, see
@{tf.nn.log_uniform_candidate_sampler}.
Note: In the case where `num_true` > 1, we assign to each target class
the target probability 1 / `num_true` so that the target probabilities
sum to 1 per-example.
Note: It would be useful to allow a variable number of target classes per
example. We hope to provide this functionality in a future release.
For now, if you have a variable number of target classes, you can pad them
out to a constant number by either repeating them or by padding
with an otherwise unused class.
Args:
weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`
objects whose concatenation along dimension 0 has shape
[num_classes, dim]. The (possibly-partitioned) class embeddings.
biases: A `Tensor` of shape `[num_classes]`. The class biases.
labels: A `Tensor` of type `int64` and shape `[batch_size,
num_true]`. The target classes.
inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
activations of the input network.
num_sampled: An `int`. The number of classes to randomly sample per batch.
num_classes: An `int`. The number of possible classes.
num_true: An `int`. The number of target classes per training example.
sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
`sampled_expected_count`) returned by a `*_candidate_sampler` function.
(if None, we default to `log_uniform_candidate_sampler`)
remove_accidental_hits: A `bool`. Whether to remove "accidental hits"
where a sampled class equals one of the target classes. If set to
`True`, this is a "Sampled Logistic" loss instead of NCE, and we are
learning to generate log-odds instead of log probabilities. See
our [Candidate Sampling Algorithms Reference]
(https://www.tensorflow.org/extras/candidate_sampling.pdf).
Default is False.
partition_strategy: A string specifying the partitioning strategy, relevant
if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
Default is `"mod"`. See `tf.nn.embedding_lookup` for more details.
name: A name for the operation (optional).
Returns:
A `batch_size` 1-D tensor of per-example NCE losses.
"""
logits, labels = _compute_sampled_logits(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
num_sampled=num_sampled,
num_classes=num_classes,
num_true=num_true,
sampled_values=sampled_values,
subtract_log_q=True,
remove_accidental_hits=remove_accidental_hits,
partition_strategy=partition_strategy,
name=name)
sampled_losses = sigmoid_cross_entropy_with_logits(
labels=labels, logits=logits, name="sampled_losses")
# sampled_losses is batch_size x {true_loss, sampled_losses...}
# We sum out true and sampled losses.
return _sum_rows(sampled_losses) | [
"def",
"nce_loss",
"(",
"weights",
",",
"biases",
",",
"labels",
",",
"inputs",
",",
"num_sampled",
",",
"num_classes",
",",
"num_true",
"=",
"1",
",",
"sampled_values",
"=",
"None",
",",
"remove_accidental_hits",
"=",
"False",
",",
"partition_strategy",
"=",
"\"mod\"",
",",
"name",
"=",
"\"nce_loss\"",
")",
":",
"logits",
",",
"labels",
"=",
"_compute_sampled_logits",
"(",
"weights",
"=",
"weights",
",",
"biases",
"=",
"biases",
",",
"labels",
"=",
"labels",
",",
"inputs",
"=",
"inputs",
",",
"num_sampled",
"=",
"num_sampled",
",",
"num_classes",
"=",
"num_classes",
",",
"num_true",
"=",
"num_true",
",",
"sampled_values",
"=",
"sampled_values",
",",
"subtract_log_q",
"=",
"True",
",",
"remove_accidental_hits",
"=",
"remove_accidental_hits",
",",
"partition_strategy",
"=",
"partition_strategy",
",",
"name",
"=",
"name",
")",
"sampled_losses",
"=",
"sigmoid_cross_entropy_with_logits",
"(",
"labels",
"=",
"labels",
",",
"logits",
"=",
"logits",
",",
"name",
"=",
"\"sampled_losses\"",
")",
"# sampled_losses is batch_size x {true_loss, sampled_losses...}",
"# We sum out true and sampled losses.",
"return",
"_sum_rows",
"(",
"sampled_losses",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/nn_impl.py#L1051-L1156 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/ltisys.py | python | dlti.output | (self, u, t, x0=None) | return dlsim(self, u, t, x0=x0) | Return the response of the discrete-time system to input `u`.
See `dlsim` for details. | Return the response of the discrete-time system to input `u`.
See `dlsim` for details. | [
"Return",
"the",
"response",
"of",
"the",
"discrete",
"-",
"time",
"system",
"to",
"input",
"u",
".",
"See",
"dlsim",
"for",
"details",
"."
] | def output(self, u, t, x0=None):
"""
Return the response of the discrete-time system to input `u`.
See `dlsim` for details.
"""
return dlsim(self, u, t, x0=x0) | [
"def",
"output",
"(",
"self",
",",
"u",
",",
"t",
",",
"x0",
"=",
"None",
")",
":",
"return",
"dlsim",
"(",
"self",
",",
"u",
",",
"t",
",",
"x0",
"=",
"x0",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/ltisys.py#L603-L608 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | pythonCleanupParser | () | Cleanup function for the XML library. It tries to reclaim
all parsing related global memory allocated for the library
processing. It doesn't deallocate any document related
memory. Calling this function should not prevent reusing
the library but one should call xmlCleanupParser() only
when the process has finished using the library or XML
document built with it. | Cleanup function for the XML library. It tries to reclaim
all parsing related global memory allocated for the library
processing. It doesn't deallocate any document related
memory. Calling this function should not prevent reusing
the library but one should call xmlCleanupParser() only
when the process has finished using the library or XML
document built with it. | [
"Cleanup",
"function",
"for",
"the",
"XML",
"library",
".",
"It",
"tries",
"to",
"reclaim",
"all",
"parsing",
"related",
"global",
"memory",
"allocated",
"for",
"the",
"library",
"processing",
".",
"It",
"doesn",
"t",
"deallocate",
"any",
"document",
"related",
"memory",
".",
"Calling",
"this",
"function",
"should",
"not",
"prevent",
"reusing",
"the",
"library",
"but",
"one",
"should",
"call",
"xmlCleanupParser",
"()",
"only",
"when",
"the",
"process",
"has",
"finished",
"using",
"the",
"library",
"or",
"XML",
"document",
"built",
"with",
"it",
"."
] | def pythonCleanupParser():
"""Cleanup function for the XML library. It tries to reclaim
all parsing related global memory allocated for the library
processing. It doesn't deallocate any document related
memory. Calling this function should not prevent reusing
the library but one should call xmlCleanupParser() only
when the process has finished using the library or XML
document built with it. """
libxml2mod.xmlPythonCleanupParser() | [
"def",
"pythonCleanupParser",
"(",
")",
":",
"libxml2mod",
".",
"xmlPythonCleanupParser",
"(",
")"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L1558-L1566 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/third_party/jinja2/sandbox.py | python | SandboxedEnvironment.unsafe_undefined | (self, obj, attribute) | return self.undefined('access to attribute %r of %r '
'object is unsafe.' % (
attribute,
obj.__class__.__name__
), name=attribute, obj=obj, exc=SecurityError) | Return an undefined object for unsafe attributes. | Return an undefined object for unsafe attributes. | [
"Return",
"an",
"undefined",
"object",
"for",
"unsafe",
"attributes",
"."
] | def unsafe_undefined(self, obj, attribute):
"""Return an undefined object for unsafe attributes."""
return self.undefined('access to attribute %r of %r '
'object is unsafe.' % (
attribute,
obj.__class__.__name__
), name=attribute, obj=obj, exc=SecurityError) | [
"def",
"unsafe_undefined",
"(",
"self",
",",
"obj",
",",
"attribute",
")",
":",
"return",
"self",
".",
"undefined",
"(",
"'access to attribute %r of %r '",
"'object is unsafe.'",
"%",
"(",
"attribute",
",",
"obj",
".",
"__class__",
".",
"__name__",
")",
",",
"name",
"=",
"attribute",
",",
"obj",
"=",
"obj",
",",
"exc",
"=",
"SecurityError",
")"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/sandbox.py#L341-L347 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/ssl_support.py | python | find_ca_bundle | () | return (
get_win_certfile()
or next(extant_cert_paths, None)
or _certifi_where()
) | Return an existing CA bundle path, or None | Return an existing CA bundle path, or None | [
"Return",
"an",
"existing",
"CA",
"bundle",
"path",
"or",
"None"
] | def find_ca_bundle():
"""Return an existing CA bundle path, or None"""
extant_cert_paths = filter(os.path.isfile, cert_paths)
return (
get_win_certfile()
or next(extant_cert_paths, None)
or _certifi_where()
) | [
"def",
"find_ca_bundle",
"(",
")",
":",
"extant_cert_paths",
"=",
"filter",
"(",
"os",
".",
"path",
".",
"isfile",
",",
"cert_paths",
")",
"return",
"(",
"get_win_certfile",
"(",
")",
"or",
"next",
"(",
"extant_cert_paths",
",",
"None",
")",
"or",
"_certifi_where",
"(",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/ssl_support.py#L246-L253 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/bots/bluechip_bridge.py | python | BlueChipBridgeBot.step | (self, state) | Returns an action for the given state. | Returns an action for the given state. | [
"Returns",
"an",
"action",
"for",
"the",
"given",
"state",
"."
] | def step(self, state):
"""Returns an action for the given state."""
# Bring the external bot up-to-date.
self.inform_state(state)
# If we're on a new trick, tell the bot it is its turn.
if self.is_play_phase and self.cards_played % 4 == 0:
self._controller.send_line(_PLAYER_TO_LEAD.format(seat=self._seat))
# Get our action from the bot.
our_action = _expect_regex(self._controller, _PLAYER_ACTION)
self._num_actions += 1
if our_action["pass"]:
return _ACTION_PASS
elif our_action["dbl"]:
return _ACTION_DBL
elif our_action["rdbl"]:
return _ACTION_RDBL
elif our_action["bid"]:
return _bid_to_action(our_action["bid"])
elif our_action["play"]:
return _play_to_action(our_action["play"]) | [
"def",
"step",
"(",
"self",
",",
"state",
")",
":",
"# Bring the external bot up-to-date.",
"self",
".",
"inform_state",
"(",
"state",
")",
"# If we're on a new trick, tell the bot it is its turn.",
"if",
"self",
".",
"is_play_phase",
"and",
"self",
".",
"cards_played",
"%",
"4",
"==",
"0",
":",
"self",
".",
"_controller",
".",
"send_line",
"(",
"_PLAYER_TO_LEAD",
".",
"format",
"(",
"seat",
"=",
"self",
".",
"_seat",
")",
")",
"# Get our action from the bot.",
"our_action",
"=",
"_expect_regex",
"(",
"self",
".",
"_controller",
",",
"_PLAYER_ACTION",
")",
"self",
".",
"_num_actions",
"+=",
"1",
"if",
"our_action",
"[",
"\"pass\"",
"]",
":",
"return",
"_ACTION_PASS",
"elif",
"our_action",
"[",
"\"dbl\"",
"]",
":",
"return",
"_ACTION_DBL",
"elif",
"our_action",
"[",
"\"rdbl\"",
"]",
":",
"return",
"_ACTION_RDBL",
"elif",
"our_action",
"[",
"\"bid\"",
"]",
":",
"return",
"_bid_to_action",
"(",
"our_action",
"[",
"\"bid\"",
"]",
")",
"elif",
"our_action",
"[",
"\"play\"",
"]",
":",
"return",
"_play_to_action",
"(",
"our_action",
"[",
"\"play\"",
"]",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/bots/bluechip_bridge.py#L323-L344 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Rect.__iadd__ | (*args, **kwargs) | return _core_.Rect___iadd__(*args, **kwargs) | __iadd__(self, Rect rect) -> Rect
Add the properties of rect to this rectangle, updating this rectangle. | __iadd__(self, Rect rect) -> Rect | [
"__iadd__",
"(",
"self",
"Rect",
"rect",
")",
"-",
">",
"Rect"
] | def __iadd__(*args, **kwargs):
"""
__iadd__(self, Rect rect) -> Rect
Add the properties of rect to this rectangle, updating this rectangle.
"""
return _core_.Rect___iadd__(*args, **kwargs) | [
"def",
"__iadd__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect___iadd__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L1493-L1499 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/Paste/paste/wsgiwrappers.py | python | WSGIRequest.urlvars | (self) | Return any variables matched in the URL (e.g.,
``wsgiorg.routing_args``). | Return any variables matched in the URL (e.g.,
``wsgiorg.routing_args``). | [
"Return",
"any",
"variables",
"matched",
"in",
"the",
"URL",
"(",
"e",
".",
"g",
".",
"wsgiorg",
".",
"routing_args",
")",
"."
] | def urlvars(self):
"""
Return any variables matched in the URL (e.g.,
``wsgiorg.routing_args``).
"""
if 'paste.urlvars' in self.environ:
return self.environ['paste.urlvars']
elif 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][1]
else:
return {} | [
"def",
"urlvars",
"(",
"self",
")",
":",
"if",
"'paste.urlvars'",
"in",
"self",
".",
"environ",
":",
"return",
"self",
".",
"environ",
"[",
"'paste.urlvars'",
"]",
"elif",
"'wsgiorg.routing_args'",
"in",
"self",
".",
"environ",
":",
"return",
"self",
".",
"environ",
"[",
"'wsgiorg.routing_args'",
"]",
"[",
"1",
"]",
"else",
":",
"return",
"{",
"}"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/wsgiwrappers.py#L135-L145 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/asn1.py | python | DerSequence.decode | (self, der_encoded, strict=False, nr_elements=None, only_ints_expected=False) | return result | Decode a complete DER SEQUENCE, and re-initializes this
object with it.
Args:
der_encoded (byte string):
A complete SEQUENCE DER element.
nr_elements (None or integer or list of integers):
The number of members the SEQUENCE can have
only_ints_expected (boolean):
Whether the SEQUENCE is expected to contain only integers.
strict (boolean):
Whether decoding must check for strict DER compliancy.
Raises:
ValueError: in case of parsing errors.
DER INTEGERs are decoded into Python integers. Any other DER
element is not decoded. Its validity is not checked. | Decode a complete DER SEQUENCE, and re-initializes this
object with it. | [
"Decode",
"a",
"complete",
"DER",
"SEQUENCE",
"and",
"re",
"-",
"initializes",
"this",
"object",
"with",
"it",
"."
] | def decode(self, der_encoded, strict=False, nr_elements=None, only_ints_expected=False):
"""Decode a complete DER SEQUENCE, and re-initializes this
object with it.
Args:
der_encoded (byte string):
A complete SEQUENCE DER element.
nr_elements (None or integer or list of integers):
The number of members the SEQUENCE can have
only_ints_expected (boolean):
Whether the SEQUENCE is expected to contain only integers.
strict (boolean):
Whether decoding must check for strict DER compliancy.
Raises:
ValueError: in case of parsing errors.
DER INTEGERs are decoded into Python integers. Any other DER
element is not decoded. Its validity is not checked.
"""
self._nr_elements = nr_elements
result = DerObject.decode(self, der_encoded, strict=strict)
if only_ints_expected and not self.hasOnlyInts():
raise ValueError("Some members are not INTEGERs")
return result | [
"def",
"decode",
"(",
"self",
",",
"der_encoded",
",",
"strict",
"=",
"False",
",",
"nr_elements",
"=",
"None",
",",
"only_ints_expected",
"=",
"False",
")",
":",
"self",
".",
"_nr_elements",
"=",
"nr_elements",
"result",
"=",
"DerObject",
".",
"decode",
"(",
"self",
",",
"der_encoded",
",",
"strict",
"=",
"strict",
")",
"if",
"only_ints_expected",
"and",
"not",
"self",
".",
"hasOnlyInts",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Some members are not INTEGERs\"",
")",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/asn1.py#L480-L507 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pathlib2/pathlib2/__init__.py | python | Path.is_char_device | (self) | Whether this path is a character device. | Whether this path is a character device. | [
"Whether",
"this",
"path",
"is",
"a",
"character",
"device",
"."
] | def is_char_device(self):
"""
Whether this path is a character device.
"""
try:
return S_ISCHR(self.stat().st_mode)
except OSError as e:
if not _ignore_error(e):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
except ValueError:
# Non-encodable path
return False | [
"def",
"is_char_device",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISCHR",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"not",
"_ignore_error",
"(",
"e",
")",
":",
"raise",
"# Path doesn't exist or is a broken symlink",
"# (see https://bitbucket.org/pitrou/pathlib/issue/12/)",
"return",
"False",
"except",
"ValueError",
":",
"# Non-encodable path",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pathlib2/pathlib2/__init__.py#L1737-L1751 | ||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | tools/shared.py | python | print_compiler_stage | (cmd) | Emulate the '-v' of clang/gcc by printing the name of the sub-command
before executing it. | Emulate the '-v' of clang/gcc by printing the name of the sub-command
before executing it. | [
"Emulate",
"the",
"-",
"v",
"of",
"clang",
"/",
"gcc",
"by",
"printing",
"the",
"name",
"of",
"the",
"sub",
"-",
"command",
"before",
"executing",
"it",
"."
] | def print_compiler_stage(cmd):
"""Emulate the '-v' of clang/gcc by printing the name of the sub-command
before executing it."""
if PRINT_STAGES:
print(' "%s" %s' % (cmd[0], shlex_join(cmd[1:])), file=sys.stderr)
sys.stderr.flush() | [
"def",
"print_compiler_stage",
"(",
"cmd",
")",
":",
"if",
"PRINT_STAGES",
":",
"print",
"(",
"' \"%s\" %s'",
"%",
"(",
"cmd",
"[",
"0",
"]",
",",
"shlex_join",
"(",
"cmd",
"[",
"1",
":",
"]",
")",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/tools/shared.py#L540-L545 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/viewer/pv/show3d.py | python | Show3D._signalHandler | (self, sig, frame=None) | Stop the GUI on CTRL-C, but not the script it was called from.
from: https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python | Stop the GUI on CTRL-C, but not the script it was called from.
from: https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python | [
"Stop",
"the",
"GUI",
"on",
"CTRL",
"-",
"C",
"but",
"not",
"the",
"script",
"it",
"was",
"called",
"from",
".",
"from",
":",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"1112343",
"/",
"how",
"-",
"do",
"-",
"i",
"-",
"capture",
"-",
"sigint",
"-",
"in",
"-",
"python"
] | def _signalHandler(self, sig, frame=None):
"""
Stop the GUI on CTRL-C, but not the script it was called from.
from: https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python
"""
sys.stderr.write('\r')
self._app.quit() | [
"def",
"_signalHandler",
"(",
"self",
",",
"sig",
",",
"frame",
"=",
"None",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'\\r'",
")",
"self",
".",
"_app",
".",
"quit",
"(",
")"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/viewer/pv/show3d.py#L58-L64 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/gluon/probability/distributions/distribution.py | python | Distribution.sample_n | (self, size) | r"""
Generate samples of (n + parameter_shape) from the distribution. | r"""
Generate samples of (n + parameter_shape) from the distribution. | [
"r",
"Generate",
"samples",
"of",
"(",
"n",
"+",
"parameter_shape",
")",
"from",
"the",
"distribution",
"."
] | def sample_n(self, size):
r"""
Generate samples of (n + parameter_shape) from the distribution.
"""
raise NotImplementedError | [
"def",
"sample_n",
"(",
"self",
",",
"size",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/probability/distributions/distribution.py#L96-L100 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/rsa/rsa/_version133.py | python | gen_pubpriv_keys | (nbits) | return ( {'e': e, 'n': p*q}, {'d': d, 'p': p, 'q': q} ) | Generates public and private keys, and returns them as (pub,
priv).
The public key consists of a dict {e: ..., , n: ....). The private
key consists of a dict {d: ...., p: ...., q: ....). | Generates public and private keys, and returns them as (pub,
priv). | [
"Generates",
"public",
"and",
"private",
"keys",
"and",
"returns",
"them",
"as",
"(",
"pub",
"priv",
")",
"."
] | def gen_pubpriv_keys(nbits):
"""Generates public and private keys, and returns them as (pub,
priv).
The public key consists of a dict {e: ..., , n: ....). The private
key consists of a dict {d: ...., p: ...., q: ....).
"""
(p, q, e, d) = gen_keys(nbits)
return ( {'e': e, 'n': p*q}, {'d': d, 'p': p, 'q': q} ) | [
"def",
"gen_pubpriv_keys",
"(",
"nbits",
")",
":",
"(",
"p",
",",
"q",
",",
"e",
",",
"d",
")",
"=",
"gen_keys",
"(",
"nbits",
")",
"return",
"(",
"{",
"'e'",
":",
"e",
",",
"'n'",
":",
"p",
"*",
"q",
"}",
",",
"{",
"'d'",
":",
"d",
",",
"'p'",
":",
"p",
",",
"'q'",
":",
"q",
"}",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/rsa/rsa/_version133.py#L317-L327 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/internal/containers.py | python | RepeatedScalarFieldContainer.__eq__ | (self, other) | return other == self._values | Compares the current instance with another one. | Compares the current instance with another one. | [
"Compares",
"the",
"current",
"instance",
"with",
"another",
"one",
"."
] | def __eq__(self, other):
"""Compares the current instance with another one."""
if self is other:
return True
# Special case for the same type which should be common and fast.
if isinstance(other, self.__class__):
return other._values == self._values
# We are presumably comparing against some other sequence type.
return other == self._values | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
"is",
"other",
":",
"return",
"True",
"# Special case for the same type which should be common and fast.",
"if",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"other",
".",
"_values",
"==",
"self",
".",
"_values",
"# We are presumably comparing against some other sequence type.",
"return",
"other",
"==",
"self",
".",
"_values"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/internal/containers.py#L170-L178 | |
kismetwireless/kismet | a7c0dc270c960fb1f58bd9cec4601c201885fd4e | capture_sdr_rtl433/KismetCaptureRtl433/kismetexternal/__init__.py | python | Datasource.parse_definition | (definition) | return source, options | Parse a Kismet definition into a (source, optionsmap) tuple
:param definition: Kismet source definition
:return: (source, options{} dictionary) as tuple | Parse a Kismet definition into a (source, optionsmap) tuple | [
"Parse",
"a",
"Kismet",
"definition",
"into",
"a",
"(",
"source",
"optionsmap",
")",
"tuple"
] | def parse_definition(definition):
"""
Parse a Kismet definition into a (source, optionsmap) tuple
:param definition: Kismet source definition
:return: (source, options{} dictionary) as tuple
"""
options = {}
colon = definition.find(':')
if colon == -1:
return definition, {}
source = definition[:colon]
right = definition[colon + 1:]
while len(right):
eqpos = right.find('=')
if eqpos == -1:
return None, None
key = right[:eqpos]
right = right[eqpos + 1:]
# If we're quoted
if right[0] == '"':
right = right[1:]
endq = right.find('"')
if endq == -1:
return None, None
val = right[:endq]
options[key] = val
right = right[endq + 1:]
else:
endcomma = right.find(',')
if endcomma == -1:
endcomma = len(right)
val = right[:endcomma]
options[key] = val
right = right[endcomma + 1:]
return source, options | [
"def",
"parse_definition",
"(",
"definition",
")",
":",
"options",
"=",
"{",
"}",
"colon",
"=",
"definition",
".",
"find",
"(",
"':'",
")",
"if",
"colon",
"==",
"-",
"1",
":",
"return",
"definition",
",",
"{",
"}",
"source",
"=",
"definition",
"[",
":",
"colon",
"]",
"right",
"=",
"definition",
"[",
"colon",
"+",
"1",
":",
"]",
"while",
"len",
"(",
"right",
")",
":",
"eqpos",
"=",
"right",
".",
"find",
"(",
"'='",
")",
"if",
"eqpos",
"==",
"-",
"1",
":",
"return",
"None",
",",
"None",
"key",
"=",
"right",
"[",
":",
"eqpos",
"]",
"right",
"=",
"right",
"[",
"eqpos",
"+",
"1",
":",
"]",
"# If we're quoted",
"if",
"right",
"[",
"0",
"]",
"==",
"'\"'",
":",
"right",
"=",
"right",
"[",
"1",
":",
"]",
"endq",
"=",
"right",
".",
"find",
"(",
"'\"'",
")",
"if",
"endq",
"==",
"-",
"1",
":",
"return",
"None",
",",
"None",
"val",
"=",
"right",
"[",
":",
"endq",
"]",
"options",
"[",
"key",
"]",
"=",
"val",
"right",
"=",
"right",
"[",
"endq",
"+",
"1",
":",
"]",
"else",
":",
"endcomma",
"=",
"right",
".",
"find",
"(",
"','",
")",
"if",
"endcomma",
"==",
"-",
"1",
":",
"endcomma",
"=",
"len",
"(",
"right",
")",
"val",
"=",
"right",
"[",
":",
"endcomma",
"]",
"options",
"[",
"key",
"]",
"=",
"val",
"right",
"=",
"right",
"[",
"endcomma",
"+",
"1",
":",
"]",
"return",
"source",
",",
"options"
] | https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtl433/KismetCaptureRtl433/kismetexternal/__init__.py#L817-L864 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | Font.Strikethrough | (*args, **kwargs) | return _gdi_.Font_Strikethrough(*args, **kwargs) | Strikethrough(self) -> Font | Strikethrough(self) -> Font | [
"Strikethrough",
"(",
"self",
")",
"-",
">",
"Font"
] | def Strikethrough(*args, **kwargs):
"""Strikethrough(self) -> Font"""
return _gdi_.Font_Strikethrough(*args, **kwargs) | [
"def",
"Strikethrough",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Font_Strikethrough",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L2577-L2579 | |
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/iwd/GUIINV.py | python | RefreshInventoryWindow | (Window) | return | Partial redraw without resetting TopIndex. | Partial redraw without resetting TopIndex. | [
"Partial",
"redraw",
"without",
"resetting",
"TopIndex",
"."
] | def RefreshInventoryWindow (Window):
"""Partial redraw without resetting TopIndex."""
pc = GemRB.GameGetSelectedPCSingle ()
# name
Label = Window.GetControl (0x10000032)
Label.SetText (GemRB.GetPlayerName (pc, 0))
# portrait
Button = Window.GetControl (50)
Color1 = GemRB.GetPlayerStat (pc, IE_METAL_COLOR)
Color2 = GemRB.GetPlayerStat (pc, IE_MINOR_COLOR)
Color3 = GemRB.GetPlayerStat (pc, IE_MAJOR_COLOR)
Color4 = GemRB.GetPlayerStat (pc, IE_SKIN_COLOR)
Color5 = GemRB.GetPlayerStat (pc, IE_LEATHER_COLOR)
Color6 = GemRB.GetPlayerStat (pc, IE_ARMOR_COLOR)
Color7 = GemRB.GetPlayerStat (pc, IE_HAIR_COLOR)
Button.SetPLT (GUICommon.GetActorPaperDoll (pc),
Color1, Color2, Color3, Color4, Color5, Color6, Color7, 0, 0)
anim_id = GemRB.GetPlayerStat (pc, IE_ANIMATION_ID)
row = "0x%04X" %anim_id
size = CommonTables.Pdolls.GetValue (row, "SIZE")
# Weapon
slot_item = GemRB.GetSlotItem (pc, GemRB.GetEquippedQuickSlot (pc) )
if slot_item:
item = GemRB.GetItem (slot_item["ItemResRef"])
if (item['AnimationType'] != ''):
Button.SetPLT("WP" + size + item['AnimationType'] + "INV", Color1, Color2, Color3, Color4, Color5, Color6, Color7, 0, 1)
# Shield
slot_item = GemRB.GetSlotItem (pc, 3)
if slot_item:
itemname = slot_item["ItemResRef"]
item = GemRB.GetItem (itemname)
if (item['AnimationType'] != ''):
if (GemRB.CanUseItemType (SLOT_WEAPON, itemname)):
#off-hand weapon
Button.SetPLT("WP" + size + item['AnimationType'] + "OIN", Color1, Color2, Color3, Color4, Color5, Color6, Color7, 0, 2)
else:
#shield
Button.SetPLT("WP" + size + item['AnimationType'] + "INV", Color1, Color2, Color3, Color4, Color5, Color6, Color7, 0, 2)
# Helmet
slot_item = GemRB.GetSlotItem (pc, 1)
if slot_item:
item = GemRB.GetItem (slot_item["ItemResRef"])
if (item['AnimationType'] != ''):
Button.SetPLT("WP" + size + item['AnimationType'] + "INV", Color1, Color2, Color3, Color4, Color5, Color6, Color7, 0, 3)
# encumbrance
GUICommon.SetEncumbranceLabels ( Window, 0x10000043, 0x10000044, pc)
# armor class
Label = Window.GetControl (0x10000038)
ac = GemRB.GetPlayerStat (pc, IE_ARMORCLASS)
Label.SetText (str (ac))
Label.SetTooltip (10339)
# hp current
hp = GemRB.GetPlayerStat (pc, IE_HITPOINTS)
Label = Window.GetControl (0x10000039)
Label.SetText (str (hp))
Label.SetTooltip (17184)
# hp max
hpmax = GemRB.GetPlayerStat (pc, IE_MAXHITPOINTS)
Label = Window.GetControl (0x1000003a)
Label.SetText (str (hpmax))
Label.SetTooltip (17378)
# party gold
Label = Window.GetControl (0x10000040)
Label.SetText (str (GemRB.GameGetPartyGold ()))
# class
ClassTitle = GUICommon.GetActorClassTitle (pc)
Label = Window.GetControl (0x10000042)
Label.SetText (ClassTitle)
Button = Window.GetControl (62)
Color = GemRB.GetPlayerStat (pc, IE_MAJOR_COLOR, 1) & 0xFF
Button.SetBAM ("COLGRAD", 1, 0, Color)
Button = Window.GetControl (63)
Color = GemRB.GetPlayerStat (pc, IE_MINOR_COLOR, 1) & 0xFF
Button.SetBAM ("COLGRAD", 1, 0, Color)
# update ground inventory slots
TopIndex = GemRB.GetVar ("TopIndex")
for i in range (5):
Button = Window.GetControl (i+68)
if GemRB.IsDraggingItem ()==1:
Button.SetState (IE_GUI_BUTTON_FAKEPRESSED)
else:
Button.SetState (IE_GUI_BUTTON_ENABLED)
Button.SetAction (InventoryCommon.OnDragItemGround, IE_ACT_DRAG_DROP_DST)
Slot = GemRB.GetContainerItem (pc, i+TopIndex)
if Slot == None:
Button.SetEvent (IE_GUI_BUTTON_ON_PRESS, None)
Button.SetEvent (IE_GUI_BUTTON_ON_RIGHT_PRESS, None)
Button.SetEvent (IE_GUI_BUTTON_ON_SHIFT_PRESS, None)
else:
Button.SetValue (i + TopIndex)
Button.SetAction(InventoryCommon.OnDragItemGround, IE_ACT_DRAG_DROP_CRT)
Button.SetEvent (IE_GUI_BUTTON_ON_PRESS, InventoryCommon.OnDragItemGround)
Button.SetEvent (IE_GUI_BUTTON_ON_RIGHT_PRESS, InventoryCommon.OpenGroundItemInfoWindow)
Button.SetEvent (IE_GUI_BUTTON_ON_SHIFT_PRESS, InventoryCommon.OpenGroundItemAmountWindow)
InventoryCommon.UpdateInventorySlot (pc, Button, Slot, "ground")
# making window visible/shaded depending on the pc's state
GUICommon.AdjustWindowVisibility (Window, pc, False)
return | [
"def",
"RefreshInventoryWindow",
"(",
"Window",
")",
":",
"pc",
"=",
"GemRB",
".",
"GameGetSelectedPCSingle",
"(",
")",
"# name",
"Label",
"=",
"Window",
".",
"GetControl",
"(",
"0x10000032",
")",
"Label",
".",
"SetText",
"(",
"GemRB",
".",
"GetPlayerName",
"(",
"pc",
",",
"0",
")",
")",
"# portrait",
"Button",
"=",
"Window",
".",
"GetControl",
"(",
"50",
")",
"Color1",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_METAL_COLOR",
")",
"Color2",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_MINOR_COLOR",
")",
"Color3",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_MAJOR_COLOR",
")",
"Color4",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_SKIN_COLOR",
")",
"Color5",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_LEATHER_COLOR",
")",
"Color6",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_ARMOR_COLOR",
")",
"Color7",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_HAIR_COLOR",
")",
"Button",
".",
"SetPLT",
"(",
"GUICommon",
".",
"GetActorPaperDoll",
"(",
"pc",
")",
",",
"Color1",
",",
"Color2",
",",
"Color3",
",",
"Color4",
",",
"Color5",
",",
"Color6",
",",
"Color7",
",",
"0",
",",
"0",
")",
"anim_id",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_ANIMATION_ID",
")",
"row",
"=",
"\"0x%04X\"",
"%",
"anim_id",
"size",
"=",
"CommonTables",
".",
"Pdolls",
".",
"GetValue",
"(",
"row",
",",
"\"SIZE\"",
")",
"# Weapon",
"slot_item",
"=",
"GemRB",
".",
"GetSlotItem",
"(",
"pc",
",",
"GemRB",
".",
"GetEquippedQuickSlot",
"(",
"pc",
")",
")",
"if",
"slot_item",
":",
"item",
"=",
"GemRB",
".",
"GetItem",
"(",
"slot_item",
"[",
"\"ItemResRef\"",
"]",
")",
"if",
"(",
"item",
"[",
"'AnimationType'",
"]",
"!=",
"''",
")",
":",
"Button",
".",
"SetPLT",
"(",
"\"WP\"",
"+",
"size",
"+",
"item",
"[",
"'AnimationType'",
"]",
"+",
"\"INV\"",
",",
"Color1",
",",
"Color2",
",",
"Color3",
",",
"Color4",
",",
"Color5",
",",
"Color6",
",",
"Color7",
",",
"0",
",",
"1",
")",
"# Shield",
"slot_item",
"=",
"GemRB",
".",
"GetSlotItem",
"(",
"pc",
",",
"3",
")",
"if",
"slot_item",
":",
"itemname",
"=",
"slot_item",
"[",
"\"ItemResRef\"",
"]",
"item",
"=",
"GemRB",
".",
"GetItem",
"(",
"itemname",
")",
"if",
"(",
"item",
"[",
"'AnimationType'",
"]",
"!=",
"''",
")",
":",
"if",
"(",
"GemRB",
".",
"CanUseItemType",
"(",
"SLOT_WEAPON",
",",
"itemname",
")",
")",
":",
"#off-hand weapon",
"Button",
".",
"SetPLT",
"(",
"\"WP\"",
"+",
"size",
"+",
"item",
"[",
"'AnimationType'",
"]",
"+",
"\"OIN\"",
",",
"Color1",
",",
"Color2",
",",
"Color3",
",",
"Color4",
",",
"Color5",
",",
"Color6",
",",
"Color7",
",",
"0",
",",
"2",
")",
"else",
":",
"#shield",
"Button",
".",
"SetPLT",
"(",
"\"WP\"",
"+",
"size",
"+",
"item",
"[",
"'AnimationType'",
"]",
"+",
"\"INV\"",
",",
"Color1",
",",
"Color2",
",",
"Color3",
",",
"Color4",
",",
"Color5",
",",
"Color6",
",",
"Color7",
",",
"0",
",",
"2",
")",
"# Helmet",
"slot_item",
"=",
"GemRB",
".",
"GetSlotItem",
"(",
"pc",
",",
"1",
")",
"if",
"slot_item",
":",
"item",
"=",
"GemRB",
".",
"GetItem",
"(",
"slot_item",
"[",
"\"ItemResRef\"",
"]",
")",
"if",
"(",
"item",
"[",
"'AnimationType'",
"]",
"!=",
"''",
")",
":",
"Button",
".",
"SetPLT",
"(",
"\"WP\"",
"+",
"size",
"+",
"item",
"[",
"'AnimationType'",
"]",
"+",
"\"INV\"",
",",
"Color1",
",",
"Color2",
",",
"Color3",
",",
"Color4",
",",
"Color5",
",",
"Color6",
",",
"Color7",
",",
"0",
",",
"3",
")",
"# encumbrance",
"GUICommon",
".",
"SetEncumbranceLabels",
"(",
"Window",
",",
"0x10000043",
",",
"0x10000044",
",",
"pc",
")",
"# armor class",
"Label",
"=",
"Window",
".",
"GetControl",
"(",
"0x10000038",
")",
"ac",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_ARMORCLASS",
")",
"Label",
".",
"SetText",
"(",
"str",
"(",
"ac",
")",
")",
"Label",
".",
"SetTooltip",
"(",
"10339",
")",
"# hp current",
"hp",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_HITPOINTS",
")",
"Label",
"=",
"Window",
".",
"GetControl",
"(",
"0x10000039",
")",
"Label",
".",
"SetText",
"(",
"str",
"(",
"hp",
")",
")",
"Label",
".",
"SetTooltip",
"(",
"17184",
")",
"# hp max",
"hpmax",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_MAXHITPOINTS",
")",
"Label",
"=",
"Window",
".",
"GetControl",
"(",
"0x1000003a",
")",
"Label",
".",
"SetText",
"(",
"str",
"(",
"hpmax",
")",
")",
"Label",
".",
"SetTooltip",
"(",
"17378",
")",
"# party gold",
"Label",
"=",
"Window",
".",
"GetControl",
"(",
"0x10000040",
")",
"Label",
".",
"SetText",
"(",
"str",
"(",
"GemRB",
".",
"GameGetPartyGold",
"(",
")",
")",
")",
"# class",
"ClassTitle",
"=",
"GUICommon",
".",
"GetActorClassTitle",
"(",
"pc",
")",
"Label",
"=",
"Window",
".",
"GetControl",
"(",
"0x10000042",
")",
"Label",
".",
"SetText",
"(",
"ClassTitle",
")",
"Button",
"=",
"Window",
".",
"GetControl",
"(",
"62",
")",
"Color",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_MAJOR_COLOR",
",",
"1",
")",
"&",
"0xFF",
"Button",
".",
"SetBAM",
"(",
"\"COLGRAD\"",
",",
"1",
",",
"0",
",",
"Color",
")",
"Button",
"=",
"Window",
".",
"GetControl",
"(",
"63",
")",
"Color",
"=",
"GemRB",
".",
"GetPlayerStat",
"(",
"pc",
",",
"IE_MINOR_COLOR",
",",
"1",
")",
"&",
"0xFF",
"Button",
".",
"SetBAM",
"(",
"\"COLGRAD\"",
",",
"1",
",",
"0",
",",
"Color",
")",
"# update ground inventory slots",
"TopIndex",
"=",
"GemRB",
".",
"GetVar",
"(",
"\"TopIndex\"",
")",
"for",
"i",
"in",
"range",
"(",
"5",
")",
":",
"Button",
"=",
"Window",
".",
"GetControl",
"(",
"i",
"+",
"68",
")",
"if",
"GemRB",
".",
"IsDraggingItem",
"(",
")",
"==",
"1",
":",
"Button",
".",
"SetState",
"(",
"IE_GUI_BUTTON_FAKEPRESSED",
")",
"else",
":",
"Button",
".",
"SetState",
"(",
"IE_GUI_BUTTON_ENABLED",
")",
"Button",
".",
"SetAction",
"(",
"InventoryCommon",
".",
"OnDragItemGround",
",",
"IE_ACT_DRAG_DROP_DST",
")",
"Slot",
"=",
"GemRB",
".",
"GetContainerItem",
"(",
"pc",
",",
"i",
"+",
"TopIndex",
")",
"if",
"Slot",
"==",
"None",
":",
"Button",
".",
"SetEvent",
"(",
"IE_GUI_BUTTON_ON_PRESS",
",",
"None",
")",
"Button",
".",
"SetEvent",
"(",
"IE_GUI_BUTTON_ON_RIGHT_PRESS",
",",
"None",
")",
"Button",
".",
"SetEvent",
"(",
"IE_GUI_BUTTON_ON_SHIFT_PRESS",
",",
"None",
")",
"else",
":",
"Button",
".",
"SetValue",
"(",
"i",
"+",
"TopIndex",
")",
"Button",
".",
"SetAction",
"(",
"InventoryCommon",
".",
"OnDragItemGround",
",",
"IE_ACT_DRAG_DROP_CRT",
")",
"Button",
".",
"SetEvent",
"(",
"IE_GUI_BUTTON_ON_PRESS",
",",
"InventoryCommon",
".",
"OnDragItemGround",
")",
"Button",
".",
"SetEvent",
"(",
"IE_GUI_BUTTON_ON_RIGHT_PRESS",
",",
"InventoryCommon",
".",
"OpenGroundItemInfoWindow",
")",
"Button",
".",
"SetEvent",
"(",
"IE_GUI_BUTTON_ON_SHIFT_PRESS",
",",
"InventoryCommon",
".",
"OpenGroundItemAmountWindow",
")",
"InventoryCommon",
".",
"UpdateInventorySlot",
"(",
"pc",
",",
"Button",
",",
"Slot",
",",
"\"ground\"",
")",
"# making window visible/shaded depending on the pc's state",
"GUICommon",
".",
"AdjustWindowVisibility",
"(",
"Window",
",",
"pc",
",",
"False",
")",
"return"
] | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/iwd/GUIINV.py#L132-L248 | |
shuyo/ldig | 27599a23a24fb4b95e57213aa942b4c94fe1104a | ldig.py | python | ldig.init | (self, temp_path, corpus_list, lbff, ngram_bound) | Extract features from corpus and generate TRIE(DoubleArray) data
- load corpus
- generate temporary file for maxsubst
- generate double array and save it
- parameter: lbff = lower bound of feature frequency | Extract features from corpus and generate TRIE(DoubleArray) data
- load corpus
- generate temporary file for maxsubst
- generate double array and save it
- parameter: lbff = lower bound of feature frequency | [
"Extract",
"features",
"from",
"corpus",
"and",
"generate",
"TRIE",
"(",
"DoubleArray",
")",
"data",
"-",
"load",
"corpus",
"-",
"generate",
"temporary",
"file",
"for",
"maxsubst",
"-",
"generate",
"double",
"array",
"and",
"save",
"it",
"-",
"parameter",
":",
"lbff",
"=",
"lower",
"bound",
"of",
"feature",
"frequency"
] | def init(self, temp_path, corpus_list, lbff, ngram_bound):
"""
Extract features from corpus and generate TRIE(DoubleArray) data
- load corpus
- generate temporary file for maxsubst
- generate double array and save it
- parameter: lbff = lower bound of feature frequency
"""
labels = []
with codecs.open(temp_path, 'wb', 'utf-8') as f:
for file in corpus_list:
with codecs.open(file, 'rb', 'utf-8') as g:
for i, s in enumerate(g):
label, text, org_text = normalize_text(s)
if label is None or label == "":
sys.stderr.write("no label data at %d in %s \n" % (i+1, file))
continue
if label not in labels:
labels.append(label)
f.write(text)
f.write("\n")
labels.sort()
print "labels: %d" % len(labels)
with open(self.labels, 'wb') as f:
f.write(json.dumps(labels))
print "generating max-substrings..."
temp_features = self.features + ".temp"
maxsubst = options.maxsubst
if os.name == 'nt': maxsubst += ".exe"
subprocess.call([maxsubst, temp_path, temp_features])
# count features
M = 0
features = []
r1 = re.compile(u'.\u0001.')
r2 = re.compile(u'[A-Za-z\u00a1-\u00a3\u00bf-\u024f\u1e00-\u1eff]')
with codecs.open(temp_features, 'rb', 'utf-8') as f:
for line in f:
i = line.index('\t')
st = line[0:i]
c = int(line[i+1:-1])
if c >= lbff and len(st) <= ngram_bound and (not r1.search(st)) and r2.search(st) and (st[0] != u'\u0001' or st[-1] != u'\u0001'):
M += 1
features.append((st, line))
print "# of features = %d" % M
features.sort()
with codecs.open(self.features, 'wb', 'utf-8') as f:
for s in features:
f.write(s[1])
generate_doublearray(self.doublearray, [s[0] for s in features])
numpy.save(self.param, numpy.zeros((M, len(labels)))) | [
"def",
"init",
"(",
"self",
",",
"temp_path",
",",
"corpus_list",
",",
"lbff",
",",
"ngram_bound",
")",
":",
"labels",
"=",
"[",
"]",
"with",
"codecs",
".",
"open",
"(",
"temp_path",
",",
"'wb'",
",",
"'utf-8'",
")",
"as",
"f",
":",
"for",
"file",
"in",
"corpus_list",
":",
"with",
"codecs",
".",
"open",
"(",
"file",
",",
"'rb'",
",",
"'utf-8'",
")",
"as",
"g",
":",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"g",
")",
":",
"label",
",",
"text",
",",
"org_text",
"=",
"normalize_text",
"(",
"s",
")",
"if",
"label",
"is",
"None",
"or",
"label",
"==",
"\"\"",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"no label data at %d in %s \\n\"",
"%",
"(",
"i",
"+",
"1",
",",
"file",
")",
")",
"continue",
"if",
"label",
"not",
"in",
"labels",
":",
"labels",
".",
"append",
"(",
"label",
")",
"f",
".",
"write",
"(",
"text",
")",
"f",
".",
"write",
"(",
"\"\\n\"",
")",
"labels",
".",
"sort",
"(",
")",
"print",
"\"labels: %d\"",
"%",
"len",
"(",
"labels",
")",
"with",
"open",
"(",
"self",
".",
"labels",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"labels",
")",
")",
"print",
"\"generating max-substrings...\"",
"temp_features",
"=",
"self",
".",
"features",
"+",
"\".temp\"",
"maxsubst",
"=",
"options",
".",
"maxsubst",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"maxsubst",
"+=",
"\".exe\"",
"subprocess",
".",
"call",
"(",
"[",
"maxsubst",
",",
"temp_path",
",",
"temp_features",
"]",
")",
"# count features",
"M",
"=",
"0",
"features",
"=",
"[",
"]",
"r1",
"=",
"re",
".",
"compile",
"(",
"u'.\\u0001.'",
")",
"r2",
"=",
"re",
".",
"compile",
"(",
"u'[A-Za-z\\u00a1-\\u00a3\\u00bf-\\u024f\\u1e00-\\u1eff]'",
")",
"with",
"codecs",
".",
"open",
"(",
"temp_features",
",",
"'rb'",
",",
"'utf-8'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"i",
"=",
"line",
".",
"index",
"(",
"'\\t'",
")",
"st",
"=",
"line",
"[",
"0",
":",
"i",
"]",
"c",
"=",
"int",
"(",
"line",
"[",
"i",
"+",
"1",
":",
"-",
"1",
"]",
")",
"if",
"c",
">=",
"lbff",
"and",
"len",
"(",
"st",
")",
"<=",
"ngram_bound",
"and",
"(",
"not",
"r1",
".",
"search",
"(",
"st",
")",
")",
"and",
"r2",
".",
"search",
"(",
"st",
")",
"and",
"(",
"st",
"[",
"0",
"]",
"!=",
"u'\\u0001'",
"or",
"st",
"[",
"-",
"1",
"]",
"!=",
"u'\\u0001'",
")",
":",
"M",
"+=",
"1",
"features",
".",
"append",
"(",
"(",
"st",
",",
"line",
")",
")",
"print",
"\"# of features = %d\"",
"%",
"M",
"features",
".",
"sort",
"(",
")",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"features",
",",
"'wb'",
",",
"'utf-8'",
")",
"as",
"f",
":",
"for",
"s",
"in",
"features",
":",
"f",
".",
"write",
"(",
"s",
"[",
"1",
"]",
")",
"generate_doublearray",
"(",
"self",
".",
"doublearray",
",",
"[",
"s",
"[",
"0",
"]",
"for",
"s",
"in",
"features",
"]",
")",
"numpy",
".",
"save",
"(",
"self",
".",
"param",
",",
"numpy",
".",
"zeros",
"(",
"(",
"M",
",",
"len",
"(",
"labels",
")",
")",
")",
")"
] | https://github.com/shuyo/ldig/blob/27599a23a24fb4b95e57213aa942b4c94fe1104a/ldig.py#L47-L103 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/ao/quantization/fx/prepare.py | python | get_target_activation_dtype_for_node | (
node: Node,
qconfig: QConfigAny,
inputs_seen_counter: int,
outputs_seen_counter: int,
input_quantized_idxs: List[int],
output_quantized_idxs: List[int],
qhandler: Optional[QuantizeHandler],
modules: Dict[str, torch.nn.Module],
cache_for_no_tensor_check: Dict[Node, bool],
) | Returns the expected dtype of the input and output of this node after
convert. If the value is not None, it represents the dtype of the
Tensor. If the value is None, it means the value is not a Tensor.
Note: this is for activations only, weight dtypes are not handled here.
TODO(future PR, if needed): explicitly spell out the non-Tensor
dtypes. | Returns the expected dtype of the input and output of this node after
convert. If the value is not None, it represents the dtype of the
Tensor. If the value is None, it means the value is not a Tensor. | [
"Returns",
"the",
"expected",
"dtype",
"of",
"the",
"input",
"and",
"output",
"of",
"this",
"node",
"after",
"convert",
".",
"If",
"the",
"value",
"is",
"not",
"None",
"it",
"represents",
"the",
"dtype",
"of",
"the",
"Tensor",
".",
"If",
"the",
"value",
"is",
"None",
"it",
"means",
"the",
"value",
"is",
"not",
"a",
"Tensor",
"."
] | def get_target_activation_dtype_for_node(
node: Node,
qconfig: QConfigAny,
inputs_seen_counter: int,
outputs_seen_counter: int,
input_quantized_idxs: List[int],
output_quantized_idxs: List[int],
qhandler: Optional[QuantizeHandler],
modules: Dict[str, torch.nn.Module],
cache_for_no_tensor_check: Dict[Node, bool],
) -> Dict[str, Optional[torch.dtype]]:
"""
Returns the expected dtype of the input and output of this node after
convert. If the value is not None, it represents the dtype of the
Tensor. If the value is None, it means the value is not a Tensor.
Note: this is for activations only, weight dtypes are not handled here.
TODO(future PR, if needed): explicitly spell out the non-Tensor
dtypes.
"""
if node.op == 'placeholder':
if inputs_seen_counter in input_quantized_idxs:
return {
"input_activation_dtype": torch.quint8,
"output_activation_dtype": torch.quint8,
}
else:
# if dtype is fp32 (default), do nothing
# note: other dtypes are not supported
return {
"input_activation_dtype": torch.float,
"output_activation_dtype": torch.float,
}
elif node.op in ('call_module', 'call_method', 'call_function'):
args_have_no_tensors = \
all_node_args_have_no_tensors(
node, modules, cache_for_no_tensor_check)
if args_have_no_tensors:
return {
"input_activation_dtype": None,
"output_activation_dtype": None,
}
# TODO(future PR): consider stopping matching getitem
is_getitem = node.op == 'call_function' and \
node.target == operator.getitem
if is_getitem:
return {
"input_activation_dtype": torch.float,
"output_activation_dtype": torch.float,
}
# get qconfig to determine the eventual dtype of this node
if qconfig is not None:
if qhandler is not None and qhandler.input_output_observed() and qhandler.is_output_quantized(qconfig):
act_dtype, weight_dtype, act_compute_dtype = \
get_qconfig_dtypes(qconfig)
bias_dtype = torch.float16 \
if act_dtype == torch.float16 and weight_dtype == torch.float16 \
else torch.float
return {
"input_activation_dtype": act_dtype,
"weight_dtype": weight_dtype,
"bias_dtype": bias_dtype,
"output_activation_dtype": act_dtype,
}
return {
"input_activation_dtype": torch.float,
"output_activation_dtype": torch.float,
}
elif node.op == 'get_attr':
return {
"input_activation_dtype": torch.float,
"output_activation_dtype": torch.float,
}
elif node.op == 'output':
if outputs_seen_counter in output_quantized_idxs:
return {
"input_activation_dtype": torch.quint8,
"output_activation_dtype": torch.quint8
}
else:
# if dtype is fp32 (default), do nothing
# note: other dtypes are not supported
return {
"input_activation_dtype": torch.float,
"output_activation_dtype": torch.float,
}
else:
raise AssertionError(f'need to handle {node.format_node()}') | [
"def",
"get_target_activation_dtype_for_node",
"(",
"node",
":",
"Node",
",",
"qconfig",
":",
"QConfigAny",
",",
"inputs_seen_counter",
":",
"int",
",",
"outputs_seen_counter",
":",
"int",
",",
"input_quantized_idxs",
":",
"List",
"[",
"int",
"]",
",",
"output_quantized_idxs",
":",
"List",
"[",
"int",
"]",
",",
"qhandler",
":",
"Optional",
"[",
"QuantizeHandler",
"]",
",",
"modules",
":",
"Dict",
"[",
"str",
",",
"torch",
".",
"nn",
".",
"Module",
"]",
",",
"cache_for_no_tensor_check",
":",
"Dict",
"[",
"Node",
",",
"bool",
"]",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Optional",
"[",
"torch",
".",
"dtype",
"]",
"]",
":",
"if",
"node",
".",
"op",
"==",
"'placeholder'",
":",
"if",
"inputs_seen_counter",
"in",
"input_quantized_idxs",
":",
"return",
"{",
"\"input_activation_dtype\"",
":",
"torch",
".",
"quint8",
",",
"\"output_activation_dtype\"",
":",
"torch",
".",
"quint8",
",",
"}",
"else",
":",
"# if dtype is fp32 (default), do nothing",
"# note: other dtypes are not supported",
"return",
"{",
"\"input_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"\"output_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"}",
"elif",
"node",
".",
"op",
"in",
"(",
"'call_module'",
",",
"'call_method'",
",",
"'call_function'",
")",
":",
"args_have_no_tensors",
"=",
"all_node_args_have_no_tensors",
"(",
"node",
",",
"modules",
",",
"cache_for_no_tensor_check",
")",
"if",
"args_have_no_tensors",
":",
"return",
"{",
"\"input_activation_dtype\"",
":",
"None",
",",
"\"output_activation_dtype\"",
":",
"None",
",",
"}",
"# TODO(future PR): consider stopping matching getitem",
"is_getitem",
"=",
"node",
".",
"op",
"==",
"'call_function'",
"and",
"node",
".",
"target",
"==",
"operator",
".",
"getitem",
"if",
"is_getitem",
":",
"return",
"{",
"\"input_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"\"output_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"}",
"# get qconfig to determine the eventual dtype of this node",
"if",
"qconfig",
"is",
"not",
"None",
":",
"if",
"qhandler",
"is",
"not",
"None",
"and",
"qhandler",
".",
"input_output_observed",
"(",
")",
"and",
"qhandler",
".",
"is_output_quantized",
"(",
"qconfig",
")",
":",
"act_dtype",
",",
"weight_dtype",
",",
"act_compute_dtype",
"=",
"get_qconfig_dtypes",
"(",
"qconfig",
")",
"bias_dtype",
"=",
"torch",
".",
"float16",
"if",
"act_dtype",
"==",
"torch",
".",
"float16",
"and",
"weight_dtype",
"==",
"torch",
".",
"float16",
"else",
"torch",
".",
"float",
"return",
"{",
"\"input_activation_dtype\"",
":",
"act_dtype",
",",
"\"weight_dtype\"",
":",
"weight_dtype",
",",
"\"bias_dtype\"",
":",
"bias_dtype",
",",
"\"output_activation_dtype\"",
":",
"act_dtype",
",",
"}",
"return",
"{",
"\"input_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"\"output_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"}",
"elif",
"node",
".",
"op",
"==",
"'get_attr'",
":",
"return",
"{",
"\"input_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"\"output_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"}",
"elif",
"node",
".",
"op",
"==",
"'output'",
":",
"if",
"outputs_seen_counter",
"in",
"output_quantized_idxs",
":",
"return",
"{",
"\"input_activation_dtype\"",
":",
"torch",
".",
"quint8",
",",
"\"output_activation_dtype\"",
":",
"torch",
".",
"quint8",
"}",
"else",
":",
"# if dtype is fp32 (default), do nothing",
"# note: other dtypes are not supported",
"return",
"{",
"\"input_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"\"output_activation_dtype\"",
":",
"torch",
".",
"float",
",",
"}",
"else",
":",
"raise",
"AssertionError",
"(",
"f'need to handle {node.format_node()}'",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/fx/prepare.py#L264-L358 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/adidas_utils/helpers/simplex.py | python | euclidean_projection_onto_simplex | (y, eps=1e-3, subset=True) | return x | O(n log n) Euclidean projection of y onto the simplex.
Args:
y: np.array
eps: float, ensure x remains at least eps / dim away from facets of simplex
subset: bool, whether to project onto a subset of the simplex defined by eps
Returns:
np.array, y projected onto the simplex | O(n log n) Euclidean projection of y onto the simplex. | [
"O",
"(",
"n",
"log",
"n",
")",
"Euclidean",
"projection",
"of",
"y",
"onto",
"the",
"simplex",
"."
] | def euclidean_projection_onto_simplex(y, eps=1e-3, subset=True):
"""O(n log n) Euclidean projection of y onto the simplex.
Args:
y: np.array
eps: float, ensure x remains at least eps / dim away from facets of simplex
subset: bool, whether to project onto a subset of the simplex defined by eps
Returns:
np.array, y projected onto the simplex
"""
if np.all(y >= 0.) and np.abs(np.sum(y) - 1.) < 1e-8:
return y
d = len(y)
u = sorted(y, reverse=True)
sum_uj = 0.
for j in range(d):
sum_uj += u[j]
tj = (1. - sum_uj) / (j + 1.)
if u[j] + tj <= 0:
rho = j - 1
sum_uj = sum_uj - u[j]
break
else:
rho = j
lam = (1. - sum_uj) / (rho + 1.)
x = np.array([max(y[i] + lam, 0.) for i in range(d)])
if subset:
scale = 1. - eps * float(d + 1) / d
offset = eps / float(d)
x = scale * x + offset
x /= x.sum()
return x | [
"def",
"euclidean_projection_onto_simplex",
"(",
"y",
",",
"eps",
"=",
"1e-3",
",",
"subset",
"=",
"True",
")",
":",
"if",
"np",
".",
"all",
"(",
"y",
">=",
"0.",
")",
"and",
"np",
".",
"abs",
"(",
"np",
".",
"sum",
"(",
"y",
")",
"-",
"1.",
")",
"<",
"1e-8",
":",
"return",
"y",
"d",
"=",
"len",
"(",
"y",
")",
"u",
"=",
"sorted",
"(",
"y",
",",
"reverse",
"=",
"True",
")",
"sum_uj",
"=",
"0.",
"for",
"j",
"in",
"range",
"(",
"d",
")",
":",
"sum_uj",
"+=",
"u",
"[",
"j",
"]",
"tj",
"=",
"(",
"1.",
"-",
"sum_uj",
")",
"/",
"(",
"j",
"+",
"1.",
")",
"if",
"u",
"[",
"j",
"]",
"+",
"tj",
"<=",
"0",
":",
"rho",
"=",
"j",
"-",
"1",
"sum_uj",
"=",
"sum_uj",
"-",
"u",
"[",
"j",
"]",
"break",
"else",
":",
"rho",
"=",
"j",
"lam",
"=",
"(",
"1.",
"-",
"sum_uj",
")",
"/",
"(",
"rho",
"+",
"1.",
")",
"x",
"=",
"np",
".",
"array",
"(",
"[",
"max",
"(",
"y",
"[",
"i",
"]",
"+",
"lam",
",",
"0.",
")",
"for",
"i",
"in",
"range",
"(",
"d",
")",
"]",
")",
"if",
"subset",
":",
"scale",
"=",
"1.",
"-",
"eps",
"*",
"float",
"(",
"d",
"+",
"1",
")",
"/",
"d",
"offset",
"=",
"eps",
"/",
"float",
"(",
"d",
")",
"x",
"=",
"scale",
"*",
"x",
"+",
"offset",
"x",
"/=",
"x",
".",
"sum",
"(",
")",
"return",
"x"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/helpers/simplex.py#L62-L93 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/io/matlab/mio4.py | python | VarReader4.read_sub_array | (self, hdr, copy=True) | return arr | Mat4 read using header `hdr` dtype and dims
Parameters
----------
hdr : object
object with attributes ``dtype``, ``dims``. dtype is assumed to be
the correct endianness
copy : bool, optional
copies array before return if True (default True)
(buffer is usually read only)
Returns
-------
arr : ndarray
of dtype givem by `hdr` ``dtype`` and shape givem by `hdr` ``dims`` | Mat4 read using header `hdr` dtype and dims | [
"Mat4",
"read",
"using",
"header",
"hdr",
"dtype",
"and",
"dims"
] | def read_sub_array(self, hdr, copy=True):
''' Mat4 read using header `hdr` dtype and dims
Parameters
----------
hdr : object
object with attributes ``dtype``, ``dims``. dtype is assumed to be
the correct endianness
copy : bool, optional
copies array before return if True (default True)
(buffer is usually read only)
Returns
-------
arr : ndarray
of dtype givem by `hdr` ``dtype`` and shape givem by `hdr` ``dims``
'''
dt = hdr.dtype
dims = hdr.dims
num_bytes = dt.itemsize
for d in dims:
num_bytes *= d
buffer = self.mat_stream.read(int(num_bytes))
if len(buffer) != num_bytes:
raise ValueError("Not enough bytes to read matrix '%s'; is this "
"a badly-formed file? Consider listing matrices "
"with `whosmat` and loading named matrices with "
"`variable_names` kwarg to `loadmat`" % hdr.name)
arr = np.ndarray(shape=dims,
dtype=dt,
buffer=buffer,
order='F')
if copy:
arr = arr.copy()
return arr | [
"def",
"read_sub_array",
"(",
"self",
",",
"hdr",
",",
"copy",
"=",
"True",
")",
":",
"dt",
"=",
"hdr",
".",
"dtype",
"dims",
"=",
"hdr",
".",
"dims",
"num_bytes",
"=",
"dt",
".",
"itemsize",
"for",
"d",
"in",
"dims",
":",
"num_bytes",
"*=",
"d",
"buffer",
"=",
"self",
".",
"mat_stream",
".",
"read",
"(",
"int",
"(",
"num_bytes",
")",
")",
"if",
"len",
"(",
"buffer",
")",
"!=",
"num_bytes",
":",
"raise",
"ValueError",
"(",
"\"Not enough bytes to read matrix '%s'; is this \"",
"\"a badly-formed file? Consider listing matrices \"",
"\"with `whosmat` and loading named matrices with \"",
"\"`variable_names` kwarg to `loadmat`\"",
"%",
"hdr",
".",
"name",
")",
"arr",
"=",
"np",
".",
"ndarray",
"(",
"shape",
"=",
"dims",
",",
"dtype",
"=",
"dt",
",",
"buffer",
"=",
"buffer",
",",
"order",
"=",
"'F'",
")",
"if",
"copy",
":",
"arr",
"=",
"arr",
".",
"copy",
"(",
")",
"return",
"arr"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/matlab/mio4.py#L151-L185 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/codegen.py | python | BaseCPUCodegen.target_data | (self) | return self._target_data | The LLVM "target data" object for this codegen instance. | The LLVM "target data" object for this codegen instance. | [
"The",
"LLVM",
"target",
"data",
"object",
"for",
"this",
"codegen",
"instance",
"."
] | def target_data(self):
"""
The LLVM "target data" object for this codegen instance.
"""
return self._target_data | [
"def",
"target_data",
"(",
"self",
")",
":",
"return",
"self",
".",
"_target_data"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/codegen.py#L660-L664 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathCommands.py | python | findShape | (shape, subname=None, subtype=None) | return ret | To find a higher order shape containing the subshape with subname.
E.g. to find the wire containing 'Edge1' in shape,
findShape(shape,'Edge1','Wires') | To find a higher order shape containing the subshape with subname.
E.g. to find the wire containing 'Edge1' in shape,
findShape(shape,'Edge1','Wires') | [
"To",
"find",
"a",
"higher",
"order",
"shape",
"containing",
"the",
"subshape",
"with",
"subname",
".",
"E",
".",
"g",
".",
"to",
"find",
"the",
"wire",
"containing",
"Edge1",
"in",
"shape",
"findShape",
"(",
"shape",
"Edge1",
"Wires",
")"
] | def findShape(shape, subname=None, subtype=None):
"""To find a higher order shape containing the subshape with subname.
E.g. to find the wire containing 'Edge1' in shape,
findShape(shape,'Edge1','Wires')
"""
if not subname:
return shape
ret = shape.getElement(subname)
if not subtype or not ret or ret.isNull():
return ret
if subname.startswith("Face"):
tp = "Faces"
elif subname.startswith("Edge"):
tp = "Edges"
elif subname.startswith("Vertex"):
tp = "Vertex"
else:
return ret
for obj in getattr(shape, subtype):
for sobj in getattr(obj, tp):
if sobj.isEqual(ret):
return obj
return ret | [
"def",
"findShape",
"(",
"shape",
",",
"subname",
"=",
"None",
",",
"subtype",
"=",
"None",
")",
":",
"if",
"not",
"subname",
":",
"return",
"shape",
"ret",
"=",
"shape",
".",
"getElement",
"(",
"subname",
")",
"if",
"not",
"subtype",
"or",
"not",
"ret",
"or",
"ret",
".",
"isNull",
"(",
")",
":",
"return",
"ret",
"if",
"subname",
".",
"startswith",
"(",
"\"Face\"",
")",
":",
"tp",
"=",
"\"Faces\"",
"elif",
"subname",
".",
"startswith",
"(",
"\"Edge\"",
")",
":",
"tp",
"=",
"\"Edges\"",
"elif",
"subname",
".",
"startswith",
"(",
"\"Vertex\"",
")",
":",
"tp",
"=",
"\"Vertex\"",
"else",
":",
"return",
"ret",
"for",
"obj",
"in",
"getattr",
"(",
"shape",
",",
"subtype",
")",
":",
"for",
"sobj",
"in",
"getattr",
"(",
"obj",
",",
"tp",
")",
":",
"if",
"sobj",
".",
"isEqual",
"(",
"ret",
")",
":",
"return",
"obj",
"return",
"ret"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathCommands.py#L224-L246 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewListCtrl.GetTextValue | (*args, **kwargs) | return _dataview.DataViewListCtrl_GetTextValue(*args, **kwargs) | GetTextValue(self, unsigned int row, unsigned int col) -> String | GetTextValue(self, unsigned int row, unsigned int col) -> String | [
"GetTextValue",
"(",
"self",
"unsigned",
"int",
"row",
"unsigned",
"int",
"col",
")",
"-",
">",
"String"
] | def GetTextValue(*args, **kwargs):
"""GetTextValue(self, unsigned int row, unsigned int col) -> String"""
return _dataview.DataViewListCtrl_GetTextValue(*args, **kwargs) | [
"def",
"GetTextValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewListCtrl_GetTextValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L2188-L2190 | |
QMCPACK/qmcpack | d0948ab455e38364458740cc8e2239600a14c5cd | utils/afqmctools/afqmctools/hamiltonian/mol.py | python | write_hamil_mol | (scf_data, hamil_file, chol_cut,
verbose=True, cas=None,
ortho_ao=False, nelec=None,
real_chol=False, df=False,
dense=False) | Write QMCPACK hamiltonian from pyscf scf calculation on mol object. | Write QMCPACK hamiltonian from pyscf scf calculation on mol object. | [
"Write",
"QMCPACK",
"hamiltonian",
"from",
"pyscf",
"scf",
"calculation",
"on",
"mol",
"object",
"."
] | def write_hamil_mol(scf_data, hamil_file, chol_cut,
verbose=True, cas=None,
ortho_ao=False, nelec=None,
real_chol=False, df=False,
dense=False):
"""Write QMCPACK hamiltonian from pyscf scf calculation on mol object.
"""
hcore, chol_vecs, nelec, enuc, X = generate_hamiltonian(scf_data,
verbose=verbose,
chol_cut=chol_cut,
cas=cas,
ortho_ao=ortho_ao,
nelec=nelec,
df=df)
# Want L_{(ik),n}
chol_vecs = chol_vecs.T
nbasis = hcore.shape[-1]
if dense:
write_qmcpack_dense(hcore, chol_vecs, nelec,
nbasis, enuc, real_chol=real_chol,
filename=hamil_file,
ortho=X)
else:
write_qmcpack_sparse(hcore, chol_vecs, nelec, nbasis, enuc,
filename=hamil_file, real_chol=real_chol,
verbose=verbose, ortho=X) | [
"def",
"write_hamil_mol",
"(",
"scf_data",
",",
"hamil_file",
",",
"chol_cut",
",",
"verbose",
"=",
"True",
",",
"cas",
"=",
"None",
",",
"ortho_ao",
"=",
"False",
",",
"nelec",
"=",
"None",
",",
"real_chol",
"=",
"False",
",",
"df",
"=",
"False",
",",
"dense",
"=",
"False",
")",
":",
"hcore",
",",
"chol_vecs",
",",
"nelec",
",",
"enuc",
",",
"X",
"=",
"generate_hamiltonian",
"(",
"scf_data",
",",
"verbose",
"=",
"verbose",
",",
"chol_cut",
"=",
"chol_cut",
",",
"cas",
"=",
"cas",
",",
"ortho_ao",
"=",
"ortho_ao",
",",
"nelec",
"=",
"nelec",
",",
"df",
"=",
"df",
")",
"# Want L_{(ik),n}",
"chol_vecs",
"=",
"chol_vecs",
".",
"T",
"nbasis",
"=",
"hcore",
".",
"shape",
"[",
"-",
"1",
"]",
"if",
"dense",
":",
"write_qmcpack_dense",
"(",
"hcore",
",",
"chol_vecs",
",",
"nelec",
",",
"nbasis",
",",
"enuc",
",",
"real_chol",
"=",
"real_chol",
",",
"filename",
"=",
"hamil_file",
",",
"ortho",
"=",
"X",
")",
"else",
":",
"write_qmcpack_sparse",
"(",
"hcore",
",",
"chol_vecs",
",",
"nelec",
",",
"nbasis",
",",
"enuc",
",",
"filename",
"=",
"hamil_file",
",",
"real_chol",
"=",
"real_chol",
",",
"verbose",
"=",
"verbose",
",",
"ortho",
"=",
"X",
")"
] | https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/utils/afqmctools/afqmctools/hamiltonian/mol.py#L20-L45 | ||
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/feature.py | python | get | (name) | return __all_features[name] | Return the Feature instance for the specified name.
Throws if no feature by such name exists | Return the Feature instance for the specified name. | [
"Return",
"the",
"Feature",
"instance",
"for",
"the",
"specified",
"name",
"."
] | def get(name):
"""Return the Feature instance for the specified name.
Throws if no feature by such name exists
"""
assert isinstance(name, basestring)
return __all_features[name] | [
"def",
"get",
"(",
"name",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"return",
"__all_features",
"[",
"name",
"]"
] | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/feature.py#L125-L131 | |
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/MSVSSettings.py | python | _ValidateSettings | (validators, settings, stderr) | Validates that the settings are valid for MSBuild or MSVS.
We currently only validate the names of the settings, not their values.
Args:
validators: A dictionary of tools and their validators.
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages. | Validates that the settings are valid for MSBuild or MSVS. | [
"Validates",
"that",
"the",
"settings",
"are",
"valid",
"for",
"MSBuild",
"or",
"MSVS",
"."
] | def _ValidateSettings(validators, settings, stderr):
"""Validates that the settings are valid for MSBuild or MSVS.
We currently only validate the names of the settings, not their values.
Args:
validators: A dictionary of tools and their validators.
settings: A dictionary. The key is the tool name. The values are
themselves dictionaries of settings and their values.
stderr: The stream receiving the error messages.
"""
for tool_name in settings:
if tool_name in validators:
tool_validators = validators[tool_name]
for setting, value in settings[tool_name].iteritems():
if setting in tool_validators:
try:
tool_validators[setting](value)
except ValueError, e:
print >> stderr, ('Warning: for %s/%s, %s' %
(tool_name, setting, e))
else:
print >> stderr, ('Warning: unrecognized setting %s/%s' %
(tool_name, setting))
else:
print >> stderr, ('Warning: unrecognized tool %s' % tool_name) | [
"def",
"_ValidateSettings",
"(",
"validators",
",",
"settings",
",",
"stderr",
")",
":",
"for",
"tool_name",
"in",
"settings",
":",
"if",
"tool_name",
"in",
"validators",
":",
"tool_validators",
"=",
"validators",
"[",
"tool_name",
"]",
"for",
"setting",
",",
"value",
"in",
"settings",
"[",
"tool_name",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"setting",
"in",
"tool_validators",
":",
"try",
":",
"tool_validators",
"[",
"setting",
"]",
"(",
"value",
")",
"except",
"ValueError",
",",
"e",
":",
"print",
">>",
"stderr",
",",
"(",
"'Warning: for %s/%s, %s'",
"%",
"(",
"tool_name",
",",
"setting",
",",
"e",
")",
")",
"else",
":",
"print",
">>",
"stderr",
",",
"(",
"'Warning: unrecognized setting %s/%s'",
"%",
"(",
"tool_name",
",",
"setting",
")",
")",
"else",
":",
"print",
">>",
"stderr",
",",
"(",
"'Warning: unrecognized tool %s'",
"%",
"tool_name",
")"
] | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/MSVSSettings.py#L464-L489 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Pygments/py3/pygments/lexers/graphics.py | python | PovrayLexer.analyse_text | (text) | return result | POVRAY is similar to JSON/C, but the combination of camera and
light_source is probably not very likely elsewhere. HLSL or GLSL
are similar (GLSL even has #version), but they miss #declare, and
light_source/camera are not keywords anywhere else -- it's fair
to assume though that any POVRAY scene must have a camera and
lightsource. | POVRAY is similar to JSON/C, but the combination of camera and
light_source is probably not very likely elsewhere. HLSL or GLSL
are similar (GLSL even has #version), but they miss #declare, and
light_source/camera are not keywords anywhere else -- it's fair
to assume though that any POVRAY scene must have a camera and
lightsource. | [
"POVRAY",
"is",
"similar",
"to",
"JSON",
"/",
"C",
"but",
"the",
"combination",
"of",
"camera",
"and",
"light_source",
"is",
"probably",
"not",
"very",
"likely",
"elsewhere",
".",
"HLSL",
"or",
"GLSL",
"are",
"similar",
"(",
"GLSL",
"even",
"has",
"#version",
")",
"but",
"they",
"miss",
"#declare",
"and",
"light_source",
"/",
"camera",
"are",
"not",
"keywords",
"anywhere",
"else",
"--",
"it",
"s",
"fair",
"to",
"assume",
"though",
"that",
"any",
"POVRAY",
"scene",
"must",
"have",
"a",
"camera",
"and",
"lightsource",
"."
] | def analyse_text(text):
"""POVRAY is similar to JSON/C, but the combination of camera and
light_source is probably not very likely elsewhere. HLSL or GLSL
are similar (GLSL even has #version), but they miss #declare, and
light_source/camera are not keywords anywhere else -- it's fair
to assume though that any POVRAY scene must have a camera and
lightsource."""
result = 0
if '#version' in text:
result += 0.05
if '#declare' in text:
result += 0.05
if 'camera' in text:
result += 0.05
if 'light_source' in text:
result += 0.1
return result | [
"def",
"analyse_text",
"(",
"text",
")",
":",
"result",
"=",
"0",
"if",
"'#version'",
"in",
"text",
":",
"result",
"+=",
"0.05",
"if",
"'#declare'",
"in",
"text",
":",
"result",
"+=",
"0.05",
"if",
"'camera'",
"in",
"text",
":",
"result",
"+=",
"0.05",
"if",
"'light_source'",
"in",
"text",
":",
"result",
"+=",
"0.1",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/lexers/graphics.py#L782-L799 | |
twtygqyy/caffe-augmentation | c76600d247e5132fa5bd89d87bb5df458341fa84 | scripts/cpp_lint.py | python | CheckCStyleCast | (filename, linenum, line, raw_line, cast_type, pattern,
error) | return True | Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise. | Checks for a C-style cast by looking for the pattern. | [
"Checks",
"for",
"a",
"C",
"-",
"style",
"cast",
"by",
"looking",
"for",
"the",
"pattern",
"."
] | def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
match = Search(pattern, line)
if not match:
return False
# Exclude lines with sizeof, since sizeof looks like a cast.
sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
if sizeof_match:
return False
# operator++(int) and operator--(int)
if (line[0:match.start(1) - 1].endswith(' operator++') or
line[0:match.start(1) - 1].endswith(' operator--')):
return False
# A single unnamed argument for a function tends to look like old
# style cast. If we see those, don't issue warnings for deprecated
# casts, instead issue warnings for unnamed arguments where
# appropriate.
#
# These are things that we want warnings for, since the style guide
# explicitly require all parameters to be named:
# Function(int);
# Function(int) {
# ConstMember(int) const;
# ConstMember(int) const {
# ExceptionMember(int) throw (...);
# ExceptionMember(int) throw (...) {
# PureVirtual(int) = 0;
#
# These are functions of some sort, where the compiler would be fine
# if they had named parameters, but people often omit those
# identifiers to reduce clutter:
# (FunctionPointer)(int);
# (FunctionPointer)(int) = value;
# Function((function_pointer_arg)(int))
# <TemplateArgument(int)>;
# <(FunctionPointerTemplateArgument)(int)>;
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder):
# Looks like an unnamed parameter.
# Don't warn on any kind of template arguments.
if Match(r'^\s*>', remainder):
return False
# Don't warn on assignments to function pointers, but keep warnings for
# unnamed parameters to pure virtual functions. Note that this pattern
# will also pass on assignments of "0" to function pointers, but the
# preferred values for those would be "nullptr" or "NULL".
matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
if matched_zero and matched_zero.group(1) != '0':
return False
# Don't warn on function pointer declarations. For this we need
# to check what came before the "(type)" string.
if Match(r'.*\)\s*$', line[0:match.start(0)]):
return False
# Don't warn if the parameter is named with block comments, e.g.:
# Function(int /*unused_param*/);
if '/*' in raw_line:
return False
# Passed all filters, issue warning here.
error(filename, linenum, 'readability/function', 3,
'All parameters should be named in a function')
return True
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True | [
"def",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"raw_line",
",",
"cast_type",
",",
"pattern",
",",
"error",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"not",
"match",
":",
"return",
"False",
"# Exclude lines with sizeof, since sizeof looks like a cast.",
"sizeof_match",
"=",
"Match",
"(",
"r'.*sizeof\\s*$'",
",",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
")",
"if",
"sizeof_match",
":",
"return",
"False",
"# operator++(int) and operator--(int)",
"if",
"(",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
".",
"endswith",
"(",
"' operator++'",
")",
"or",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
".",
"endswith",
"(",
"' operator--'",
")",
")",
":",
"return",
"False",
"# A single unnamed argument for a function tends to look like old",
"# style cast. If we see those, don't issue warnings for deprecated",
"# casts, instead issue warnings for unnamed arguments where",
"# appropriate.",
"#",
"# These are things that we want warnings for, since the style guide",
"# explicitly require all parameters to be named:",
"# Function(int);",
"# Function(int) {",
"# ConstMember(int) const;",
"# ConstMember(int) const {",
"# ExceptionMember(int) throw (...);",
"# ExceptionMember(int) throw (...) {",
"# PureVirtual(int) = 0;",
"#",
"# These are functions of some sort, where the compiler would be fine",
"# if they had named parameters, but people often omit those",
"# identifiers to reduce clutter:",
"# (FunctionPointer)(int);",
"# (FunctionPointer)(int) = value;",
"# Function((function_pointer_arg)(int))",
"# <TemplateArgument(int)>;",
"# <(FunctionPointerTemplateArgument)(int)>;",
"remainder",
"=",
"line",
"[",
"match",
".",
"end",
"(",
"0",
")",
":",
"]",
"if",
"Match",
"(",
"r'^\\s*(?:;|const\\b|throw\\b|=|>|\\{|\\))'",
",",
"remainder",
")",
":",
"# Looks like an unnamed parameter.",
"# Don't warn on any kind of template arguments.",
"if",
"Match",
"(",
"r'^\\s*>'",
",",
"remainder",
")",
":",
"return",
"False",
"# Don't warn on assignments to function pointers, but keep warnings for",
"# unnamed parameters to pure virtual functions. Note that this pattern",
"# will also pass on assignments of \"0\" to function pointers, but the",
"# preferred values for those would be \"nullptr\" or \"NULL\".",
"matched_zero",
"=",
"Match",
"(",
"r'^\\s=\\s*(\\S+)\\s*;'",
",",
"remainder",
")",
"if",
"matched_zero",
"and",
"matched_zero",
".",
"group",
"(",
"1",
")",
"!=",
"'0'",
":",
"return",
"False",
"# Don't warn on function pointer declarations. For this we need",
"# to check what came before the \"(type)\" string.",
"if",
"Match",
"(",
"r'.*\\)\\s*$'",
",",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"0",
")",
"]",
")",
":",
"return",
"False",
"# Don't warn if the parameter is named with block comments, e.g.:",
"# Function(int /*unused_param*/);",
"if",
"'/*'",
"in",
"raw_line",
":",
"return",
"False",
"# Passed all filters, issue warning here.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/function'",
",",
"3",
",",
"'All parameters should be named in a function'",
")",
"return",
"True",
"# At this point, all that should be left is actual casts.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/casting'",
",",
"4",
",",
"'Using C-style cast. Use %s<%s>(...) instead'",
"%",
"(",
"cast_type",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"return",
"True"
] | https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/scripts/cpp_lint.py#L4251-L4342 | |
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/transform_impls/aggregate.py | python | aggregate | (ptype, zero, aggregate_fn, combine_fn, *side_inputs, **kargs) | return pobject.PObject(non_partial_node, ptype.pipeline()) | Implementation of transforms.aggregate() | Implementation of transforms.aggregate() | [
"Implementation",
"of",
"transforms",
".",
"aggregate",
"()"
] | def aggregate(ptype, zero, aggregate_fn, combine_fn, *side_inputs, **kargs):
"""
Implementation of transforms.aggregate()
"""
if utils.is_infinite(ptype):
raise ValueError("aggregate not supported infinite PType")
objector = kargs.get('serde', ptype.pipeline().default_objector())
scale = kargs.get('scale', 0.1)
partial_scale = math.sqrt(scale)
size = kargs.get('output_size', None)
if size is None:
partial_size = None
else:
partial_size = ptype.node().size() * math.sqrt(size / ptype.node().size())
memory = kargs.get('memory_limit', -1)
cpu = kargs.get('cpu_limit', -1)
side_inputs = side_input_util.SideInputsUtil.get_dealt_side_inputs_tuple(side_inputs)
partial_helper = side_input_util.SideInputsUtil(ptype, side_inputs)
partial_node = partial_helper.process_with_side_inputs() \
.by(entity.AccumulateProcessor(zero, aggregate_fn).set_side_inputs(*side_inputs)) \
.as_type(objector) \
.set_debug_info("AggregatePartial") \
.input(-1).allow_partial_processing().done()\
.set_effective_key_num(0) \
.set_size(partial_size, partial_scale) \
.set_memory(memory) \
.set_cpu(cpu)
non_partial_helper = side_input_util.SideInputsUtil(partial_node, side_inputs)
non_partial_node = non_partial_helper.process_with_side_inputs() \
.by(entity.AccumulateProcessor(zero, combine_fn).set_side_inputs(*side_inputs)) \
.as_type(objector) \
.set_debug_info("Aggregate") \
.set_effective_key_num(0) \
.set_size(size, partial_scale) \
.set_memory(memory) \
.set_cpu(cpu)
return pobject.PObject(non_partial_node, ptype.pipeline()) | [
"def",
"aggregate",
"(",
"ptype",
",",
"zero",
",",
"aggregate_fn",
",",
"combine_fn",
",",
"*",
"side_inputs",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"utils",
".",
"is_infinite",
"(",
"ptype",
")",
":",
"raise",
"ValueError",
"(",
"\"aggregate not supported infinite PType\"",
")",
"objector",
"=",
"kargs",
".",
"get",
"(",
"'serde'",
",",
"ptype",
".",
"pipeline",
"(",
")",
".",
"default_objector",
"(",
")",
")",
"scale",
"=",
"kargs",
".",
"get",
"(",
"'scale'",
",",
"0.1",
")",
"partial_scale",
"=",
"math",
".",
"sqrt",
"(",
"scale",
")",
"size",
"=",
"kargs",
".",
"get",
"(",
"'output_size'",
",",
"None",
")",
"if",
"size",
"is",
"None",
":",
"partial_size",
"=",
"None",
"else",
":",
"partial_size",
"=",
"ptype",
".",
"node",
"(",
")",
".",
"size",
"(",
")",
"*",
"math",
".",
"sqrt",
"(",
"size",
"/",
"ptype",
".",
"node",
"(",
")",
".",
"size",
"(",
")",
")",
"memory",
"=",
"kargs",
".",
"get",
"(",
"'memory_limit'",
",",
"-",
"1",
")",
"cpu",
"=",
"kargs",
".",
"get",
"(",
"'cpu_limit'",
",",
"-",
"1",
")",
"side_inputs",
"=",
"side_input_util",
".",
"SideInputsUtil",
".",
"get_dealt_side_inputs_tuple",
"(",
"side_inputs",
")",
"partial_helper",
"=",
"side_input_util",
".",
"SideInputsUtil",
"(",
"ptype",
",",
"side_inputs",
")",
"partial_node",
"=",
"partial_helper",
".",
"process_with_side_inputs",
"(",
")",
".",
"by",
"(",
"entity",
".",
"AccumulateProcessor",
"(",
"zero",
",",
"aggregate_fn",
")",
".",
"set_side_inputs",
"(",
"*",
"side_inputs",
")",
")",
".",
"as_type",
"(",
"objector",
")",
".",
"set_debug_info",
"(",
"\"AggregatePartial\"",
")",
".",
"input",
"(",
"-",
"1",
")",
".",
"allow_partial_processing",
"(",
")",
".",
"done",
"(",
")",
".",
"set_effective_key_num",
"(",
"0",
")",
".",
"set_size",
"(",
"partial_size",
",",
"partial_scale",
")",
".",
"set_memory",
"(",
"memory",
")",
".",
"set_cpu",
"(",
"cpu",
")",
"non_partial_helper",
"=",
"side_input_util",
".",
"SideInputsUtil",
"(",
"partial_node",
",",
"side_inputs",
")",
"non_partial_node",
"=",
"non_partial_helper",
".",
"process_with_side_inputs",
"(",
")",
".",
"by",
"(",
"entity",
".",
"AccumulateProcessor",
"(",
"zero",
",",
"combine_fn",
")",
".",
"set_side_inputs",
"(",
"*",
"side_inputs",
")",
")",
".",
"as_type",
"(",
"objector",
")",
".",
"set_debug_info",
"(",
"\"Aggregate\"",
")",
".",
"set_effective_key_num",
"(",
"0",
")",
".",
"set_size",
"(",
"size",
",",
"partial_scale",
")",
".",
"set_memory",
"(",
"memory",
")",
".",
"set_cpu",
"(",
"cpu",
")",
"return",
"pobject",
".",
"PObject",
"(",
"non_partial_node",
",",
"ptype",
".",
"pipeline",
"(",
")",
")"
] | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/transform_impls/aggregate.py#L30-L73 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py | python | _MuxHandshaker.__init__ | (self, request, dispatcher, send_quota, receive_quota) | Constructs an instance.
Args:
request: _LogicalRequest instance.
dispatcher: Dispatcher instance (dispatch.Dispatcher).
send_quota: Initial send quota.
receive_quota: Initial receive quota. | Constructs an instance.
Args:
request: _LogicalRequest instance.
dispatcher: Dispatcher instance (dispatch.Dispatcher).
send_quota: Initial send quota.
receive_quota: Initial receive quota. | [
"Constructs",
"an",
"instance",
".",
"Args",
":",
"request",
":",
"_LogicalRequest",
"instance",
".",
"dispatcher",
":",
"Dispatcher",
"instance",
"(",
"dispatch",
".",
"Dispatcher",
")",
".",
"send_quota",
":",
"Initial",
"send",
"quota",
".",
"receive_quota",
":",
"Initial",
"receive",
"quota",
"."
] | def __init__(self, request, dispatcher, send_quota, receive_quota):
"""Constructs an instance.
Args:
request: _LogicalRequest instance.
dispatcher: Dispatcher instance (dispatch.Dispatcher).
send_quota: Initial send quota.
receive_quota: Initial receive quota.
"""
hybi.Handshaker.__init__(self, request, dispatcher)
self._send_quota = send_quota
self._receive_quota = receive_quota
# Append headers which should not be included in handshake field of
# AddChannelRequest.
# TODO(bashi): Make sure whether we should raise exception when
# these headers are included already.
request.headers_in[common.UPGRADE_HEADER] = (
common.WEBSOCKET_UPGRADE_TYPE)
request.headers_in[common.SEC_WEBSOCKET_VERSION_HEADER] = (
str(common.VERSION_HYBI_LATEST))
request.headers_in[common.SEC_WEBSOCKET_KEY_HEADER] = (
self._DUMMY_WEBSOCKET_KEY) | [
"def",
"__init__",
"(",
"self",
",",
"request",
",",
"dispatcher",
",",
"send_quota",
",",
"receive_quota",
")",
":",
"hybi",
".",
"Handshaker",
".",
"__init__",
"(",
"self",
",",
"request",
",",
"dispatcher",
")",
"self",
".",
"_send_quota",
"=",
"send_quota",
"self",
".",
"_receive_quota",
"=",
"receive_quota",
"# Append headers which should not be included in handshake field of",
"# AddChannelRequest.",
"# TODO(bashi): Make sure whether we should raise exception when",
"# these headers are included already.",
"request",
".",
"headers_in",
"[",
"common",
".",
"UPGRADE_HEADER",
"]",
"=",
"(",
"common",
".",
"WEBSOCKET_UPGRADE_TYPE",
")",
"request",
".",
"headers_in",
"[",
"common",
".",
"SEC_WEBSOCKET_VERSION_HEADER",
"]",
"=",
"(",
"str",
"(",
"common",
".",
"VERSION_HYBI_LATEST",
")",
")",
"request",
".",
"headers_in",
"[",
"common",
".",
"SEC_WEBSOCKET_KEY_HEADER",
"]",
"=",
"(",
"self",
".",
"_DUMMY_WEBSOCKET_KEY",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py#L1293-L1315 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | utils/lui/lldbutil.py | python | get_symbol_names | (thread) | return [GetSymbol(i) for i in range(thread.GetNumFrames())] | Returns a sequence of symbols for this thread. | Returns a sequence of symbols for this thread. | [
"Returns",
"a",
"sequence",
"of",
"symbols",
"for",
"this",
"thread",
"."
] | def get_symbol_names(thread):
"""
Returns a sequence of symbols for this thread.
"""
def GetSymbol(i):
return thread.GetFrameAtIndex(i).GetSymbol().GetName()
return [GetSymbol(i) for i in range(thread.GetNumFrames())] | [
"def",
"get_symbol_names",
"(",
"thread",
")",
":",
"def",
"GetSymbol",
"(",
"i",
")",
":",
"return",
"thread",
".",
"GetFrameAtIndex",
"(",
"i",
")",
".",
"GetSymbol",
"(",
")",
".",
"GetName",
"(",
")",
"return",
"[",
"GetSymbol",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"thread",
".",
"GetNumFrames",
"(",
")",
")",
"]"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/lui/lldbutil.py#L714-L721 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py | python | _format_mapdict | (mapdict, script=False) | return _flatten(opts) | Formats mapdict to pass it to tk.call.
E.g. (script=False):
{'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]}
returns:
('-expand', '{active selected} grey focus {1, 2, 3, 4}') | Formats mapdict to pass it to tk.call. | [
"Formats",
"mapdict",
"to",
"pass",
"it",
"to",
"tk",
".",
"call",
"."
] | def _format_mapdict(mapdict, script=False):
"""Formats mapdict to pass it to tk.call.
E.g. (script=False):
{'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]}
returns:
('-expand', '{active selected} grey focus {1, 2, 3, 4}')"""
opts = []
for opt, value in mapdict.items():
opts.extend(("-%s" % opt,
_format_optvalue(_mapdict_values(value), script)))
return _flatten(opts) | [
"def",
"_format_mapdict",
"(",
"mapdict",
",",
"script",
"=",
"False",
")",
":",
"opts",
"=",
"[",
"]",
"for",
"opt",
",",
"value",
"in",
"mapdict",
".",
"items",
"(",
")",
":",
"opts",
".",
"extend",
"(",
"(",
"\"-%s\"",
"%",
"opt",
",",
"_format_optvalue",
"(",
"_mapdict_values",
"(",
"value",
")",
",",
"script",
")",
")",
")",
"return",
"_flatten",
"(",
"opts",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py#L100-L115 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py | python | AppendableTable.write_data | (self, chunksize: Optional[int], dropna: bool = False) | we form the data into a 2-d including indexes,values,mask
write chunk-by-chunk | we form the data into a 2-d including indexes,values,mask
write chunk-by-chunk | [
"we",
"form",
"the",
"data",
"into",
"a",
"2",
"-",
"d",
"including",
"indexes",
"values",
"mask",
"write",
"chunk",
"-",
"by",
"-",
"chunk"
] | def write_data(self, chunksize: Optional[int], dropna: bool = False):
""" we form the data into a 2-d including indexes,values,mask
write chunk-by-chunk """
names = self.dtype.names
nrows = self.nrows_expected
# if dropna==True, then drop ALL nan rows
masks = []
if dropna:
for a in self.values_axes:
# figure the mask: only do if we can successfully process this
# column, otherwise ignore the mask
mask = isna(a.data).all(axis=0)
if isinstance(mask, np.ndarray):
masks.append(mask.astype("u1", copy=False))
# consolidate masks
if len(masks):
mask = masks[0]
for m in masks[1:]:
mask = mask & m
mask = mask.ravel()
else:
mask = None
# broadcast the indexes if needed
indexes = [a.cvalues for a in self.index_axes]
nindexes = len(indexes)
assert nindexes == 1, nindexes # ensures we dont need to broadcast
# transpose the values so first dimension is last
# reshape the values if needed
values = [a.take_data() for a in self.values_axes]
values = [v.transpose(np.roll(np.arange(v.ndim), v.ndim - 1)) for v in values]
bvalues = []
for i, v in enumerate(values):
new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape
bvalues.append(values[i].reshape(new_shape))
# write the chunks
if chunksize is None:
chunksize = 100000
rows = np.empty(min(chunksize, nrows), dtype=self.dtype)
chunks = int(nrows / chunksize) + 1
for i in range(chunks):
start_i = i * chunksize
end_i = min((i + 1) * chunksize, nrows)
if start_i >= end_i:
break
self.write_data_chunk(
rows,
indexes=[a[start_i:end_i] for a in indexes],
mask=mask[start_i:end_i] if mask is not None else None,
values=[v[start_i:end_i] for v in bvalues],
) | [
"def",
"write_data",
"(",
"self",
",",
"chunksize",
":",
"Optional",
"[",
"int",
"]",
",",
"dropna",
":",
"bool",
"=",
"False",
")",
":",
"names",
"=",
"self",
".",
"dtype",
".",
"names",
"nrows",
"=",
"self",
".",
"nrows_expected",
"# if dropna==True, then drop ALL nan rows",
"masks",
"=",
"[",
"]",
"if",
"dropna",
":",
"for",
"a",
"in",
"self",
".",
"values_axes",
":",
"# figure the mask: only do if we can successfully process this",
"# column, otherwise ignore the mask",
"mask",
"=",
"isna",
"(",
"a",
".",
"data",
")",
".",
"all",
"(",
"axis",
"=",
"0",
")",
"if",
"isinstance",
"(",
"mask",
",",
"np",
".",
"ndarray",
")",
":",
"masks",
".",
"append",
"(",
"mask",
".",
"astype",
"(",
"\"u1\"",
",",
"copy",
"=",
"False",
")",
")",
"# consolidate masks",
"if",
"len",
"(",
"masks",
")",
":",
"mask",
"=",
"masks",
"[",
"0",
"]",
"for",
"m",
"in",
"masks",
"[",
"1",
":",
"]",
":",
"mask",
"=",
"mask",
"&",
"m",
"mask",
"=",
"mask",
".",
"ravel",
"(",
")",
"else",
":",
"mask",
"=",
"None",
"# broadcast the indexes if needed",
"indexes",
"=",
"[",
"a",
".",
"cvalues",
"for",
"a",
"in",
"self",
".",
"index_axes",
"]",
"nindexes",
"=",
"len",
"(",
"indexes",
")",
"assert",
"nindexes",
"==",
"1",
",",
"nindexes",
"# ensures we dont need to broadcast",
"# transpose the values so first dimension is last",
"# reshape the values if needed",
"values",
"=",
"[",
"a",
".",
"take_data",
"(",
")",
"for",
"a",
"in",
"self",
".",
"values_axes",
"]",
"values",
"=",
"[",
"v",
".",
"transpose",
"(",
"np",
".",
"roll",
"(",
"np",
".",
"arange",
"(",
"v",
".",
"ndim",
")",
",",
"v",
".",
"ndim",
"-",
"1",
")",
")",
"for",
"v",
"in",
"values",
"]",
"bvalues",
"=",
"[",
"]",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"values",
")",
":",
"new_shape",
"=",
"(",
"nrows",
",",
")",
"+",
"self",
".",
"dtype",
"[",
"names",
"[",
"nindexes",
"+",
"i",
"]",
"]",
".",
"shape",
"bvalues",
".",
"append",
"(",
"values",
"[",
"i",
"]",
".",
"reshape",
"(",
"new_shape",
")",
")",
"# write the chunks",
"if",
"chunksize",
"is",
"None",
":",
"chunksize",
"=",
"100000",
"rows",
"=",
"np",
".",
"empty",
"(",
"min",
"(",
"chunksize",
",",
"nrows",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"chunks",
"=",
"int",
"(",
"nrows",
"/",
"chunksize",
")",
"+",
"1",
"for",
"i",
"in",
"range",
"(",
"chunks",
")",
":",
"start_i",
"=",
"i",
"*",
"chunksize",
"end_i",
"=",
"min",
"(",
"(",
"i",
"+",
"1",
")",
"*",
"chunksize",
",",
"nrows",
")",
"if",
"start_i",
">=",
"end_i",
":",
"break",
"self",
".",
"write_data_chunk",
"(",
"rows",
",",
"indexes",
"=",
"[",
"a",
"[",
"start_i",
":",
"end_i",
"]",
"for",
"a",
"in",
"indexes",
"]",
",",
"mask",
"=",
"mask",
"[",
"start_i",
":",
"end_i",
"]",
"if",
"mask",
"is",
"not",
"None",
"else",
"None",
",",
"values",
"=",
"[",
"v",
"[",
"start_i",
":",
"end_i",
"]",
"for",
"v",
"in",
"bvalues",
"]",
",",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py#L4175-L4234 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/command.py | python | InitializeMultiprocessingVariables | () | Initializes module-level variables that will be inherited by subprocesses.
On Windows, a multiprocessing.Manager object should only
be created within an "if __name__ == '__main__':" block. This function
must be called, otherwise every command that calls Command.Apply will fail. | Initializes module-level variables that will be inherited by subprocesses. | [
"Initializes",
"module",
"-",
"level",
"variables",
"that",
"will",
"be",
"inherited",
"by",
"subprocesses",
"."
] | def InitializeMultiprocessingVariables():
"""Initializes module-level variables that will be inherited by subprocesses.
On Windows, a multiprocessing.Manager object should only
be created within an "if __name__ == '__main__':" block. This function
must be called, otherwise every command that calls Command.Apply will fail.
"""
# This list of global variables must exactly match the above list of
# declarations.
# pylint: disable=global-variable-undefined
global manager, consumer_pools, task_queues, caller_id_lock, caller_id_counter
global total_tasks, call_completed_map, global_return_values_map
global need_pool_or_done_cond, caller_id_finished_count, new_pool_needed
global current_max_recursive_level, shared_vars_map, shared_vars_list_map
global class_map, worker_checking_level_lock, failure_count
manager = multiprocessing.Manager()
consumer_pools = []
# List of all existing task queues - used by all pools to find the queue
# that's appropriate for the given recursive_apply_level.
task_queues = []
# Used to assign a globally unique caller ID to each Apply call.
caller_id_lock = manager.Lock()
caller_id_counter = multiprocessing.Value('i', 0)
# Map from caller_id to total number of tasks to be completed for that ID.
total_tasks = AtomicDict(manager=manager)
# Map from caller_id to a boolean which is True iff all its tasks are
# finished.
call_completed_map = AtomicDict(manager=manager)
# Used to keep track of the set of return values for each caller ID.
global_return_values_map = AtomicDict(manager=manager)
# Condition used to notify any waiting threads that a task has finished or
# that a call to Apply needs a new set of consumer processes.
need_pool_or_done_cond = manager.Condition()
# Lock used to prevent multiple worker processes from asking the main thread
# to create a new consumer pool for the same level.
worker_checking_level_lock = manager.Lock()
# Map from caller_id to the current number of completed tasks for that ID.
caller_id_finished_count = AtomicDict(manager=manager)
# Used as a way for the main thread to distinguish between being woken up
# by another call finishing and being woken up by a call that needs a new set
# of consumer processes.
new_pool_needed = multiprocessing.Value('i', 0)
current_max_recursive_level = multiprocessing.Value('i', 0)
# Map from (caller_id, name) to the value of that shared variable.
shared_vars_map = AtomicDict(manager=manager)
shared_vars_list_map = AtomicDict(manager=manager)
# Map from caller_id to calling class.
class_map = manager.dict()
# Number of tasks that resulted in an exception in calls to Apply().
failure_count = multiprocessing.Value('i', 0) | [
"def",
"InitializeMultiprocessingVariables",
"(",
")",
":",
"# This list of global variables must exactly match the above list of",
"# declarations.",
"# pylint: disable=global-variable-undefined",
"global",
"manager",
",",
"consumer_pools",
",",
"task_queues",
",",
"caller_id_lock",
",",
"caller_id_counter",
"global",
"total_tasks",
",",
"call_completed_map",
",",
"global_return_values_map",
"global",
"need_pool_or_done_cond",
",",
"caller_id_finished_count",
",",
"new_pool_needed",
"global",
"current_max_recursive_level",
",",
"shared_vars_map",
",",
"shared_vars_list_map",
"global",
"class_map",
",",
"worker_checking_level_lock",
",",
"failure_count",
"manager",
"=",
"multiprocessing",
".",
"Manager",
"(",
")",
"consumer_pools",
"=",
"[",
"]",
"# List of all existing task queues - used by all pools to find the queue",
"# that's appropriate for the given recursive_apply_level.",
"task_queues",
"=",
"[",
"]",
"# Used to assign a globally unique caller ID to each Apply call.",
"caller_id_lock",
"=",
"manager",
".",
"Lock",
"(",
")",
"caller_id_counter",
"=",
"multiprocessing",
".",
"Value",
"(",
"'i'",
",",
"0",
")",
"# Map from caller_id to total number of tasks to be completed for that ID.",
"total_tasks",
"=",
"AtomicDict",
"(",
"manager",
"=",
"manager",
")",
"# Map from caller_id to a boolean which is True iff all its tasks are",
"# finished.",
"call_completed_map",
"=",
"AtomicDict",
"(",
"manager",
"=",
"manager",
")",
"# Used to keep track of the set of return values for each caller ID.",
"global_return_values_map",
"=",
"AtomicDict",
"(",
"manager",
"=",
"manager",
")",
"# Condition used to notify any waiting threads that a task has finished or",
"# that a call to Apply needs a new set of consumer processes.",
"need_pool_or_done_cond",
"=",
"manager",
".",
"Condition",
"(",
")",
"# Lock used to prevent multiple worker processes from asking the main thread",
"# to create a new consumer pool for the same level.",
"worker_checking_level_lock",
"=",
"manager",
".",
"Lock",
"(",
")",
"# Map from caller_id to the current number of completed tasks for that ID.",
"caller_id_finished_count",
"=",
"AtomicDict",
"(",
"manager",
"=",
"manager",
")",
"# Used as a way for the main thread to distinguish between being woken up",
"# by another call finishing and being woken up by a call that needs a new set",
"# of consumer processes.",
"new_pool_needed",
"=",
"multiprocessing",
".",
"Value",
"(",
"'i'",
",",
"0",
")",
"current_max_recursive_level",
"=",
"multiprocessing",
".",
"Value",
"(",
"'i'",
",",
"0",
")",
"# Map from (caller_id, name) to the value of that shared variable.",
"shared_vars_map",
"=",
"AtomicDict",
"(",
"manager",
"=",
"manager",
")",
"shared_vars_list_map",
"=",
"AtomicDict",
"(",
"manager",
"=",
"manager",
")",
"# Map from caller_id to calling class.",
"class_map",
"=",
"manager",
".",
"dict",
"(",
")",
"# Number of tasks that resulted in an exception in calls to Apply().",
"failure_count",
"=",
"multiprocessing",
".",
"Value",
"(",
"'i'",
",",
"0",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/command.py#L194-L258 | ||
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_6_0_0.py | python | MiroInterpreter.do_items | (self, line) | items -- Lists the items in the feed/playlist/tab selected. | items -- Lists the items in the feed/playlist/tab selected. | [
"items",
"--",
"Lists",
"the",
"items",
"in",
"the",
"feed",
"/",
"playlist",
"/",
"tab",
"selected",
"."
] | def do_items(self, line):
"""items -- Lists the items in the feed/playlist/tab selected."""
if self.selection_type is None:
print "Error: No tab/feed/playlist selected."
return
elif self.selection_type == 'feed':
feed = self.tab
view = feed.items
self.printout_item_list(view)
elif self.selection_type == 'playlist':
playlist = self.tab.obj
self.printout_item_list(playlist.getView())
elif self.selection_type == 'downloads':
self.printout_item_list(item.Item.downloading_view(),
item.Item.paused_view())
elif self.selection_type == 'channel-folder':
folder = self.tab.obj
allItems = views.items.filterWithIndex(
indexes.itemsByChannelFolder, folder)
allItemsSorted = allItems.sort(folder.itemSort.sort)
self.printout_item_list(allItemsSorted)
allItemsSorted.unlink()
else:
raise ValueError("Unknown tab type") | [
"def",
"do_items",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"selection_type",
"is",
"None",
":",
"print",
"\"Error: No tab/feed/playlist selected.\"",
"return",
"elif",
"self",
".",
"selection_type",
"==",
"'feed'",
":",
"feed",
"=",
"self",
".",
"tab",
"view",
"=",
"feed",
".",
"items",
"self",
".",
"printout_item_list",
"(",
"view",
")",
"elif",
"self",
".",
"selection_type",
"==",
"'playlist'",
":",
"playlist",
"=",
"self",
".",
"tab",
".",
"obj",
"self",
".",
"printout_item_list",
"(",
"playlist",
".",
"getView",
"(",
")",
")",
"elif",
"self",
".",
"selection_type",
"==",
"'downloads'",
":",
"self",
".",
"printout_item_list",
"(",
"item",
".",
"Item",
".",
"downloading_view",
"(",
")",
",",
"item",
".",
"Item",
".",
"paused_view",
"(",
")",
")",
"elif",
"self",
".",
"selection_type",
"==",
"'channel-folder'",
":",
"folder",
"=",
"self",
".",
"tab",
".",
"obj",
"allItems",
"=",
"views",
".",
"items",
".",
"filterWithIndex",
"(",
"indexes",
".",
"itemsByChannelFolder",
",",
"folder",
")",
"allItemsSorted",
"=",
"allItems",
".",
"sort",
"(",
"folder",
".",
"itemSort",
".",
"sort",
")",
"self",
".",
"printout_item_list",
"(",
"allItemsSorted",
")",
"allItemsSorted",
".",
"unlink",
"(",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown tab type\"",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_6_0_0.py#L606-L629 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | PyDataViewCustomRenderer.GetTextExtent | (*args, **kwargs) | return _dataview.PyDataViewCustomRenderer_GetTextExtent(*args, **kwargs) | GetTextExtent(self, String str) -> Size | GetTextExtent(self, String str) -> Size | [
"GetTextExtent",
"(",
"self",
"String",
"str",
")",
"-",
">",
"Size"
] | def GetTextExtent(*args, **kwargs):
"""GetTextExtent(self, String str) -> Size"""
return _dataview.PyDataViewCustomRenderer_GetTextExtent(*args, **kwargs) | [
"def",
"GetTextExtent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"PyDataViewCustomRenderer_GetTextExtent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1505-L1507 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathProfile.py | python | ObjectProfile._getOffsetArea | (self, obj, fcShape, isHole) | return PathUtils.getOffsetArea(
fcShape, offset, plane=fcShape, tolerance=tolerance
) | Get an offset area for a shape. Wrapper around
PathUtils.getOffsetArea. | Get an offset area for a shape. Wrapper around
PathUtils.getOffsetArea. | [
"Get",
"an",
"offset",
"area",
"for",
"a",
"shape",
".",
"Wrapper",
"around",
"PathUtils",
".",
"getOffsetArea",
"."
] | def _getOffsetArea(self, obj, fcShape, isHole):
"""Get an offset area for a shape. Wrapper around
PathUtils.getOffsetArea."""
PathLog.debug("_getOffsetArea()")
JOB = PathUtils.findParentJob(obj)
tolerance = JOB.GeometryTolerance.Value
offset = self.ofstRadius
if isHole is False:
offset = 0 - offset
return PathUtils.getOffsetArea(
fcShape, offset, plane=fcShape, tolerance=tolerance
) | [
"def",
"_getOffsetArea",
"(",
"self",
",",
"obj",
",",
"fcShape",
",",
"isHole",
")",
":",
"PathLog",
".",
"debug",
"(",
"\"_getOffsetArea()\"",
")",
"JOB",
"=",
"PathUtils",
".",
"findParentJob",
"(",
"obj",
")",
"tolerance",
"=",
"JOB",
".",
"GeometryTolerance",
".",
"Value",
"offset",
"=",
"self",
".",
"ofstRadius",
"if",
"isHole",
"is",
"False",
":",
"offset",
"=",
"0",
"-",
"offset",
"return",
"PathUtils",
".",
"getOffsetArea",
"(",
"fcShape",
",",
"offset",
",",
"plane",
"=",
"fcShape",
",",
"tolerance",
"=",
"tolerance",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathProfile.py#L1032-L1046 | |
openweave/openweave-core | 11ceb6b7efd39fe05de7f79229247a5774d56766 | src/tools/factory-prov-tool/WeaveTLV.py | python | TLVWriter.putFloat | (self, tag, val) | Write a value as a TLV float with the specified TLV tag. | Write a value as a TLV float with the specified TLV tag. | [
"Write",
"a",
"value",
"as",
"a",
"TLV",
"float",
"with",
"the",
"specified",
"TLV",
"tag",
"."
] | def putFloat(self, tag, val):
'''Write a value as a TLV float with the specified TLV tag.'''
val = struct.pack('d', val)
controlAndTag = self._encodeControlAndTag(TLVType_FloatingPointNumber, tag, lenOfLenOrVal=len(val))
self._encoding.extend(controlAndTag)
self._encoding.extend(val) | [
"def",
"putFloat",
"(",
"self",
",",
"tag",
",",
"val",
")",
":",
"val",
"=",
"struct",
".",
"pack",
"(",
"'d'",
",",
"val",
")",
"controlAndTag",
"=",
"self",
".",
"_encodeControlAndTag",
"(",
"TLVType_FloatingPointNumber",
",",
"tag",
",",
"lenOfLenOrVal",
"=",
"len",
"(",
"val",
")",
")",
"self",
".",
"_encoding",
".",
"extend",
"(",
"controlAndTag",
")",
"self",
".",
"_encoding",
".",
"extend",
"(",
"val",
")"
] | https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/tools/factory-prov-tool/WeaveTLV.py#L186-L191 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/text_format.py | python | _Tokenizer._ConsumeSingleByteString | (self) | return result | Consume one token of a string literal.
String literals (whether bytes or text) can come in multiple adjacent
tokens which are automatically concatenated, like in C or Python. This
method only consumes one token. | Consume one token of a string literal. | [
"Consume",
"one",
"token",
"of",
"a",
"string",
"literal",
"."
] | def _ConsumeSingleByteString(self):
"""Consume one token of a string literal.
String literals (whether bytes or text) can come in multiple adjacent
tokens which are automatically concatenated, like in C or Python. This
method only consumes one token.
"""
text = self.token
if len(text) < 1 or text[0] not in ('\'', '"'):
raise self._ParseError('Exptected string.')
if len(text) < 2 or text[-1] != text[0]:
raise self._ParseError('String missing ending quote.')
try:
result = _CUnescape(text[1:-1])
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result | [
"def",
"_ConsumeSingleByteString",
"(",
"self",
")",
":",
"text",
"=",
"self",
".",
"token",
"if",
"len",
"(",
"text",
")",
"<",
"1",
"or",
"text",
"[",
"0",
"]",
"not",
"in",
"(",
"'\\''",
",",
"'\"'",
")",
":",
"raise",
"self",
".",
"_ParseError",
"(",
"'Exptected string.'",
")",
"if",
"len",
"(",
"text",
")",
"<",
"2",
"or",
"text",
"[",
"-",
"1",
"]",
"!=",
"text",
"[",
"0",
"]",
":",
"raise",
"self",
".",
"_ParseError",
"(",
"'String missing ending quote.'",
")",
"try",
":",
"result",
"=",
"_CUnescape",
"(",
"text",
"[",
"1",
":",
"-",
"1",
"]",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"self",
".",
"_ParseError",
"(",
"str",
"(",
"e",
")",
")",
"self",
".",
"NextToken",
"(",
")",
"return",
"result"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/text_format.py#L560-L579 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py | python | HighPage.var_changed_custom_name | (self, *params) | Process new custom theme selection.
If a new custom theme is selected, add the name to the
changed_items and apply the theme to the sample. | Process new custom theme selection. | [
"Process",
"new",
"custom",
"theme",
"selection",
"."
] | def var_changed_custom_name(self, *params):
"""Process new custom theme selection.
If a new custom theme is selected, add the name to the
changed_items and apply the theme to the sample.
"""
value = self.custom_name.get()
if value != '- no custom themes -':
changes.add_option('main', 'Theme', 'name', value)
self.paint_theme_sample() | [
"def",
"var_changed_custom_name",
"(",
"self",
",",
"*",
"params",
")",
":",
"value",
"=",
"self",
".",
"custom_name",
".",
"get",
"(",
")",
"if",
"value",
"!=",
"'- no custom themes -'",
":",
"changes",
".",
"add_option",
"(",
"'main'",
",",
"'Theme'",
",",
"'name'",
",",
"value",
")",
"self",
".",
"paint_theme_sample",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/configdialog.py#L1020-L1029 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/idl_parser/idl_parser.py | python | IDLParser.p_StaticMemberRest | (self, p) | StaticMemberRest : ReadOnly AttributeRest
| ReturnType OperationRest | StaticMemberRest : ReadOnly AttributeRest
| ReturnType OperationRest | [
"StaticMemberRest",
":",
"ReadOnly",
"AttributeRest",
"|",
"ReturnType",
"OperationRest"
] | def p_StaticMemberRest(self, p):
"""StaticMemberRest : ReadOnly AttributeRest
| ReturnType OperationRest"""
if len(p) == 2:
p[0] = p[1]
else:
p[2].AddChildren(p[1])
p[0] = p[2] | [
"def",
"p_StaticMemberRest",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"2",
"]",
".",
"AddChildren",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"2",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_parser.py#L572-L579 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSNew.py | python | MSVSProject.__init__ | (self, path, name = None, dependencies = None, guid = None,
spec = None, build_file = None, config_platform_overrides = None,
fixpath_prefix = None) | Initializes the project.
Args:
path: Absolute path to the project file.
name: Name of project. If None, the name will be the same as the base
name of the project file.
dependencies: List of other Project objects this project is dependent
upon, if not None.
guid: GUID to use for project, if not None.
spec: Dictionary specifying how to build this project.
build_file: Filename of the .gyp file that the vcproj file comes from.
config_platform_overrides: optional dict of configuration platforms to
used in place of the default for this target.
fixpath_prefix: the path used to adjust the behavior of _fixpath | Initializes the project. | [
"Initializes",
"the",
"project",
"."
] | def __init__(self, path, name = None, dependencies = None, guid = None,
spec = None, build_file = None, config_platform_overrides = None,
fixpath_prefix = None):
"""Initializes the project.
Args:
path: Absolute path to the project file.
name: Name of project. If None, the name will be the same as the base
name of the project file.
dependencies: List of other Project objects this project is dependent
upon, if not None.
guid: GUID to use for project, if not None.
spec: Dictionary specifying how to build this project.
build_file: Filename of the .gyp file that the vcproj file comes from.
config_platform_overrides: optional dict of configuration platforms to
used in place of the default for this target.
fixpath_prefix: the path used to adjust the behavior of _fixpath
"""
self.path = path
self.guid = guid
self.spec = spec
self.build_file = build_file
# Use project filename if name not specified
self.name = name or os.path.splitext(os.path.basename(path))[0]
# Copy passed lists (or set to empty lists)
self.dependencies = list(dependencies or [])
self.entry_type_guid = ENTRY_TYPE_GUIDS['project']
if config_platform_overrides:
self.config_platform_overrides = config_platform_overrides
else:
self.config_platform_overrides = {}
self.fixpath_prefix = fixpath_prefix
self.msbuild_toolset = None | [
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"name",
"=",
"None",
",",
"dependencies",
"=",
"None",
",",
"guid",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"build_file",
"=",
"None",
",",
"config_platform_overrides",
"=",
"None",
",",
"fixpath_prefix",
"=",
"None",
")",
":",
"self",
".",
"path",
"=",
"path",
"self",
".",
"guid",
"=",
"guid",
"self",
".",
"spec",
"=",
"spec",
"self",
".",
"build_file",
"=",
"build_file",
"# Use project filename if name not specified",
"self",
".",
"name",
"=",
"name",
"or",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"0",
"]",
"# Copy passed lists (or set to empty lists)",
"self",
".",
"dependencies",
"=",
"list",
"(",
"dependencies",
"or",
"[",
"]",
")",
"self",
".",
"entry_type_guid",
"=",
"ENTRY_TYPE_GUIDS",
"[",
"'project'",
"]",
"if",
"config_platform_overrides",
":",
"self",
".",
"config_platform_overrides",
"=",
"config_platform_overrides",
"else",
":",
"self",
".",
"config_platform_overrides",
"=",
"{",
"}",
"self",
".",
"fixpath_prefix",
"=",
"fixpath_prefix",
"self",
".",
"msbuild_toolset",
"=",
"None"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/MSVSNew.py#L112-L147 | ||
isl-org/Open3D | 79aec3ddde6a571ce2f28e4096477e52ec465244 | python/open3d/visualization/tensorboard_plugin/util.py | python | Open3DPluginDataReader.read_geometry | (self, run, tag, step, batch_idx, step_to_idx) | return geometry, data_bbox_proto | Geometry reader from msgpack files. | Geometry reader from msgpack files. | [
"Geometry",
"reader",
"from",
"msgpack",
"files",
"."
] | def read_geometry(self, run, tag, step, batch_idx, step_to_idx):
"""Geometry reader from msgpack files."""
idx = step_to_idx[step]
metadata_proto = plugin_data_pb2.Open3DPluginData()
run_tensor_events = self.tensor_events(run)
metadata_proto.ParseFromString(
run_tensor_events[tag][idx].tensor_proto.string_val[0])
data_dir = PluginDirectory(os.path.join(self.logdir, run),
metadata.PLUGIN_NAME)
filename = os.path.join(data_dir, metadata_proto.batch_index.filename)
read_location = metadata_proto.batch_index.start_size[batch_idx].start
read_size = metadata_proto.batch_index.start_size[batch_idx].size
read_masked_crc32c = metadata_proto.batch_index.start_size[
batch_idx].masked_crc32c
cache_key = (filename, read_location, read_size, run, tag, step,
batch_idx)
geometry = self.geometry_cache.get(cache_key)
if geometry is None: # Read from storage
buf = self.read_from_file(filename, read_location, read_size,
read_masked_crc32c)
if buf is None:
raise IOError(f"Geometry {cache_key} reading failed! CRC "
"mismatch in msgpack data.")
msg_tag, msg_step, geometry = o3d.io.rpc.data_buffer_to_meta_geometry(
buf)
if geometry is None:
raise IOError(f"Geometry {cache_key} reading failed! Possible "
"msgpack or TensorFlow event file corruption.")
if tag != msg_tag or step != msg_step:
_log.warning(
f"Mismatch between TensorFlow event (tag={tag}, step={step})"
f" and msgpack (tag={msg_tag}, step={msg_step}) data. "
"Possible data corruption.")
_log.debug(f"Geometry {cache_key} reading successful!")
self.geometry_cache.put(cache_key, geometry)
# Fill in properties by reference
for prop_ref in metadata_proto.property_references:
prop = plugin_data_pb2.Open3DPluginData.GeometryProperty.Name(
prop_ref.geometry_property)
if prop_ref.step_ref >= step:
_log.warning(
f"Incorrect future step reference {prop_ref.step_ref} for"
f" property {prop} of geometry at step {step}. Ignoring.")
continue
geometry_ref = self.read_geometry(run, tag, prop_ref.step_ref,
batch_idx, step_to_idx)[0]
# "vertex_normals" -> ["vertex", "normals"]
prop_map, prop_attribute = prop.split("_")
if prop_map == "vertex" and not isinstance(
geometry, o3d.t.geometry.TriangleMesh):
prop_map = "point"
# geometry.vertex["normals"] = geometry_ref.vertex["normals"]
getattr(geometry, prop_map)[prop_attribute] = getattr(
geometry_ref, prop_map)[prop_attribute]
# Aux data (e.g. labels, confidences) -> not cached
aux_read_location = metadata_proto.batch_index.start_size[
batch_idx].aux_start
aux_read_size = metadata_proto.batch_index.start_size[
batch_idx].aux_size
aux_read_masked_crc32c = metadata_proto.batch_index.start_size[
batch_idx].aux_masked_crc32c
data_bbox_proto = plugin_data_pb2.InferenceData()
if aux_read_size > 0:
data_bbox_serial = self.read_from_file(filename, aux_read_location,
aux_read_size,
aux_read_masked_crc32c)
if data_bbox_serial is None:
raise IOError(f"Aux data for {cache_key} reading failed! CRC "
"mismatch in protobuf data.")
data_bbox_proto.ParseFromString(data_bbox_serial)
self.update_runtag_prop_shape(run, tag, geometry, data_bbox_proto)
return geometry, data_bbox_proto | [
"def",
"read_geometry",
"(",
"self",
",",
"run",
",",
"tag",
",",
"step",
",",
"batch_idx",
",",
"step_to_idx",
")",
":",
"idx",
"=",
"step_to_idx",
"[",
"step",
"]",
"metadata_proto",
"=",
"plugin_data_pb2",
".",
"Open3DPluginData",
"(",
")",
"run_tensor_events",
"=",
"self",
".",
"tensor_events",
"(",
"run",
")",
"metadata_proto",
".",
"ParseFromString",
"(",
"run_tensor_events",
"[",
"tag",
"]",
"[",
"idx",
"]",
".",
"tensor_proto",
".",
"string_val",
"[",
"0",
"]",
")",
"data_dir",
"=",
"PluginDirectory",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"logdir",
",",
"run",
")",
",",
"metadata",
".",
"PLUGIN_NAME",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"metadata_proto",
".",
"batch_index",
".",
"filename",
")",
"read_location",
"=",
"metadata_proto",
".",
"batch_index",
".",
"start_size",
"[",
"batch_idx",
"]",
".",
"start",
"read_size",
"=",
"metadata_proto",
".",
"batch_index",
".",
"start_size",
"[",
"batch_idx",
"]",
".",
"size",
"read_masked_crc32c",
"=",
"metadata_proto",
".",
"batch_index",
".",
"start_size",
"[",
"batch_idx",
"]",
".",
"masked_crc32c",
"cache_key",
"=",
"(",
"filename",
",",
"read_location",
",",
"read_size",
",",
"run",
",",
"tag",
",",
"step",
",",
"batch_idx",
")",
"geometry",
"=",
"self",
".",
"geometry_cache",
".",
"get",
"(",
"cache_key",
")",
"if",
"geometry",
"is",
"None",
":",
"# Read from storage",
"buf",
"=",
"self",
".",
"read_from_file",
"(",
"filename",
",",
"read_location",
",",
"read_size",
",",
"read_masked_crc32c",
")",
"if",
"buf",
"is",
"None",
":",
"raise",
"IOError",
"(",
"f\"Geometry {cache_key} reading failed! CRC \"",
"\"mismatch in msgpack data.\"",
")",
"msg_tag",
",",
"msg_step",
",",
"geometry",
"=",
"o3d",
".",
"io",
".",
"rpc",
".",
"data_buffer_to_meta_geometry",
"(",
"buf",
")",
"if",
"geometry",
"is",
"None",
":",
"raise",
"IOError",
"(",
"f\"Geometry {cache_key} reading failed! Possible \"",
"\"msgpack or TensorFlow event file corruption.\"",
")",
"if",
"tag",
"!=",
"msg_tag",
"or",
"step",
"!=",
"msg_step",
":",
"_log",
".",
"warning",
"(",
"f\"Mismatch between TensorFlow event (tag={tag}, step={step})\"",
"f\" and msgpack (tag={msg_tag}, step={msg_step}) data. \"",
"\"Possible data corruption.\"",
")",
"_log",
".",
"debug",
"(",
"f\"Geometry {cache_key} reading successful!\"",
")",
"self",
".",
"geometry_cache",
".",
"put",
"(",
"cache_key",
",",
"geometry",
")",
"# Fill in properties by reference",
"for",
"prop_ref",
"in",
"metadata_proto",
".",
"property_references",
":",
"prop",
"=",
"plugin_data_pb2",
".",
"Open3DPluginData",
".",
"GeometryProperty",
".",
"Name",
"(",
"prop_ref",
".",
"geometry_property",
")",
"if",
"prop_ref",
".",
"step_ref",
">=",
"step",
":",
"_log",
".",
"warning",
"(",
"f\"Incorrect future step reference {prop_ref.step_ref} for\"",
"f\" property {prop} of geometry at step {step}. Ignoring.\"",
")",
"continue",
"geometry_ref",
"=",
"self",
".",
"read_geometry",
"(",
"run",
",",
"tag",
",",
"prop_ref",
".",
"step_ref",
",",
"batch_idx",
",",
"step_to_idx",
")",
"[",
"0",
"]",
"# \"vertex_normals\" -> [\"vertex\", \"normals\"]",
"prop_map",
",",
"prop_attribute",
"=",
"prop",
".",
"split",
"(",
"\"_\"",
")",
"if",
"prop_map",
"==",
"\"vertex\"",
"and",
"not",
"isinstance",
"(",
"geometry",
",",
"o3d",
".",
"t",
".",
"geometry",
".",
"TriangleMesh",
")",
":",
"prop_map",
"=",
"\"point\"",
"# geometry.vertex[\"normals\"] = geometry_ref.vertex[\"normals\"]",
"getattr",
"(",
"geometry",
",",
"prop_map",
")",
"[",
"prop_attribute",
"]",
"=",
"getattr",
"(",
"geometry_ref",
",",
"prop_map",
")",
"[",
"prop_attribute",
"]",
"# Aux data (e.g. labels, confidences) -> not cached",
"aux_read_location",
"=",
"metadata_proto",
".",
"batch_index",
".",
"start_size",
"[",
"batch_idx",
"]",
".",
"aux_start",
"aux_read_size",
"=",
"metadata_proto",
".",
"batch_index",
".",
"start_size",
"[",
"batch_idx",
"]",
".",
"aux_size",
"aux_read_masked_crc32c",
"=",
"metadata_proto",
".",
"batch_index",
".",
"start_size",
"[",
"batch_idx",
"]",
".",
"aux_masked_crc32c",
"data_bbox_proto",
"=",
"plugin_data_pb2",
".",
"InferenceData",
"(",
")",
"if",
"aux_read_size",
">",
"0",
":",
"data_bbox_serial",
"=",
"self",
".",
"read_from_file",
"(",
"filename",
",",
"aux_read_location",
",",
"aux_read_size",
",",
"aux_read_masked_crc32c",
")",
"if",
"data_bbox_serial",
"is",
"None",
":",
"raise",
"IOError",
"(",
"f\"Aux data for {cache_key} reading failed! CRC \"",
"\"mismatch in protobuf data.\"",
")",
"data_bbox_proto",
".",
"ParseFromString",
"(",
"data_bbox_serial",
")",
"self",
".",
"update_runtag_prop_shape",
"(",
"run",
",",
"tag",
",",
"geometry",
",",
"data_bbox_proto",
")",
"return",
"geometry",
",",
"data_bbox_proto"
] | https://github.com/isl-org/Open3D/blob/79aec3ddde6a571ce2f28e4096477e52ec465244/python/open3d/visualization/tensorboard_plugin/util.py#L319-L393 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/tools/pretty_gyp.py | python | split_double_braces | (input) | return output | Masks out the quotes and comments, and then splits appropriate
lines (lines that matche the double_*_brace re's above) before
indenting them below.
These are used to split lines which have multiple braces on them, so
that the indentation looks prettier when all laid out (e.g. closing
braces make a nice diagonal line). | Masks out the quotes and comments, and then splits appropriate
lines (lines that matche the double_*_brace re's above) before
indenting them below. | [
"Masks",
"out",
"the",
"quotes",
"and",
"comments",
"and",
"then",
"splits",
"appropriate",
"lines",
"(",
"lines",
"that",
"matche",
"the",
"double_",
"*",
"_brace",
"re",
"s",
"above",
")",
"before",
"indenting",
"them",
"below",
"."
] | def split_double_braces(input):
"""Masks out the quotes and comments, and then splits appropriate
lines (lines that matche the double_*_brace re's above) before
indenting them below.
These are used to split lines which have multiple braces on them, so
that the indentation looks prettier when all laid out (e.g. closing
braces make a nice diagonal line).
"""
double_open_brace_re = re.compile(r'(.*?[\[\{\(,])(\s*)([\[\{\(])')
double_close_brace_re = re.compile(r'(.*?[\]\}\)],?)(\s*)([\]\}\)])')
masked_input = mask_quotes(input)
masked_input = mask_comments(masked_input)
(output, mask_output) = do_split(input, masked_input, double_open_brace_re)
(output, mask_output) = do_split(output, mask_output, double_close_brace_re)
return output | [
"def",
"split_double_braces",
"(",
"input",
")",
":",
"double_open_brace_re",
"=",
"re",
".",
"compile",
"(",
"r'(.*?[\\[\\{\\(,])(\\s*)([\\[\\{\\(])'",
")",
"double_close_brace_re",
"=",
"re",
".",
"compile",
"(",
"r'(.*?[\\]\\}\\)],?)(\\s*)([\\]\\}\\)])'",
")",
"masked_input",
"=",
"mask_quotes",
"(",
"input",
")",
"masked_input",
"=",
"mask_comments",
"(",
"masked_input",
")",
"(",
"output",
",",
"mask_output",
")",
"=",
"do_split",
"(",
"input",
",",
"masked_input",
",",
"double_open_brace_re",
")",
"(",
"output",
",",
"mask_output",
")",
"=",
"do_split",
"(",
"output",
",",
"mask_output",
",",
"double_close_brace_re",
")",
"return",
"output"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/tools/pretty_gyp.py#L64-L82 | |
OGRECave/ogre | d2cae7220c21e9cf6cc5a00b35c351c38914bcf0 | Tools/Wings3DExporter/mesh.py | python | Mesh.submeshize | (self) | create submeshes | create submeshes | [
"create",
"submeshes"
] | def submeshize(self):
"create submeshes"
print "creating submeshes..."
temp = {}
for t in self.tri_materials:
temp[t] = 1
trimats = temp.keys()
self.subs = []
for mat in trimats:
submesh = SubMesh()
submesh.material = mat
submesh.mat_data = self.materials[mat]
if self.shared_geometry:
# use shared geometry
for i in range(len(self.tri_materials)):
if self.tri_materials[i] == mat:
submesh.gltris.append(self.gltris[i])
else:
verts = {}
for i in range(len(self.tri_materials)):
if self.tri_materials[i] == mat:
for vert in self.gltris[i]:
verts[vert] = 1
verts = verts.keys()
verts.sort()
for i in verts:
submesh.glverts.append(self.glverts[i])
for i in range(len(self.tri_materials)):
if self.tri_materials[i] == mat:
tri = []
for vert in self.gltris[i]:
tri.append(verts.index(vert))
submesh.gltris.append(tri)
self.subs.append(submesh) | [
"def",
"submeshize",
"(",
"self",
")",
":",
"print",
"\"creating submeshes...\"",
"temp",
"=",
"{",
"}",
"for",
"t",
"in",
"self",
".",
"tri_materials",
":",
"temp",
"[",
"t",
"]",
"=",
"1",
"trimats",
"=",
"temp",
".",
"keys",
"(",
")",
"self",
".",
"subs",
"=",
"[",
"]",
"for",
"mat",
"in",
"trimats",
":",
"submesh",
"=",
"SubMesh",
"(",
")",
"submesh",
".",
"material",
"=",
"mat",
"submesh",
".",
"mat_data",
"=",
"self",
".",
"materials",
"[",
"mat",
"]",
"if",
"self",
".",
"shared_geometry",
":",
"# use shared geometry",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"tri_materials",
")",
")",
":",
"if",
"self",
".",
"tri_materials",
"[",
"i",
"]",
"==",
"mat",
":",
"submesh",
".",
"gltris",
".",
"append",
"(",
"self",
".",
"gltris",
"[",
"i",
"]",
")",
"else",
":",
"verts",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"tri_materials",
")",
")",
":",
"if",
"self",
".",
"tri_materials",
"[",
"i",
"]",
"==",
"mat",
":",
"for",
"vert",
"in",
"self",
".",
"gltris",
"[",
"i",
"]",
":",
"verts",
"[",
"vert",
"]",
"=",
"1",
"verts",
"=",
"verts",
".",
"keys",
"(",
")",
"verts",
".",
"sort",
"(",
")",
"for",
"i",
"in",
"verts",
":",
"submesh",
".",
"glverts",
".",
"append",
"(",
"self",
".",
"glverts",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"tri_materials",
")",
")",
":",
"if",
"self",
".",
"tri_materials",
"[",
"i",
"]",
"==",
"mat",
":",
"tri",
"=",
"[",
"]",
"for",
"vert",
"in",
"self",
".",
"gltris",
"[",
"i",
"]",
":",
"tri",
".",
"append",
"(",
"verts",
".",
"index",
"(",
"vert",
")",
")",
"submesh",
".",
"gltris",
".",
"append",
"(",
"tri",
")",
"self",
".",
"subs",
".",
"append",
"(",
"submesh",
")"
] | https://github.com/OGRECave/ogre/blob/d2cae7220c21e9cf6cc5a00b35c351c38914bcf0/Tools/Wings3DExporter/mesh.py#L356-L392 | ||
sonyxperiadev/WebGL | 0299b38196f78c6d5f74bcf6fa312a3daee6de60 | Tools/Scripts/webkitpy/style/checker.py | python | CheckerDispatcher._file_extension | (self, file_path) | return os.path.splitext(file_path)[1].lstrip(".") | Return the file extension without the leading dot. | Return the file extension without the leading dot. | [
"Return",
"the",
"file",
"extension",
"without",
"the",
"leading",
"dot",
"."
] | def _file_extension(self, file_path):
"""Return the file extension without the leading dot."""
return os.path.splitext(file_path)[1].lstrip(".") | [
"def",
"_file_extension",
"(",
"self",
",",
"file_path",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"file_path",
")",
"[",
"1",
"]",
".",
"lstrip",
"(",
"\".\"",
")"
] | https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/style/checker.py#L435-L437 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/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/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pipes.py#L96-L102 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozbuild/frontend/reader.py | python | MozbuildSandbox.add_android_eclipse_project_helper | (self, name) | return data | Add an Android Eclipse project target. | Add an Android Eclipse project target. | [
"Add",
"an",
"Android",
"Eclipse",
"project",
"target",
"."
] | def add_android_eclipse_project_helper(self, name):
"""Add an Android Eclipse project target."""
if not name:
raise Exception('Android Eclipse project cannot be registered without a name')
if name in self['ANDROID_ECLIPSE_PROJECT_TARGETS']:
raise Exception('Android Eclipse project has already been registered: %s' % name)
data = AndroidEclipseProjectData(name)
self['ANDROID_ECLIPSE_PROJECT_TARGETS'][name] = data
return data | [
"def",
"add_android_eclipse_project_helper",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"raise",
"Exception",
"(",
"'Android Eclipse project cannot be registered without a name'",
")",
"if",
"name",
"in",
"self",
"[",
"'ANDROID_ECLIPSE_PROJECT_TARGETS'",
"]",
":",
"raise",
"Exception",
"(",
"'Android Eclipse project has already been registered: %s'",
"%",
"name",
")",
"data",
"=",
"AndroidEclipseProjectData",
"(",
"name",
")",
"self",
"[",
"'ANDROID_ECLIPSE_PROJECT_TARGETS'",
"]",
"[",
"name",
"]",
"=",
"data",
"return",
"data"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/frontend/reader.py#L224-L234 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/packaging/utils.py | python | canonicalize_version | (version) | return "".join(parts) | This is very similar to Version.__str__, but has one subtle differences
with the way it handles the release segment. | This is very similar to Version.__str__, but has one subtle differences
with the way it handles the release segment. | [
"This",
"is",
"very",
"similar",
"to",
"Version",
".",
"__str__",
"but",
"has",
"one",
"subtle",
"differences",
"with",
"the",
"way",
"it",
"handles",
"the",
"release",
"segment",
"."
] | def canonicalize_version(version):
"""
This is very similar to Version.__str__, but has one subtle differences
with the way it handles the release segment.
"""
try:
version = Version(version)
except InvalidVersion:
# Legacy versions cannot be normalized
return version
parts = []
# Epoch
if version.epoch != 0:
parts.append("{0}!".format(version.epoch))
# Release segment
# NB: This strips trailing '.0's to normalize
parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in version.release)))
# Pre-release
if version.pre is not None:
parts.append("".join(str(x) for x in version.pre))
# Post-release
if version.post is not None:
parts.append(".post{0}".format(version.post))
# Development release
if version.dev is not None:
parts.append(".dev{0}".format(version.dev))
# Local version segment
if version.local is not None:
parts.append("+{0}".format(version.local))
return "".join(parts) | [
"def",
"canonicalize_version",
"(",
"version",
")",
":",
"try",
":",
"version",
"=",
"Version",
"(",
"version",
")",
"except",
"InvalidVersion",
":",
"# Legacy versions cannot be normalized",
"return",
"version",
"parts",
"=",
"[",
"]",
"# Epoch",
"if",
"version",
".",
"epoch",
"!=",
"0",
":",
"parts",
".",
"append",
"(",
"\"{0}!\"",
".",
"format",
"(",
"version",
".",
"epoch",
")",
")",
"# Release segment",
"# NB: This strips trailing '.0's to normalize",
"parts",
".",
"append",
"(",
"re",
".",
"sub",
"(",
"r\"(\\.0)+$\"",
",",
"\"\"",
",",
"\".\"",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"version",
".",
"release",
")",
")",
")",
"# Pre-release",
"if",
"version",
".",
"pre",
"is",
"not",
"None",
":",
"parts",
".",
"append",
"(",
"\"\"",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"version",
".",
"pre",
")",
")",
"# Post-release",
"if",
"version",
".",
"post",
"is",
"not",
"None",
":",
"parts",
".",
"append",
"(",
"\".post{0}\"",
".",
"format",
"(",
"version",
".",
"post",
")",
")",
"# Development release",
"if",
"version",
".",
"dev",
"is",
"not",
"None",
":",
"parts",
".",
"append",
"(",
"\".dev{0}\"",
".",
"format",
"(",
"version",
".",
"dev",
")",
")",
"# Local version segment",
"if",
"version",
".",
"local",
"is",
"not",
"None",
":",
"parts",
".",
"append",
"(",
"\"+{0}\"",
".",
"format",
"(",
"version",
".",
"local",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"parts",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/packaging/utils.py#L19-L57 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/recordio.py | python | MXRecordIO._check_pid | (self, allow_reset=False) | Check process id to ensure integrity, reset if in new process. | Check process id to ensure integrity, reset if in new process. | [
"Check",
"process",
"id",
"to",
"ensure",
"integrity",
"reset",
"if",
"in",
"new",
"process",
"."
] | def _check_pid(self, allow_reset=False):
"""Check process id to ensure integrity, reset if in new process."""
# pylint: disable=not-callable
# It's bug from pylint(astroid). See https://github.com/PyCQA/pylint/issues/1699
if not self.pid == current_process().pid:
if allow_reset:
self.reset()
else:
raise RuntimeError("Forbidden operation in multiple processes") | [
"def",
"_check_pid",
"(",
"self",
",",
"allow_reset",
"=",
"False",
")",
":",
"# pylint: disable=not-callable",
"# It's bug from pylint(astroid). See https://github.com/PyCQA/pylint/issues/1699",
"if",
"not",
"self",
".",
"pid",
"==",
"current_process",
"(",
")",
".",
"pid",
":",
"if",
"allow_reset",
":",
"self",
".",
"reset",
"(",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Forbidden operation in multiple processes\"",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/recordio.py#L117-L125 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/setup_multiversion/setup_multiversion.py | python | SetupMultiversion.download_and_extract_from_urls | (self, urls, bin_suffix, install_dir) | Download and extract values indicated in `urls`. | Download and extract values indicated in `urls`. | [
"Download",
"and",
"extract",
"values",
"indicated",
"in",
"urls",
"."
] | def download_and_extract_from_urls(self, urls, bin_suffix, install_dir):
"""Download and extract values indicated in `urls`."""
artifacts_url = urls.get("Artifacts", "") if self.download_artifacts else None
binaries_url = urls.get("Binaries", "") if self.download_binaries else None
python_venv_url = urls.get("Python venv (see included README.txt)", "") or urls.get(
"Python venv (see included venv_readme.txt)", "") if self.download_python_venv else None
download_symbols_url = None
if self.download_symbols:
for name in [
" mongo-debugsymbols.tgz", " mongo-debugsymbols.zip", "mongo-debugsymbols.tgz",
"mongo-debugsymbols.zip"
]:
download_symbols_url = urls.get(name, None)
if download_symbols_url:
break
if self.download_symbols and not download_symbols_url:
raise download.DownloadError("Symbols download requested but not URL available")
if self.download_artifacts and not artifacts_url:
raise download.DownloadError(
"Evergreen artifacts download requested but not URL available")
if self.download_binaries and not binaries_url:
raise download.DownloadError("Binaries download requested but not URL available")
if self.download_python_venv and not python_venv_url:
raise download.DownloadError("Python venv download requested but not URL available")
self.setup_mongodb(artifacts_url, binaries_url, download_symbols_url, python_venv_url,
install_dir, bin_suffix, link_dir=self.link_dir,
install_dir_list=self._windows_bin_install_dirs) | [
"def",
"download_and_extract_from_urls",
"(",
"self",
",",
"urls",
",",
"bin_suffix",
",",
"install_dir",
")",
":",
"artifacts_url",
"=",
"urls",
".",
"get",
"(",
"\"Artifacts\"",
",",
"\"\"",
")",
"if",
"self",
".",
"download_artifacts",
"else",
"None",
"binaries_url",
"=",
"urls",
".",
"get",
"(",
"\"Binaries\"",
",",
"\"\"",
")",
"if",
"self",
".",
"download_binaries",
"else",
"None",
"python_venv_url",
"=",
"urls",
".",
"get",
"(",
"\"Python venv (see included README.txt)\"",
",",
"\"\"",
")",
"or",
"urls",
".",
"get",
"(",
"\"Python venv (see included venv_readme.txt)\"",
",",
"\"\"",
")",
"if",
"self",
".",
"download_python_venv",
"else",
"None",
"download_symbols_url",
"=",
"None",
"if",
"self",
".",
"download_symbols",
":",
"for",
"name",
"in",
"[",
"\" mongo-debugsymbols.tgz\"",
",",
"\" mongo-debugsymbols.zip\"",
",",
"\"mongo-debugsymbols.tgz\"",
",",
"\"mongo-debugsymbols.zip\"",
"]",
":",
"download_symbols_url",
"=",
"urls",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"download_symbols_url",
":",
"break",
"if",
"self",
".",
"download_symbols",
"and",
"not",
"download_symbols_url",
":",
"raise",
"download",
".",
"DownloadError",
"(",
"\"Symbols download requested but not URL available\"",
")",
"if",
"self",
".",
"download_artifacts",
"and",
"not",
"artifacts_url",
":",
"raise",
"download",
".",
"DownloadError",
"(",
"\"Evergreen artifacts download requested but not URL available\"",
")",
"if",
"self",
".",
"download_binaries",
"and",
"not",
"binaries_url",
":",
"raise",
"download",
".",
"DownloadError",
"(",
"\"Binaries download requested but not URL available\"",
")",
"if",
"self",
".",
"download_python_venv",
"and",
"not",
"python_venv_url",
":",
"raise",
"download",
".",
"DownloadError",
"(",
"\"Python venv download requested but not URL available\"",
")",
"self",
".",
"setup_mongodb",
"(",
"artifacts_url",
",",
"binaries_url",
",",
"download_symbols_url",
",",
"python_venv_url",
",",
"install_dir",
",",
"bin_suffix",
",",
"link_dir",
"=",
"self",
".",
"link_dir",
",",
"install_dir_list",
"=",
"self",
".",
"_windows_bin_install_dirs",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/setup_multiversion/setup_multiversion.py#L239-L271 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | Indigo.loadReaction | (self, string) | return self.IndigoObject(
self,
self._checkResult(
Indigo._lib.indigoLoadReactionFromString(
string.encode(ENCODE_ENCODING)
)
),
) | Loads reaction from string. Format will be automatically recognized.
Args:
string (str): reaction format
Returns:
IndigoObject: reaction object
Raises:
IndigoException: Exception if structure format is incorrect | Loads reaction from string. Format will be automatically recognized. | [
"Loads",
"reaction",
"from",
"string",
".",
"Format",
"will",
"be",
"automatically",
"recognized",
"."
] | def loadReaction(self, string):
"""Loads reaction from string. Format will be automatically recognized.
Args:
string (str): reaction format
Returns:
IndigoObject: reaction object
Raises:
IndigoException: Exception if structure format is incorrect
"""
self._setSessionId()
return self.IndigoObject(
self,
self._checkResult(
Indigo._lib.indigoLoadReactionFromString(
string.encode(ENCODE_ENCODING)
)
),
) | [
"def",
"loadReaction",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"IndigoObject",
"(",
"self",
",",
"self",
".",
"_checkResult",
"(",
"Indigo",
".",
"_lib",
".",
"indigoLoadReactionFromString",
"(",
"string",
".",
"encode",
"(",
"ENCODE_ENCODING",
")",
")",
")",
",",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L5656-L5676 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | dom/bindings/mozwebidlcodegen/__init__.py | python | WebIDLCodegenManager.generate_build_files | (self) | return result | Generate files required for the build.
This function is in charge of generating all the .h/.cpp files derived
from input .webidl files. Please note that there are build actions
required to produce .webidl files and these build actions are
explicitly not captured here: this function assumes all .webidl files
are present and up to date.
This routine is called as part of the build to ensure files that need
to exist are present and up to date. This routine may not be called if
the build dependencies (generated as a result of calling this the first
time) say everything is up to date.
Because reprocessing outputs for every .webidl on every invocation
is expensive, we only regenerate the minimal set of files on every
invocation. The rules for deciding what needs done are roughly as
follows:
1. If any .webidl changes, reparse all .webidl files and regenerate
the global derived files. Only regenerate output files (.h/.cpp)
impacted by the modified .webidl files.
2. If an non-.webidl dependency (Python files, config file) changes,
assume everything is out of date and regenerate the world. This
is because changes in those could globally impact every output
file.
3. If an output file is missing, ensure it is present by performing
necessary regeneration. | Generate files required for the build. | [
"Generate",
"files",
"required",
"for",
"the",
"build",
"."
] | def generate_build_files(self):
"""Generate files required for the build.
This function is in charge of generating all the .h/.cpp files derived
from input .webidl files. Please note that there are build actions
required to produce .webidl files and these build actions are
explicitly not captured here: this function assumes all .webidl files
are present and up to date.
This routine is called as part of the build to ensure files that need
to exist are present and up to date. This routine may not be called if
the build dependencies (generated as a result of calling this the first
time) say everything is up to date.
Because reprocessing outputs for every .webidl on every invocation
is expensive, we only regenerate the minimal set of files on every
invocation. The rules for deciding what needs done are roughly as
follows:
1. If any .webidl changes, reparse all .webidl files and regenerate
the global derived files. Only regenerate output files (.h/.cpp)
impacted by the modified .webidl files.
2. If an non-.webidl dependency (Python files, config file) changes,
assume everything is out of date and regenerate the world. This
is because changes in those could globally impact every output
file.
3. If an output file is missing, ensure it is present by performing
necessary regeneration.
"""
# Despite #1 above, we assume the build system is smart enough to not
# invoke us if nothing has changed. Therefore, any invocation means
# something has changed. And, if anything has changed, we need to
# parse the WebIDL.
self._parse_webidl()
result = BuildResult()
# If we parse, we always update globals - they are cheap and it is
# easier that way.
created, updated, unchanged = self._write_global_derived()
result.created |= created
result.updated |= updated
result.unchanged |= unchanged
# If any of the extra dependencies changed, regenerate the world.
global_changed, global_hashes = self._global_dependencies_changed()
if global_changed:
# Make a copy because we may modify.
changed_inputs = set(self._input_paths)
else:
changed_inputs = self._compute_changed_inputs()
self._state['global_depends'] = global_hashes
# Generate bindings from .webidl files.
for filename in sorted(changed_inputs):
basename = mozpath.basename(filename)
result.inputs.add(filename)
written, deps = self._generate_build_files_for_webidl(filename)
result.created |= written[0]
result.updated |= written[1]
result.unchanged |= written[2]
self._state['webidls'][basename] = dict(
filename=filename,
outputs=written[0] | written[1] | written[2],
inputs=set(deps),
sha1=self._input_hashes[filename],
)
# Process some special interfaces required for testing.
for interface in self._example_interfaces:
written = self.generate_example_files(interface)
result.created |= written[0]
result.updated |= written[1]
result.unchanged |= written[2]
# Generate a make dependency file.
if self._make_deps_path:
mk = Makefile()
codegen_rule = mk.create_rule([self._make_deps_target])
codegen_rule.add_dependencies(global_hashes.keys())
codegen_rule.add_dependencies(self._input_paths)
with FileAvoidWrite(self._make_deps_path) as fh:
mk.dump(fh)
self._save_state()
return result | [
"def",
"generate_build_files",
"(",
"self",
")",
":",
"# Despite #1 above, we assume the build system is smart enough to not",
"# invoke us if nothing has changed. Therefore, any invocation means",
"# something has changed. And, if anything has changed, we need to",
"# parse the WebIDL.",
"self",
".",
"_parse_webidl",
"(",
")",
"result",
"=",
"BuildResult",
"(",
")",
"# If we parse, we always update globals - they are cheap and it is",
"# easier that way.",
"created",
",",
"updated",
",",
"unchanged",
"=",
"self",
".",
"_write_global_derived",
"(",
")",
"result",
".",
"created",
"|=",
"created",
"result",
".",
"updated",
"|=",
"updated",
"result",
".",
"unchanged",
"|=",
"unchanged",
"# If any of the extra dependencies changed, regenerate the world.",
"global_changed",
",",
"global_hashes",
"=",
"self",
".",
"_global_dependencies_changed",
"(",
")",
"if",
"global_changed",
":",
"# Make a copy because we may modify.",
"changed_inputs",
"=",
"set",
"(",
"self",
".",
"_input_paths",
")",
"else",
":",
"changed_inputs",
"=",
"self",
".",
"_compute_changed_inputs",
"(",
")",
"self",
".",
"_state",
"[",
"'global_depends'",
"]",
"=",
"global_hashes",
"# Generate bindings from .webidl files.",
"for",
"filename",
"in",
"sorted",
"(",
"changed_inputs",
")",
":",
"basename",
"=",
"mozpath",
".",
"basename",
"(",
"filename",
")",
"result",
".",
"inputs",
".",
"add",
"(",
"filename",
")",
"written",
",",
"deps",
"=",
"self",
".",
"_generate_build_files_for_webidl",
"(",
"filename",
")",
"result",
".",
"created",
"|=",
"written",
"[",
"0",
"]",
"result",
".",
"updated",
"|=",
"written",
"[",
"1",
"]",
"result",
".",
"unchanged",
"|=",
"written",
"[",
"2",
"]",
"self",
".",
"_state",
"[",
"'webidls'",
"]",
"[",
"basename",
"]",
"=",
"dict",
"(",
"filename",
"=",
"filename",
",",
"outputs",
"=",
"written",
"[",
"0",
"]",
"|",
"written",
"[",
"1",
"]",
"|",
"written",
"[",
"2",
"]",
",",
"inputs",
"=",
"set",
"(",
"deps",
")",
",",
"sha1",
"=",
"self",
".",
"_input_hashes",
"[",
"filename",
"]",
",",
")",
"# Process some special interfaces required for testing.",
"for",
"interface",
"in",
"self",
".",
"_example_interfaces",
":",
"written",
"=",
"self",
".",
"generate_example_files",
"(",
"interface",
")",
"result",
".",
"created",
"|=",
"written",
"[",
"0",
"]",
"result",
".",
"updated",
"|=",
"written",
"[",
"1",
"]",
"result",
".",
"unchanged",
"|=",
"written",
"[",
"2",
"]",
"# Generate a make dependency file.",
"if",
"self",
".",
"_make_deps_path",
":",
"mk",
"=",
"Makefile",
"(",
")",
"codegen_rule",
"=",
"mk",
".",
"create_rule",
"(",
"[",
"self",
".",
"_make_deps_target",
"]",
")",
"codegen_rule",
".",
"add_dependencies",
"(",
"global_hashes",
".",
"keys",
"(",
")",
")",
"codegen_rule",
".",
"add_dependencies",
"(",
"self",
".",
"_input_paths",
")",
"with",
"FileAvoidWrite",
"(",
"self",
".",
"_make_deps_path",
")",
"as",
"fh",
":",
"mk",
".",
"dump",
"(",
"fh",
")",
"self",
".",
"_save_state",
"(",
")",
"return",
"result"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/mozwebidlcodegen/__init__.py#L208-L297 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/pydoc.py | python | importfile | (path) | return module | Import a Python source file or compiled file given its path. | Import a Python source file or compiled file given its path. | [
"Import",
"a",
"Python",
"source",
"file",
"or",
"compiled",
"file",
"given",
"its",
"path",
"."
] | def importfile(path):
"""Import a Python source file or compiled file given its path."""
magic = imp.get_magic()
file = open(path, 'r')
if file.read(len(magic)) == magic:
kind = imp.PY_COMPILED
else:
kind = imp.PY_SOURCE
file.close()
filename = os.path.basename(path)
name, ext = os.path.splitext(filename)
file = open(path, 'r')
try:
module = imp.load_module(name, file, path, (ext, 'r', kind))
except:
raise ErrorDuringImport(path, sys.exc_info())
file.close()
return module | [
"def",
"importfile",
"(",
"path",
")",
":",
"magic",
"=",
"imp",
".",
"get_magic",
"(",
")",
"file",
"=",
"open",
"(",
"path",
",",
"'r'",
")",
"if",
"file",
".",
"read",
"(",
"len",
"(",
"magic",
")",
")",
"==",
"magic",
":",
"kind",
"=",
"imp",
".",
"PY_COMPILED",
"else",
":",
"kind",
"=",
"imp",
".",
"PY_SOURCE",
"file",
".",
"close",
"(",
")",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"file",
"=",
"open",
"(",
"path",
",",
"'r'",
")",
"try",
":",
"module",
"=",
"imp",
".",
"load_module",
"(",
"name",
",",
"file",
",",
"path",
",",
"(",
"ext",
",",
"'r'",
",",
"kind",
")",
")",
"except",
":",
"raise",
"ErrorDuringImport",
"(",
"path",
",",
"sys",
".",
"exc_info",
"(",
")",
")",
"file",
".",
"close",
"(",
")",
"return",
"module"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pydoc.py#L281-L298 | |
InteractiveComputerGraphics/PositionBasedDynamics | 136469f03f7869666d907ea8d27872b098715f4a | extern/pybind/pybind11/setup_helpers.py | python | ParallelCompile.function | (self) | return compile_function | Builds a function object usable as distutils.ccompiler.CCompiler.compile. | Builds a function object usable as distutils.ccompiler.CCompiler.compile. | [
"Builds",
"a",
"function",
"object",
"usable",
"as",
"distutils",
".",
"ccompiler",
".",
"CCompiler",
".",
"compile",
"."
] | def function(self):
"""
Builds a function object usable as distutils.ccompiler.CCompiler.compile.
"""
def compile_function(
compiler,
sources,
output_dir=None,
macros=None,
include_dirs=None,
debug=0,
extra_preargs=None,
extra_postargs=None,
depends=None,
):
# These lines are directly from distutils.ccompiler.CCompiler
macros, objects, extra_postargs, pp_opts, build = compiler._setup_compile(
output_dir, macros, include_dirs, sources, depends, extra_postargs
)
cc_args = compiler._get_cc_args(pp_opts, debug, extra_preargs)
# The number of threads; start with default.
threads = self.default
# Determine the number of compilation threads, unless set by an environment variable.
if self.envvar is not None:
threads = int(os.environ.get(self.envvar, self.default))
def _single_compile(obj):
try:
src, ext = build[obj]
except KeyError:
return
compiler._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
try:
import multiprocessing
from multiprocessing.pool import ThreadPool
except ImportError:
threads = 1
if threads == 0:
try:
threads = multiprocessing.cpu_count()
threads = self.max if self.max and self.max < threads else threads
except NotImplementedError:
threads = 1
if threads > 1:
for _ in ThreadPool(threads).imap_unordered(_single_compile, objects):
pass
else:
for ob in objects:
_single_compile(ob)
return objects
return compile_function | [
"def",
"function",
"(",
"self",
")",
":",
"def",
"compile_function",
"(",
"compiler",
",",
"sources",
",",
"output_dir",
"=",
"None",
",",
"macros",
"=",
"None",
",",
"include_dirs",
"=",
"None",
",",
"debug",
"=",
"0",
",",
"extra_preargs",
"=",
"None",
",",
"extra_postargs",
"=",
"None",
",",
"depends",
"=",
"None",
",",
")",
":",
"# These lines are directly from distutils.ccompiler.CCompiler",
"macros",
",",
"objects",
",",
"extra_postargs",
",",
"pp_opts",
",",
"build",
"=",
"compiler",
".",
"_setup_compile",
"(",
"output_dir",
",",
"macros",
",",
"include_dirs",
",",
"sources",
",",
"depends",
",",
"extra_postargs",
")",
"cc_args",
"=",
"compiler",
".",
"_get_cc_args",
"(",
"pp_opts",
",",
"debug",
",",
"extra_preargs",
")",
"# The number of threads; start with default.",
"threads",
"=",
"self",
".",
"default",
"# Determine the number of compilation threads, unless set by an environment variable.",
"if",
"self",
".",
"envvar",
"is",
"not",
"None",
":",
"threads",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"self",
".",
"envvar",
",",
"self",
".",
"default",
")",
")",
"def",
"_single_compile",
"(",
"obj",
")",
":",
"try",
":",
"src",
",",
"ext",
"=",
"build",
"[",
"obj",
"]",
"except",
"KeyError",
":",
"return",
"compiler",
".",
"_compile",
"(",
"obj",
",",
"src",
",",
"ext",
",",
"cc_args",
",",
"extra_postargs",
",",
"pp_opts",
")",
"try",
":",
"import",
"multiprocessing",
"from",
"multiprocessing",
".",
"pool",
"import",
"ThreadPool",
"except",
"ImportError",
":",
"threads",
"=",
"1",
"if",
"threads",
"==",
"0",
":",
"try",
":",
"threads",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"threads",
"=",
"self",
".",
"max",
"if",
"self",
".",
"max",
"and",
"self",
".",
"max",
"<",
"threads",
"else",
"threads",
"except",
"NotImplementedError",
":",
"threads",
"=",
"1",
"if",
"threads",
">",
"1",
":",
"for",
"_",
"in",
"ThreadPool",
"(",
"threads",
")",
".",
"imap_unordered",
"(",
"_single_compile",
",",
"objects",
")",
":",
"pass",
"else",
":",
"for",
"ob",
"in",
"objects",
":",
"_single_compile",
"(",
"ob",
")",
"return",
"objects",
"return",
"compile_function"
] | https://github.com/InteractiveComputerGraphics/PositionBasedDynamics/blob/136469f03f7869666d907ea8d27872b098715f4a/extern/pybind/pybind11/setup_helpers.py#L328-L387 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | TopLevelWindow.SetIcons | (*args, **kwargs) | return _windows_.TopLevelWindow_SetIcons(*args, **kwargs) | SetIcons(self, wxIconBundle icons) | SetIcons(self, wxIconBundle icons) | [
"SetIcons",
"(",
"self",
"wxIconBundle",
"icons",
")"
] | def SetIcons(*args, **kwargs):
"""SetIcons(self, wxIconBundle icons)"""
return _windows_.TopLevelWindow_SetIcons(*args, **kwargs) | [
"def",
"SetIcons",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"TopLevelWindow_SetIcons",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L437-L439 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/expressions/expression.py | python | Expression.sign | (self) | return sign_str | str: The sign of the expression. | str: The sign of the expression. | [
"str",
":",
"The",
"sign",
"of",
"the",
"expression",
"."
] | def sign(self) -> str:
"""str: The sign of the expression.
"""
if self.is_zero():
sign_str = s.ZERO
elif self.is_nonneg():
sign_str = s.NONNEG
elif self.is_nonpos():
sign_str = s.NONPOS
else:
sign_str = s.UNKNOWN
return sign_str | [
"def",
"sign",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"is_zero",
"(",
")",
":",
"sign_str",
"=",
"s",
".",
"ZERO",
"elif",
"self",
".",
"is_nonneg",
"(",
")",
":",
"sign_str",
"=",
"s",
".",
"NONNEG",
"elif",
"self",
".",
"is_nonpos",
"(",
")",
":",
"sign_str",
"=",
"s",
".",
"NONPOS",
"else",
":",
"sign_str",
"=",
"s",
".",
"UNKNOWN",
"return",
"sign_str"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/expressions/expression.py#L334-L345 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/tools/run_perf.py | python | RunnableConfig.ProcessOutput | (self, output, result_tracker, count) | Processes test run output and updates result tracker.
Args:
output: Output object from the test run.
result_tracker: ResultTracker object to be updated.
count: Index of the test run (used for better logging). | Processes test run output and updates result tracker. | [
"Processes",
"test",
"run",
"output",
"and",
"updates",
"result",
"tracker",
"."
] | def ProcessOutput(self, output, result_tracker, count):
"""Processes test run output and updates result tracker.
Args:
output: Output object from the test run.
result_tracker: ResultTracker object to be updated.
count: Index of the test run (used for better logging).
"""
if self.results_processor:
output = RunResultsProcessor(self.results_processor, output, count)
results_for_total = []
for trace in self.children:
result = trace.ConsumeOutput(output, result_tracker)
if result:
results_for_total.append(result)
if self.total:
# Produce total metric only when all traces have produced results.
if len(self.children) != len(results_for_total):
result_tracker.AddError(
'Not all traces have produced results. Can not compute total for '
'%s.' % self.name)
return
# Calculate total as a the geometric mean for results from all traces.
total_trace = TraceConfig(
{'name': 'Total', 'units': self.children[0].units}, self, self.arch)
result_tracker.AddTraceResult(
total_trace, GeometricMean(results_for_total), '') | [
"def",
"ProcessOutput",
"(",
"self",
",",
"output",
",",
"result_tracker",
",",
"count",
")",
":",
"if",
"self",
".",
"results_processor",
":",
"output",
"=",
"RunResultsProcessor",
"(",
"self",
".",
"results_processor",
",",
"output",
",",
"count",
")",
"results_for_total",
"=",
"[",
"]",
"for",
"trace",
"in",
"self",
".",
"children",
":",
"result",
"=",
"trace",
".",
"ConsumeOutput",
"(",
"output",
",",
"result_tracker",
")",
"if",
"result",
":",
"results_for_total",
".",
"append",
"(",
"result",
")",
"if",
"self",
".",
"total",
":",
"# Produce total metric only when all traces have produced results.",
"if",
"len",
"(",
"self",
".",
"children",
")",
"!=",
"len",
"(",
"results_for_total",
")",
":",
"result_tracker",
".",
"AddError",
"(",
"'Not all traces have produced results. Can not compute total for '",
"'%s.'",
"%",
"self",
".",
"name",
")",
"return",
"# Calculate total as a the geometric mean for results from all traces.",
"total_trace",
"=",
"TraceConfig",
"(",
"{",
"'name'",
":",
"'Total'",
",",
"'units'",
":",
"self",
".",
"children",
"[",
"0",
"]",
".",
"units",
"}",
",",
"self",
",",
"self",
".",
"arch",
")",
"result_tracker",
".",
"AddTraceResult",
"(",
"total_trace",
",",
"GeometricMean",
"(",
"results_for_total",
")",
",",
"''",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/run_perf.py#L485-L514 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/__init__.py | python | Environment.best_match | (
self, req, working_set, installer=None, replace_conflicting=False) | return self.obtain(req, installer) | Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned. | Find distribution best matching `req` and usable on `working_set` | [
"Find",
"distribution",
"best",
"matching",
"req",
"and",
"usable",
"on",
"working_set"
] | def best_match(
self, req, working_set, installer=None, replace_conflicting=False):
"""Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned.
"""
try:
dist = working_set.find(req)
except VersionConflict:
if not replace_conflicting:
raise
dist = None
if dist is not None:
return dist
for dist in self[req.key]:
if dist in req:
return dist
# try to download/install
return self.obtain(req, installer) | [
"def",
"best_match",
"(",
"self",
",",
"req",
",",
"working_set",
",",
"installer",
"=",
"None",
",",
"replace_conflicting",
"=",
"False",
")",
":",
"try",
":",
"dist",
"=",
"working_set",
".",
"find",
"(",
"req",
")",
"except",
"VersionConflict",
":",
"if",
"not",
"replace_conflicting",
":",
"raise",
"dist",
"=",
"None",
"if",
"dist",
"is",
"not",
"None",
":",
"return",
"dist",
"for",
"dist",
"in",
"self",
"[",
"req",
".",
"key",
"]",
":",
"if",
"dist",
"in",
"req",
":",
"return",
"dist",
"# try to download/install",
"return",
"self",
".",
"obtain",
"(",
"req",
",",
"installer",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/__init__.py#L1040-L1066 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/os.py | python | removedirs | (name) | removedirs(name)
Super-rmdir; remove a leaf directory and all empty intermediate
ones. Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole path is
consumed or an error occurs. Errors during this latter phase are
ignored -- they generally mean that a directory was not empty. | removedirs(name) | [
"removedirs",
"(",
"name",
")"
] | def removedirs(name):
"""removedirs(name)
Super-rmdir; remove a leaf directory and all empty intermediate
ones. Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole path is
consumed or an error occurs. Errors during this latter phase are
ignored -- they generally mean that a directory was not empty.
"""
rmdir(name)
head, tail = path.split(name)
if not tail:
head, tail = path.split(head)
while head and tail:
try:
rmdir(head)
except OSError:
break
head, tail = path.split(head) | [
"def",
"removedirs",
"(",
"name",
")",
":",
"rmdir",
"(",
"name",
")",
"head",
",",
"tail",
"=",
"path",
".",
"split",
"(",
"name",
")",
"if",
"not",
"tail",
":",
"head",
",",
"tail",
"=",
"path",
".",
"split",
"(",
"head",
")",
"while",
"head",
"and",
"tail",
":",
"try",
":",
"rmdir",
"(",
"head",
")",
"except",
"OSError",
":",
"break",
"head",
",",
"tail",
"=",
"path",
".",
"split",
"(",
"head",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/os.py#L230-L250 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/win/toolchain/toolchain.py | python | Download | (url, local_path) | Download a large-ish binary file and print some status information while
doing so. | Download a large-ish binary file and print some status information while
doing so. | [
"Download",
"a",
"large",
"-",
"ish",
"binary",
"file",
"and",
"print",
"some",
"status",
"information",
"while",
"doing",
"so",
"."
] | def Download(url, local_path):
"""Download a large-ish binary file and print some status information while
doing so."""
sys.stdout.write('Downloading %s...\n' % url)
req = urllib2.urlopen(url)
content_length = int(req.headers.get('Content-Length', 0))
bytes_read = 0
terminator = '\r' if sys.stdout.isatty() else '\n'
with open(local_path, 'wb') as file:
while True:
chunk = req.read(1024 * 1024)
if not chunk:
break
bytes_read += len(chunk)
file.write(chunk)
sys.stdout.write('... %d/%d%s' % (bytes_read, content_length, terminator))
sys.stdout.flush()
sys.stdout.write('\n')
if content_length and content_length != bytes_read:
raise SystemExit('Got incorrect number of bytes downloading %s' % url) | [
"def",
"Download",
"(",
"url",
",",
"local_path",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'Downloading %s...\\n'",
"%",
"url",
")",
"req",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"content_length",
"=",
"int",
"(",
"req",
".",
"headers",
".",
"get",
"(",
"'Content-Length'",
",",
"0",
")",
")",
"bytes_read",
"=",
"0",
"terminator",
"=",
"'\\r'",
"if",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
"else",
"'\\n'",
"with",
"open",
"(",
"local_path",
",",
"'wb'",
")",
"as",
"file",
":",
"while",
"True",
":",
"chunk",
"=",
"req",
".",
"read",
"(",
"1024",
"*",
"1024",
")",
"if",
"not",
"chunk",
":",
"break",
"bytes_read",
"+=",
"len",
"(",
"chunk",
")",
"file",
".",
"write",
"(",
"chunk",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'... %d/%d%s'",
"%",
"(",
"bytes_read",
",",
"content_length",
",",
"terminator",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"if",
"content_length",
"and",
"content_length",
"!=",
"bytes_read",
":",
"raise",
"SystemExit",
"(",
"'Got incorrect number of bytes downloading %s'",
"%",
"url",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/win/toolchain/toolchain.py#L57-L76 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/database.py | python | DependencyGraph.add_edge | (self, x, y, label=None) | Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type label: ``str`` or ``None`` | Add an edge from distribution *x* to distribution *y* with the given
*label*. | [
"Add",
"an",
"edge",
"from",
"distribution",
"*",
"x",
"*",
"to",
"distribution",
"*",
"y",
"*",
"with",
"the",
"given",
"*",
"label",
"*",
"."
] | def add_edge(self, x, y, label=None):
"""Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type label: ``str`` or ``None``
"""
self.adjacency_list[x].append((y, label))
# multiple edges are allowed, so be careful
if x not in self.reverse_list[y]:
self.reverse_list[y].append(x) | [
"def",
"add_edge",
"(",
"self",
",",
"x",
",",
"y",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"adjacency_list",
"[",
"x",
"]",
".",
"append",
"(",
"(",
"y",
",",
"label",
")",
")",
"# multiple edges are allowed, so be careful",
"if",
"x",
"not",
"in",
"self",
".",
"reverse_list",
"[",
"y",
"]",
":",
"self",
".",
"reverse_list",
"[",
"y",
"]",
".",
"append",
"(",
"x",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/database.py#L1112-L1125 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/metrics_utils.py | python | update_state_wrapper | (update_state_fn) | return tf_decorator.make_decorator(update_state_fn, decorated) | Decorator to wrap metric `update_state()` with `add_update()`.
Args:
update_state_fn: function that accumulates metric statistics.
Returns:
Decorated function that wraps `update_state_fn()` with `add_update()`. | Decorator to wrap metric `update_state()` with `add_update()`. | [
"Decorator",
"to",
"wrap",
"metric",
"update_state",
"()",
"with",
"add_update",
"()",
"."
] | def update_state_wrapper(update_state_fn):
"""Decorator to wrap metric `update_state()` with `add_update()`.
Args:
update_state_fn: function that accumulates metric statistics.
Returns:
Decorated function that wraps `update_state_fn()` with `add_update()`.
"""
def decorated(metric_obj, *args, **kwargs):
"""Decorated function with `add_update()`."""
with tf_utils.graph_context_for_symbolic_tensors(*args, **kwargs):
update_op = update_state_fn(*args, **kwargs)
if update_op is not None: # update_op will be None in eager execution.
metric_obj.add_update(update_op)
return update_op
return tf_decorator.make_decorator(update_state_fn, decorated) | [
"def",
"update_state_wrapper",
"(",
"update_state_fn",
")",
":",
"def",
"decorated",
"(",
"metric_obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Decorated function with `add_update()`.\"\"\"",
"with",
"tf_utils",
".",
"graph_context_for_symbolic_tensors",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"update_op",
"=",
"update_state_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"update_op",
"is",
"not",
"None",
":",
"# update_op will be None in eager execution.",
"metric_obj",
".",
"add_update",
"(",
"update_op",
")",
"return",
"update_op",
"return",
"tf_decorator",
".",
"make_decorator",
"(",
"update_state_fn",
",",
"decorated",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/metrics_utils.py#L61-L80 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_book.py | python | EdBaseBook.SetPageBitmap | (self, pg, bmp) | Set a tabs bitmap
@param pg: page index
@param bmp: Bitmap
@note: no action if user prefs have turned off bmp | Set a tabs bitmap
@param pg: page index
@param bmp: Bitmap
@note: no action if user prefs have turned off bmp | [
"Set",
"a",
"tabs",
"bitmap",
"@param",
"pg",
":",
"page",
"index",
"@param",
"bmp",
":",
"Bitmap",
"@note",
":",
"no",
"action",
"if",
"user",
"prefs",
"have",
"turned",
"off",
"bmp"
] | def SetPageBitmap(self, pg, bmp):
"""Set a tabs bitmap
@param pg: page index
@param bmp: Bitmap
@note: no action if user prefs have turned off bmp
"""
if not self.UseIcons():
bmp = wx.NullBitmap
super(EdBaseBook, self).SetPageBitmap(pg, bmp) | [
"def",
"SetPageBitmap",
"(",
"self",
",",
"pg",
",",
"bmp",
")",
":",
"if",
"not",
"self",
".",
"UseIcons",
"(",
")",
":",
"bmp",
"=",
"wx",
".",
"NullBitmap",
"super",
"(",
"EdBaseBook",
",",
"self",
")",
".",
"SetPageBitmap",
"(",
"pg",
",",
"bmp",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_book.py#L78-L87 | ||
wy1iu/LargeMargin_Softmax_Loss | c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec | scripts/cpp_lint.py | python | FileInfo.Split | (self) | return (project,) + os.path.splitext(rest) | Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension). | Splits the file into the directory, basename, and extension. | [
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
"."
] | def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest) | [
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
".",
"splitext",
"(",
"rest",
")"
] | https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/scripts/cpp_lint.py#L930-L942 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/gdc.py | python | configure | (conf) | Configuration for gdc | Configuration for gdc | [
"Configuration",
"for",
"gdc"
] | def configure(conf):
"""
Configuration for gdc
"""
conf.find_gdc()
conf.load('ar')
conf.load('d')
conf.common_flags_gdc()
conf.d_platform_flags() | [
"def",
"configure",
"(",
"conf",
")",
":",
"conf",
".",
"find_gdc",
"(",
")",
"conf",
".",
"load",
"(",
"'ar'",
")",
"conf",
".",
"load",
"(",
"'d'",
")",
"conf",
".",
"common_flags_gdc",
"(",
")",
"conf",
".",
"d_platform_flags",
"(",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/gdc.py#L51-L59 | ||
NVIDIA-Merlin/HugeCTR | b596bcc44e14bb0c62c4f7e9c0b55301d94f2154 | sparse_operation_kit/sparse_operation_kit/kit_lib.py | python | in_tensorflow2 | () | return using_tf2 | This function will tell whether the installed TensorFlow is 2.x | This function will tell whether the installed TensorFlow is 2.x | [
"This",
"function",
"will",
"tell",
"whether",
"the",
"installed",
"TensorFlow",
"is",
"2",
".",
"x"
] | def in_tensorflow2():
"""
This function will tell whether the installed TensorFlow is 2.x
"""
return using_tf2 | [
"def",
"in_tensorflow2",
"(",
")",
":",
"return",
"using_tf2"
] | https://github.com/NVIDIA-Merlin/HugeCTR/blob/b596bcc44e14bb0c62c4f7e9c0b55301d94f2154/sparse_operation_kit/sparse_operation_kit/kit_lib.py#L32-L36 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBBreakpointLocation.GetID | (self) | return _lldb.SBBreakpointLocation_GetID(self) | GetID(SBBreakpointLocation self) -> lldb::break_id_t | GetID(SBBreakpointLocation self) -> lldb::break_id_t | [
"GetID",
"(",
"SBBreakpointLocation",
"self",
")",
"-",
">",
"lldb",
"::",
"break_id_t"
] | def GetID(self):
"""GetID(SBBreakpointLocation self) -> lldb::break_id_t"""
return _lldb.SBBreakpointLocation_GetID(self) | [
"def",
"GetID",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBBreakpointLocation_GetID",
"(",
"self",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L1964-L1966 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/ccroot.py | python | apply_vnum | (self) | Enforce version numbering on shared libraries. The valid version numbers must have at most two dots::
def build(bld):
bld.shlib(source='a.c', target='foo', vnum='14.15.16')
In this example, ``libfoo.so`` is installed as ``libfoo.so.1.2.3``, and the following symbolic links are created:
* ``libfoo.so → libfoo.so.1.2.3``
* ``libfoo.so.1 → libfoo.so.1.2.3`` | Enforce version numbering on shared libraries. The valid version numbers must have at most two dots:: | [
"Enforce",
"version",
"numbering",
"on",
"shared",
"libraries",
".",
"The",
"valid",
"version",
"numbers",
"must",
"have",
"at",
"most",
"two",
"dots",
"::"
] | def apply_vnum(self):
"""
Enforce version numbering on shared libraries. The valid version numbers must have at most two dots::
def build(bld):
bld.shlib(source='a.c', target='foo', vnum='14.15.16')
In this example, ``libfoo.so`` is installed as ``libfoo.so.1.2.3``, and the following symbolic links are created:
* ``libfoo.so → libfoo.so.1.2.3``
* ``libfoo.so.1 → libfoo.so.1.2.3``
"""
if not getattr(self, 'vnum', '') or os.name != 'posix' or self.env.DEST_BINFMT not in ('elf', 'mac-o'):
return
link = self.link_task
if not re_vnum.match(self.vnum):
raise Errors.WafError('Invalid version %r for %r' % (self.vnum, self))
nums = self.vnum.split('.')
node = link.outputs[0]
libname = node.name
if libname.endswith('.dylib'):
name3 = libname.replace('.dylib', '.%s.dylib' % self.vnum)
name2 = libname.replace('.dylib', '.%s.dylib' % nums[0])
else:
name3 = libname + '.' + self.vnum
name2 = libname + '.' + nums[0]
# add the so name for the ld linker - to disable, just unset env.SONAME_ST
if self.env.SONAME_ST:
v = self.env.SONAME_ST % name2
self.env.append_value('LINKFLAGS', v.split())
# the following task is just to enable execution from the build dir :-/
if self.env.DEST_OS != 'openbsd':
self.create_task('vnum', node, [node.parent.find_or_declare(name2), node.parent.find_or_declare(name3)])
if getattr(self, 'install_task', None):
self.install_task.hasrun = Task.SKIP_ME
bld = self.bld
path = self.install_task.dest
if self.env.DEST_OS == 'openbsd':
libname = self.link_task.outputs[0].name
t1 = bld.install_as('%s%s%s' % (path, os.sep, libname), node, env=self.env, chmod=self.link_task.chmod)
self.vnum_install_task = (t1,)
else:
t1 = bld.install_as(path + os.sep + name3, node, env=self.env, chmod=self.link_task.chmod)
t2 = bld.symlink_as(path + os.sep + name2, name3)
t3 = bld.symlink_as(path + os.sep + libname, name3)
self.vnum_install_task = (t1, t2, t3)
if '-dynamiclib' in self.env['LINKFLAGS']:
# this requires after(propagate_uselib_vars)
try:
inst_to = self.install_path
except AttributeError:
inst_to = self.link_task.__class__.inst_to
if inst_to:
p = Utils.subst_vars(inst_to, self.env)
path = os.path.join(p, self.link_task.outputs[0].name)
self.env.append_value('LINKFLAGS', ['-install_name', path]) | [
"def",
"apply_vnum",
"(",
"self",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'vnum'",
",",
"''",
")",
"or",
"os",
".",
"name",
"!=",
"'posix'",
"or",
"self",
".",
"env",
".",
"DEST_BINFMT",
"not",
"in",
"(",
"'elf'",
",",
"'mac-o'",
")",
":",
"return",
"link",
"=",
"self",
".",
"link_task",
"if",
"not",
"re_vnum",
".",
"match",
"(",
"self",
".",
"vnum",
")",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"'Invalid version %r for %r'",
"%",
"(",
"self",
".",
"vnum",
",",
"self",
")",
")",
"nums",
"=",
"self",
".",
"vnum",
".",
"split",
"(",
"'.'",
")",
"node",
"=",
"link",
".",
"outputs",
"[",
"0",
"]",
"libname",
"=",
"node",
".",
"name",
"if",
"libname",
".",
"endswith",
"(",
"'.dylib'",
")",
":",
"name3",
"=",
"libname",
".",
"replace",
"(",
"'.dylib'",
",",
"'.%s.dylib'",
"%",
"self",
".",
"vnum",
")",
"name2",
"=",
"libname",
".",
"replace",
"(",
"'.dylib'",
",",
"'.%s.dylib'",
"%",
"nums",
"[",
"0",
"]",
")",
"else",
":",
"name3",
"=",
"libname",
"+",
"'.'",
"+",
"self",
".",
"vnum",
"name2",
"=",
"libname",
"+",
"'.'",
"+",
"nums",
"[",
"0",
"]",
"# add the so name for the ld linker - to disable, just unset env.SONAME_ST",
"if",
"self",
".",
"env",
".",
"SONAME_ST",
":",
"v",
"=",
"self",
".",
"env",
".",
"SONAME_ST",
"%",
"name2",
"self",
".",
"env",
".",
"append_value",
"(",
"'LINKFLAGS'",
",",
"v",
".",
"split",
"(",
")",
")",
"# the following task is just to enable execution from the build dir :-/",
"if",
"self",
".",
"env",
".",
"DEST_OS",
"!=",
"'openbsd'",
":",
"self",
".",
"create_task",
"(",
"'vnum'",
",",
"node",
",",
"[",
"node",
".",
"parent",
".",
"find_or_declare",
"(",
"name2",
")",
",",
"node",
".",
"parent",
".",
"find_or_declare",
"(",
"name3",
")",
"]",
")",
"if",
"getattr",
"(",
"self",
",",
"'install_task'",
",",
"None",
")",
":",
"self",
".",
"install_task",
".",
"hasrun",
"=",
"Task",
".",
"SKIP_ME",
"bld",
"=",
"self",
".",
"bld",
"path",
"=",
"self",
".",
"install_task",
".",
"dest",
"if",
"self",
".",
"env",
".",
"DEST_OS",
"==",
"'openbsd'",
":",
"libname",
"=",
"self",
".",
"link_task",
".",
"outputs",
"[",
"0",
"]",
".",
"name",
"t1",
"=",
"bld",
".",
"install_as",
"(",
"'%s%s%s'",
"%",
"(",
"path",
",",
"os",
".",
"sep",
",",
"libname",
")",
",",
"node",
",",
"env",
"=",
"self",
".",
"env",
",",
"chmod",
"=",
"self",
".",
"link_task",
".",
"chmod",
")",
"self",
".",
"vnum_install_task",
"=",
"(",
"t1",
",",
")",
"else",
":",
"t1",
"=",
"bld",
".",
"install_as",
"(",
"path",
"+",
"os",
".",
"sep",
"+",
"name3",
",",
"node",
",",
"env",
"=",
"self",
".",
"env",
",",
"chmod",
"=",
"self",
".",
"link_task",
".",
"chmod",
")",
"t2",
"=",
"bld",
".",
"symlink_as",
"(",
"path",
"+",
"os",
".",
"sep",
"+",
"name2",
",",
"name3",
")",
"t3",
"=",
"bld",
".",
"symlink_as",
"(",
"path",
"+",
"os",
".",
"sep",
"+",
"libname",
",",
"name3",
")",
"self",
".",
"vnum_install_task",
"=",
"(",
"t1",
",",
"t2",
",",
"t3",
")",
"if",
"'-dynamiclib'",
"in",
"self",
".",
"env",
"[",
"'LINKFLAGS'",
"]",
":",
"# this requires after(propagate_uselib_vars)",
"try",
":",
"inst_to",
"=",
"self",
".",
"install_path",
"except",
"AttributeError",
":",
"inst_to",
"=",
"self",
".",
"link_task",
".",
"__class__",
".",
"inst_to",
"if",
"inst_to",
":",
"p",
"=",
"Utils",
".",
"subst_vars",
"(",
"inst_to",
",",
"self",
".",
"env",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"self",
".",
"link_task",
".",
"outputs",
"[",
"0",
"]",
".",
"name",
")",
"self",
".",
"env",
".",
"append_value",
"(",
"'LINKFLAGS'",
",",
"[",
"'-install_name'",
",",
"path",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/ccroot.py#L550-L612 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/locale_tool.py | python | _IsGritInputFile | (input_file) | return input_file.endswith('.grd') | Returns True iff this is a GRIT input file. | Returns True iff this is a GRIT input file. | [
"Returns",
"True",
"iff",
"this",
"is",
"a",
"GRIT",
"input",
"file",
"."
] | def _IsGritInputFile(input_file):
"""Returns True iff this is a GRIT input file."""
return input_file.endswith('.grd') | [
"def",
"_IsGritInputFile",
"(",
"input_file",
")",
":",
"return",
"input_file",
".",
"endswith",
"(",
"'.grd'",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/locale_tool.py#L486-L488 | |
3drobotics/ardupilot-solo | 05a123b002c11dccc905d4d7703a38e5f36ee723 | mk/PX4/Tools/gencpp/src/gencpp/__init__.py | python | is_fixed_length | (spec, msg_context, includepath) | return True | Returns whether or not the message is fixed-length
@param spec: The message spec
@type spec: genmsg.msgs.MsgSpec
@param package: The package of the
@type package: str | Returns whether or not the message is fixed-length | [
"Returns",
"whether",
"or",
"not",
"the",
"message",
"is",
"fixed",
"-",
"length"
] | def is_fixed_length(spec, msg_context, includepath):
"""
Returns whether or not the message is fixed-length
@param spec: The message spec
@type spec: genmsg.msgs.MsgSpec
@param package: The package of the
@type package: str
"""
types = []
for field in spec.parsed_fields():
if (field.is_array and field.array_len is None):
return False
if (field.base_type == 'string'):
return False
if (not field.is_builtin):
types.append(field.base_type)
types = set(types)
for t in types:
t = genmsg.msgs.resolve_type(t, spec.package)
assert isinstance(includepath, dict)
new_spec = genmsg.msg_loader.load_msg_by_type(msg_context, t, includepath)
if (not is_fixed_length(new_spec, msg_context, includepath)):
return False
return True | [
"def",
"is_fixed_length",
"(",
"spec",
",",
"msg_context",
",",
"includepath",
")",
":",
"types",
"=",
"[",
"]",
"for",
"field",
"in",
"spec",
".",
"parsed_fields",
"(",
")",
":",
"if",
"(",
"field",
".",
"is_array",
"and",
"field",
".",
"array_len",
"is",
"None",
")",
":",
"return",
"False",
"if",
"(",
"field",
".",
"base_type",
"==",
"'string'",
")",
":",
"return",
"False",
"if",
"(",
"not",
"field",
".",
"is_builtin",
")",
":",
"types",
".",
"append",
"(",
"field",
".",
"base_type",
")",
"types",
"=",
"set",
"(",
"types",
")",
"for",
"t",
"in",
"types",
":",
"t",
"=",
"genmsg",
".",
"msgs",
".",
"resolve_type",
"(",
"t",
",",
"spec",
".",
"package",
")",
"assert",
"isinstance",
"(",
"includepath",
",",
"dict",
")",
"new_spec",
"=",
"genmsg",
".",
"msg_loader",
".",
"load_msg_by_type",
"(",
"msg_context",
",",
"t",
",",
"includepath",
")",
"if",
"(",
"not",
"is_fixed_length",
"(",
"new_spec",
",",
"msg_context",
",",
"includepath",
")",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/3drobotics/ardupilot-solo/blob/05a123b002c11dccc905d4d7703a38e5f36ee723/mk/PX4/Tools/gencpp/src/gencpp/__init__.py#L128-L156 | |
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/generator/msvs.py | python | _GetMSBuildPropertyGroup | (spec, label, properties) | return [group] | Returns a PropertyGroup definition for the specified properties.
Arguments:
spec: The target project dict.
label: An optional label for the PropertyGroup.
properties: The dictionary to be converted. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true. | Returns a PropertyGroup definition for the specified properties. | [
"Returns",
"a",
"PropertyGroup",
"definition",
"for",
"the",
"specified",
"properties",
"."
] | def _GetMSBuildPropertyGroup(spec, label, properties):
"""Returns a PropertyGroup definition for the specified properties.
Arguments:
spec: The target project dict.
label: An optional label for the PropertyGroup.
properties: The dictionary to be converted. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true.
"""
group = ['PropertyGroup']
if label:
group.append({'Label': label})
num_configurations = len(spec['configurations'])
def GetEdges(node):
# Use a definition of edges such that user_of_variable -> used_varible.
# This happens to be easier in this case, since a variable's
# definition contains all variables it references in a single string.
edges = set()
for value in sorted(properties[node].keys()):
# Add to edges all $(...) references to variables.
#
# Variable references that refer to names not in properties are excluded
# These can exist for instance to refer built in definitions like
# $(SolutionDir).
#
# Self references are ignored. Self reference is used in a few places to
# append to the default value. I.e. PATH=$(PATH);other_path
edges.update(set([v for v in MSVS_VARIABLE_REFERENCE.findall(value)
if v in properties and v != node]))
return edges
properties_ordered = gyp.common.TopologicallySorted(
properties.keys(), GetEdges)
# Walk properties in the reverse of a topological sort on
# user_of_variable -> used_variable as this ensures variables are
# defined before they are used.
# NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
for name in reversed(properties_ordered):
values = properties[name]
for value, conditions in sorted(values.iteritems()):
if len(conditions) == num_configurations:
# If the value is the same all configurations,
# just add one unconditional entry.
group.append([name, value])
else:
for condition in conditions:
group.append([name, {'Condition': condition}, value])
return [group] | [
"def",
"_GetMSBuildPropertyGroup",
"(",
"spec",
",",
"label",
",",
"properties",
")",
":",
"group",
"=",
"[",
"'PropertyGroup'",
"]",
"if",
"label",
":",
"group",
".",
"append",
"(",
"{",
"'Label'",
":",
"label",
"}",
")",
"num_configurations",
"=",
"len",
"(",
"spec",
"[",
"'configurations'",
"]",
")",
"def",
"GetEdges",
"(",
"node",
")",
":",
"# Use a definition of edges such that user_of_variable -> used_varible.",
"# This happens to be easier in this case, since a variable's",
"# definition contains all variables it references in a single string.",
"edges",
"=",
"set",
"(",
")",
"for",
"value",
"in",
"sorted",
"(",
"properties",
"[",
"node",
"]",
".",
"keys",
"(",
")",
")",
":",
"# Add to edges all $(...) references to variables.",
"#",
"# Variable references that refer to names not in properties are excluded",
"# These can exist for instance to refer built in definitions like",
"# $(SolutionDir).",
"#",
"# Self references are ignored. Self reference is used in a few places to",
"# append to the default value. I.e. PATH=$(PATH);other_path",
"edges",
".",
"update",
"(",
"set",
"(",
"[",
"v",
"for",
"v",
"in",
"MSVS_VARIABLE_REFERENCE",
".",
"findall",
"(",
"value",
")",
"if",
"v",
"in",
"properties",
"and",
"v",
"!=",
"node",
"]",
")",
")",
"return",
"edges",
"properties_ordered",
"=",
"gyp",
".",
"common",
".",
"TopologicallySorted",
"(",
"properties",
".",
"keys",
"(",
")",
",",
"GetEdges",
")",
"# Walk properties in the reverse of a topological sort on",
"# user_of_variable -> used_variable as this ensures variables are",
"# defined before they are used.",
"# NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))",
"for",
"name",
"in",
"reversed",
"(",
"properties_ordered",
")",
":",
"values",
"=",
"properties",
"[",
"name",
"]",
"for",
"value",
",",
"conditions",
"in",
"sorted",
"(",
"values",
".",
"iteritems",
"(",
")",
")",
":",
"if",
"len",
"(",
"conditions",
")",
"==",
"num_configurations",
":",
"# If the value is the same all configurations,",
"# just add one unconditional entry.",
"group",
".",
"append",
"(",
"[",
"name",
",",
"value",
"]",
")",
"else",
":",
"for",
"condition",
"in",
"conditions",
":",
"group",
".",
"append",
"(",
"[",
"name",
",",
"{",
"'Condition'",
":",
"condition",
"}",
",",
"value",
"]",
")",
"return",
"[",
"group",
"]"
] | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/generator/msvs.py#L2696-L2743 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.py | python | get_subj_alt_name | (peer_cert) | return names | Given an PyOpenSSL certificate, provides all the subject alternative names. | Given an PyOpenSSL certificate, provides all the subject alternative names. | [
"Given",
"an",
"PyOpenSSL",
"certificate",
"provides",
"all",
"the",
"subject",
"alternative",
"names",
"."
] | def get_subj_alt_name(peer_cert):
"""
Given an PyOpenSSL certificate, provides all the subject alternative names.
"""
# Pass the cert to cryptography, which has much better APIs for this.
if hasattr(peer_cert, "to_cryptography"):
cert = peer_cert.to_cryptography()
else:
# This is technically using private APIs, but should work across all
# relevant versions before PyOpenSSL got a proper API for this.
cert = _Certificate(openssl_backend, peer_cert._x509)
# We want to find the SAN extension. Ask Cryptography to locate it (it's
# faster than looping in Python)
try:
ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
except x509.ExtensionNotFound:
# No such extension, return the empty list.
return []
except (
x509.DuplicateExtension,
UnsupportedExtension,
x509.UnsupportedGeneralNameType,
UnicodeError,
) as e:
# A problem has been found with the quality of the certificate. Assume
# no SAN field is present.
log.warning(
"A problem was encountered with the certificate that prevented "
"urllib3 from finding the SubjectAlternativeName field. This can "
"affect certificate validation. The error was %s",
e,
)
return []
# We want to return dNSName and iPAddress fields. We need to cast the IPs
# back to strings because the match_hostname function wants them as
# strings.
# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
# decoded. This is pretty frustrating, but that's what the standard library
# does with certificates, and so we need to attempt to do the same.
# We also want to skip over names which cannot be idna encoded.
names = [
("DNS", name)
for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
if name is not None
]
names.extend(
("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress)
)
return names | [
"def",
"get_subj_alt_name",
"(",
"peer_cert",
")",
":",
"# Pass the cert to cryptography, which has much better APIs for this.",
"if",
"hasattr",
"(",
"peer_cert",
",",
"\"to_cryptography\"",
")",
":",
"cert",
"=",
"peer_cert",
".",
"to_cryptography",
"(",
")",
"else",
":",
"# This is technically using private APIs, but should work across all",
"# relevant versions before PyOpenSSL got a proper API for this.",
"cert",
"=",
"_Certificate",
"(",
"openssl_backend",
",",
"peer_cert",
".",
"_x509",
")",
"# We want to find the SAN extension. Ask Cryptography to locate it (it's",
"# faster than looping in Python)",
"try",
":",
"ext",
"=",
"cert",
".",
"extensions",
".",
"get_extension_for_class",
"(",
"x509",
".",
"SubjectAlternativeName",
")",
".",
"value",
"except",
"x509",
".",
"ExtensionNotFound",
":",
"# No such extension, return the empty list.",
"return",
"[",
"]",
"except",
"(",
"x509",
".",
"DuplicateExtension",
",",
"UnsupportedExtension",
",",
"x509",
".",
"UnsupportedGeneralNameType",
",",
"UnicodeError",
",",
")",
"as",
"e",
":",
"# A problem has been found with the quality of the certificate. Assume",
"# no SAN field is present.",
"log",
".",
"warning",
"(",
"\"A problem was encountered with the certificate that prevented \"",
"\"urllib3 from finding the SubjectAlternativeName field. This can \"",
"\"affect certificate validation. The error was %s\"",
",",
"e",
",",
")",
"return",
"[",
"]",
"# We want to return dNSName and iPAddress fields. We need to cast the IPs",
"# back to strings because the match_hostname function wants them as",
"# strings.",
"# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8",
"# decoded. This is pretty frustrating, but that's what the standard library",
"# does with certificates, and so we need to attempt to do the same.",
"# We also want to skip over names which cannot be idna encoded.",
"names",
"=",
"[",
"(",
"\"DNS\"",
",",
"name",
")",
"for",
"name",
"in",
"map",
"(",
"_dnsname_to_stdlib",
",",
"ext",
".",
"get_values_for_type",
"(",
"x509",
".",
"DNSName",
")",
")",
"if",
"name",
"is",
"not",
"None",
"]",
"names",
".",
"extend",
"(",
"(",
"\"IP Address\"",
",",
"str",
"(",
"name",
")",
")",
"for",
"name",
"in",
"ext",
".",
"get_values_for_type",
"(",
"x509",
".",
"IPAddress",
")",
")",
"return",
"names"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.py#L212-L263 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/io/ros.py | python | to_JointTrajectory | (klampt_traj,indices='auto',link_joint_names=None) | Returns a ROS JointTrajectory message for a Klamp't Trajectory or
RobotTrajectory.
Args:
klampt_traj (Trajectory or RobotTrajectory): the trajectory
indices (str or list of ints): the indices to send (only valid with RobotTrajectory)
link_joint_names (list of str, optional): if given, the i'th link is
mapped to the ROS joint name link_joint_names[i]. | Returns a ROS JointTrajectory message for a Klamp't Trajectory or
RobotTrajectory. | [
"Returns",
"a",
"ROS",
"JointTrajectory",
"message",
"for",
"a",
"Klamp",
"t",
"Trajectory",
"or",
"RobotTrajectory",
"."
] | def to_JointTrajectory(klampt_traj,indices='auto',link_joint_names=None):
"""Returns a ROS JointTrajectory message for a Klamp't Trajectory or
RobotTrajectory.
Args:
klampt_traj (Trajectory or RobotTrajectory): the trajectory
indices (str or list of ints): the indices to send (only valid with RobotTrajectory)
link_joint_names (list of str, optional): if given, the i'th link is
mapped to the ROS joint name link_joint_names[i].
"""
from trajectory_msgs.msg import JointTrajectoryPoint
res = JointTrajectory()
if len(klampt_traj.milestones) == 0:
res.joint_names = []
res.points = []
return res
if not hasattr(klampt_traj,'robot'):
if link_joint_names is None:
for i in range(len(klampt_traj.milestones[0])):
res.joint_names.append(chr(ord('0')+i))
else:
assert len(link_joint_names) == len(klampt_traj.milestones[0])
for i in range(len(klampt_traj.milestones[0])):
res.joint_names.append(link_joint_names)
for i,q in enumerate(klampt_traj.milestones):
res.points.append(JointTrajectoryPoint())
res.points[-1].time_from_start = rospy.Duration(klampt_traj.times[i])
res.points[-1].positions = q
return res
else:
#TODO: hermite trajectories?
if indices == 'auto':
indices = range(klampt_traj.robot.numLinks())
if link_joint_names is None:
link_joint_names = [klampt_traj.robot.link(i).getName() for i in range(klampt_traj.robot.numLinks())]
for i,link in enumerate(indices):
res.joint_names.append(link_joint_names[link])
if len(indices) != len(klampt_traj.milestones[0]):
raise ValueError("Path doesn't have same number of milestones as the robot")
for i,q in enumerate(klampt_traj.milestones):
res.points.append(JointTrajectoryPoint())
res.points[-1].time_from_start = rospy.Duration(klampt_traj.times[i])
for link in indices:
res.points[-1].positions.append = klampt_traj.milestones[i][link]
return res | [
"def",
"to_JointTrajectory",
"(",
"klampt_traj",
",",
"indices",
"=",
"'auto'",
",",
"link_joint_names",
"=",
"None",
")",
":",
"from",
"trajectory_msgs",
".",
"msg",
"import",
"JointTrajectoryPoint",
"res",
"=",
"JointTrajectory",
"(",
")",
"if",
"len",
"(",
"klampt_traj",
".",
"milestones",
")",
"==",
"0",
":",
"res",
".",
"joint_names",
"=",
"[",
"]",
"res",
".",
"points",
"=",
"[",
"]",
"return",
"res",
"if",
"not",
"hasattr",
"(",
"klampt_traj",
",",
"'robot'",
")",
":",
"if",
"link_joint_names",
"is",
"None",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"klampt_traj",
".",
"milestones",
"[",
"0",
"]",
")",
")",
":",
"res",
".",
"joint_names",
".",
"append",
"(",
"chr",
"(",
"ord",
"(",
"'0'",
")",
"+",
"i",
")",
")",
"else",
":",
"assert",
"len",
"(",
"link_joint_names",
")",
"==",
"len",
"(",
"klampt_traj",
".",
"milestones",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"klampt_traj",
".",
"milestones",
"[",
"0",
"]",
")",
")",
":",
"res",
".",
"joint_names",
".",
"append",
"(",
"link_joint_names",
")",
"for",
"i",
",",
"q",
"in",
"enumerate",
"(",
"klampt_traj",
".",
"milestones",
")",
":",
"res",
".",
"points",
".",
"append",
"(",
"JointTrajectoryPoint",
"(",
")",
")",
"res",
".",
"points",
"[",
"-",
"1",
"]",
".",
"time_from_start",
"=",
"rospy",
".",
"Duration",
"(",
"klampt_traj",
".",
"times",
"[",
"i",
"]",
")",
"res",
".",
"points",
"[",
"-",
"1",
"]",
".",
"positions",
"=",
"q",
"return",
"res",
"else",
":",
"#TODO: hermite trajectories?",
"if",
"indices",
"==",
"'auto'",
":",
"indices",
"=",
"range",
"(",
"klampt_traj",
".",
"robot",
".",
"numLinks",
"(",
")",
")",
"if",
"link_joint_names",
"is",
"None",
":",
"link_joint_names",
"=",
"[",
"klampt_traj",
".",
"robot",
".",
"link",
"(",
"i",
")",
".",
"getName",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"klampt_traj",
".",
"robot",
".",
"numLinks",
"(",
")",
")",
"]",
"for",
"i",
",",
"link",
"in",
"enumerate",
"(",
"indices",
")",
":",
"res",
".",
"joint_names",
".",
"append",
"(",
"link_joint_names",
"[",
"link",
"]",
")",
"if",
"len",
"(",
"indices",
")",
"!=",
"len",
"(",
"klampt_traj",
".",
"milestones",
"[",
"0",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Path doesn't have same number of milestones as the robot\"",
")",
"for",
"i",
",",
"q",
"in",
"enumerate",
"(",
"klampt_traj",
".",
"milestones",
")",
":",
"res",
".",
"points",
".",
"append",
"(",
"JointTrajectoryPoint",
"(",
")",
")",
"res",
".",
"points",
"[",
"-",
"1",
"]",
".",
"time_from_start",
"=",
"rospy",
".",
"Duration",
"(",
"klampt_traj",
".",
"times",
"[",
"i",
"]",
")",
"for",
"link",
"in",
"indices",
":",
"res",
".",
"points",
"[",
"-",
"1",
"]",
".",
"positions",
".",
"append",
"=",
"klampt_traj",
".",
"milestones",
"[",
"i",
"]",
"[",
"link",
"]",
"return",
"res"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/io/ros.py#L279-L323 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/_version.py | python | git_versions_from_keywords | (keywords, tag_prefix, verbose) | return {
"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
"date": None,
} | Get version information from git keywords. | Get version information from git keywords. | [
"Get",
"version",
"information",
"from",
"git",
"keywords",
"."
] | def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
# datestamp. However we prefer "%ci" (which expands to an "ISO-8601
# -like" string, which we must then edit to make compliant), because
# it's been around since git-1.5.3, and it's too difficult to
# discover which version we're using, or to work around using an
# older one.
date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = {r.strip() for r in refnames.strip("()").split(",")}
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
# expansion behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = {r for r in refs if re.search(r"\d", r)}
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix) :]
if verbose:
print("picking %s" % r)
return {
"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": None,
"date": date,
}
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {
"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
"date": None,
} | [
"def",
"git_versions_from_keywords",
"(",
"keywords",
",",
"tag_prefix",
",",
"verbose",
")",
":",
"if",
"not",
"keywords",
":",
"raise",
"NotThisMethod",
"(",
"\"no keywords at all, weird\"",
")",
"date",
"=",
"keywords",
".",
"get",
"(",
"\"date\"",
")",
"if",
"date",
"is",
"not",
"None",
":",
"# git-2.2.0 added \"%cI\", which expands to an ISO-8601 -compliant",
"# datestamp. However we prefer \"%ci\" (which expands to an \"ISO-8601",
"# -like\" string, which we must then edit to make compliant), because",
"# it's been around since git-1.5.3, and it's too difficult to",
"# discover which version we're using, or to work around using an",
"# older one.",
"date",
"=",
"date",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"T\"",
",",
"1",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
",",
"1",
")",
"refnames",
"=",
"keywords",
"[",
"\"refnames\"",
"]",
".",
"strip",
"(",
")",
"if",
"refnames",
".",
"startswith",
"(",
"\"$Format\"",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"keywords are unexpanded, not using\"",
")",
"raise",
"NotThisMethod",
"(",
"\"unexpanded keywords, not a git-archive tarball\"",
")",
"refs",
"=",
"{",
"r",
".",
"strip",
"(",
")",
"for",
"r",
"in",
"refnames",
".",
"strip",
"(",
"\"()\"",
")",
".",
"split",
"(",
"\",\"",
")",
"}",
"# starting in git-1.8.3, tags are listed as \"tag: foo-1.0\" instead of",
"# just \"foo-1.0\". If we see a \"tag: \" prefix, prefer those.",
"TAG",
"=",
"\"tag: \"",
"tags",
"=",
"{",
"r",
"[",
"len",
"(",
"TAG",
")",
":",
"]",
"for",
"r",
"in",
"refs",
"if",
"r",
".",
"startswith",
"(",
"TAG",
")",
"}",
"if",
"not",
"tags",
":",
"# Either we're using git < 1.8.3, or there really are no tags. We use",
"# a heuristic: assume all version tags have a digit. The old git %d",
"# expansion behaves like git log --decorate=short and strips out the",
"# refs/heads/ and refs/tags/ prefixes that would let us distinguish",
"# between branches and tags. By ignoring refnames without digits, we",
"# filter out many common branch names like \"release\" and",
"# \"stabilization\", as well as \"HEAD\" and \"master\".",
"tags",
"=",
"{",
"r",
"for",
"r",
"in",
"refs",
"if",
"re",
".",
"search",
"(",
"r\"\\d\"",
",",
"r",
")",
"}",
"if",
"verbose",
":",
"print",
"(",
"\"discarding '%s', no digits\"",
"%",
"\",\"",
".",
"join",
"(",
"refs",
"-",
"tags",
")",
")",
"if",
"verbose",
":",
"print",
"(",
"\"likely tags: %s\"",
"%",
"\",\"",
".",
"join",
"(",
"sorted",
"(",
"tags",
")",
")",
")",
"for",
"ref",
"in",
"sorted",
"(",
"tags",
")",
":",
"# sorting will prefer e.g. \"2.0\" over \"2.0rc1\"",
"if",
"ref",
".",
"startswith",
"(",
"tag_prefix",
")",
":",
"r",
"=",
"ref",
"[",
"len",
"(",
"tag_prefix",
")",
":",
"]",
"if",
"verbose",
":",
"print",
"(",
"\"picking %s\"",
"%",
"r",
")",
"return",
"{",
"\"version\"",
":",
"r",
",",
"\"full-revisionid\"",
":",
"keywords",
"[",
"\"full\"",
"]",
".",
"strip",
"(",
")",
",",
"\"dirty\"",
":",
"False",
",",
"\"error\"",
":",
"None",
",",
"\"date\"",
":",
"date",
",",
"}",
"# no suitable tags, so version is \"0+unknown\", but full hex is still there",
"if",
"verbose",
":",
"print",
"(",
"\"no suitable tags, using unknown + full revision id\"",
")",
"return",
"{",
"\"version\"",
":",
"\"0+unknown\"",
",",
"\"full-revisionid\"",
":",
"keywords",
"[",
"\"full\"",
"]",
".",
"strip",
"(",
")",
",",
"\"dirty\"",
":",
"False",
",",
"\"error\"",
":",
"\"no suitable tags\"",
",",
"\"date\"",
":",
"None",
",",
"}"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/_version.py#L173-L231 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/dateutil/tz/tz.py | python | tzfile._set_tzdata | (self, tzobj) | Set the time zone data of this object from a _tzfile object | Set the time zone data of this object from a _tzfile object | [
"Set",
"the",
"time",
"zone",
"data",
"of",
"this",
"object",
"from",
"a",
"_tzfile",
"object"
] | def _set_tzdata(self, tzobj):
""" Set the time zone data of this object from a _tzfile object """
# Copy the relevant attributes over as private attributes
for attr in _tzfile.attrs:
setattr(self, '_' + attr, getattr(tzobj, attr)) | [
"def",
"_set_tzdata",
"(",
"self",
",",
"tzobj",
")",
":",
"# Copy the relevant attributes over as private attributes",
"for",
"attr",
"in",
"_tzfile",
".",
"attrs",
":",
"setattr",
"(",
"self",
",",
"'_'",
"+",
"attr",
",",
"getattr",
"(",
"tzobj",
",",
"attr",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/dateutil/tz/tz.py#L482-L486 | ||
ucsb-seclab/difuze | bb59a12ff87ad5ae45d9c60e349891bf80d72877 | helper_scripts/components/parse_headers.py | python | ParseHeaders.get_name | (self) | return "ParseHeaders" | get component name.
:return: Str | get component name.
:return: Str | [
"get",
"component",
"name",
".",
":",
"return",
":",
"Str"
] | def get_name(self):
"""
get component name.
:return: Str
"""
return "ParseHeaders" | [
"def",
"get_name",
"(",
"self",
")",
":",
"return",
"\"ParseHeaders\""
] | https://github.com/ucsb-seclab/difuze/blob/bb59a12ff87ad5ae45d9c60e349891bf80d72877/helper_scripts/components/parse_headers.py#L76-L81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.