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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/gpu_util.py | python | compute_capability_from_device_desc | (device_attrs) | return GpuInfo(match.group(1), cc) | Returns the GpuInfo given a DeviceAttributes proto.
Args:
device_attrs: A DeviceAttributes proto.
Returns
A gpu_info tuple. Both fields are None if `device_attrs` does not have a
valid physical_device_desc field. | Returns the GpuInfo given a DeviceAttributes proto. | [
"Returns",
"the",
"GpuInfo",
"given",
"a",
"DeviceAttributes",
"proto",
"."
] | def compute_capability_from_device_desc(device_attrs):
"""Returns the GpuInfo given a DeviceAttributes proto.
Args:
device_attrs: A DeviceAttributes proto.
Returns
A gpu_info tuple. Both fields are None if `device_attrs` does not have a
valid physical_device_desc field.
"""
# TODO(jingyue): The device description generator has to be in sync with
# this file. Another option is to put compute capability in
# DeviceAttributes, but I avoided that to keep DeviceAttributes
# target-independent. Reconsider this option when we have more things like
# this to keep in sync.
# LINT.IfChange
match = _PHYSICAL_DEVICE_DESCRIPTION_REGEX.search(
device_attrs.physical_device_desc)
# LINT.ThenChange(//tensorflow/core/common_runtime/gpu/gpu_device.cc)
if not match:
return GpuInfo(None, None)
cc = (int(match.group(2)), int(match.group(3))) if match.group(2) else None
return GpuInfo(match.group(1), cc) | [
"def",
"compute_capability_from_device_desc",
"(",
"device_attrs",
")",
":",
"# TODO(jingyue): The device description generator has to be in sync with",
"# this file. Another option is to put compute capability in",
"# DeviceAttributes, but I avoided that to keep DeviceAttributes",
"# target-independent. Reconsider this option when we have more things like",
"# this to keep in sync.",
"# LINT.IfChange",
"match",
"=",
"_PHYSICAL_DEVICE_DESCRIPTION_REGEX",
".",
"search",
"(",
"device_attrs",
".",
"physical_device_desc",
")",
"# LINT.ThenChange(//tensorflow/core/common_runtime/gpu/gpu_device.cc)",
"if",
"not",
"match",
":",
"return",
"GpuInfo",
"(",
"None",
",",
"None",
")",
"cc",
"=",
"(",
"int",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
",",
"int",
"(",
"match",
".",
"group",
"(",
"3",
")",
")",
")",
"if",
"match",
".",
"group",
"(",
"2",
")",
"else",
"None",
"return",
"GpuInfo",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"cc",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/gpu_util.py#L31-L53 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.DelLineRight | (*args, **kwargs) | return _stc.StyledTextCtrl_DelLineRight(*args, **kwargs) | DelLineRight(self)
Delete forwards from the current position to the end of the line. | DelLineRight(self) | [
"DelLineRight",
"(",
"self",
")"
] | def DelLineRight(*args, **kwargs):
"""
DelLineRight(self)
Delete forwards from the current position to the end of the line.
"""
return _stc.StyledTextCtrl_DelLineRight(*args, **kwargs) | [
"def",
"DelLineRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_DelLineRight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L5154-L5160 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py | python | PartitionedVariable._concat | (self) | Returns the overall concatenated value as a `Tensor`.
This is different from using the partitioned variable directly as a tensor
(through tensor conversion and `as_tensor`) in that it creates a new set of
operations that keeps the control dependencies from its scope.
Returns:
`Tensor` containing the concatenated value. | Returns the overall concatenated value as a `Tensor`. | [
"Returns",
"the",
"overall",
"concatenated",
"value",
"as",
"a",
"Tensor",
"."
] | def _concat(self):
"""Returns the overall concatenated value as a `Tensor`.
This is different from using the partitioned variable directly as a tensor
(through tensor conversion and `as_tensor`) in that it creates a new set of
operations that keeps the control dependencies from its scope.
Returns:
`Tensor` containing the concatenated value.
"""
if len(self._variable_list) == 1:
with ops.name_scope(None):
return array_ops.identity(self._variable_list[0], name=self._name)
partition_axes = self._partition_axes()
if len(partition_axes) > 1:
raise NotImplementedError(
"Cannot concatenate along more than one dimension: %s. "
"Multi-axis partition concat is not supported" % str(partition_axes))
partition_ix = partition_axes[0]
with ops.name_scope(self._name + "/ConcatPartitions/"):
concatenated = array_ops.concat(self._variable_list, partition_ix)
with ops.name_scope(None):
return array_ops.identity(concatenated, name=self._name) | [
"def",
"_concat",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_variable_list",
")",
"==",
"1",
":",
"with",
"ops",
".",
"name_scope",
"(",
"None",
")",
":",
"return",
"array_ops",
".",
"identity",
"(",
"self",
".",
"_variable_list",
"[",
"0",
"]",
",",
"name",
"=",
"self",
".",
"_name",
")",
"partition_axes",
"=",
"self",
".",
"_partition_axes",
"(",
")",
"if",
"len",
"(",
"partition_axes",
")",
">",
"1",
":",
"raise",
"NotImplementedError",
"(",
"\"Cannot concatenate along more than one dimension: %s. \"",
"\"Multi-axis partition concat is not supported\"",
"%",
"str",
"(",
"partition_axes",
")",
")",
"partition_ix",
"=",
"partition_axes",
"[",
"0",
"]",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"_name",
"+",
"\"/ConcatPartitions/\"",
")",
":",
"concatenated",
"=",
"array_ops",
".",
"concat",
"(",
"self",
".",
"_variable_list",
",",
"partition_ix",
")",
"with",
"ops",
".",
"name_scope",
"(",
"None",
")",
":",
"return",
"array_ops",
".",
"identity",
"(",
"concatenated",
",",
"name",
"=",
"self",
".",
"_name",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py#L2915-L2941 | ||
ianmaclarty/amulet | 3d1363e0a0dde5e4c346409cefab66c2dc91b237 | third_party/freetype-2.5.5/src/tools/glnames.py | python | dump_array | ( the_array, write, array_name ) | dumps a given encoding | dumps a given encoding | [
"dumps",
"a",
"given",
"encoding"
] | def dump_array( the_array, write, array_name ):
"""dumps a given encoding"""
write( " static const unsigned char " + array_name +
"[" + repr( len( the_array ) ) + "L] =\n" )
write( " {\n" )
line = ""
comma = " "
col = 0
for value in the_array:
line += comma
line += "%3d" % ord( value )
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
if len( line ) > 1024:
write( line )
line = ""
write( line + "\n };\n\n\n" ) | [
"def",
"dump_array",
"(",
"the_array",
",",
"write",
",",
"array_name",
")",
":",
"write",
"(",
"\" static const unsigned char \"",
"+",
"array_name",
"+",
"\"[\"",
"+",
"repr",
"(",
"len",
"(",
"the_array",
")",
")",
"+",
"\"L] =\\n\"",
")",
"write",
"(",
"\" {\\n\"",
")",
"line",
"=",
"\"\"",
"comma",
"=",
"\" \"",
"col",
"=",
"0",
"for",
"value",
"in",
"the_array",
":",
"line",
"+=",
"comma",
"line",
"+=",
"\"%3d\"",
"%",
"ord",
"(",
"value",
")",
"comma",
"=",
"\",\"",
"col",
"+=",
"1",
"if",
"col",
"==",
"16",
":",
"col",
"=",
"0",
"comma",
"=",
"\",\\n \"",
"if",
"len",
"(",
"line",
")",
">",
"1024",
":",
"write",
"(",
"line",
")",
"line",
"=",
"\"\"",
"write",
"(",
"line",
"+",
"\"\\n };\\n\\n\\n\"",
")"
] | https://github.com/ianmaclarty/amulet/blob/3d1363e0a0dde5e4c346409cefab66c2dc91b237/third_party/freetype-2.5.5/src/tools/glnames.py#L5210-L5235 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/quantization/quantize.py | python | disable_fake_quant | (module: Module) | r"""Recursively disable ``module`` fake quantization in QATModule through :meth:`~.Module.apply`
Args:
module: root module to do disable fake quantization recursively. | r"""Recursively disable ``module`` fake quantization in QATModule through :meth:`~.Module.apply` | [
"r",
"Recursively",
"disable",
"module",
"fake",
"quantization",
"in",
"QATModule",
"through",
":",
"meth",
":",
"~",
".",
"Module",
".",
"apply"
] | def disable_fake_quant(module: Module):
r"""Recursively disable ``module`` fake quantization in QATModule through :meth:`~.Module.apply`
Args:
module: root module to do disable fake quantization recursively.
"""
_propagate(module, "set_fake_quant", False) | [
"def",
"disable_fake_quant",
"(",
"module",
":",
"Module",
")",
":",
"_propagate",
"(",
"module",
",",
"\"set_fake_quant\"",
",",
"False",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/quantization/quantize.py#L268-L275 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_carbon/gizmos.py | python | LEDNumberCtrl.SetAlignment | (*args, **kwargs) | return _gizmos.LEDNumberCtrl_SetAlignment(*args, **kwargs) | SetAlignment(self, int Alignment, bool Redraw=True) | SetAlignment(self, int Alignment, bool Redraw=True) | [
"SetAlignment",
"(",
"self",
"int",
"Alignment",
"bool",
"Redraw",
"=",
"True",
")"
] | def SetAlignment(*args, **kwargs):
"""SetAlignment(self, int Alignment, bool Redraw=True)"""
return _gizmos.LEDNumberCtrl_SetAlignment(*args, **kwargs) | [
"def",
"SetAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"LEDNumberCtrl_SetAlignment",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L338-L340 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/fcompiler/__init__.py | python | get_default_fcompiler | (osname=None, platform=None, requiref90=False,
c_compiler=None) | return compiler_type | Determine the default Fortran compiler to use for the given
platform. | Determine the default Fortran compiler to use for the given
platform. | [
"Determine",
"the",
"default",
"Fortran",
"compiler",
"to",
"use",
"for",
"the",
"given",
"platform",
"."
] | def get_default_fcompiler(osname=None, platform=None, requiref90=False,
c_compiler=None):
"""Determine the default Fortran compiler to use for the given
platform."""
matching_compiler_types = available_fcompilers_for_platform(osname,
platform)
log.info("get_default_fcompiler: matching types: '%s'",
matching_compiler_types)
compiler_type = _find_existing_fcompiler(matching_compiler_types,
osname=osname,
platform=platform,
requiref90=requiref90,
c_compiler=c_compiler)
return compiler_type | [
"def",
"get_default_fcompiler",
"(",
"osname",
"=",
"None",
",",
"platform",
"=",
"None",
",",
"requiref90",
"=",
"False",
",",
"c_compiler",
"=",
"None",
")",
":",
"matching_compiler_types",
"=",
"available_fcompilers_for_platform",
"(",
"osname",
",",
"platform",
")",
"log",
".",
"info",
"(",
"\"get_default_fcompiler: matching types: '%s'\"",
",",
"matching_compiler_types",
")",
"compiler_type",
"=",
"_find_existing_fcompiler",
"(",
"matching_compiler_types",
",",
"osname",
"=",
"osname",
",",
"platform",
"=",
"platform",
",",
"requiref90",
"=",
"requiref90",
",",
"c_compiler",
"=",
"c_compiler",
")",
"return",
"compiler_type"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/fcompiler/__init__.py#L847-L860 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | TopLevelWindow.ShowFullScreen | (*args, **kwargs) | return _windows_.TopLevelWindow_ShowFullScreen(*args, **kwargs) | ShowFullScreen(self, bool show, long style=FULLSCREEN_ALL) -> bool | ShowFullScreen(self, bool show, long style=FULLSCREEN_ALL) -> bool | [
"ShowFullScreen",
"(",
"self",
"bool",
"show",
"long",
"style",
"=",
"FULLSCREEN_ALL",
")",
"-",
">",
"bool"
] | def ShowFullScreen(*args, **kwargs):
"""ShowFullScreen(self, bool show, long style=FULLSCREEN_ALL) -> bool"""
return _windows_.TopLevelWindow_ShowFullScreen(*args, **kwargs) | [
"def",
"ShowFullScreen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"TopLevelWindow_ShowFullScreen",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L441-L443 | |
ErLinErYi/PlantsVsZombies | 3a61d9dd4ffb65749a92c4f785315f79077b8555 | PlantsVsZombies/cocos2d/plugin/tools/pluginx-bindings-generator/genbindings-lua.py | python | _check_ndk_root_env | () | return NDK_ROOT | Checking the environment NDK_ROOT, which will be used for building | Checking the environment NDK_ROOT, which will be used for building | [
"Checking",
"the",
"environment",
"NDK_ROOT",
"which",
"will",
"be",
"used",
"for",
"building"
] | def _check_ndk_root_env():
''' Checking the environment NDK_ROOT, which will be used for building
'''
try:
NDK_ROOT = os.environ['NDK_ROOT']
except Exception:
print "NDK_ROOT not defined. Please define NDK_ROOT in your environment."
sys.exit(1)
return NDK_ROOT | [
"def",
"_check_ndk_root_env",
"(",
")",
":",
"try",
":",
"NDK_ROOT",
"=",
"os",
".",
"environ",
"[",
"'NDK_ROOT'",
"]",
"except",
"Exception",
":",
"print",
"\"NDK_ROOT not defined. Please define NDK_ROOT in your environment.\"",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"NDK_ROOT"
] | https://github.com/ErLinErYi/PlantsVsZombies/blob/3a61d9dd4ffb65749a92c4f785315f79077b8555/PlantsVsZombies/cocos2d/plugin/tools/pluginx-bindings-generator/genbindings-lua.py#L19-L29 | |
ros-planning/moveit | ee48dc5cedc981d0869352aa3db0b41469c2735c | moveit_commander/src/moveit_commander/move_group.py | python | MoveGroupCommander.get_interface_description | (self) | return desc | Get the description of the planner interface (list of planner ids) | Get the description of the planner interface (list of planner ids) | [
"Get",
"the",
"description",
"of",
"the",
"planner",
"interface",
"(",
"list",
"of",
"planner",
"ids",
")"
] | def get_interface_description(self):
""" Get the description of the planner interface (list of planner ids) """
desc = PlannerInterfaceDescription()
conversions.msg_from_string(desc, self._g.get_interface_description())
return desc | [
"def",
"get_interface_description",
"(",
"self",
")",
":",
"desc",
"=",
"PlannerInterfaceDescription",
"(",
")",
"conversions",
".",
"msg_from_string",
"(",
"desc",
",",
"self",
".",
"_g",
".",
"get_interface_description",
"(",
")",
")",
"return",
"desc"
] | https://github.com/ros-planning/moveit/blob/ee48dc5cedc981d0869352aa3db0b41469c2735c/moveit_commander/src/moveit_commander/move_group.py#L103-L107 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/util/_cloudpickle/_cloudpickle_py27.py | python | _rehydrate_skeleton_class | (skeleton_class, class_dict) | return skeleton_class | Put attributes from `class_dict` back on `skeleton_class`.
See CloudPickler.save_dynamic_class for more info. | Put attributes from `class_dict` back on `skeleton_class`. | [
"Put",
"attributes",
"from",
"class_dict",
"back",
"on",
"skeleton_class",
"."
] | def _rehydrate_skeleton_class(skeleton_class, class_dict):
"""Put attributes from `class_dict` back on `skeleton_class`.
See CloudPickler.save_dynamic_class for more info.
"""
for attrname, attr in class_dict.items():
setattr(skeleton_class, attrname, attr)
return skeleton_class | [
"def",
"_rehydrate_skeleton_class",
"(",
"skeleton_class",
",",
"class_dict",
")",
":",
"for",
"attrname",
",",
"attr",
"in",
"class_dict",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"skeleton_class",
",",
"attrname",
",",
"attr",
")",
"return",
"skeleton_class"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/util/_cloudpickle/_cloudpickle_py27.py#L1219-L1226 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/summary/text_summary.py | python | text_summary | (name, tensor, collections=None) | return t_summary | Summarizes textual data.
Text data summarized via this plugin will be visible in the Text Dashboard
in TensorBoard. The standard TensorBoard Text Dashboard will render markdown
in the strings, and will automatically organize 1d and 2d tensors into tables.
If a tensor with more than 2 dimensions is provided, a 2d subarray will be
displayed along with a warning message. (Note that this behavior is not
intrinsic to the text summary api, but rather to the default TensorBoard text
plugin.)
Args:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
tensor: a string-type Tensor to summarize.
collections: Optional list of ops.GraphKeys. The collections to add the
summary to. Defaults to [_ops.GraphKeys.SUMMARIES]
Returns:
A TensorSummary op that is configured so that TensorBoard will recognize
that it contains textual data. The TensorSummary is a scalar `Tensor` of
type `string` which contains `Summary` protobufs.
Raises:
ValueError: If tensor has the wrong type. | Summarizes textual data. | [
"Summarizes",
"textual",
"data",
"."
] | def text_summary(name, tensor, collections=None):
"""Summarizes textual data.
Text data summarized via this plugin will be visible in the Text Dashboard
in TensorBoard. The standard TensorBoard Text Dashboard will render markdown
in the strings, and will automatically organize 1d and 2d tensors into tables.
If a tensor with more than 2 dimensions is provided, a 2d subarray will be
displayed along with a warning message. (Note that this behavior is not
intrinsic to the text summary api, but rather to the default TensorBoard text
plugin.)
Args:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
tensor: a string-type Tensor to summarize.
collections: Optional list of ops.GraphKeys. The collections to add the
summary to. Defaults to [_ops.GraphKeys.SUMMARIES]
Returns:
A TensorSummary op that is configured so that TensorBoard will recognize
that it contains textual data. The TensorSummary is a scalar `Tensor` of
type `string` which contains `Summary` protobufs.
Raises:
ValueError: If tensor has the wrong type.
"""
if tensor.dtype != dtypes.string:
raise ValueError("Expected tensor %s to have dtype string, got %s" %
(tensor.name, tensor.dtype))
summary_metadata = summary_pb2.SummaryMetadata()
text_plugin_data = _TextPluginData()
data_dict = text_plugin_data._asdict() # pylint: disable=protected-access
summary_metadata.plugin_data.add(
plugin_name=PLUGIN_NAME, content=json.dumps(data_dict))
t_summary = tensor_summary(
name=name,
tensor=tensor,
summary_metadata=summary_metadata,
collections=collections)
return t_summary | [
"def",
"text_summary",
"(",
"name",
",",
"tensor",
",",
"collections",
"=",
"None",
")",
":",
"if",
"tensor",
".",
"dtype",
"!=",
"dtypes",
".",
"string",
":",
"raise",
"ValueError",
"(",
"\"Expected tensor %s to have dtype string, got %s\"",
"%",
"(",
"tensor",
".",
"name",
",",
"tensor",
".",
"dtype",
")",
")",
"summary_metadata",
"=",
"summary_pb2",
".",
"SummaryMetadata",
"(",
")",
"text_plugin_data",
"=",
"_TextPluginData",
"(",
")",
"data_dict",
"=",
"text_plugin_data",
".",
"_asdict",
"(",
")",
"# pylint: disable=protected-access",
"summary_metadata",
".",
"plugin_data",
".",
"add",
"(",
"plugin_name",
"=",
"PLUGIN_NAME",
",",
"content",
"=",
"json",
".",
"dumps",
"(",
"data_dict",
")",
")",
"t_summary",
"=",
"tensor_summary",
"(",
"name",
"=",
"name",
",",
"tensor",
"=",
"tensor",
",",
"summary_metadata",
"=",
"summary_metadata",
",",
"collections",
"=",
"collections",
")",
"return",
"t_summary"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/summary/text_summary.py#L40-L80 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/polynomial/legendre.py | python | legvander | (x, deg) | return np.moveaxis(v, 0, -1) | Pseudo-Vandermonde matrix of given degree.
Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
`x`. The pseudo-Vandermonde matrix is defined by
.. math:: V[..., i] = L_i(x)
where `0 <= i <= deg`. The leading indices of `V` index the elements of
`x` and the last index is the degree of the Legendre polynomial.
If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
array ``V = legvander(x, n)``, then ``np.dot(V, c)`` and
``legval(x, c)`` are the same up to roundoff. This equivalence is
useful both for least squares fitting and for the evaluation of a large
number of Legendre series of the same degree and sample points.
Parameters
----------
x : array_like
Array of points. The dtype is converted to float64 or complex128
depending on whether any of the elements are complex. If `x` is
scalar it is converted to a 1-D array.
deg : int
Degree of the resulting matrix.
Returns
-------
vander : ndarray
The pseudo-Vandermonde matrix. The shape of the returned matrix is
``x.shape + (deg + 1,)``, where The last index is the degree of the
corresponding Legendre polynomial. The dtype will be the same as
the converted `x`. | Pseudo-Vandermonde matrix of given degree. | [
"Pseudo",
"-",
"Vandermonde",
"matrix",
"of",
"given",
"degree",
"."
] | def legvander(x, deg):
"""Pseudo-Vandermonde matrix of given degree.
Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
`x`. The pseudo-Vandermonde matrix is defined by
.. math:: V[..., i] = L_i(x)
where `0 <= i <= deg`. The leading indices of `V` index the elements of
`x` and the last index is the degree of the Legendre polynomial.
If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
array ``V = legvander(x, n)``, then ``np.dot(V, c)`` and
``legval(x, c)`` are the same up to roundoff. This equivalence is
useful both for least squares fitting and for the evaluation of a large
number of Legendre series of the same degree and sample points.
Parameters
----------
x : array_like
Array of points. The dtype is converted to float64 or complex128
depending on whether any of the elements are complex. If `x` is
scalar it is converted to a 1-D array.
deg : int
Degree of the resulting matrix.
Returns
-------
vander : ndarray
The pseudo-Vandermonde matrix. The shape of the returned matrix is
``x.shape + (deg + 1,)``, where The last index is the degree of the
corresponding Legendre polynomial. The dtype will be the same as
the converted `x`.
"""
ideg = int(deg)
if ideg != deg:
raise ValueError("deg must be integer")
if ideg < 0:
raise ValueError("deg must be non-negative")
x = np.array(x, copy=0, ndmin=1) + 0.0
dims = (ideg + 1,) + x.shape
dtyp = x.dtype
v = np.empty(dims, dtype=dtyp)
# Use forward recursion to generate the entries. This is not as accurate
# as reverse recursion in this application but it is more efficient.
v[0] = x*0 + 1
if ideg > 0:
v[1] = x
for i in range(2, ideg + 1):
v[i] = (v[i-1]*x*(2*i - 1) - v[i-2]*(i - 1))/i
return np.moveaxis(v, 0, -1) | [
"def",
"legvander",
"(",
"x",
",",
"deg",
")",
":",
"ideg",
"=",
"int",
"(",
"deg",
")",
"if",
"ideg",
"!=",
"deg",
":",
"raise",
"ValueError",
"(",
"\"deg must be integer\"",
")",
"if",
"ideg",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"deg must be non-negative\"",
")",
"x",
"=",
"np",
".",
"array",
"(",
"x",
",",
"copy",
"=",
"0",
",",
"ndmin",
"=",
"1",
")",
"+",
"0.0",
"dims",
"=",
"(",
"ideg",
"+",
"1",
",",
")",
"+",
"x",
".",
"shape",
"dtyp",
"=",
"x",
".",
"dtype",
"v",
"=",
"np",
".",
"empty",
"(",
"dims",
",",
"dtype",
"=",
"dtyp",
")",
"# Use forward recursion to generate the entries. This is not as accurate",
"# as reverse recursion in this application but it is more efficient.",
"v",
"[",
"0",
"]",
"=",
"x",
"*",
"0",
"+",
"1",
"if",
"ideg",
">",
"0",
":",
"v",
"[",
"1",
"]",
"=",
"x",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"ideg",
"+",
"1",
")",
":",
"v",
"[",
"i",
"]",
"=",
"(",
"v",
"[",
"i",
"-",
"1",
"]",
"*",
"x",
"*",
"(",
"2",
"*",
"i",
"-",
"1",
")",
"-",
"v",
"[",
"i",
"-",
"2",
"]",
"*",
"(",
"i",
"-",
"1",
")",
")",
"/",
"i",
"return",
"np",
".",
"moveaxis",
"(",
"v",
",",
"0",
",",
"-",
"1",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/legendre.py#L1224-L1276 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py | python | _MergedKeyBindings._update_cache | (self) | If one of the original registries was changed. Update our merged
version. | If one of the original registries was changed. Update our merged
version. | [
"If",
"one",
"of",
"the",
"original",
"registries",
"was",
"changed",
".",
"Update",
"our",
"merged",
"version",
"."
] | def _update_cache(self) -> None:
"""
If one of the original registries was changed. Update our merged
version.
"""
expected_version = tuple(r._version for r in self.registries)
if self._last_version != expected_version:
bindings2 = KeyBindings()
for reg in self.registries:
bindings2.bindings.extend(reg.bindings)
self._bindings2 = bindings2
self._last_version = expected_version | [
"def",
"_update_cache",
"(",
"self",
")",
"->",
"None",
":",
"expected_version",
"=",
"tuple",
"(",
"r",
".",
"_version",
"for",
"r",
"in",
"self",
".",
"registries",
")",
"if",
"self",
".",
"_last_version",
"!=",
"expected_version",
":",
"bindings2",
"=",
"KeyBindings",
"(",
")",
"for",
"reg",
"in",
"self",
".",
"registries",
":",
"bindings2",
".",
"bindings",
".",
"extend",
"(",
"reg",
".",
"bindings",
")",
"self",
".",
"_bindings2",
"=",
"bindings2",
"self",
".",
"_last_version",
"=",
"expected_version"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py#L595-L609 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/sndhdr.py | python | whathdr | (filename) | return None | Recognize sound headers | Recognize sound headers | [
"Recognize",
"sound",
"headers"
] | def whathdr(filename):
"""Recognize sound headers"""
f = open(filename, 'rb')
h = f.read(512)
for tf in tests:
res = tf(h, f)
if res:
return res
return None | [
"def",
"whathdr",
"(",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"h",
"=",
"f",
".",
"read",
"(",
"512",
")",
"for",
"tf",
"in",
"tests",
":",
"res",
"=",
"tf",
"(",
"h",
",",
"f",
")",
"if",
"res",
":",
"return",
"res",
"return",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/sndhdr.py#L41-L49 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_impl.py | python | swish | (features) | return features * math_ops.sigmoid(features), grad | Computes the Swish activation function: `x * sigmoid(x)`.
Source: "Searching for Activation Functions" (Ramachandran et al. 2017)
https://arxiv.org/abs/1710.05941
Args:
features: A `Tensor` representing preactivation values.
name: A name for the operation (optional).
Returns:
The activation value. | Computes the Swish activation function: `x * sigmoid(x)`. | [
"Computes",
"the",
"Swish",
"activation",
"function",
":",
"x",
"*",
"sigmoid",
"(",
"x",
")",
"."
] | def swish(features):
# pylint: disable=g-doc-args
"""Computes the Swish activation function: `x * sigmoid(x)`.
Source: "Searching for Activation Functions" (Ramachandran et al. 2017)
https://arxiv.org/abs/1710.05941
Args:
features: A `Tensor` representing preactivation values.
name: A name for the operation (optional).
Returns:
The activation value.
"""
# pylint: enable=g-doc-args
features = ops.convert_to_tensor(features, name="features")
def grad(dy):
"""Gradient for the Swish activation function"""
# Naively, x * tf.nn.sigmoid(x) requires keeping both x and sigmoid(x)
# around for backprop, effectively doubling the tensor's memory consumption.
# We use a control dependency here so that sigmoid(features) is re-computed
# during backprop (the control dep prevents it being de-duped with the
# forward pass) and we can free the sigmoid(features) expression immediately
# after use during the forward pass.
with ops.control_dependencies([dy]):
sigmoid_features = math_ops.sigmoid(features)
activation_grad = (
sigmoid_features * (1.0 + features * (1.0 - sigmoid_features)))
return dy * activation_grad
return features * math_ops.sigmoid(features), grad | [
"def",
"swish",
"(",
"features",
")",
":",
"# pylint: disable=g-doc-args",
"# pylint: enable=g-doc-args",
"features",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"features",
",",
"name",
"=",
"\"features\"",
")",
"def",
"grad",
"(",
"dy",
")",
":",
"\"\"\"Gradient for the Swish activation function\"\"\"",
"# Naively, x * tf.nn.sigmoid(x) requires keeping both x and sigmoid(x)",
"# around for backprop, effectively doubling the tensor's memory consumption.",
"# We use a control dependency here so that sigmoid(features) is re-computed",
"# during backprop (the control dep prevents it being de-duped with the",
"# forward pass) and we can free the sigmoid(features) expression immediately",
"# after use during the forward pass.",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"dy",
"]",
")",
":",
"sigmoid_features",
"=",
"math_ops",
".",
"sigmoid",
"(",
"features",
")",
"activation_grad",
"=",
"(",
"sigmoid_features",
"*",
"(",
"1.0",
"+",
"features",
"*",
"(",
"1.0",
"-",
"sigmoid_features",
")",
")",
")",
"return",
"dy",
"*",
"activation_grad",
"return",
"features",
"*",
"math_ops",
".",
"sigmoid",
"(",
"features",
")",
",",
"grad"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_impl.py#L504-L535 | |
nest/nest-simulator | f2623eb78518cdbd55e77e0ed486bf1111bcb62f | pynest/nest/lib/hl_api_helper.py | python | get_help_fname | (obj) | Get file name for help object
Raises FileNotFound if no help is available for ``obj``.
Parameters
----------
obj : string
Object to get help filename for
Returns
-------
string:
File name of the help text for obj | Get file name for help object | [
"Get",
"file",
"name",
"for",
"help",
"object"
] | def get_help_fname(obj):
"""Get file name for help object
Raises FileNotFound if no help is available for ``obj``.
Parameters
----------
obj : string
Object to get help filename for
Returns
-------
string:
File name of the help text for obj
"""
docdir = sli_func("statusdict/prgdocdir ::")
help_fname = os.path.join(docdir, 'html', 'models', f'{obj}.rst')
if os.path.isfile(help_fname):
return help_fname
else:
raise FileNotFoundError(f"Sorry, there is no help for '{obj}'.") | [
"def",
"get_help_fname",
"(",
"obj",
")",
":",
"docdir",
"=",
"sli_func",
"(",
"\"statusdict/prgdocdir ::\"",
")",
"help_fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"docdir",
",",
"'html'",
",",
"'models'",
",",
"f'{obj}.rst'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"help_fname",
")",
":",
"return",
"help_fname",
"else",
":",
"raise",
"FileNotFoundError",
"(",
"f\"Sorry, there is no help for '{obj}'.\"",
")"
] | https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/lib/hl_api_helper.py#L369-L391 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py | python | cram | (text, maxlen) | return text | Omit part of a string if needed to make it fit in a maximum length. | Omit part of a string if needed to make it fit in a maximum length. | [
"Omit",
"part",
"of",
"a",
"string",
"if",
"needed",
"to",
"make",
"it",
"fit",
"in",
"a",
"maximum",
"length",
"."
] | def cram(text, maxlen):
"""Omit part of a string if needed to make it fit in a maximum length."""
if len(text) > maxlen:
pre = max(0, (maxlen-3)//2)
post = max(0, maxlen-3-pre)
return text[:pre] + '...' + text[len(text)-post:]
return text | [
"def",
"cram",
"(",
"text",
",",
"maxlen",
")",
":",
"if",
"len",
"(",
"text",
")",
">",
"maxlen",
":",
"pre",
"=",
"max",
"(",
"0",
",",
"(",
"maxlen",
"-",
"3",
")",
"//",
"2",
")",
"post",
"=",
"max",
"(",
"0",
",",
"maxlen",
"-",
"3",
"-",
"pre",
")",
"return",
"text",
"[",
":",
"pre",
"]",
"+",
"'...'",
"+",
"text",
"[",
"len",
"(",
"text",
")",
"-",
"post",
":",
"]",
"return",
"text"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py#L127-L133 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/segmentbk.py | python | SegmentBook.CurrentPage | (self) | Get the currently selected page
@return: wxWindow or None | Get the currently selected page
@return: wxWindow or None | [
"Get",
"the",
"currently",
"selected",
"page",
"@return",
":",
"wxWindow",
"or",
"None"
] | def CurrentPage(self):
"""Get the currently selected page
@return: wxWindow or None
"""
idx = self._segbar.GetSelection()
if idx != -1:
return self._pages[idx]['page']
else:
return None | [
"def",
"CurrentPage",
"(",
"self",
")",
":",
"idx",
"=",
"self",
".",
"_segbar",
".",
"GetSelection",
"(",
")",
"if",
"idx",
"!=",
"-",
"1",
":",
"return",
"self",
".",
"_pages",
"[",
"idx",
"]",
"[",
"'page'",
"]",
"else",
":",
"return",
"None"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/segmentbk.py#L264-L273 | ||
CGRU/cgru | 1881a4128530e3d31ac6c25314c18314fc50c2c7 | plugins/maya/afanasy/maya_ui_proc.py | python | getDefaultStrValue | (self_prefix, name, value) | return ret | getDefaultStrValue
:param self_prefix:
:param name:
:param value:
:return: | getDefaultStrValue | [
"getDefaultStrValue"
] | def getDefaultStrValue(self_prefix, name, value):
"""getDefaultStrValue
:param self_prefix:
:param name:
:param value:
:return:
"""
var_name = self_prefix + name
if cmds.optionVar(exists=var_name) == 1:
ret = cmds.optionVar(q=var_name)
else:
cmds.optionVar(sv=(var_name, value))
ret = value
return ret | [
"def",
"getDefaultStrValue",
"(",
"self_prefix",
",",
"name",
",",
"value",
")",
":",
"var_name",
"=",
"self_prefix",
"+",
"name",
"if",
"cmds",
".",
"optionVar",
"(",
"exists",
"=",
"var_name",
")",
"==",
"1",
":",
"ret",
"=",
"cmds",
".",
"optionVar",
"(",
"q",
"=",
"var_name",
")",
"else",
":",
"cmds",
".",
"optionVar",
"(",
"sv",
"=",
"(",
"var_name",
",",
"value",
")",
")",
"ret",
"=",
"value",
"return",
"ret"
] | https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/plugins/maya/afanasy/maya_ui_proc.py#L34-L48 | |
nnrg/opennero | 43e12a1bcba6e228639db3886fec1dc47ddc24cb | mods/Roomba/module.py | python | SandboxMod.mark | (self, x, y, marker) | Mark a position (x, y) with the specified color | Mark a position (x, y) with the specified color | [
"Mark",
"a",
"position",
"(",
"x",
"y",
")",
"with",
"the",
"specified",
"color"
] | def mark(self, x, y, marker):
""" Mark a position (x, y) with the specified color """
# remove the previous object, if necessary
self.unmark(x, y)
# add a new marker object
id = common.addObject(marker, OpenNero.Vector3f(x, y, -1), OpenNero.Vector3f(0,0,0), OpenNero.Vector3f(0.5,0.5,0.5), type = constants.OBJECT_TYPE_MARKER)
# remember the ID of the object we are about to create
self.marker_map[(x, y)] = id | [
"def",
"mark",
"(",
"self",
",",
"x",
",",
"y",
",",
"marker",
")",
":",
"# remove the previous object, if necessary",
"self",
".",
"unmark",
"(",
"x",
",",
"y",
")",
"# add a new marker object",
"id",
"=",
"common",
".",
"addObject",
"(",
"marker",
",",
"OpenNero",
".",
"Vector3f",
"(",
"x",
",",
"y",
",",
"-",
"1",
")",
",",
"OpenNero",
".",
"Vector3f",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"OpenNero",
".",
"Vector3f",
"(",
"0.5",
",",
"0.5",
",",
"0.5",
")",
",",
"type",
"=",
"constants",
".",
"OBJECT_TYPE_MARKER",
")",
"# remember the ID of the object we are about to create",
"self",
".",
"marker_map",
"[",
"(",
"x",
",",
"y",
")",
"]",
"=",
"id"
] | https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Roomba/module.py#L30-L37 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py | python | HTTPConnectionPool._make_request | (
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
) | return httplib_response | Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts. | [] | def _make_request(
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts.
"""
self.num_requests += 1
timeout_obj = self._get_timeout(timeout)
timeout_obj.start_connect()
conn.timeout = timeout_obj.connect_timeout
# Trigger any extra validation we need to do.
try:
self._validate_conn(conn)
except (SocketTimeout, BaseSSLError) as e:
# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
raise
# conn.request() calls http.client.*.request, not the method in
# urllib3.request. It also calls makefile (recv) on the socket.
try:
if chunked:
conn.request_chunked(method, url, **httplib_request_kw)
else:
conn.request(method, url, **httplib_request_kw)
# We are swallowing BrokenPipeError (errno.EPIPE) since the server is
# legitimately able to close the connection after sending a valid response.
# With this behaviour, the received response is still readable.
except BrokenPipeError:
# Python 3
pass
except IOError as e:
# Python 2 and macOS/Linux
# EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE is needed on macOS
# https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
if e.errno not in {
errno.EPIPE,
errno.ESHUTDOWN,
errno.EPROTOTYPE,
}:
raise
# Reset the timeout for the recv() on the socket
read_timeout = timeout_obj.read_timeout
# App Engine doesn't have a sock attr
if getattr(conn, "sock", None):
# In Python 3 socket.py will catch EAGAIN and return None when you
# try and read into the file pointer created by http.client, which
# instead raises a BadStatusLine exception. Instead of catching
# the exception and assuming all BadStatusLine exceptions are read
# timeouts, check for a zero timeout before making the request.
if read_timeout == 0:
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % read_timeout
)
if read_timeout is Timeout.DEFAULT_TIMEOUT:
conn.sock.settimeout(socket.getdefaulttimeout())
else: # None or a value
conn.sock.settimeout(read_timeout)
# Receive the response from the server
try:
try:
# Python 2.7, use buffering of HTTP responses
httplib_response = conn.getresponse(buffering=True)
except TypeError:
# Python 3
try:
httplib_response = conn.getresponse()
except BaseException as e:
# Remove the TypeError from the exception chain in
# Python 3 (including for exceptions like SystemExit).
# Otherwise it looks like a bug in the code.
six.raise_from(e, None)
except (SocketTimeout, BaseSSLError, SocketError) as e:
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
raise
# AppEngine doesn't have a version attr.
http_version = getattr(conn, "_http_vsn_str", "HTTP/?")
log.debug(
'%s://%s:%s "%s %s %s" %s %s',
self.scheme,
self.host,
self.port,
method,
url,
http_version,
httplib_response.status,
httplib_response.length,
)
try:
assert_header_parsing(httplib_response.msg)
except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3
log.warning(
"Failed to parse headers (url=%s): %s",
self._absolute_url(url),
hpe,
exc_info=True,
)
return httplib_response | [
"def",
"_make_request",
"(",
"self",
",",
"conn",
",",
"method",
",",
"url",
",",
"timeout",
"=",
"_Default",
",",
"chunked",
"=",
"False",
",",
"*",
"*",
"httplib_request_kw",
")",
":",
"self",
".",
"num_requests",
"+=",
"1",
"timeout_obj",
"=",
"self",
".",
"_get_timeout",
"(",
"timeout",
")",
"timeout_obj",
".",
"start_connect",
"(",
")",
"conn",
".",
"timeout",
"=",
"timeout_obj",
".",
"connect_timeout",
"# Trigger any extra validation we need to do.",
"try",
":",
"self",
".",
"_validate_conn",
"(",
"conn",
")",
"except",
"(",
"SocketTimeout",
",",
"BaseSSLError",
")",
"as",
"e",
":",
"# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.",
"self",
".",
"_raise_timeout",
"(",
"err",
"=",
"e",
",",
"url",
"=",
"url",
",",
"timeout_value",
"=",
"conn",
".",
"timeout",
")",
"raise",
"# conn.request() calls http.client.*.request, not the method in",
"# urllib3.request. It also calls makefile (recv) on the socket.",
"try",
":",
"if",
"chunked",
":",
"conn",
".",
"request_chunked",
"(",
"method",
",",
"url",
",",
"*",
"*",
"httplib_request_kw",
")",
"else",
":",
"conn",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"httplib_request_kw",
")",
"# We are swallowing BrokenPipeError (errno.EPIPE) since the server is",
"# legitimately able to close the connection after sending a valid response.",
"# With this behaviour, the received response is still readable.",
"except",
"BrokenPipeError",
":",
"# Python 3",
"pass",
"except",
"IOError",
"as",
"e",
":",
"# Python 2 and macOS/Linux",
"# EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE is needed on macOS",
"# https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/",
"if",
"e",
".",
"errno",
"not",
"in",
"{",
"errno",
".",
"EPIPE",
",",
"errno",
".",
"ESHUTDOWN",
",",
"errno",
".",
"EPROTOTYPE",
",",
"}",
":",
"raise",
"# Reset the timeout for the recv() on the socket",
"read_timeout",
"=",
"timeout_obj",
".",
"read_timeout",
"# App Engine doesn't have a sock attr",
"if",
"getattr",
"(",
"conn",
",",
"\"sock\"",
",",
"None",
")",
":",
"# In Python 3 socket.py will catch EAGAIN and return None when you",
"# try and read into the file pointer created by http.client, which",
"# instead raises a BadStatusLine exception. Instead of catching",
"# the exception and assuming all BadStatusLine exceptions are read",
"# timeouts, check for a zero timeout before making the request.",
"if",
"read_timeout",
"==",
"0",
":",
"raise",
"ReadTimeoutError",
"(",
"self",
",",
"url",
",",
"\"Read timed out. (read timeout=%s)\"",
"%",
"read_timeout",
")",
"if",
"read_timeout",
"is",
"Timeout",
".",
"DEFAULT_TIMEOUT",
":",
"conn",
".",
"sock",
".",
"settimeout",
"(",
"socket",
".",
"getdefaulttimeout",
"(",
")",
")",
"else",
":",
"# None or a value",
"conn",
".",
"sock",
".",
"settimeout",
"(",
"read_timeout",
")",
"# Receive the response from the server",
"try",
":",
"try",
":",
"# Python 2.7, use buffering of HTTP responses",
"httplib_response",
"=",
"conn",
".",
"getresponse",
"(",
"buffering",
"=",
"True",
")",
"except",
"TypeError",
":",
"# Python 3",
"try",
":",
"httplib_response",
"=",
"conn",
".",
"getresponse",
"(",
")",
"except",
"BaseException",
"as",
"e",
":",
"# Remove the TypeError from the exception chain in",
"# Python 3 (including for exceptions like SystemExit).",
"# Otherwise it looks like a bug in the code.",
"six",
".",
"raise_from",
"(",
"e",
",",
"None",
")",
"except",
"(",
"SocketTimeout",
",",
"BaseSSLError",
",",
"SocketError",
")",
"as",
"e",
":",
"self",
".",
"_raise_timeout",
"(",
"err",
"=",
"e",
",",
"url",
"=",
"url",
",",
"timeout_value",
"=",
"read_timeout",
")",
"raise",
"# AppEngine doesn't have a version attr.",
"http_version",
"=",
"getattr",
"(",
"conn",
",",
"\"_http_vsn_str\"",
",",
"\"HTTP/?\"",
")",
"log",
".",
"debug",
"(",
"'%s://%s:%s \"%s %s %s\" %s %s'",
",",
"self",
".",
"scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"method",
",",
"url",
",",
"http_version",
",",
"httplib_response",
".",
"status",
",",
"httplib_response",
".",
"length",
",",
")",
"try",
":",
"assert_header_parsing",
"(",
"httplib_response",
".",
"msg",
")",
"except",
"(",
"HeaderParsingError",
",",
"TypeError",
")",
"as",
"hpe",
":",
"# Platform-specific: Python 3",
"log",
".",
"warning",
"(",
"\"Failed to parse headers (url=%s): %s\"",
",",
"self",
".",
"_absolute_url",
"(",
"url",
")",
",",
"hpe",
",",
"exc_info",
"=",
"True",
",",
")",
"return",
"httplib_response"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py#L713-L947 | ||
ValveSoftware/source-sdk-2013 | 0d8dceea4310fde5706b3ce1c70609d72a38efdf | sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/descriptor.py | python | FieldDescriptor.__init__ | (self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
has_default_value=True) | The arguments are as described in the description of FieldDescriptor
attributes above.
Note that containing_type may be None, and may be set later if necessary
(to deal with circular references between message types, for example).
Likewise for extension_scope. | The arguments are as described in the description of FieldDescriptor
attributes above. | [
"The",
"arguments",
"are",
"as",
"described",
"in",
"the",
"description",
"of",
"FieldDescriptor",
"attributes",
"above",
"."
] | def __init__(self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
has_default_value=True):
"""The arguments are as described in the description of FieldDescriptor
attributes above.
Note that containing_type may be None, and may be set later if necessary
(to deal with circular references between message types, for example).
Likewise for extension_scope.
"""
super(FieldDescriptor, self).__init__(options, 'FieldOptions')
self.name = name
self.full_name = full_name
self.index = index
self.number = number
self.type = type
self.cpp_type = cpp_type
self.label = label
self.has_default_value = has_default_value
self.default_value = default_value
self.containing_type = containing_type
self.message_type = message_type
self.enum_type = enum_type
self.is_extension = is_extension
self.extension_scope = extension_scope | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"index",
",",
"number",
",",
"type",
",",
"cpp_type",
",",
"label",
",",
"default_value",
",",
"message_type",
",",
"enum_type",
",",
"containing_type",
",",
"is_extension",
",",
"extension_scope",
",",
"options",
"=",
"None",
",",
"has_default_value",
"=",
"True",
")",
":",
"super",
"(",
"FieldDescriptor",
",",
"self",
")",
".",
"__init__",
"(",
"options",
",",
"'FieldOptions'",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"full_name",
"=",
"full_name",
"self",
".",
"index",
"=",
"index",
"self",
".",
"number",
"=",
"number",
"self",
".",
"type",
"=",
"type",
"self",
".",
"cpp_type",
"=",
"cpp_type",
"self",
".",
"label",
"=",
"label",
"self",
".",
"has_default_value",
"=",
"has_default_value",
"self",
".",
"default_value",
"=",
"default_value",
"self",
".",
"containing_type",
"=",
"containing_type",
"self",
".",
"message_type",
"=",
"message_type",
"self",
".",
"enum_type",
"=",
"enum_type",
"self",
".",
"is_extension",
"=",
"is_extension",
"self",
".",
"extension_scope",
"=",
"extension_scope"
] | https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/descriptor.py#L373-L398 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/js/src/builtin/make_intl_data.py | python | writeLanguageTagData | (intlData, fileDate, url, langTagMappings, langSubtagMappings, extlangMappings) | Writes the language tag data to the Intl data file. | Writes the language tag data to the Intl data file. | [
"Writes",
"the",
"language",
"tag",
"data",
"to",
"the",
"Intl",
"data",
"file",
"."
] | def writeLanguageTagData(intlData, fileDate, url, langTagMappings, langSubtagMappings, extlangMappings):
""" Writes the language tag data to the Intl data file. """
writeMappingsVar(intlData, langTagMappings, "langTagMappings",
"Mappings from complete tags to preferred values", fileDate, url)
writeMappingsVar(intlData, langSubtagMappings, "langSubtagMappings",
"Mappings from non-extlang subtags to preferred values", fileDate, url)
writeMappingsVar(intlData, extlangMappings, "extlangMappings",
"Mappings from extlang subtags to preferred values", fileDate, url) | [
"def",
"writeLanguageTagData",
"(",
"intlData",
",",
"fileDate",
",",
"url",
",",
"langTagMappings",
",",
"langSubtagMappings",
",",
"extlangMappings",
")",
":",
"writeMappingsVar",
"(",
"intlData",
",",
"langTagMappings",
",",
"\"langTagMappings\"",
",",
"\"Mappings from complete tags to preferred values\"",
",",
"fileDate",
",",
"url",
")",
"writeMappingsVar",
"(",
"intlData",
",",
"langSubtagMappings",
",",
"\"langSubtagMappings\"",
",",
"\"Mappings from non-extlang subtags to preferred values\"",
",",
"fileDate",
",",
"url",
")",
"writeMappingsVar",
"(",
"intlData",
",",
"extlangMappings",
",",
"\"extlangMappings\"",
",",
"\"Mappings from extlang subtags to preferred values\"",
",",
"fileDate",
",",
"url",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/js/src/builtin/make_intl_data.py#L159-L166 | ||
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32com/demos/excelRTDServer.py | python | ExcelRTDServer.CreateTopic | (self, TopicStrings=None) | Topic factory method. Subclass must override.
Topic objects need to provide:
* GetValue() method which returns an atomic value.
Will raise NotImplemented if not overridden. | Topic factory method. Subclass must override. | [
"Topic",
"factory",
"method",
".",
"Subclass",
"must",
"override",
"."
] | def CreateTopic(self, TopicStrings=None):
"""Topic factory method. Subclass must override.
Topic objects need to provide:
* GetValue() method which returns an atomic value.
Will raise NotImplemented if not overridden.
"""
raise NotImplemented("Subclass must implement") | [
"def",
"CreateTopic",
"(",
"self",
",",
"TopicStrings",
"=",
"None",
")",
":",
"raise",
"NotImplemented",
"(",
"\"Subclass must implement\"",
")"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/demos/excelRTDServer.py#L231-L239 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | configs/common/MemConfig.py | python | create_mem_intf | (intf, r, i, intlv_bits, intlv_size,
xor_low_bit) | return interface | Helper function for creating a single memoy controller from the given
options. This function is invoked multiple times in config_mem function
to create an array of controllers. | Helper function for creating a single memoy controller from the given
options. This function is invoked multiple times in config_mem function
to create an array of controllers. | [
"Helper",
"function",
"for",
"creating",
"a",
"single",
"memoy",
"controller",
"from",
"the",
"given",
"options",
".",
"This",
"function",
"is",
"invoked",
"multiple",
"times",
"in",
"config_mem",
"function",
"to",
"create",
"an",
"array",
"of",
"controllers",
"."
] | def create_mem_intf(intf, r, i, intlv_bits, intlv_size,
xor_low_bit):
"""
Helper function for creating a single memoy controller from the given
options. This function is invoked multiple times in config_mem function
to create an array of controllers.
"""
import math
intlv_low_bit = int(math.log(intlv_size, 2))
# Use basic hashing for the channel selection, and preferably use
# the lower tag bits from the last level cache. As we do not know
# the details of the caches here, make an educated guess. 4 MByte
# 4-way associative with 64 byte cache lines is 6 offset bits and
# 14 index bits.
if (xor_low_bit):
xor_high_bit = xor_low_bit + intlv_bits - 1
else:
xor_high_bit = 0
# Create an instance so we can figure out the address
# mapping and row-buffer size
interface = intf()
# Only do this for DRAMs
if issubclass(intf, m5.objects.DRAMInterface):
# If the channel bits are appearing after the column
# bits, we need to add the appropriate number of bits
# for the row buffer size
if interface.addr_mapping.value == 'RoRaBaChCo':
# This computation only really needs to happen
# once, but as we rely on having an instance we
# end up having to repeat it for each and every
# one
rowbuffer_size = interface.device_rowbuffer_size.value * \
interface.devices_per_rank.value
intlv_low_bit = int(math.log(rowbuffer_size, 2))
# Also adjust interleaving bits for NVM attached as memory
# Will have separate range defined with unique interleaving
if issubclass(intf, m5.objects.NVMInterface):
# If the channel bits are appearing after the low order
# address bits (buffer bits), we need to add the appropriate
# number of bits for the buffer size
if interface.addr_mapping.value == 'RoRaBaChCo':
# This computation only really needs to happen
# once, but as we rely on having an instance we
# end up having to repeat it for each and every
# one
buffer_size = interface.per_bank_buffer_size.value
intlv_low_bit = int(math.log(buffer_size, 2))
# We got all we need to configure the appropriate address
# range
interface.range = m5.objects.AddrRange(r.start, size = r.size(),
intlvHighBit = \
intlv_low_bit + intlv_bits - 1,
xorHighBit = xor_high_bit,
intlvBits = intlv_bits,
intlvMatch = i)
return interface | [
"def",
"create_mem_intf",
"(",
"intf",
",",
"r",
",",
"i",
",",
"intlv_bits",
",",
"intlv_size",
",",
"xor_low_bit",
")",
":",
"import",
"math",
"intlv_low_bit",
"=",
"int",
"(",
"math",
".",
"log",
"(",
"intlv_size",
",",
"2",
")",
")",
"# Use basic hashing for the channel selection, and preferably use",
"# the lower tag bits from the last level cache. As we do not know",
"# the details of the caches here, make an educated guess. 4 MByte",
"# 4-way associative with 64 byte cache lines is 6 offset bits and",
"# 14 index bits.",
"if",
"(",
"xor_low_bit",
")",
":",
"xor_high_bit",
"=",
"xor_low_bit",
"+",
"intlv_bits",
"-",
"1",
"else",
":",
"xor_high_bit",
"=",
"0",
"# Create an instance so we can figure out the address",
"# mapping and row-buffer size",
"interface",
"=",
"intf",
"(",
")",
"# Only do this for DRAMs",
"if",
"issubclass",
"(",
"intf",
",",
"m5",
".",
"objects",
".",
"DRAMInterface",
")",
":",
"# If the channel bits are appearing after the column",
"# bits, we need to add the appropriate number of bits",
"# for the row buffer size",
"if",
"interface",
".",
"addr_mapping",
".",
"value",
"==",
"'RoRaBaChCo'",
":",
"# This computation only really needs to happen",
"# once, but as we rely on having an instance we",
"# end up having to repeat it for each and every",
"# one",
"rowbuffer_size",
"=",
"interface",
".",
"device_rowbuffer_size",
".",
"value",
"*",
"interface",
".",
"devices_per_rank",
".",
"value",
"intlv_low_bit",
"=",
"int",
"(",
"math",
".",
"log",
"(",
"rowbuffer_size",
",",
"2",
")",
")",
"# Also adjust interleaving bits for NVM attached as memory",
"# Will have separate range defined with unique interleaving",
"if",
"issubclass",
"(",
"intf",
",",
"m5",
".",
"objects",
".",
"NVMInterface",
")",
":",
"# If the channel bits are appearing after the low order",
"# address bits (buffer bits), we need to add the appropriate",
"# number of bits for the buffer size",
"if",
"interface",
".",
"addr_mapping",
".",
"value",
"==",
"'RoRaBaChCo'",
":",
"# This computation only really needs to happen",
"# once, but as we rely on having an instance we",
"# end up having to repeat it for each and every",
"# one",
"buffer_size",
"=",
"interface",
".",
"per_bank_buffer_size",
".",
"value",
"intlv_low_bit",
"=",
"int",
"(",
"math",
".",
"log",
"(",
"buffer_size",
",",
"2",
")",
")",
"# We got all we need to configure the appropriate address",
"# range",
"interface",
".",
"range",
"=",
"m5",
".",
"objects",
".",
"AddrRange",
"(",
"r",
".",
"start",
",",
"size",
"=",
"r",
".",
"size",
"(",
")",
",",
"intlvHighBit",
"=",
"intlv_low_bit",
"+",
"intlv_bits",
"-",
"1",
",",
"xorHighBit",
"=",
"xor_high_bit",
",",
"intlvBits",
"=",
"intlv_bits",
",",
"intlvMatch",
"=",
"i",
")",
"return",
"interface"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/configs/common/MemConfig.py#L40-L103 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/outbuff.py | python | OutputBuffer.Clear | (self) | Clear the Buffer | Clear the Buffer | [
"Clear",
"the",
"Buffer"
] | def Clear(self):
"""Clear the Buffer"""
self.SetReadOnly(False)
self.ClearAll()
self.EmptyUndoBuffer()
self.SetReadOnly(True) | [
"def",
"Clear",
"(",
"self",
")",
":",
"self",
".",
"SetReadOnly",
"(",
"False",
")",
"self",
".",
"ClearAll",
"(",
")",
"self",
".",
"EmptyUndoBuffer",
"(",
")",
"self",
".",
"SetReadOnly",
"(",
"True",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/outbuff.py#L366-L371 | ||
arx/ArxLibertatis | 0313c51625f3f55016cdad43d2c7f7296d27949c | scripts/cpplint.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.
This also handles sizeof(type) warnings, due to similarity of content.
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.
This also handles sizeof(type) warnings, due to similarity of content.
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
# e.g., sizeof(int)
sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
if sizeof_match:
error(filename, linenum, 'runtime/sizeof', 1,
'Using sizeof(type). Use sizeof(varname) instead if possible')
return True
remainder = line[match.end(0):]
# The close paren is for function pointers as arguments to a function.
# eg, void foo(void (*bar)(int));
# The semicolon check is a more basic function check; also possibly a
# function pointer typedef.
# eg, void foo(int); or void foo(int) const;
# The equals check is for function pointer assignment.
# eg, void *(*foo)(int) = ...
# The > is for MockCallback<...> ...
#
# Right now, this will only catch cases where there's a single argument, and
# it's unnamed. It should probably be expanded to check for multiple
# arguments with some unnamed.
function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder)
if function_match:
if ((not function_match.group(3) or
function_match.group(3) == ';' or
('MockCallback<' not in raw_line and
'/*' not in raw_line)) and
'SIGNAL' not in raw_line and
'SLOT' not in raw_line):
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",
"# e.g., sizeof(int)",
"sizeof_match",
"=",
"Match",
"(",
"r'.*sizeof\\s*$'",
",",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
")",
"if",
"sizeof_match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/sizeof'",
",",
"1",
",",
"'Using sizeof(type). Use sizeof(varname) instead if possible'",
")",
"return",
"True",
"remainder",
"=",
"line",
"[",
"match",
".",
"end",
"(",
"0",
")",
":",
"]",
"# The close paren is for function pointers as arguments to a function.",
"# eg, void foo(void (*bar)(int));",
"# The semicolon check is a more basic function check; also possibly a",
"# function pointer typedef.",
"# eg, void foo(int); or void foo(int) const;",
"# The equals check is for function pointer assignment.",
"# eg, void *(*foo)(int) = ...",
"# The > is for MockCallback<...> ...",
"#",
"# Right now, this will only catch cases where there's a single argument, and",
"# it's unnamed. It should probably be expanded to check for multiple",
"# arguments with some unnamed.",
"function_match",
"=",
"Match",
"(",
"r'\\s*(\\)|=|(const)?\\s*(;|\\{|throw\\(\\)|>))'",
",",
"remainder",
")",
"if",
"function_match",
":",
"if",
"(",
"(",
"not",
"function_match",
".",
"group",
"(",
"3",
")",
"or",
"function_match",
".",
"group",
"(",
"3",
")",
"==",
"';'",
"or",
"(",
"'MockCallback<'",
"not",
"in",
"raw_line",
"and",
"'/*'",
"not",
"in",
"raw_line",
")",
")",
"and",
"'SIGNAL'",
"not",
"in",
"raw_line",
"and",
"'SLOT'",
"not",
"in",
"raw_line",
")",
":",
"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/arx/ArxLibertatis/blob/0313c51625f3f55016cdad43d2c7f7296d27949c/scripts/cpplint.py#L3006-L3068 | |
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/yply/yparse.py | python | p_defsection | (p) | defsection : definitions SECTION
| SECTION | defsection : definitions SECTION
| SECTION | [
"defsection",
":",
"definitions",
"SECTION",
"|",
"SECTION"
] | def p_defsection(p):
'''defsection : definitions SECTION
| SECTION'''
p.lexer.lastsection = 1
print "tokens = ", repr(tokenlist)
print
print "precedence = ", repr(preclist)
print
print "# -------------- RULES ----------------"
print | [
"def",
"p_defsection",
"(",
"p",
")",
":",
"p",
".",
"lexer",
".",
"lastsection",
"=",
"1",
"print",
"\"tokens = \"",
",",
"repr",
"(",
"tokenlist",
")",
"print",
"print",
"\"precedence = \"",
",",
"repr",
"(",
"preclist",
")",
"print",
"print",
"\"# -------------- RULES ----------------\"",
"print"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/yply/yparse.py#L19-L28 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/customtreectrl.py | python | CustomTreeCtrl.PaintItem | (self, item, dc, level, align) | Actually draws an item.
:param `item`: an instance of :class:`GenericTreeItem`;
:param `dc`: an instance of :class:`DC`;
:param integer `level`: the item level in the tree hierarchy;
:param integer `align`: an integer specifying the alignment type:
=============== =========================================
`align` Value Description
=============== =========================================
0 No horizontal alignment of windows (in items with windows).
1 Windows (in items with windows) are aligned at the same horizontal position.
2 Windows (in items with windows) are aligned at the rightmost edge of :class:`CustomTreeCtrl`.
=============== ========================================= | Actually draws an item. | [
"Actually",
"draws",
"an",
"item",
"."
] | def PaintItem(self, item, dc, level, align):
"""
Actually draws an item.
:param `item`: an instance of :class:`GenericTreeItem`;
:param `dc`: an instance of :class:`DC`;
:param integer `level`: the item level in the tree hierarchy;
:param integer `align`: an integer specifying the alignment type:
=============== =========================================
`align` Value Description
=============== =========================================
0 No horizontal alignment of windows (in items with windows).
1 Windows (in items with windows) are aligned at the same horizontal position.
2 Windows (in items with windows) are aligned at the rightmost edge of :class:`CustomTreeCtrl`.
=============== =========================================
"""
attr = item.GetAttributes()
if attr and attr.HasFont():
dc.SetFont(attr.GetFont())
else:
if item.IsBold():
dc.SetFont(self._boldFont)
elif item.IsItalic():
dc.SetFont(self._italicFont)
if item.IsHyperText():
dc.SetFont(self.GetHyperTextFont())
if item.GetVisited():
dc.SetTextForeground(self.GetHyperTextVisitedColour())
else:
dc.SetTextForeground(self.GetHyperTextNewColour())
text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText())
w, h = self.GetClientSize()
image = item.GetCurrentImage()
checkimage = item.GetCurrentCheckedImage()
leftimage = _NO_IMAGE
separator = item.IsSeparator()
if self._imageListLeft:
leftimage = item.GetLeftImage()
image_w, image_h = 0, 0
if image != _NO_IMAGE:
if self._imageListNormal:
image_w, image_h = self._imageListNormal.GetSize(image)
image_w += 4
else:
image = _NO_IMAGE
if item.GetType() != 0:
wcheck, hcheck = self._imageListCheck.GetSize(item.GetType())
wcheck += 4
else:
wcheck, hcheck = 0, 0
if leftimage != _NO_IMAGE:
l_image_w, l_image_h = self._imageListLeft.GetSize(leftimage)
total_h = self.GetLineHeight(item)
drawItemBackground = False
if item.IsSelected():
# under mac selections are only a rectangle in case they don't have the focus
if wx.Platform == "__WXMAC__":
if not self._hasFocus:
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT), 1, wx.SOLID))
else:
dc.SetBrush(self._hilightBrush)
else:
dc.SetBrush((self._hasFocus and [self._hilightBrush] or [self._hilightUnfocusedBrush])[0])
drawItemBackground = True
else:
if attr and attr.HasBackgroundColour():
drawItemBackground = True
colBg = attr.GetBackgroundColour()
else:
colBg = self._backgroundColour
dc.SetBrush(wx.Brush(colBg, wx.SOLID))
if attr and attr.HasBorderColour():
colBorder = attr.GetBorderColour()
dc.SetPen(wx.Pen(colBorder, 1, wx.SOLID))
else:
dc.SetPen(wx.TRANSPARENT_PEN)
offset = (self.HasAGWFlag(TR_ROW_LINES) and [1] or [0])[0]
if self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
x = 0
itemrect = wx.Rect(x, item.GetY()+offset, w, total_h-offset)
if item.IsSelected():
if self._usegradients:
if self._gradientstyle == 0: # Horizontal
self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
else: # Vertical
self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
elif self._vistaselection:
self.DrawVistaRectangle(dc, itemrect, self._hasFocus)
else:
if wx.Platform in ["__WXGTK2__", "__WXMAC__"]:
flags = wx.CONTROL_SELECTED
if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED
wx.RendererNative.Get().DrawItemSelectionRect(self, dc, itemrect, flags)
else:
dc.DrawRectangleRect(itemrect)
else:
if drawItemBackground:
minusicon = wcheck + image_w - 2
itemrect = wx.Rect(item.GetX()+minusicon,
item.GetY()+offset,
item.GetWidth()-minusicon,
total_h-offset)
dc.DrawRectangleRect(itemrect)
else:
if item.IsSelected():
# If it's selected, and there's an image, then we should
# take care to leave the area under the image painted in the
# background colour.
wnd = item.GetWindow()
wndx = 0
if wnd:
wndx, wndy = item.GetWindowSize()
if separator:
item_width = w
else:
item_width = item.GetWidth() - image_w - wcheck + 2 - wndx
itemrect = wx.Rect(item.GetX() + wcheck + image_w - 2,
item.GetY()+offset,
item_width,
total_h-offset)
if self._usegradients:
if self._gradientstyle == 0: # Horizontal
self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
else: # Vertical
self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
elif self._vistaselection:
self.DrawVistaRectangle(dc, itemrect, self._hasFocus)
else:
if wx.Platform in ["__WXGTK2__", "__WXMAC__"]:
flags = wx.CONTROL_SELECTED
if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED
wx.RendererNative.Get().DrawItemSelectionRect(self, dc, itemrect, flags)
else:
dc.DrawRectangleRect(itemrect)
# On GTK+ 2, drawing a 'normal' background is wrong for themes that
# don't allow backgrounds to be customized. Not drawing the background,
# except for custom item backgrounds, works for both kinds of theme.
elif drawItemBackground:
minusicon = wcheck + image_w - 2
if separator:
item_width = w
else:
item_width = item.GetWidth()-minusicon
itemrect = wx.Rect(item.GetX()+minusicon,
item.GetY()+offset,
item_width,
total_h-offset)
if self._usegradients and self._hasFocus:
if self._gradientstyle == 0: # Horizontal
self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
else: # Vertical
self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
else:
dc.DrawRectangleRect(itemrect)
if image != _NO_IMAGE:
dc.SetClippingRegion(item.GetX(), item.GetY(), wcheck+image_w-2, total_h)
if item.IsEnabled():
imglist = self._imageListNormal
else:
imglist = self._grayedImageList
imglist.Draw(image, dc,
item.GetX() + wcheck,
item.GetY() + ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0],
wx.IMAGELIST_DRAW_TRANSPARENT)
dc.DestroyClippingRegion()
if wcheck:
if item.IsEnabled():
imglist = self._imageListCheck
else:
imglist = self._grayedCheckList
imglist.Draw(checkimage, dc,
item.GetX(),
item.GetY() + ((total_h > hcheck) and [(total_h-hcheck)/2] or [0])[0],
wx.IMAGELIST_DRAW_TRANSPARENT)
if leftimage != _NO_IMAGE:
if item.IsEnabled():
imglist = self._imageListLeft
else:
imglist = self._grayedImageListLeft
imglist.Draw(leftimage, dc,
4,
item.GetY() + ((total_h > l_image_h) and [(total_h-l_image_h)/2] or [0])[0],
wx.IMAGELIST_DRAW_TRANSPARENT)
dc.SetBackgroundMode(wx.TRANSPARENT)
extraH = ((total_h > text_h) and [(total_h - text_h)/2] or [0])[0]
textrect = wx.Rect(wcheck + image_w + item.GetX(), item.GetY() + extraH, text_w, text_h)
itemText = item.GetText()
if self.HasAGWFlag(TR_ELLIPSIZE_LONG_ITEMS) and not separator:
xa, ya = self.CalcScrolledPosition((0, item.GetY()))
maxsize = w - (wcheck + image_w + item.GetX()) + xa
itemText = ChopText(dc, itemText, maxsize)
if not item.IsEnabled():
foreground = dc.GetTextForeground()
dc.SetTextForeground(self._disabledColour)
dc.DrawLabel(itemText, textrect)
dc.SetTextForeground(foreground)
else:
if wx.Platform == "__WXMAC__" and item.IsSelected() and self._hasFocus:
dc.SetTextForeground(wx.WHITE)
dc.DrawLabel(itemText, textrect)
wnd = item.GetWindow()
if wnd:
wndx = wcheck + image_w + item.GetX() + text_w + 4
xa, ya = self.CalcScrolledPosition((0, item.GetY()))
wndx += xa
if item.GetHeight() > item.GetWindowSize()[1]:
ya += (item.GetHeight() - item.GetWindowSize()[1])/2
if align == 1:
# Horizontal alignment of windows
if level in self.absoluteWindows:
wndx = self.absoluteWindows[level] + item.GetX() + 2 + xa
elif align == 2:
# Rightmost alignment of windows
wndx = w - item.GetWindowSize().x - 2 + xa
if not wnd.IsShown():
wnd.Show()
if wnd.GetPosition() != (wndx, ya):
wnd.SetPosition((wndx, ya))
if separator:
oldPen = dc.GetPen()
if item.IsEnabled():
if attr and attr.HasTextColour():
separatorPen = wx.Pen(attr.GetTextColour(), 1)
else:
separatorPen = self._separatorPen
else:
separatorPen = wx.GREY_PEN
dc.SetPen(separatorPen)
dc.DrawLine(item.GetX()+2, item.GetY()+total_h/2, w, item.GetY()+total_h/2)
dc.SetPen(oldPen)
# restore normal font
dc.SetFont(self._normalFont) | [
"def",
"PaintItem",
"(",
"self",
",",
"item",
",",
"dc",
",",
"level",
",",
"align",
")",
":",
"attr",
"=",
"item",
".",
"GetAttributes",
"(",
")",
"if",
"attr",
"and",
"attr",
".",
"HasFont",
"(",
")",
":",
"dc",
".",
"SetFont",
"(",
"attr",
".",
"GetFont",
"(",
")",
")",
"else",
":",
"if",
"item",
".",
"IsBold",
"(",
")",
":",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_boldFont",
")",
"elif",
"item",
".",
"IsItalic",
"(",
")",
":",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_italicFont",
")",
"if",
"item",
".",
"IsHyperText",
"(",
")",
":",
"dc",
".",
"SetFont",
"(",
"self",
".",
"GetHyperTextFont",
"(",
")",
")",
"if",
"item",
".",
"GetVisited",
"(",
")",
":",
"dc",
".",
"SetTextForeground",
"(",
"self",
".",
"GetHyperTextVisitedColour",
"(",
")",
")",
"else",
":",
"dc",
".",
"SetTextForeground",
"(",
"self",
".",
"GetHyperTextNewColour",
"(",
")",
")",
"text_w",
",",
"text_h",
",",
"dummy",
"=",
"dc",
".",
"GetMultiLineTextExtent",
"(",
"item",
".",
"GetText",
"(",
")",
")",
"w",
",",
"h",
"=",
"self",
".",
"GetClientSize",
"(",
")",
"image",
"=",
"item",
".",
"GetCurrentImage",
"(",
")",
"checkimage",
"=",
"item",
".",
"GetCurrentCheckedImage",
"(",
")",
"leftimage",
"=",
"_NO_IMAGE",
"separator",
"=",
"item",
".",
"IsSeparator",
"(",
")",
"if",
"self",
".",
"_imageListLeft",
":",
"leftimage",
"=",
"item",
".",
"GetLeftImage",
"(",
")",
"image_w",
",",
"image_h",
"=",
"0",
",",
"0",
"if",
"image",
"!=",
"_NO_IMAGE",
":",
"if",
"self",
".",
"_imageListNormal",
":",
"image_w",
",",
"image_h",
"=",
"self",
".",
"_imageListNormal",
".",
"GetSize",
"(",
"image",
")",
"image_w",
"+=",
"4",
"else",
":",
"image",
"=",
"_NO_IMAGE",
"if",
"item",
".",
"GetType",
"(",
")",
"!=",
"0",
":",
"wcheck",
",",
"hcheck",
"=",
"self",
".",
"_imageListCheck",
".",
"GetSize",
"(",
"item",
".",
"GetType",
"(",
")",
")",
"wcheck",
"+=",
"4",
"else",
":",
"wcheck",
",",
"hcheck",
"=",
"0",
",",
"0",
"if",
"leftimage",
"!=",
"_NO_IMAGE",
":",
"l_image_w",
",",
"l_image_h",
"=",
"self",
".",
"_imageListLeft",
".",
"GetSize",
"(",
"leftimage",
")",
"total_h",
"=",
"self",
".",
"GetLineHeight",
"(",
"item",
")",
"drawItemBackground",
"=",
"False",
"if",
"item",
".",
"IsSelected",
"(",
")",
":",
"# under mac selections are only a rectangle in case they don't have the focus",
"if",
"wx",
".",
"Platform",
"==",
"\"__WXMAC__\"",
":",
"if",
"not",
"self",
".",
"_hasFocus",
":",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"TRANSPARENT_BRUSH",
")",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"wx",
".",
"SystemSettings_GetColour",
"(",
"wx",
".",
"SYS_COLOUR_HIGHLIGHT",
")",
",",
"1",
",",
"wx",
".",
"SOLID",
")",
")",
"else",
":",
"dc",
".",
"SetBrush",
"(",
"self",
".",
"_hilightBrush",
")",
"else",
":",
"dc",
".",
"SetBrush",
"(",
"(",
"self",
".",
"_hasFocus",
"and",
"[",
"self",
".",
"_hilightBrush",
"]",
"or",
"[",
"self",
".",
"_hilightUnfocusedBrush",
"]",
")",
"[",
"0",
"]",
")",
"drawItemBackground",
"=",
"True",
"else",
":",
"if",
"attr",
"and",
"attr",
".",
"HasBackgroundColour",
"(",
")",
":",
"drawItemBackground",
"=",
"True",
"colBg",
"=",
"attr",
".",
"GetBackgroundColour",
"(",
")",
"else",
":",
"colBg",
"=",
"self",
".",
"_backgroundColour",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"Brush",
"(",
"colBg",
",",
"wx",
".",
"SOLID",
")",
")",
"if",
"attr",
"and",
"attr",
".",
"HasBorderColour",
"(",
")",
":",
"colBorder",
"=",
"attr",
".",
"GetBorderColour",
"(",
")",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"colBorder",
",",
"1",
",",
"wx",
".",
"SOLID",
")",
")",
"else",
":",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"TRANSPARENT_PEN",
")",
"offset",
"=",
"(",
"self",
".",
"HasAGWFlag",
"(",
"TR_ROW_LINES",
")",
"and",
"[",
"1",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"if",
"self",
".",
"HasAGWFlag",
"(",
"TR_FULL_ROW_HIGHLIGHT",
")",
":",
"x",
"=",
"0",
"itemrect",
"=",
"wx",
".",
"Rect",
"(",
"x",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"offset",
",",
"w",
",",
"total_h",
"-",
"offset",
")",
"if",
"item",
".",
"IsSelected",
"(",
")",
":",
"if",
"self",
".",
"_usegradients",
":",
"if",
"self",
".",
"_gradientstyle",
"==",
"0",
":",
"# Horizontal",
"self",
".",
"DrawHorizontalGradient",
"(",
"dc",
",",
"itemrect",
",",
"self",
".",
"_hasFocus",
")",
"else",
":",
"# Vertical",
"self",
".",
"DrawVerticalGradient",
"(",
"dc",
",",
"itemrect",
",",
"self",
".",
"_hasFocus",
")",
"elif",
"self",
".",
"_vistaselection",
":",
"self",
".",
"DrawVistaRectangle",
"(",
"dc",
",",
"itemrect",
",",
"self",
".",
"_hasFocus",
")",
"else",
":",
"if",
"wx",
".",
"Platform",
"in",
"[",
"\"__WXGTK2__\"",
",",
"\"__WXMAC__\"",
"]",
":",
"flags",
"=",
"wx",
".",
"CONTROL_SELECTED",
"if",
"self",
".",
"_hasFocus",
":",
"flags",
"=",
"flags",
"|",
"wx",
".",
"CONTROL_FOCUSED",
"wx",
".",
"RendererNative",
".",
"Get",
"(",
")",
".",
"DrawItemSelectionRect",
"(",
"self",
",",
"dc",
",",
"itemrect",
",",
"flags",
")",
"else",
":",
"dc",
".",
"DrawRectangleRect",
"(",
"itemrect",
")",
"else",
":",
"if",
"drawItemBackground",
":",
"minusicon",
"=",
"wcheck",
"+",
"image_w",
"-",
"2",
"itemrect",
"=",
"wx",
".",
"Rect",
"(",
"item",
".",
"GetX",
"(",
")",
"+",
"minusicon",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"offset",
",",
"item",
".",
"GetWidth",
"(",
")",
"-",
"minusicon",
",",
"total_h",
"-",
"offset",
")",
"dc",
".",
"DrawRectangleRect",
"(",
"itemrect",
")",
"else",
":",
"if",
"item",
".",
"IsSelected",
"(",
")",
":",
"# If it's selected, and there's an image, then we should",
"# take care to leave the area under the image painted in the",
"# background colour.",
"wnd",
"=",
"item",
".",
"GetWindow",
"(",
")",
"wndx",
"=",
"0",
"if",
"wnd",
":",
"wndx",
",",
"wndy",
"=",
"item",
".",
"GetWindowSize",
"(",
")",
"if",
"separator",
":",
"item_width",
"=",
"w",
"else",
":",
"item_width",
"=",
"item",
".",
"GetWidth",
"(",
")",
"-",
"image_w",
"-",
"wcheck",
"+",
"2",
"-",
"wndx",
"itemrect",
"=",
"wx",
".",
"Rect",
"(",
"item",
".",
"GetX",
"(",
")",
"+",
"wcheck",
"+",
"image_w",
"-",
"2",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"offset",
",",
"item_width",
",",
"total_h",
"-",
"offset",
")",
"if",
"self",
".",
"_usegradients",
":",
"if",
"self",
".",
"_gradientstyle",
"==",
"0",
":",
"# Horizontal",
"self",
".",
"DrawHorizontalGradient",
"(",
"dc",
",",
"itemrect",
",",
"self",
".",
"_hasFocus",
")",
"else",
":",
"# Vertical",
"self",
".",
"DrawVerticalGradient",
"(",
"dc",
",",
"itemrect",
",",
"self",
".",
"_hasFocus",
")",
"elif",
"self",
".",
"_vistaselection",
":",
"self",
".",
"DrawVistaRectangle",
"(",
"dc",
",",
"itemrect",
",",
"self",
".",
"_hasFocus",
")",
"else",
":",
"if",
"wx",
".",
"Platform",
"in",
"[",
"\"__WXGTK2__\"",
",",
"\"__WXMAC__\"",
"]",
":",
"flags",
"=",
"wx",
".",
"CONTROL_SELECTED",
"if",
"self",
".",
"_hasFocus",
":",
"flags",
"=",
"flags",
"|",
"wx",
".",
"CONTROL_FOCUSED",
"wx",
".",
"RendererNative",
".",
"Get",
"(",
")",
".",
"DrawItemSelectionRect",
"(",
"self",
",",
"dc",
",",
"itemrect",
",",
"flags",
")",
"else",
":",
"dc",
".",
"DrawRectangleRect",
"(",
"itemrect",
")",
"# On GTK+ 2, drawing a 'normal' background is wrong for themes that",
"# don't allow backgrounds to be customized. Not drawing the background,",
"# except for custom item backgrounds, works for both kinds of theme.",
"elif",
"drawItemBackground",
":",
"minusicon",
"=",
"wcheck",
"+",
"image_w",
"-",
"2",
"if",
"separator",
":",
"item_width",
"=",
"w",
"else",
":",
"item_width",
"=",
"item",
".",
"GetWidth",
"(",
")",
"-",
"minusicon",
"itemrect",
"=",
"wx",
".",
"Rect",
"(",
"item",
".",
"GetX",
"(",
")",
"+",
"minusicon",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"offset",
",",
"item_width",
",",
"total_h",
"-",
"offset",
")",
"if",
"self",
".",
"_usegradients",
"and",
"self",
".",
"_hasFocus",
":",
"if",
"self",
".",
"_gradientstyle",
"==",
"0",
":",
"# Horizontal",
"self",
".",
"DrawHorizontalGradient",
"(",
"dc",
",",
"itemrect",
",",
"self",
".",
"_hasFocus",
")",
"else",
":",
"# Vertical",
"self",
".",
"DrawVerticalGradient",
"(",
"dc",
",",
"itemrect",
",",
"self",
".",
"_hasFocus",
")",
"else",
":",
"dc",
".",
"DrawRectangleRect",
"(",
"itemrect",
")",
"if",
"image",
"!=",
"_NO_IMAGE",
":",
"dc",
".",
"SetClippingRegion",
"(",
"item",
".",
"GetX",
"(",
")",
",",
"item",
".",
"GetY",
"(",
")",
",",
"wcheck",
"+",
"image_w",
"-",
"2",
",",
"total_h",
")",
"if",
"item",
".",
"IsEnabled",
"(",
")",
":",
"imglist",
"=",
"self",
".",
"_imageListNormal",
"else",
":",
"imglist",
"=",
"self",
".",
"_grayedImageList",
"imglist",
".",
"Draw",
"(",
"image",
",",
"dc",
",",
"item",
".",
"GetX",
"(",
")",
"+",
"wcheck",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"(",
"(",
"total_h",
">",
"image_h",
")",
"and",
"[",
"(",
"total_h",
"-",
"image_h",
")",
"/",
"2",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
",",
"wx",
".",
"IMAGELIST_DRAW_TRANSPARENT",
")",
"dc",
".",
"DestroyClippingRegion",
"(",
")",
"if",
"wcheck",
":",
"if",
"item",
".",
"IsEnabled",
"(",
")",
":",
"imglist",
"=",
"self",
".",
"_imageListCheck",
"else",
":",
"imglist",
"=",
"self",
".",
"_grayedCheckList",
"imglist",
".",
"Draw",
"(",
"checkimage",
",",
"dc",
",",
"item",
".",
"GetX",
"(",
")",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"(",
"(",
"total_h",
">",
"hcheck",
")",
"and",
"[",
"(",
"total_h",
"-",
"hcheck",
")",
"/",
"2",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
",",
"wx",
".",
"IMAGELIST_DRAW_TRANSPARENT",
")",
"if",
"leftimage",
"!=",
"_NO_IMAGE",
":",
"if",
"item",
".",
"IsEnabled",
"(",
")",
":",
"imglist",
"=",
"self",
".",
"_imageListLeft",
"else",
":",
"imglist",
"=",
"self",
".",
"_grayedImageListLeft",
"imglist",
".",
"Draw",
"(",
"leftimage",
",",
"dc",
",",
"4",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"(",
"(",
"total_h",
">",
"l_image_h",
")",
"and",
"[",
"(",
"total_h",
"-",
"l_image_h",
")",
"/",
"2",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
",",
"wx",
".",
"IMAGELIST_DRAW_TRANSPARENT",
")",
"dc",
".",
"SetBackgroundMode",
"(",
"wx",
".",
"TRANSPARENT",
")",
"extraH",
"=",
"(",
"(",
"total_h",
">",
"text_h",
")",
"and",
"[",
"(",
"total_h",
"-",
"text_h",
")",
"/",
"2",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"textrect",
"=",
"wx",
".",
"Rect",
"(",
"wcheck",
"+",
"image_w",
"+",
"item",
".",
"GetX",
"(",
")",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"extraH",
",",
"text_w",
",",
"text_h",
")",
"itemText",
"=",
"item",
".",
"GetText",
"(",
")",
"if",
"self",
".",
"HasAGWFlag",
"(",
"TR_ELLIPSIZE_LONG_ITEMS",
")",
"and",
"not",
"separator",
":",
"xa",
",",
"ya",
"=",
"self",
".",
"CalcScrolledPosition",
"(",
"(",
"0",
",",
"item",
".",
"GetY",
"(",
")",
")",
")",
"maxsize",
"=",
"w",
"-",
"(",
"wcheck",
"+",
"image_w",
"+",
"item",
".",
"GetX",
"(",
")",
")",
"+",
"xa",
"itemText",
"=",
"ChopText",
"(",
"dc",
",",
"itemText",
",",
"maxsize",
")",
"if",
"not",
"item",
".",
"IsEnabled",
"(",
")",
":",
"foreground",
"=",
"dc",
".",
"GetTextForeground",
"(",
")",
"dc",
".",
"SetTextForeground",
"(",
"self",
".",
"_disabledColour",
")",
"dc",
".",
"DrawLabel",
"(",
"itemText",
",",
"textrect",
")",
"dc",
".",
"SetTextForeground",
"(",
"foreground",
")",
"else",
":",
"if",
"wx",
".",
"Platform",
"==",
"\"__WXMAC__\"",
"and",
"item",
".",
"IsSelected",
"(",
")",
"and",
"self",
".",
"_hasFocus",
":",
"dc",
".",
"SetTextForeground",
"(",
"wx",
".",
"WHITE",
")",
"dc",
".",
"DrawLabel",
"(",
"itemText",
",",
"textrect",
")",
"wnd",
"=",
"item",
".",
"GetWindow",
"(",
")",
"if",
"wnd",
":",
"wndx",
"=",
"wcheck",
"+",
"image_w",
"+",
"item",
".",
"GetX",
"(",
")",
"+",
"text_w",
"+",
"4",
"xa",
",",
"ya",
"=",
"self",
".",
"CalcScrolledPosition",
"(",
"(",
"0",
",",
"item",
".",
"GetY",
"(",
")",
")",
")",
"wndx",
"+=",
"xa",
"if",
"item",
".",
"GetHeight",
"(",
")",
">",
"item",
".",
"GetWindowSize",
"(",
")",
"[",
"1",
"]",
":",
"ya",
"+=",
"(",
"item",
".",
"GetHeight",
"(",
")",
"-",
"item",
".",
"GetWindowSize",
"(",
")",
"[",
"1",
"]",
")",
"/",
"2",
"if",
"align",
"==",
"1",
":",
"# Horizontal alignment of windows",
"if",
"level",
"in",
"self",
".",
"absoluteWindows",
":",
"wndx",
"=",
"self",
".",
"absoluteWindows",
"[",
"level",
"]",
"+",
"item",
".",
"GetX",
"(",
")",
"+",
"2",
"+",
"xa",
"elif",
"align",
"==",
"2",
":",
"# Rightmost alignment of windows",
"wndx",
"=",
"w",
"-",
"item",
".",
"GetWindowSize",
"(",
")",
".",
"x",
"-",
"2",
"+",
"xa",
"if",
"not",
"wnd",
".",
"IsShown",
"(",
")",
":",
"wnd",
".",
"Show",
"(",
")",
"if",
"wnd",
".",
"GetPosition",
"(",
")",
"!=",
"(",
"wndx",
",",
"ya",
")",
":",
"wnd",
".",
"SetPosition",
"(",
"(",
"wndx",
",",
"ya",
")",
")",
"if",
"separator",
":",
"oldPen",
"=",
"dc",
".",
"GetPen",
"(",
")",
"if",
"item",
".",
"IsEnabled",
"(",
")",
":",
"if",
"attr",
"and",
"attr",
".",
"HasTextColour",
"(",
")",
":",
"separatorPen",
"=",
"wx",
".",
"Pen",
"(",
"attr",
".",
"GetTextColour",
"(",
")",
",",
"1",
")",
"else",
":",
"separatorPen",
"=",
"self",
".",
"_separatorPen",
"else",
":",
"separatorPen",
"=",
"wx",
".",
"GREY_PEN",
"dc",
".",
"SetPen",
"(",
"separatorPen",
")",
"dc",
".",
"DrawLine",
"(",
"item",
".",
"GetX",
"(",
")",
"+",
"2",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"total_h",
"/",
"2",
",",
"w",
",",
"item",
".",
"GetY",
"(",
")",
"+",
"total_h",
"/",
"2",
")",
"dc",
".",
"SetPen",
"(",
"oldPen",
")",
"# restore normal font",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_normalFont",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L6467-L6753 | ||
maidsafe-archive/MaidSafe | defd65e1c8cfb6a1cbdeaaa0eee31d065421792d | src/third_party_libs/googlemock/scripts/generator/cpp/utils.py | python | ReadFile | (filename, print_error=True) | Returns the contents of a file. | Returns the contents of a file. | [
"Returns",
"the",
"contents",
"of",
"a",
"file",
"."
] | def ReadFile(filename, print_error=True):
"""Returns the contents of a file."""
try:
fp = open(filename)
try:
return fp.read()
finally:
fp.close()
except IOError:
if print_error:
print('Error reading %s: %s' % (filename, sys.exc_info()[1]))
return None | [
"def",
"ReadFile",
"(",
"filename",
",",
"print_error",
"=",
"True",
")",
":",
"try",
":",
"fp",
"=",
"open",
"(",
"filename",
")",
"try",
":",
"return",
"fp",
".",
"read",
"(",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")",
"except",
"IOError",
":",
"if",
"print_error",
":",
"print",
"(",
"'Error reading %s: %s'",
"%",
"(",
"filename",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
")",
")",
"return",
"None"
] | https://github.com/maidsafe-archive/MaidSafe/blob/defd65e1c8cfb6a1cbdeaaa0eee31d065421792d/src/third_party_libs/googlemock/scripts/generator/cpp/utils.py#L30-L41 | ||
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/tyr/tyr/resources.py | python | check_cities_job | () | return (
models.Job.query.join(models.DataSet)
.filter(models.DataSet.type == 'cities')
.order_by(models.Job.created_at.desc())
.first()
) | Check status of cities job in Tyr db
:return: the latest cities job | Check status of cities job in Tyr db
:return: the latest cities job | [
"Check",
"status",
"of",
"cities",
"job",
"in",
"Tyr",
"db",
":",
"return",
":",
"the",
"latest",
"cities",
"job"
] | def check_cities_job():
"""
Check status of cities job in Tyr db
:return: the latest cities job
"""
return (
models.Job.query.join(models.DataSet)
.filter(models.DataSet.type == 'cities')
.order_by(models.Job.created_at.desc())
.first()
) | [
"def",
"check_cities_job",
"(",
")",
":",
"return",
"(",
"models",
".",
"Job",
".",
"query",
".",
"join",
"(",
"models",
".",
"DataSet",
")",
".",
"filter",
"(",
"models",
".",
"DataSet",
".",
"type",
"==",
"'cities'",
")",
".",
"order_by",
"(",
"models",
".",
"Job",
".",
"created_at",
".",
"desc",
"(",
")",
")",
".",
"first",
"(",
")",
")"
] | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/tyr/tyr/resources.py#L2304-L2314 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/csv.py | python | Sniffer._guess_quote_and_delimiter | (self, data, delimiters) | return (quotechar, doublequote, delim, skipinitialspace) | Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,'some text',
The quote with the most wins, same with the delimiter.
If there is no quotechar the delimiter can't be determined
this way. | Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,'some text',
The quote with the most wins, same with the delimiter.
If there is no quotechar the delimiter can't be determined
this way. | [
"Looks",
"for",
"text",
"enclosed",
"between",
"two",
"identical",
"quotes",
"(",
"the",
"probable",
"quotechar",
")",
"which",
"are",
"preceded",
"and",
"followed",
"by",
"the",
"same",
"character",
"(",
"the",
"probable",
"delimiter",
")",
".",
"For",
"example",
":",
"some",
"text",
"The",
"quote",
"with",
"the",
"most",
"wins",
"same",
"with",
"the",
"delimiter",
".",
"If",
"there",
"is",
"no",
"quotechar",
"the",
"delimiter",
"can",
"t",
"be",
"determined",
"this",
"way",
"."
] | def _guess_quote_and_delimiter(self, data, delimiters):
"""
Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,'some text',
The quote with the most wins, same with the delimiter.
If there is no quotechar the delimiter can't be determined
this way.
"""
matches = []
for restr in (r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', # ,".*?",
r'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\w\n"\'])(?P<space> ?)', # ".*?",
r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', # ,".*?"
r'(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n)'): # ".*?" (no delim, no space)
regexp = re.compile(restr, re.DOTALL | re.MULTILINE)
matches = regexp.findall(data)
if matches:
break
if not matches:
# (quotechar, doublequote, delimiter, skipinitialspace)
return ('', False, None, 0)
quotes = {}
delims = {}
spaces = 0
groupindex = regexp.groupindex
for m in matches:
n = groupindex['quote'] - 1
key = m[n]
if key:
quotes[key] = quotes.get(key, 0) + 1
try:
n = groupindex['delim'] - 1
key = m[n]
except KeyError:
continue
if key and (delimiters is None or key in delimiters):
delims[key] = delims.get(key, 0) + 1
try:
n = groupindex['space'] - 1
except KeyError:
continue
if m[n]:
spaces += 1
quotechar = max(quotes, key=quotes.get)
if delims:
delim = max(delims, key=delims.get)
skipinitialspace = delims[delim] == spaces
if delim == '\n': # most likely a file with a single column
delim = ''
else:
# there is *no* delimiter, it's a single column of quoted data
delim = ''
skipinitialspace = 0
# if we see an extra quote between delimiters, we've got a
# double quoted format
dq_regexp = re.compile(
r"((%(delim)s)|^)\W*%(quote)s[^%(delim)s\n]*%(quote)s[^%(delim)s\n]*%(quote)s\W*((%(delim)s)|$)" % \
{'delim':re.escape(delim), 'quote':quotechar}, re.MULTILINE)
if dq_regexp.search(data):
doublequote = True
else:
doublequote = False
return (quotechar, doublequote, delim, skipinitialspace) | [
"def",
"_guess_quote_and_delimiter",
"(",
"self",
",",
"data",
",",
"delimiters",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"restr",
"in",
"(",
"r'(?P<delim>[^\\w\\n\"\\'])(?P<space> ?)(?P<quote>[\"\\']).*?(?P=quote)(?P=delim)'",
",",
"# ,\".*?\",",
"r'(?:^|\\n)(?P<quote>[\"\\']).*?(?P=quote)(?P<delim>[^\\w\\n\"\\'])(?P<space> ?)'",
",",
"# \".*?\",",
"r'(?P<delim>[^\\w\\n\"\\'])(?P<space> ?)(?P<quote>[\"\\']).*?(?P=quote)(?:$|\\n)'",
",",
"# ,\".*?\"",
"r'(?:^|\\n)(?P<quote>[\"\\']).*?(?P=quote)(?:$|\\n)'",
")",
":",
"# \".*?\" (no delim, no space)",
"regexp",
"=",
"re",
".",
"compile",
"(",
"restr",
",",
"re",
".",
"DOTALL",
"|",
"re",
".",
"MULTILINE",
")",
"matches",
"=",
"regexp",
".",
"findall",
"(",
"data",
")",
"if",
"matches",
":",
"break",
"if",
"not",
"matches",
":",
"# (quotechar, doublequote, delimiter, skipinitialspace)",
"return",
"(",
"''",
",",
"False",
",",
"None",
",",
"0",
")",
"quotes",
"=",
"{",
"}",
"delims",
"=",
"{",
"}",
"spaces",
"=",
"0",
"groupindex",
"=",
"regexp",
".",
"groupindex",
"for",
"m",
"in",
"matches",
":",
"n",
"=",
"groupindex",
"[",
"'quote'",
"]",
"-",
"1",
"key",
"=",
"m",
"[",
"n",
"]",
"if",
"key",
":",
"quotes",
"[",
"key",
"]",
"=",
"quotes",
".",
"get",
"(",
"key",
",",
"0",
")",
"+",
"1",
"try",
":",
"n",
"=",
"groupindex",
"[",
"'delim'",
"]",
"-",
"1",
"key",
"=",
"m",
"[",
"n",
"]",
"except",
"KeyError",
":",
"continue",
"if",
"key",
"and",
"(",
"delimiters",
"is",
"None",
"or",
"key",
"in",
"delimiters",
")",
":",
"delims",
"[",
"key",
"]",
"=",
"delims",
".",
"get",
"(",
"key",
",",
"0",
")",
"+",
"1",
"try",
":",
"n",
"=",
"groupindex",
"[",
"'space'",
"]",
"-",
"1",
"except",
"KeyError",
":",
"continue",
"if",
"m",
"[",
"n",
"]",
":",
"spaces",
"+=",
"1",
"quotechar",
"=",
"max",
"(",
"quotes",
",",
"key",
"=",
"quotes",
".",
"get",
")",
"if",
"delims",
":",
"delim",
"=",
"max",
"(",
"delims",
",",
"key",
"=",
"delims",
".",
"get",
")",
"skipinitialspace",
"=",
"delims",
"[",
"delim",
"]",
"==",
"spaces",
"if",
"delim",
"==",
"'\\n'",
":",
"# most likely a file with a single column",
"delim",
"=",
"''",
"else",
":",
"# there is *no* delimiter, it's a single column of quoted data",
"delim",
"=",
"''",
"skipinitialspace",
"=",
"0",
"# if we see an extra quote between delimiters, we've got a",
"# double quoted format",
"dq_regexp",
"=",
"re",
".",
"compile",
"(",
"r\"((%(delim)s)|^)\\W*%(quote)s[^%(delim)s\\n]*%(quote)s[^%(delim)s\\n]*%(quote)s\\W*((%(delim)s)|$)\"",
"%",
"{",
"'delim'",
":",
"re",
".",
"escape",
"(",
"delim",
")",
",",
"'quote'",
":",
"quotechar",
"}",
",",
"re",
".",
"MULTILINE",
")",
"if",
"dq_regexp",
".",
"search",
"(",
"data",
")",
":",
"doublequote",
"=",
"True",
"else",
":",
"doublequote",
"=",
"False",
"return",
"(",
"quotechar",
",",
"doublequote",
",",
"delim",
",",
"skipinitialspace",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/csv.py#L204-L277 | |
tkn-tub/ns3-gym | 19bfe0a583e641142609939a090a09dfc63a095f | src/flow-monitor/examples/flowmon-parse-results.py | python | FiveTuple.__init__ | (self, el) | The initializer.
@param self The object pointer.
@param el The element. | The initializer. | [
"The",
"initializer",
"."
] | def __init__(self, el):
'''The initializer.
@param self The object pointer.
@param el The element.
'''
self.sourceAddress = el.get('sourceAddress')
self.destinationAddress = el.get('destinationAddress')
self.sourcePort = int(el.get('sourcePort'))
self.destinationPort = int(el.get('destinationPort'))
self.protocol = int(el.get('protocol')) | [
"def",
"__init__",
"(",
"self",
",",
"el",
")",
":",
"self",
".",
"sourceAddress",
"=",
"el",
".",
"get",
"(",
"'sourceAddress'",
")",
"self",
".",
"destinationAddress",
"=",
"el",
".",
"get",
"(",
"'destinationAddress'",
")",
"self",
".",
"sourcePort",
"=",
"int",
"(",
"el",
".",
"get",
"(",
"'sourcePort'",
")",
")",
"self",
".",
"destinationPort",
"=",
"int",
"(",
"el",
".",
"get",
"(",
"'destinationPort'",
")",
")",
"self",
".",
"protocol",
"=",
"int",
"(",
"el",
".",
"get",
"(",
"'protocol'",
")",
")"
] | https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/src/flow-monitor/examples/flowmon-parse-results.py#L32-L41 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/layers/python/ops/sparse_ops.py | python | indicators_to_sparse_ids | (indicators, ignore_value=None, dtype=dtypes.int64) | Convert a dense indicator tensor to sparse IDs.
This is commonly used for converting a dense classification label to sparse.
In the following example, we have an input of shape (2, 2, num_classes),
where num_classes=4.
```python
indicators = [
[
[0, 0, 1, 0],
[0, 0, 0, 0]
], [
[1, 0, 1, 1],
[0, 0, 1, 0]
]
]
sparse_ids = indicator_to_sparse_ids(indicators)
```
`sparse_ids` in "jagged" format:
[
[
[2],
[]
], [
[0, 2, 3],
[2]
]
]
`sparse_ids` in `SparseTensor` format:
```python
{
indices: [[0, 0, 1], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0]],
values: [2, 0, 2, 3, 2],
dense_shape: [2, 2, 3]
}
```
Args:
indicators: Dense `Tensor` of shape `(d0, ..., dn, num_classes)`.
`ignore_value` values are ignored. For other values (typically, ones), the
index along the last dimension is returned.
ignore_value: Entries in `indicators` equal to this value will be
absent from the returned `SparseTensor`. If `None`, default value of
`indicators` dtype will be used (e.g. '' for `str`, 0 for `int`).
dtype: Type of result, must be integer type.
Returns:
`SparseTensor` of type `dtype` and shape `(d0, ..., dn, max_num_labels)`,
where `max_num_labels` is the maximum number of non-zero values in any
row (in the example above, row (1, 1) has 3 non-zero values, so the result
shape is (2, 2, 3)). The values of this `SparseTensor` are in the range
`[0, num_classes)` and correspond to the index of non-ignore values along
the last dimension of `indicators`.
Raises:
ValueError: if `dtype` is not integer. | Convert a dense indicator tensor to sparse IDs. | [
"Convert",
"a",
"dense",
"indicator",
"tensor",
"to",
"sparse",
"IDs",
"."
] | def indicators_to_sparse_ids(indicators, ignore_value=None, dtype=dtypes.int64):
"""Convert a dense indicator tensor to sparse IDs.
This is commonly used for converting a dense classification label to sparse.
In the following example, we have an input of shape (2, 2, num_classes),
where num_classes=4.
```python
indicators = [
[
[0, 0, 1, 0],
[0, 0, 0, 0]
], [
[1, 0, 1, 1],
[0, 0, 1, 0]
]
]
sparse_ids = indicator_to_sparse_ids(indicators)
```
`sparse_ids` in "jagged" format:
[
[
[2],
[]
], [
[0, 2, 3],
[2]
]
]
`sparse_ids` in `SparseTensor` format:
```python
{
indices: [[0, 0, 1], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0]],
values: [2, 0, 2, 3, 2],
dense_shape: [2, 2, 3]
}
```
Args:
indicators: Dense `Tensor` of shape `(d0, ..., dn, num_classes)`.
`ignore_value` values are ignored. For other values (typically, ones), the
index along the last dimension is returned.
ignore_value: Entries in `indicators` equal to this value will be
absent from the returned `SparseTensor`. If `None`, default value of
`indicators` dtype will be used (e.g. '' for `str`, 0 for `int`).
dtype: Type of result, must be integer type.
Returns:
`SparseTensor` of type `dtype` and shape `(d0, ..., dn, max_num_labels)`,
where `max_num_labels` is the maximum number of non-zero values in any
row (in the example above, row (1, 1) has 3 non-zero values, so the result
shape is (2, 2, 3)). The values of this `SparseTensor` are in the range
`[0, num_classes)` and correspond to the index of non-ignore values along
the last dimension of `indicators`.
Raises:
ValueError: if `dtype` is not integer.
"""
if not dtype.is_integer:
raise ValueError("Invalid dtype {} not integer.".format(dtype))
with ops.name_scope(
None, "indicators_to_sparse_ids", (indicators, ignore_value)):
# Convert indicators to binary ones and zeros. We use int64 since
# SparseTensor requires int64 indices.
indicators = ops.convert_to_tensor(indicators, name="indicators")
missing_indicators = math_ops.equal(
indicators, _ignore_value_tensor(indicators.dtype, ignore_value),
name="missing")
zeros_like_indicators = array_ops.zeros_like(
indicators, dtype=dtypes.int64, name="zeros")
binary_indicators = array_ops.where(
missing_indicators, zeros_like_indicators,
array_ops.ones_like(indicators, dtype=dtypes.int64, name="ones"),
name="binary_indicators")
# Use cumsum along the last dimension to generate per-row indexes.
# Note that these are 1-based (since 0 indicates missing values), so they're
# off-by-1 from the actual indices. We'll subtract 1 below. Since they're
# off-by-one, the max value is the size of the last dimension (i.e.,
# last_index + 1).
row_index_indicators = array_ops.where(
missing_indicators, zeros_like_indicators,
math_ops.cumsum(binary_indicators, axis=-1), "row_index_indicators")
result_last_dim = array_ops.reshape(
math_ops.reduce_max(row_index_indicators), shape=(1,),
name="result_last_dim")
# Convert to a SparseTensor. The values of this SparseTensor are the last
# indices of our result, and the last indices of this SparseTensor (i.e.,
# the class IDs indicated by `indicators`) are the values of our result, so
# we use tensor slicing and concat to swap them.
sparse_row_index_indicators = dense_to_sparse_tensor(
row_index_indicators, ignore_value=0)
return sparse_tensor.SparseTensor(
indices=array_ops.concat((
sparse_row_index_indicators.indices[:, :-1],
array_ops.reshape(sparse_row_index_indicators.values - 1, (-1, 1))
), axis=1, name="indices"),
values=math_ops.cast(
sparse_row_index_indicators.indices[:, -1], dtype=dtype,
name="values"),
dense_shape=array_ops.concat(
(sparse_row_index_indicators.dense_shape[0:-1], result_last_dim),
axis=0, name="dense_shape")) | [
"def",
"indicators_to_sparse_ids",
"(",
"indicators",
",",
"ignore_value",
"=",
"None",
",",
"dtype",
"=",
"dtypes",
".",
"int64",
")",
":",
"if",
"not",
"dtype",
".",
"is_integer",
":",
"raise",
"ValueError",
"(",
"\"Invalid dtype {} not integer.\"",
".",
"format",
"(",
"dtype",
")",
")",
"with",
"ops",
".",
"name_scope",
"(",
"None",
",",
"\"indicators_to_sparse_ids\"",
",",
"(",
"indicators",
",",
"ignore_value",
")",
")",
":",
"# Convert indicators to binary ones and zeros. We use int64 since",
"# SparseTensor requires int64 indices.",
"indicators",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"indicators",
",",
"name",
"=",
"\"indicators\"",
")",
"missing_indicators",
"=",
"math_ops",
".",
"equal",
"(",
"indicators",
",",
"_ignore_value_tensor",
"(",
"indicators",
".",
"dtype",
",",
"ignore_value",
")",
",",
"name",
"=",
"\"missing\"",
")",
"zeros_like_indicators",
"=",
"array_ops",
".",
"zeros_like",
"(",
"indicators",
",",
"dtype",
"=",
"dtypes",
".",
"int64",
",",
"name",
"=",
"\"zeros\"",
")",
"binary_indicators",
"=",
"array_ops",
".",
"where",
"(",
"missing_indicators",
",",
"zeros_like_indicators",
",",
"array_ops",
".",
"ones_like",
"(",
"indicators",
",",
"dtype",
"=",
"dtypes",
".",
"int64",
",",
"name",
"=",
"\"ones\"",
")",
",",
"name",
"=",
"\"binary_indicators\"",
")",
"# Use cumsum along the last dimension to generate per-row indexes.",
"# Note that these are 1-based (since 0 indicates missing values), so they're",
"# off-by-1 from the actual indices. We'll subtract 1 below. Since they're",
"# off-by-one, the max value is the size of the last dimension (i.e.,",
"# last_index + 1).",
"row_index_indicators",
"=",
"array_ops",
".",
"where",
"(",
"missing_indicators",
",",
"zeros_like_indicators",
",",
"math_ops",
".",
"cumsum",
"(",
"binary_indicators",
",",
"axis",
"=",
"-",
"1",
")",
",",
"\"row_index_indicators\"",
")",
"result_last_dim",
"=",
"array_ops",
".",
"reshape",
"(",
"math_ops",
".",
"reduce_max",
"(",
"row_index_indicators",
")",
",",
"shape",
"=",
"(",
"1",
",",
")",
",",
"name",
"=",
"\"result_last_dim\"",
")",
"# Convert to a SparseTensor. The values of this SparseTensor are the last",
"# indices of our result, and the last indices of this SparseTensor (i.e.,",
"# the class IDs indicated by `indicators`) are the values of our result, so",
"# we use tensor slicing and concat to swap them.",
"sparse_row_index_indicators",
"=",
"dense_to_sparse_tensor",
"(",
"row_index_indicators",
",",
"ignore_value",
"=",
"0",
")",
"return",
"sparse_tensor",
".",
"SparseTensor",
"(",
"indices",
"=",
"array_ops",
".",
"concat",
"(",
"(",
"sparse_row_index_indicators",
".",
"indices",
"[",
":",
",",
":",
"-",
"1",
"]",
",",
"array_ops",
".",
"reshape",
"(",
"sparse_row_index_indicators",
".",
"values",
"-",
"1",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
")",
",",
"axis",
"=",
"1",
",",
"name",
"=",
"\"indices\"",
")",
",",
"values",
"=",
"math_ops",
".",
"cast",
"(",
"sparse_row_index_indicators",
".",
"indices",
"[",
":",
",",
"-",
"1",
"]",
",",
"dtype",
"=",
"dtype",
",",
"name",
"=",
"\"values\"",
")",
",",
"dense_shape",
"=",
"array_ops",
".",
"concat",
"(",
"(",
"sparse_row_index_indicators",
".",
"dense_shape",
"[",
"0",
":",
"-",
"1",
"]",
",",
"result_last_dim",
")",
",",
"axis",
"=",
"0",
",",
"name",
"=",
"\"dense_shape\"",
")",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/layers/python/ops/sparse_ops.py#L82-L187 | ||
mysql/mysql-workbench | 2f35f9034f015cbcd22139a60e1baa2e3e8e795c | modules/db.generic/db_generic_re_grt.py | python | GenericReverseEngineering.connect | (cls, connection, password) | return 1 | Establishes a connection to the server and stores the connection object in the connections pool.
It first looks for a connection with the given connection parameters in the connections pool to
reuse existent connections. If such a connection is found, it queries the server to ensure that the
connection is alive and reestablishes it if is dead. If no suitable connection is found in the
connections pool, a new one is created and stored in the pool.
Parameters:
===========
connection: an object of the class db_mgmt_Connection storing the parameters
for the connection.
password: a string with the password to use for the connection. | Establishes a connection to the server and stores the connection object in the connections pool. | [
"Establishes",
"a",
"connection",
"to",
"the",
"server",
"and",
"stores",
"the",
"connection",
"object",
"in",
"the",
"connections",
"pool",
"."
] | def connect(cls, connection, password):
'''Establishes a connection to the server and stores the connection object in the connections pool.
It first looks for a connection with the given connection parameters in the connections pool to
reuse existent connections. If such a connection is found, it queries the server to ensure that the
connection is alive and reestablishes it if is dead. If no suitable connection is found in the
connections pool, a new one is created and stored in the pool.
Parameters:
===========
connection: an object of the class db_mgmt_Connection storing the parameters
for the connection.
password: a string with the password to use for the connection.
'''
try:
con = cls.get_connection(connection)
try:
if not con.cursor().execute('SELECT 1'):
raise Exception("connection error")
except Exception as exc:
grt.send_info("Connection to %s apparently lost, reconnecting..." % connection.hostIdentifier)
raise NotConnectedError("Connection error")
except NotConnectedError as exc:
grt.send_info("Connecting to %s..." % connection.hostIdentifier)
con = db_driver.connect(connection, password)
if not con:
grt.send_error('Connection failed', str(exc))
raise
grt.send_info("Connected")
cls._connections[connection.__id__] = {"connection": con}
return 1 | [
"def",
"connect",
"(",
"cls",
",",
"connection",
",",
"password",
")",
":",
"try",
":",
"con",
"=",
"cls",
".",
"get_connection",
"(",
"connection",
")",
"try",
":",
"if",
"not",
"con",
".",
"cursor",
"(",
")",
".",
"execute",
"(",
"'SELECT 1'",
")",
":",
"raise",
"Exception",
"(",
"\"connection error\"",
")",
"except",
"Exception",
"as",
"exc",
":",
"grt",
".",
"send_info",
"(",
"\"Connection to %s apparently lost, reconnecting...\"",
"%",
"connection",
".",
"hostIdentifier",
")",
"raise",
"NotConnectedError",
"(",
"\"Connection error\"",
")",
"except",
"NotConnectedError",
"as",
"exc",
":",
"grt",
".",
"send_info",
"(",
"\"Connecting to %s...\"",
"%",
"connection",
".",
"hostIdentifier",
")",
"con",
"=",
"db_driver",
".",
"connect",
"(",
"connection",
",",
"password",
")",
"if",
"not",
"con",
":",
"grt",
".",
"send_error",
"(",
"'Connection failed'",
",",
"str",
"(",
"exc",
")",
")",
"raise",
"grt",
".",
"send_info",
"(",
"\"Connected\"",
")",
"cls",
".",
"_connections",
"[",
"connection",
".",
"__id__",
"]",
"=",
"{",
"\"connection\"",
":",
"con",
"}",
"return",
"1"
] | https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/modules/db.generic/db_generic_re_grt.py#L123-L153 | |
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | tools/clang/bindings/python/clang/cindex.py | python | SourceLocation.column | (self) | return self._get_instantiation()[2] | Get the column represented by this source location. | Get the column represented by this source location. | [
"Get",
"the",
"column",
"represented",
"by",
"this",
"source",
"location",
"."
] | def column(self):
"""Get the column represented by this source location."""
return self._get_instantiation()[2] | [
"def",
"column",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_instantiation",
"(",
")",
"[",
"2",
"]"
] | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L208-L210 | |
pisa-engine/pisa | 0efb7926d4928c8aae672ba4d7a1419891f2676d | script/ext/baker.py | python | Baker.parse_args | (self, scriptname, cmd, argv, test=False) | return vargs, kwargs | Parse arguments from argv.
:param scriptname: The script filename.
:param cmd: The command which is being called.
:param argv: The argument list.
:param test: If True prints to stdout. | Parse arguments from argv. | [
"Parse",
"arguments",
"from",
"argv",
"."
] | def parse_args(self, scriptname, cmd, argv, test=False):
"""
Parse arguments from argv.
:param scriptname: The script filename.
:param cmd: The command which is being called.
:param argv: The argument list.
:param test: If True prints to stdout.
"""
keywords = cmd.keywords
shortopts = cmd.shortopts
def type_error(name, value, t):
if not test:
msg = "%s value %r must be %s" % (name, value, t)
raise CommandError(msg, scriptname, cmd)
# shortopts maps long option names to characters. To look up short
# options, we need to create a reverse mapping.
shortchars = dict((v, k) for k, v in shortopts.items())
# The *args list and **kwargs dict to build up from the command line
# arguments
vargs = []
kwargs = {}
double_dash = 0
single_dash = 0
while argv:
# Take the next argument
arg = argv.pop(0)
if arg == "--":
double_dash += 1
if double_dash != 1:
raise CommandError("You cannot specify -- more than once")
# All arguments following a double hyphen are treated as
# positional arguments
vargs.extend(argv)
break
elif arg == "-":
# sys.stdin
single_dash += 1
if single_dash != 1:
raise CommandError("You cannot specify - more than once")
vargs.append("-")
elif arg.startswith("--"):
# Process long option
value = None
if "=" in arg:
# The argument was specified like --keyword=value
name, value = arg[2:].split("=", 1)
# strip quotes if value is quoted like
# --keyword='multiple words'
value = value.strip('\'"')
default = keywords.get(name)
try:
value = totype(value, default)
except (TypeError, ValueError):
type_error(name, value, type(default))
else:
# The argument was not specified with an equals sign...
name = arg[2:]
default = keywords.get(name)
if type(default) is bool:
# If this option is a boolean, it doesn't need a value;
# specifying it on the command line means "do the
# opposite of the default".
value = not default
else:
# The next item in the argument list is the value, i.e.
# --keyword value
if not argv or argv[0].startswith("-"):
# Oops, there isn't a value available... just use
# True, assuming this is a flag.
value = True
else:
value = argv.pop(0)
try:
value = totype(value, default)
except (TypeError, ValueError):
type_error(name, value, type(default))
# Store this option
kwargs[name] = value
elif arg.startswith("-") and (cmd.shortopts or cmd.has_kwargs):
# Process short option(s)
# For each character after the '-'...
for i in range(1, len(arg)):
char = arg[i]
if cmd.has_kwargs:
name = char
default = keywords.get(name)
elif char not in shortchars:
continue
else:
# Get the long option name corresponding to this char
name = shortchars[char]
default = keywords[name]
if isinstance(default, bool):
# If this option is a boolean, it doesn't need a value;
# specifying it on the command line means "do the
# opposite of the default".
kwargs[name] = not default
else:
# This option requires a value...
if i == len(arg) - 1:
# This is the last character in the list, so the
# next argument on the command line is the value.
value = argv.pop(0)
else:
# There are other characters after this one, so
# the rest of the characters must represent the
# value (i.e. old-style UNIX option like -Nname)
value = arg[i + 1:]
# Remove leading equals sign if it's present. That
# means the option/value were specified as opt=value
# Then remove quotes.
value = value.lstrip("=").strip("'\"")
try:
kwargs[name] = totype(value, default)
except (TypeError, ValueError):
type_error(name, value, type(default))
break
else:
# This doesn't start with "-", so just add it to the list of
# positional arguments.
vargs.append(arg)
return vargs, kwargs | [
"def",
"parse_args",
"(",
"self",
",",
"scriptname",
",",
"cmd",
",",
"argv",
",",
"test",
"=",
"False",
")",
":",
"keywords",
"=",
"cmd",
".",
"keywords",
"shortopts",
"=",
"cmd",
".",
"shortopts",
"def",
"type_error",
"(",
"name",
",",
"value",
",",
"t",
")",
":",
"if",
"not",
"test",
":",
"msg",
"=",
"\"%s value %r must be %s\"",
"%",
"(",
"name",
",",
"value",
",",
"t",
")",
"raise",
"CommandError",
"(",
"msg",
",",
"scriptname",
",",
"cmd",
")",
"# shortopts maps long option names to characters. To look up short",
"# options, we need to create a reverse mapping.",
"shortchars",
"=",
"dict",
"(",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"shortopts",
".",
"items",
"(",
")",
")",
"# The *args list and **kwargs dict to build up from the command line",
"# arguments",
"vargs",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"double_dash",
"=",
"0",
"single_dash",
"=",
"0",
"while",
"argv",
":",
"# Take the next argument",
"arg",
"=",
"argv",
".",
"pop",
"(",
"0",
")",
"if",
"arg",
"==",
"\"--\"",
":",
"double_dash",
"+=",
"1",
"if",
"double_dash",
"!=",
"1",
":",
"raise",
"CommandError",
"(",
"\"You cannot specify -- more than once\"",
")",
"# All arguments following a double hyphen are treated as",
"# positional arguments",
"vargs",
".",
"extend",
"(",
"argv",
")",
"break",
"elif",
"arg",
"==",
"\"-\"",
":",
"# sys.stdin",
"single_dash",
"+=",
"1",
"if",
"single_dash",
"!=",
"1",
":",
"raise",
"CommandError",
"(",
"\"You cannot specify - more than once\"",
")",
"vargs",
".",
"append",
"(",
"\"-\"",
")",
"elif",
"arg",
".",
"startswith",
"(",
"\"--\"",
")",
":",
"# Process long option",
"value",
"=",
"None",
"if",
"\"=\"",
"in",
"arg",
":",
"# The argument was specified like --keyword=value",
"name",
",",
"value",
"=",
"arg",
"[",
"2",
":",
"]",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"# strip quotes if value is quoted like",
"# --keyword='multiple words'",
"value",
"=",
"value",
".",
"strip",
"(",
"'\\'\"'",
")",
"default",
"=",
"keywords",
".",
"get",
"(",
"name",
")",
"try",
":",
"value",
"=",
"totype",
"(",
"value",
",",
"default",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"type_error",
"(",
"name",
",",
"value",
",",
"type",
"(",
"default",
")",
")",
"else",
":",
"# The argument was not specified with an equals sign...",
"name",
"=",
"arg",
"[",
"2",
":",
"]",
"default",
"=",
"keywords",
".",
"get",
"(",
"name",
")",
"if",
"type",
"(",
"default",
")",
"is",
"bool",
":",
"# If this option is a boolean, it doesn't need a value;",
"# specifying it on the command line means \"do the",
"# opposite of the default\".",
"value",
"=",
"not",
"default",
"else",
":",
"# The next item in the argument list is the value, i.e.",
"# --keyword value",
"if",
"not",
"argv",
"or",
"argv",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"-\"",
")",
":",
"# Oops, there isn't a value available... just use",
"# True, assuming this is a flag.",
"value",
"=",
"True",
"else",
":",
"value",
"=",
"argv",
".",
"pop",
"(",
"0",
")",
"try",
":",
"value",
"=",
"totype",
"(",
"value",
",",
"default",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"type_error",
"(",
"name",
",",
"value",
",",
"type",
"(",
"default",
")",
")",
"# Store this option",
"kwargs",
"[",
"name",
"]",
"=",
"value",
"elif",
"arg",
".",
"startswith",
"(",
"\"-\"",
")",
"and",
"(",
"cmd",
".",
"shortopts",
"or",
"cmd",
".",
"has_kwargs",
")",
":",
"# Process short option(s)",
"# For each character after the '-'...",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"arg",
")",
")",
":",
"char",
"=",
"arg",
"[",
"i",
"]",
"if",
"cmd",
".",
"has_kwargs",
":",
"name",
"=",
"char",
"default",
"=",
"keywords",
".",
"get",
"(",
"name",
")",
"elif",
"char",
"not",
"in",
"shortchars",
":",
"continue",
"else",
":",
"# Get the long option name corresponding to this char",
"name",
"=",
"shortchars",
"[",
"char",
"]",
"default",
"=",
"keywords",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"default",
",",
"bool",
")",
":",
"# If this option is a boolean, it doesn't need a value;",
"# specifying it on the command line means \"do the",
"# opposite of the default\".",
"kwargs",
"[",
"name",
"]",
"=",
"not",
"default",
"else",
":",
"# This option requires a value...",
"if",
"i",
"==",
"len",
"(",
"arg",
")",
"-",
"1",
":",
"# This is the last character in the list, so the",
"# next argument on the command line is the value.",
"value",
"=",
"argv",
".",
"pop",
"(",
"0",
")",
"else",
":",
"# There are other characters after this one, so",
"# the rest of the characters must represent the",
"# value (i.e. old-style UNIX option like -Nname)",
"value",
"=",
"arg",
"[",
"i",
"+",
"1",
":",
"]",
"# Remove leading equals sign if it's present. That",
"# means the option/value were specified as opt=value",
"# Then remove quotes.",
"value",
"=",
"value",
".",
"lstrip",
"(",
"\"=\"",
")",
".",
"strip",
"(",
"\"'\\\"\"",
")",
"try",
":",
"kwargs",
"[",
"name",
"]",
"=",
"totype",
"(",
"value",
",",
"default",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"type_error",
"(",
"name",
",",
"value",
",",
"type",
"(",
"default",
")",
")",
"break",
"else",
":",
"# This doesn't start with \"-\", so just add it to the list of",
"# positional arguments.",
"vargs",
".",
"append",
"(",
"arg",
")",
"return",
"vargs",
",",
"kwargs"
] | https://github.com/pisa-engine/pisa/blob/0efb7926d4928c8aae672ba4d7a1419891f2676d/script/ext/baker.py#L592-L732 | |
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/site_packages/joblib3/logger.py | python | PrintTime.__call__ | (self, msg='', total=False) | Print the time elapsed between the last call and the current
call, with an optional message. | Print the time elapsed between the last call and the current
call, with an optional message. | [
"Print",
"the",
"time",
"elapsed",
"between",
"the",
"last",
"call",
"and",
"the",
"current",
"call",
"with",
"an",
"optional",
"message",
"."
] | def __call__(self, msg='', total=False):
""" Print the time elapsed between the last call and the current
call, with an optional message.
"""
if not total:
time_lapse = time.time() - self.last_time
full_msg = "%s: %s" % (msg, format_time(time_lapse))
else:
# FIXME: Too much logic duplicated
time_lapse = time.time() - self.start_time
full_msg = "%s: %.2fs, %.1f min" % (msg, time_lapse,
time_lapse / 60)
print(full_msg, file=sys.stderr)
if self.logfile is not None:
try:
with open(self.logfile, 'a') as f:
print(full_msg, file=f)
except:
""" Multiprocessing writing to files can create race
conditions. Rather fail silently than crash the
calculation.
"""
# XXX: We actually need a debug flag to disable this
# silent failure.
self.last_time = time.time() | [
"def",
"__call__",
"(",
"self",
",",
"msg",
"=",
"''",
",",
"total",
"=",
"False",
")",
":",
"if",
"not",
"total",
":",
"time_lapse",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"last_time",
"full_msg",
"=",
"\"%s: %s\"",
"%",
"(",
"msg",
",",
"format_time",
"(",
"time_lapse",
")",
")",
"else",
":",
"# FIXME: Too much logic duplicated",
"time_lapse",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"start_time",
"full_msg",
"=",
"\"%s: %.2fs, %.1f min\"",
"%",
"(",
"msg",
",",
"time_lapse",
",",
"time_lapse",
"/",
"60",
")",
"print",
"(",
"full_msg",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"if",
"self",
".",
"logfile",
"is",
"not",
"None",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"logfile",
",",
"'a'",
")",
"as",
"f",
":",
"print",
"(",
"full_msg",
",",
"file",
"=",
"f",
")",
"except",
":",
"\"\"\" Multiprocessing writing to files can create race\n conditions. Rather fail silently than crash the\n calculation.\n \"\"\"",
"# XXX: We actually need a debug flag to disable this",
"# silent failure.",
"self",
".",
"last_time",
"=",
"time",
".",
"time",
"(",
")"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/joblib3/logger.py#L133-L157 | ||
carla-simulator/carla | 8854804f4d7748e14d937ec763a2912823a7e5f5 | PythonAPI/carla/agents/navigation/behavior_agent.py | python | BehaviorAgent.run_step | (self, debug=False) | return control | Execute one step of navigation.
:param debug: boolean for debugging
:return control: carla.VehicleControl | Execute one step of navigation. | [
"Execute",
"one",
"step",
"of",
"navigation",
"."
] | def run_step(self, debug=False):
"""
Execute one step of navigation.
:param debug: boolean for debugging
:return control: carla.VehicleControl
"""
self._update_information()
control = None
if self._behavior.tailgate_counter > 0:
self._behavior.tailgate_counter -= 1
ego_vehicle_loc = self._vehicle.get_location()
ego_vehicle_wp = self._map.get_waypoint(ego_vehicle_loc)
# 1: Red lights and stops behavior
if self.traffic_light_manager():
return self.emergency_stop()
# 2.1: Pedestrian avoidance behaviors
walker_state, walker, w_distance = self.pedestrian_avoid_manager(ego_vehicle_wp)
if walker_state:
# Distance is computed from the center of the two cars,
# we use bounding boxes to calculate the actual distance
distance = w_distance - max(
walker.bounding_box.extent.y, walker.bounding_box.extent.x) - max(
self._vehicle.bounding_box.extent.y, self._vehicle.bounding_box.extent.x)
# Emergency brake if the car is very close.
if distance < self._behavior.braking_distance:
return self.emergency_stop()
# 2.2: Car following behaviors
vehicle_state, vehicle, distance = self.collision_and_car_avoid_manager(ego_vehicle_wp)
if vehicle_state:
# Distance is computed from the center of the two cars,
# we use bounding boxes to calculate the actual distance
distance = distance - max(
vehicle.bounding_box.extent.y, vehicle.bounding_box.extent.x) - max(
self._vehicle.bounding_box.extent.y, self._vehicle.bounding_box.extent.x)
# Emergency brake if the car is very close.
if distance < self._behavior.braking_distance:
return self.emergency_stop()
else:
control = self.car_following_manager(vehicle, distance)
# 3: Intersection behavior
elif self._incoming_waypoint.is_junction and (self._incoming_direction in [RoadOption.LEFT, RoadOption.RIGHT]):
target_speed = min([
self._behavior.max_speed,
self._speed_limit - 5])
self._local_planner.set_speed(target_speed)
control = self._local_planner.run_step(debug=debug)
# 4: Normal behavior
else:
target_speed = min([
self._behavior.max_speed,
self._speed_limit - self._behavior.speed_lim_dist])
self._local_planner.set_speed(target_speed)
control = self._local_planner.run_step(debug=debug)
return control | [
"def",
"run_step",
"(",
"self",
",",
"debug",
"=",
"False",
")",
":",
"self",
".",
"_update_information",
"(",
")",
"control",
"=",
"None",
"if",
"self",
".",
"_behavior",
".",
"tailgate_counter",
">",
"0",
":",
"self",
".",
"_behavior",
".",
"tailgate_counter",
"-=",
"1",
"ego_vehicle_loc",
"=",
"self",
".",
"_vehicle",
".",
"get_location",
"(",
")",
"ego_vehicle_wp",
"=",
"self",
".",
"_map",
".",
"get_waypoint",
"(",
"ego_vehicle_loc",
")",
"# 1: Red lights and stops behavior",
"if",
"self",
".",
"traffic_light_manager",
"(",
")",
":",
"return",
"self",
".",
"emergency_stop",
"(",
")",
"# 2.1: Pedestrian avoidance behaviors",
"walker_state",
",",
"walker",
",",
"w_distance",
"=",
"self",
".",
"pedestrian_avoid_manager",
"(",
"ego_vehicle_wp",
")",
"if",
"walker_state",
":",
"# Distance is computed from the center of the two cars,",
"# we use bounding boxes to calculate the actual distance",
"distance",
"=",
"w_distance",
"-",
"max",
"(",
"walker",
".",
"bounding_box",
".",
"extent",
".",
"y",
",",
"walker",
".",
"bounding_box",
".",
"extent",
".",
"x",
")",
"-",
"max",
"(",
"self",
".",
"_vehicle",
".",
"bounding_box",
".",
"extent",
".",
"y",
",",
"self",
".",
"_vehicle",
".",
"bounding_box",
".",
"extent",
".",
"x",
")",
"# Emergency brake if the car is very close.",
"if",
"distance",
"<",
"self",
".",
"_behavior",
".",
"braking_distance",
":",
"return",
"self",
".",
"emergency_stop",
"(",
")",
"# 2.2: Car following behaviors",
"vehicle_state",
",",
"vehicle",
",",
"distance",
"=",
"self",
".",
"collision_and_car_avoid_manager",
"(",
"ego_vehicle_wp",
")",
"if",
"vehicle_state",
":",
"# Distance is computed from the center of the two cars,",
"# we use bounding boxes to calculate the actual distance",
"distance",
"=",
"distance",
"-",
"max",
"(",
"vehicle",
".",
"bounding_box",
".",
"extent",
".",
"y",
",",
"vehicle",
".",
"bounding_box",
".",
"extent",
".",
"x",
")",
"-",
"max",
"(",
"self",
".",
"_vehicle",
".",
"bounding_box",
".",
"extent",
".",
"y",
",",
"self",
".",
"_vehicle",
".",
"bounding_box",
".",
"extent",
".",
"x",
")",
"# Emergency brake if the car is very close.",
"if",
"distance",
"<",
"self",
".",
"_behavior",
".",
"braking_distance",
":",
"return",
"self",
".",
"emergency_stop",
"(",
")",
"else",
":",
"control",
"=",
"self",
".",
"car_following_manager",
"(",
"vehicle",
",",
"distance",
")",
"# 3: Intersection behavior",
"elif",
"self",
".",
"_incoming_waypoint",
".",
"is_junction",
"and",
"(",
"self",
".",
"_incoming_direction",
"in",
"[",
"RoadOption",
".",
"LEFT",
",",
"RoadOption",
".",
"RIGHT",
"]",
")",
":",
"target_speed",
"=",
"min",
"(",
"[",
"self",
".",
"_behavior",
".",
"max_speed",
",",
"self",
".",
"_speed_limit",
"-",
"5",
"]",
")",
"self",
".",
"_local_planner",
".",
"set_speed",
"(",
"target_speed",
")",
"control",
"=",
"self",
".",
"_local_planner",
".",
"run_step",
"(",
"debug",
"=",
"debug",
")",
"# 4: Normal behavior",
"else",
":",
"target_speed",
"=",
"min",
"(",
"[",
"self",
".",
"_behavior",
".",
"max_speed",
",",
"self",
".",
"_speed_limit",
"-",
"self",
".",
"_behavior",
".",
"speed_lim_dist",
"]",
")",
"self",
".",
"_local_planner",
".",
"set_speed",
"(",
"target_speed",
")",
"control",
"=",
"self",
".",
"_local_planner",
".",
"run_step",
"(",
"debug",
"=",
"debug",
")",
"return",
"control"
] | https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/carla/agents/navigation/behavior_agent.py#L240-L306 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/pymock/mock.py | python | NonCallableMagicMock.mock_add_spec | (self, spec, spec_set=False) | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set. | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock. | [
"Add",
"a",
"spec",
"to",
"a",
"mock",
".",
"spec",
"can",
"either",
"be",
"an",
"object",
"or",
"a",
"list",
"of",
"strings",
".",
"Only",
"attributes",
"on",
"the",
"spec",
"can",
"be",
"fetched",
"as",
"attributes",
"from",
"the",
"mock",
"."
] | def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set)
self._mock_set_magics() | [
"def",
"mock_add_spec",
"(",
"self",
",",
"spec",
",",
"spec_set",
"=",
"False",
")",
":",
"self",
".",
"_mock_add_spec",
"(",
"spec",
",",
"spec_set",
")",
"self",
".",
"_mock_set_magics",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/pymock/mock.py#L1879-L1886 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/bz2.py | python | BZ2File.writelines | (self, seq) | Write a sequence of byte strings to the file.
Returns the number of uncompressed bytes written.
seq can be any iterable yielding byte strings.
Line separators are not added between the written byte strings. | Write a sequence of byte strings to the file. | [
"Write",
"a",
"sequence",
"of",
"byte",
"strings",
"to",
"the",
"file",
"."
] | def writelines(self, seq):
"""Write a sequence of byte strings to the file.
Returns the number of uncompressed bytes written.
seq can be any iterable yielding byte strings.
Line separators are not added between the written byte strings.
"""
with self._lock:
return _compression.BaseStream.writelines(self, seq) | [
"def",
"writelines",
"(",
"self",
",",
"seq",
")",
":",
"with",
"self",
".",
"_lock",
":",
"return",
"_compression",
".",
"BaseStream",
".",
"writelines",
"(",
"self",
",",
"seq",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/bz2.py#L246-L255 | ||
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/build/lib.linux-x86_64-2.7/mxnet/symbol.py | python | maximum | (left, right) | maximum left and right
Parameters
---------
left: Symbol or Number
right: Symbol or Number
Returns
-------
result: Symbol or Number | maximum left and right | [
"maximum",
"left",
"and",
"right"
] | def maximum(left, right):
""" maximum left and right
Parameters
---------
left: Symbol or Number
right: Symbol or Number
Returns
-------
result: Symbol or Number
"""
if isinstance(left, Symbol) and isinstance(right, Symbol):
return Symbol._Maximum(left, right)
if isinstance(left, Symbol) and isinstance(right, Number):
return Symbol._MaximumScalar(left, scalar=right)
if isinstance(left, Number) and isinstance(right, Symbol):
return Symbol._MaximumScalar(right, scalar=left, scalar_on_left=True)
if isinstance(left, Number) and isinstance(right, Number):
return left if left > right else right
else:
raise TypeError('types (%s, %s) not supported' % (str(type(left)), str(type(right)))) | [
"def",
"maximum",
"(",
"left",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"Symbol",
")",
"and",
"isinstance",
"(",
"right",
",",
"Symbol",
")",
":",
"return",
"Symbol",
".",
"_Maximum",
"(",
"left",
",",
"right",
")",
"if",
"isinstance",
"(",
"left",
",",
"Symbol",
")",
"and",
"isinstance",
"(",
"right",
",",
"Number",
")",
":",
"return",
"Symbol",
".",
"_MaximumScalar",
"(",
"left",
",",
"scalar",
"=",
"right",
")",
"if",
"isinstance",
"(",
"left",
",",
"Number",
")",
"and",
"isinstance",
"(",
"right",
",",
"Symbol",
")",
":",
"return",
"Symbol",
".",
"_MaximumScalar",
"(",
"right",
",",
"scalar",
"=",
"left",
",",
"scalar_on_left",
"=",
"True",
")",
"if",
"isinstance",
"(",
"left",
",",
"Number",
")",
"and",
"isinstance",
"(",
"right",
",",
"Number",
")",
":",
"return",
"left",
"if",
"left",
">",
"right",
"else",
"right",
"else",
":",
"raise",
"TypeError",
"(",
"'types (%s, %s) not supported'",
"%",
"(",
"str",
"(",
"type",
"(",
"left",
")",
")",
",",
"str",
"(",
"type",
"(",
"right",
")",
")",
")",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/symbol.py#L1059-L1080 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/tools/build/src/build/feature.py | python | get_values | (feature, properties) | return result | Returns all values of the given feature specified by the given property set. | Returns all values of the given feature specified by the given property set. | [
"Returns",
"all",
"values",
"of",
"the",
"given",
"feature",
"specified",
"by",
"the",
"given",
"property",
"set",
"."
] | def get_values (feature, properties):
""" Returns all values of the given feature specified by the given property set.
"""
if feature[0] != '<':
feature = '<' + feature + '>'
result = []
for p in properties:
if get_grist (p) == feature:
result.append (replace_grist (p, ''))
return result | [
"def",
"get_values",
"(",
"feature",
",",
"properties",
")",
":",
"if",
"feature",
"[",
"0",
"]",
"!=",
"'<'",
":",
"feature",
"=",
"'<'",
"+",
"feature",
"+",
"'>'",
"result",
"=",
"[",
"]",
"for",
"p",
"in",
"properties",
":",
"if",
"get_grist",
"(",
"p",
")",
"==",
"feature",
":",
"result",
".",
"append",
"(",
"replace_grist",
"(",
"p",
",",
"''",
")",
")",
"return",
"result"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/feature.py#L552-L562 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/_mode_eax.py | python | EaxMode.__init__ | (self, factory, key, nonce, mac_len, cipher_params) | EAX cipher mode | EAX cipher mode | [
"EAX",
"cipher",
"mode"
] | def __init__(self, factory, key, nonce, mac_len, cipher_params):
"""EAX cipher mode"""
self.block_size = factory.block_size
"""The block size of the underlying cipher, in bytes."""
self.nonce = _copy_bytes(None, None, nonce)
"""The nonce originally used to create the object."""
self._mac_len = mac_len
self._mac_tag = None # Cache for MAC tag
# Allowed transitions after initialization
self._next = [self.update, self.encrypt, self.decrypt,
self.digest, self.verify]
# MAC tag length
if not (4 <= self._mac_len <= self.block_size):
raise ValueError("Parameter 'mac_len' must not be larger than %d"
% self.block_size)
# Nonce cannot be empty and must be a byte string
if len(self.nonce) == 0:
raise ValueError("Nonce cannot be empty in EAX mode")
if not is_buffer(nonce):
raise TypeError("nonce must be bytes, bytearray or memoryview")
self._omac = [
CMAC.new(key,
b'\x00' * (self.block_size - 1) + struct.pack('B', i),
ciphermod=factory,
cipher_params=cipher_params)
for i in range(0, 3)
]
# Compute MAC of nonce
self._omac[0].update(self.nonce)
self._signer = self._omac[1]
# MAC of the nonce is also the initial counter for CTR encryption
counter_int = bytes_to_long(self._omac[0].digest())
self._cipher = factory.new(key,
factory.MODE_CTR,
initial_value=counter_int,
nonce=b"",
**cipher_params) | [
"def",
"__init__",
"(",
"self",
",",
"factory",
",",
"key",
",",
"nonce",
",",
"mac_len",
",",
"cipher_params",
")",
":",
"self",
".",
"block_size",
"=",
"factory",
".",
"block_size",
"\"\"\"The block size of the underlying cipher, in bytes.\"\"\"",
"self",
".",
"nonce",
"=",
"_copy_bytes",
"(",
"None",
",",
"None",
",",
"nonce",
")",
"\"\"\"The nonce originally used to create the object.\"\"\"",
"self",
".",
"_mac_len",
"=",
"mac_len",
"self",
".",
"_mac_tag",
"=",
"None",
"# Cache for MAC tag",
"# Allowed transitions after initialization",
"self",
".",
"_next",
"=",
"[",
"self",
".",
"update",
",",
"self",
".",
"encrypt",
",",
"self",
".",
"decrypt",
",",
"self",
".",
"digest",
",",
"self",
".",
"verify",
"]",
"# MAC tag length",
"if",
"not",
"(",
"4",
"<=",
"self",
".",
"_mac_len",
"<=",
"self",
".",
"block_size",
")",
":",
"raise",
"ValueError",
"(",
"\"Parameter 'mac_len' must not be larger than %d\"",
"%",
"self",
".",
"block_size",
")",
"# Nonce cannot be empty and must be a byte string",
"if",
"len",
"(",
"self",
".",
"nonce",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Nonce cannot be empty in EAX mode\"",
")",
"if",
"not",
"is_buffer",
"(",
"nonce",
")",
":",
"raise",
"TypeError",
"(",
"\"nonce must be bytes, bytearray or memoryview\"",
")",
"self",
".",
"_omac",
"=",
"[",
"CMAC",
".",
"new",
"(",
"key",
",",
"b'\\x00'",
"*",
"(",
"self",
".",
"block_size",
"-",
"1",
")",
"+",
"struct",
".",
"pack",
"(",
"'B'",
",",
"i",
")",
",",
"ciphermod",
"=",
"factory",
",",
"cipher_params",
"=",
"cipher_params",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"3",
")",
"]",
"# Compute MAC of nonce",
"self",
".",
"_omac",
"[",
"0",
"]",
".",
"update",
"(",
"self",
".",
"nonce",
")",
"self",
".",
"_signer",
"=",
"self",
".",
"_omac",
"[",
"1",
"]",
"# MAC of the nonce is also the initial counter for CTR encryption",
"counter_int",
"=",
"bytes_to_long",
"(",
"self",
".",
"_omac",
"[",
"0",
"]",
".",
"digest",
"(",
")",
")",
"self",
".",
"_cipher",
"=",
"factory",
".",
"new",
"(",
"key",
",",
"factory",
".",
"MODE_CTR",
",",
"initial_value",
"=",
"counter_int",
",",
"nonce",
"=",
"b\"\"",
",",
"*",
"*",
"cipher_params",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/_mode_eax.py#L80-L125 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/fc_scan.py | python | fortran_parser.find_deps | (self, node) | return (incs, uses, mods) | Parse a fortran file to read the dependencies used and provided
:param node: fortran file to read
:type node: :py:class:`waflib.Node.Node`
:return: lists representing the includes, the modules used, and the modules created by a fortran file
:rtype: tuple of list of strings | Parse a fortran file to read the dependencies used and provided | [
"Parse",
"a",
"fortran",
"file",
"to",
"read",
"the",
"dependencies",
"used",
"and",
"provided"
] | def find_deps(self, node):
"""
Parse a fortran file to read the dependencies used and provided
:param node: fortran file to read
:type node: :py:class:`waflib.Node.Node`
:return: lists representing the includes, the modules used, and the modules created by a fortran file
:rtype: tuple of list of strings
"""
txt = node.read()
incs = []
uses = []
mods = []
for line in txt.splitlines():
# line by line regexp search? optimize?
m = re_inc.search(line)
if m:
incs.append(m.group(1))
m = re_use.search(line)
if m:
uses.append(m.group(1))
m = re_mod.search(line)
if m:
mods.append(m.group(1))
return (incs, uses, mods) | [
"def",
"find_deps",
"(",
"self",
",",
"node",
")",
":",
"txt",
"=",
"node",
".",
"read",
"(",
")",
"incs",
"=",
"[",
"]",
"uses",
"=",
"[",
"]",
"mods",
"=",
"[",
"]",
"for",
"line",
"in",
"txt",
".",
"splitlines",
"(",
")",
":",
"# line by line regexp search? optimize?",
"m",
"=",
"re_inc",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"incs",
".",
"append",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"m",
"=",
"re_use",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"uses",
".",
"append",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"m",
"=",
"re_mod",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"mods",
".",
"append",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"return",
"(",
"incs",
",",
"uses",
",",
"mods",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/fc_scan.py#L42-L66 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | get_build_platform | () | return plat | Return this platform's string for platform-specific distributions
XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and Mac OS X. | Return this platform's string for platform-specific distributions | [
"Return",
"this",
"platform",
"s",
"string",
"for",
"platform",
"-",
"specific",
"distributions"
] | def get_build_platform():
"""Return this platform's string for platform-specific distributions
XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and Mac OS X.
"""
from sysconfig import get_platform
plat = get_platform()
if sys.platform == "darwin" and not plat.startswith('macosx-'):
try:
version = _macosx_vers()
machine = os.uname()[4].replace(" ", "_")
return "macosx-%d.%d-%s" % (
int(version[0]), int(version[1]),
_macosx_arch(machine),
)
except ValueError:
# if someone is running a non-Mac darwin system, this will fall
# through to the default implementation
pass
return plat | [
"def",
"get_build_platform",
"(",
")",
":",
"from",
"sysconfig",
"import",
"get_platform",
"plat",
"=",
"get_platform",
"(",
")",
"if",
"sys",
".",
"platform",
"==",
"\"darwin\"",
"and",
"not",
"plat",
".",
"startswith",
"(",
"'macosx-'",
")",
":",
"try",
":",
"version",
"=",
"_macosx_vers",
"(",
")",
"machine",
"=",
"os",
".",
"uname",
"(",
")",
"[",
"4",
"]",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"return",
"\"macosx-%d.%d-%s\"",
"%",
"(",
"int",
"(",
"version",
"[",
"0",
"]",
")",
",",
"int",
"(",
"version",
"[",
"1",
"]",
")",
",",
"_macosx_arch",
"(",
"machine",
")",
",",
")",
"except",
"ValueError",
":",
"# if someone is running a non-Mac darwin system, this will fall",
"# through to the default implementation",
"pass",
"return",
"plat"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L387-L408 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py | python | is_python | (text, filename='<string>') | Is this string a valid Python script? | Is this string a valid Python script? | [
"Is",
"this",
"string",
"a",
"valid",
"Python",
"script?"
] | def is_python(text, filename='<string>'):
"Is this string a valid Python script?"
try:
compile(text, filename, 'exec')
except (SyntaxError, TypeError):
return False
else:
return True | [
"def",
"is_python",
"(",
"text",
",",
"filename",
"=",
"'<string>'",
")",
":",
"try",
":",
"compile",
"(",
"text",
",",
"filename",
",",
"'exec'",
")",
"except",
"(",
"SyntaxError",
",",
"TypeError",
")",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py#L1921-L1928 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/socket.py | python | SocketIO.seekable | (self) | return super().seekable() | True if the SocketIO is open for seeking. | True if the SocketIO is open for seeking. | [
"True",
"if",
"the",
"SocketIO",
"is",
"open",
"for",
"seeking",
"."
] | def seekable(self):
"""True if the SocketIO is open for seeking.
"""
if self.closed:
raise ValueError("I/O operation on closed socket.")
return super().seekable() | [
"def",
"seekable",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed socket.\"",
")",
"return",
"super",
"(",
")",
".",
"seekable",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/socket.py#L628-L633 | |
alibaba/MNN | c4d9566171d589c3ded23aa18ffb197016995a12 | pymnn/pip_package/MNN/expr/__init__.py | python | cast | (x, dtype=_F.float) | return _F.cast(x, dtype) | cast(x, dtype=float)
Return the dtype of x.
Parameters
----------
x : var_like, input value.
dtype : dtype. Default is float.
Returns
-------
z : Var. The dtype of `x`.
Example:
-------
>>> expr.cast([[0,1],[0,3]], float)
var([[0., 1.],
[0., 3.]], dtype=float32) | cast(x, dtype=float)
Return the dtype of x. | [
"cast",
"(",
"x",
"dtype",
"=",
"float",
")",
"Return",
"the",
"dtype",
"of",
"x",
"."
] | def cast(x, dtype=_F.float):
'''
cast(x, dtype=float)
Return the dtype of x.
Parameters
----------
x : var_like, input value.
dtype : dtype. Default is float.
Returns
-------
z : Var. The dtype of `x`.
Example:
-------
>>> expr.cast([[0,1],[0,3]], float)
var([[0., 1.],
[0., 3.]], dtype=float32)
'''
x = _to_var(x)
return _F.cast(x, dtype) | [
"def",
"cast",
"(",
"x",
",",
"dtype",
"=",
"_F",
".",
"float",
")",
":",
"x",
"=",
"_to_var",
"(",
"x",
")",
"return",
"_F",
".",
"cast",
"(",
"x",
",",
"dtype",
")"
] | https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L1438-L1459 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/training/basic_session_run_hooks.py | python | FinalOpsHook.__init__ | (self, final_ops, final_ops_feed_dict=None) | Initializes `FinalOpHook` with ops to run at the end of the session.
Args:
final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of
names to `Tensors`.
final_ops_feed_dict: A feed dictionary to use when running
`final_ops_dict`. | Initializes `FinalOpHook` with ops to run at the end of the session. | [
"Initializes",
"FinalOpHook",
"with",
"ops",
"to",
"run",
"at",
"the",
"end",
"of",
"the",
"session",
"."
] | def __init__(self, final_ops, final_ops_feed_dict=None):
"""Initializes `FinalOpHook` with ops to run at the end of the session.
Args:
final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of
names to `Tensors`.
final_ops_feed_dict: A feed dictionary to use when running
`final_ops_dict`.
"""
self._final_ops = final_ops
self._final_ops_feed_dict = final_ops_feed_dict
self._final_ops_values = None | [
"def",
"__init__",
"(",
"self",
",",
"final_ops",
",",
"final_ops_feed_dict",
"=",
"None",
")",
":",
"self",
".",
"_final_ops",
"=",
"final_ops",
"self",
".",
"_final_ops_feed_dict",
"=",
"final_ops_feed_dict",
"self",
".",
"_final_ops_values",
"=",
"None"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/basic_session_run_hooks.py#L744-L755 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/idl/idl/parser.py | python | _parse_imports | (ctxt, spec, node) | Parse an imports section in the IDL file. | Parse an imports section in the IDL file. | [
"Parse",
"an",
"imports",
"section",
"in",
"the",
"IDL",
"file",
"."
] | def _parse_imports(ctxt, spec, node):
# type: (errors.ParserContext, syntax.IDLSpec, Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode]) -> None
"""Parse an imports section in the IDL file."""
if not ctxt.is_scalar_sequence(node, "imports"):
return
imports = syntax.Import(ctxt.file_name, node.start_mark.line, node.start_mark.column)
imports.imports = ctxt.get_list(node)
spec.imports = imports | [
"def",
"_parse_imports",
"(",
"ctxt",
",",
"spec",
",",
"node",
")",
":",
"# type: (errors.ParserContext, syntax.IDLSpec, Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode]) -> None",
"if",
"not",
"ctxt",
".",
"is_scalar_sequence",
"(",
"node",
",",
"\"imports\"",
")",
":",
"return",
"imports",
"=",
"syntax",
".",
"Import",
"(",
"ctxt",
".",
"file_name",
",",
"node",
".",
"start_mark",
".",
"line",
",",
"node",
".",
"start_mark",
".",
"column",
")",
"imports",
".",
"imports",
"=",
"ctxt",
".",
"get_list",
"(",
"node",
")",
"spec",
".",
"imports",
"=",
"imports"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/parser.py#L153-L161 | ||
Qihoo360/mongosync | 55b647e81c072ebe91daaa3b9dc1a953c3c22e19 | dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py | python | Search | (pattern, s) | return _regexp_compile_cache[pattern].search(s) | Searches the string for the pattern, caching the compiled regexp. | Searches the string for the pattern, caching the compiled regexp. | [
"Searches",
"the",
"string",
"for",
"the",
"pattern",
"caching",
"the",
"compiled",
"regexp",
"."
] | def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if not pattern in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s) | [
"def",
"Search",
"(",
"pattern",
",",
"s",
")",
":",
"if",
"not",
"pattern",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pattern",
"]",
".",
"search",
"(",
"s",
")"
] | https://github.com/Qihoo360/mongosync/blob/55b647e81c072ebe91daaa3b9dc1a953c3c22e19/dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py#L359-L363 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pyclbr.py | python | readmodule | (module, path=None) | return res | Return Class objects for the top-level classes in module.
This is the original interface, before Functions were added. | Return Class objects for the top-level classes in module. | [
"Return",
"Class",
"objects",
"for",
"the",
"top",
"-",
"level",
"classes",
"in",
"module",
"."
] | def readmodule(module, path=None):
"""Return Class objects for the top-level classes in module.
This is the original interface, before Functions were added.
"""
res = {}
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
return res | [
"def",
"readmodule",
"(",
"module",
",",
"path",
"=",
"None",
")",
":",
"res",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"_readmodule",
"(",
"module",
",",
"path",
"or",
"[",
"]",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Class",
")",
":",
"res",
"[",
"key",
"]",
"=",
"value",
"return",
"res"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pyclbr.py#L97-L107 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/gather_encoder.py | python | GatherEncoder.update_state | (self, state, state_update_tensors, name=None) | Updates the state of the `GatherEncoder`.
Args:
state: The (optional) current state. A tuple, matching the structure
returned by the `initial_state` method.
state_update_tensors: A tuple of `Tensor` values returned by the `encode`
method, aggregated according to modes provided by the
`state_update_aggregation_modes` property. Note that the tuple has the
same structure, but the `Tensor` values it contains do not necessarily
have the same shapes.
name: `string`, name of the operation.
Returns:
A tuple of `Tensor` values of the same structure as `state`, representing
the updated state.
Raises:
ValueError:
If `state` is not `None` and does not have the same structure as the
return value of the `initial_state` method. | Updates the state of the `GatherEncoder`. | [
"Updates",
"the",
"state",
"of",
"the",
"GatherEncoder",
"."
] | def update_state(self, state, state_update_tensors, name=None):
"""Updates the state of the `GatherEncoder`.
Args:
state: The (optional) current state. A tuple, matching the structure
returned by the `initial_state` method.
state_update_tensors: A tuple of `Tensor` values returned by the `encode`
method, aggregated according to modes provided by the
`state_update_aggregation_modes` property. Note that the tuple has the
same structure, but the `Tensor` values it contains do not necessarily
have the same shapes.
name: `string`, name of the operation.
Returns:
A tuple of `Tensor` values of the same structure as `state`, representing
the updated state.
Raises:
ValueError:
If `state` is not `None` and does not have the same structure as the
return value of the `initial_state` method.
"""
values = list(state) + list(state_update_tensors)
with tf.compat.v1.name_scope(name, 'gather_encoder_update_state', values):
state = tf.nest.map_structure(tf.convert_to_tensor, state)
state_update_tensors = tf.nest.map_structure(tf.convert_to_tensor,
state_update_tensors)
return self._update_state_fn(state, state_update_tensors) | [
"def",
"update_state",
"(",
"self",
",",
"state",
",",
"state_update_tensors",
",",
"name",
"=",
"None",
")",
":",
"values",
"=",
"list",
"(",
"state",
")",
"+",
"list",
"(",
"state_update_tensors",
")",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'gather_encoder_update_state'",
",",
"values",
")",
":",
"state",
"=",
"tf",
".",
"nest",
".",
"map_structure",
"(",
"tf",
".",
"convert_to_tensor",
",",
"state",
")",
"state_update_tensors",
"=",
"tf",
".",
"nest",
".",
"map_structure",
"(",
"tf",
".",
"convert_to_tensor",
",",
"state_update_tensors",
")",
"return",
"self",
".",
"_update_state_fn",
"(",
"state",
",",
"state_update_tensors",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/gather_encoder.py#L530-L557 | ||
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/message.py | python | Message.Clear | (self) | Clears all data that was set in the message. | Clears all data that was set in the message. | [
"Clears",
"all",
"data",
"that",
"was",
"set",
"in",
"the",
"message",
"."
] | def Clear(self):
"""Clears all data that was set in the message."""
raise NotImplementedError | [
"def",
"Clear",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/message.py#L121-L123 | ||
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/site_packages/bz2.py | python | BZ2File.readable | (self) | return self._mode == _MODE_READ | Return whether the file was opened for reading. | Return whether the file was opened for reading. | [
"Return",
"whether",
"the",
"file",
"was",
"opened",
"for",
"reading",
"."
] | def readable(self):
"""Return whether the file was opened for reading."""
self._check_not_closed()
return self._mode == _MODE_READ | [
"def",
"readable",
"(",
"self",
")",
":",
"self",
".",
"_check_not_closed",
"(",
")",
"return",
"self",
".",
"_mode",
"==",
"_MODE_READ"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/bz2.py#L154-L157 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/fileinput.py | python | filename | () | return _state.filename() | Return the name of the file currently being read.
Before the first line has been read, returns None. | Return the name of the file currently being read.
Before the first line has been read, returns None. | [
"Return",
"the",
"name",
"of",
"the",
"file",
"currently",
"being",
"read",
".",
"Before",
"the",
"first",
"line",
"has",
"been",
"read",
"returns",
"None",
"."
] | def filename():
"""
Return the name of the file currently being read.
Before the first line has been read, returns None.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.filename() | [
"def",
"filename",
"(",
")",
":",
"if",
"not",
"_state",
":",
"raise",
"RuntimeError",
"(",
"\"no active input()\"",
")",
"return",
"_state",
".",
"filename",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/fileinput.py#L119-L126 | |
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/alignment.py | python | Alignment.get_read_to_ref_ratio | (self) | return 1.0 / self.get_ref_to_read_ratio() | Returns the length ratio between the aligned parts of the read and reference. | Returns the length ratio between the aligned parts of the read and reference. | [
"Returns",
"the",
"length",
"ratio",
"between",
"the",
"aligned",
"parts",
"of",
"the",
"read",
"and",
"reference",
"."
] | def get_read_to_ref_ratio(self):
"""
Returns the length ratio between the aligned parts of the read and reference.
"""
return 1.0 / self.get_ref_to_read_ratio() | [
"def",
"get_read_to_ref_ratio",
"(",
"self",
")",
":",
"return",
"1.0",
"/",
"self",
".",
"get_ref_to_read_ratio",
"(",
")"
] | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/alignment.py#L254-L258 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pyclbr.py | python | _getname | (g) | return (".".join(parts), token) | Return (dotted-name or None, next-token) tuple for token source g. | Return (dotted-name or None, next-token) tuple for token source g. | [
"Return",
"(",
"dotted",
"-",
"name",
"or",
"None",
"next",
"-",
"token",
")",
"tuple",
"for",
"token",
"source",
"g",
"."
] | def _getname(g):
"Return (dotted-name or None, next-token) tuple for token source g."
parts = []
tokentype, token = next(g)[0:2]
if tokentype != NAME and token != '*':
return (None, token)
parts.append(token)
while True:
tokentype, token = next(g)[0:2]
if token != '.':
break
tokentype, token = next(g)[0:2]
if tokentype != NAME:
break
parts.append(token)
return (".".join(parts), token) | [
"def",
"_getname",
"(",
"g",
")",
":",
"parts",
"=",
"[",
"]",
"tokentype",
",",
"token",
"=",
"next",
"(",
"g",
")",
"[",
"0",
":",
"2",
"]",
"if",
"tokentype",
"!=",
"NAME",
"and",
"token",
"!=",
"'*'",
":",
"return",
"(",
"None",
",",
"token",
")",
"parts",
".",
"append",
"(",
"token",
")",
"while",
"True",
":",
"tokentype",
",",
"token",
"=",
"next",
"(",
"g",
")",
"[",
"0",
":",
"2",
"]",
"if",
"token",
"!=",
"'.'",
":",
"break",
"tokentype",
",",
"token",
"=",
"next",
"(",
"g",
")",
"[",
"0",
":",
"2",
"]",
"if",
"tokentype",
"!=",
"NAME",
":",
"break",
"parts",
".",
"append",
"(",
"token",
")",
"return",
"(",
"\".\"",
".",
"join",
"(",
"parts",
")",
",",
"token",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pyclbr.py#L344-L359 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/all_reduce.py | python | build_shuffle_then_shuffle | (input_tensors, first_gather_devices,
second_gather_devices, red_op, un_op=None) | return _build_shuffle_hybrid(
input_tensors, first_gather_devices, red_op, upper_level_f) | Construct hybrid of Shuffle within workers, Shuffle across workers. | Construct hybrid of Shuffle within workers, Shuffle across workers. | [
"Construct",
"hybrid",
"of",
"Shuffle",
"within",
"workers",
"Shuffle",
"across",
"workers",
"."
] | def build_shuffle_then_shuffle(input_tensors, first_gather_devices,
second_gather_devices, red_op, un_op=None):
"""Construct hybrid of Shuffle within workers, Shuffle across workers."""
def upper_builder(tensors):
return build_shuffle_all_reduce(tensors, second_gather_devices,
red_op, un_op)
def upper_level_f(tensors):
return _reduce_non_singleton(tensors, upper_builder, un_op)
return _build_shuffle_hybrid(
input_tensors, first_gather_devices, red_op, upper_level_f) | [
"def",
"build_shuffle_then_shuffle",
"(",
"input_tensors",
",",
"first_gather_devices",
",",
"second_gather_devices",
",",
"red_op",
",",
"un_op",
"=",
"None",
")",
":",
"def",
"upper_builder",
"(",
"tensors",
")",
":",
"return",
"build_shuffle_all_reduce",
"(",
"tensors",
",",
"second_gather_devices",
",",
"red_op",
",",
"un_op",
")",
"def",
"upper_level_f",
"(",
"tensors",
")",
":",
"return",
"_reduce_non_singleton",
"(",
"tensors",
",",
"upper_builder",
",",
"un_op",
")",
"return",
"_build_shuffle_hybrid",
"(",
"input_tensors",
",",
"first_gather_devices",
",",
"red_op",
",",
"upper_level_f",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/all_reduce.py#L851-L860 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/cpu.py | python | CPUContext.get_env_body | (self, builder, envptr) | return EnvBody(self, builder, ref=body_ptr, cast_ref=True) | From the given *envptr* (a pointer to a _dynfunc.Environment object),
get a EnvBody allowing structured access to environment fields. | From the given *envptr* (a pointer to a _dynfunc.Environment object),
get a EnvBody allowing structured access to environment fields. | [
"From",
"the",
"given",
"*",
"envptr",
"*",
"(",
"a",
"pointer",
"to",
"a",
"_dynfunc",
".",
"Environment",
"object",
")",
"get",
"a",
"EnvBody",
"allowing",
"structured",
"access",
"to",
"environment",
"fields",
"."
] | def get_env_body(self, builder, envptr):
"""
From the given *envptr* (a pointer to a _dynfunc.Environment object),
get a EnvBody allowing structured access to environment fields.
"""
body_ptr = cgutils.pointer_add(
builder, envptr, _dynfunc._impl_info['offsetof_env_body'])
return EnvBody(self, builder, ref=body_ptr, cast_ref=True) | [
"def",
"get_env_body",
"(",
"self",
",",
"builder",
",",
"envptr",
")",
":",
"body_ptr",
"=",
"cgutils",
".",
"pointer_add",
"(",
"builder",
",",
"envptr",
",",
"_dynfunc",
".",
"_impl_info",
"[",
"'offsetof_env_body'",
"]",
")",
"return",
"EnvBody",
"(",
"self",
",",
"builder",
",",
"ref",
"=",
"body_ptr",
",",
"cast_ref",
"=",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/cpu.py#L98-L105 | |
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/pyserial/serial/serialutil.py | python | SerialBase.dsrdtr | (self, dsrdtr=None) | Change DsrDtr flow control setting. | Change DsrDtr flow control setting. | [
"Change",
"DsrDtr",
"flow",
"control",
"setting",
"."
] | def dsrdtr(self, dsrdtr=None):
"""Change DsrDtr flow control setting."""
if dsrdtr is None:
# if not set, keep backwards compatibility and follow rtscts setting
self._dsrdtr = self._rtscts
else:
# if defined independently, follow its value
self._dsrdtr = dsrdtr
if self.is_open:
self._reconfigure_port() | [
"def",
"dsrdtr",
"(",
"self",
",",
"dsrdtr",
"=",
"None",
")",
":",
"if",
"dsrdtr",
"is",
"None",
":",
"# if not set, keep backwards compatibility and follow rtscts setting",
"self",
".",
"_dsrdtr",
"=",
"self",
".",
"_rtscts",
"else",
":",
"# if defined independently, follow its value",
"self",
".",
"_dsrdtr",
"=",
"dsrdtr",
"if",
"self",
".",
"is_open",
":",
"self",
".",
"_reconfigure_port",
"(",
")"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialutil.py#L440-L449 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/prefilter.py | python | PythonOpsChecker.check | (self, line_info) | If the 'rest' of the line begins with a function call or pretty much
any python operator, we should simply execute the line (regardless of
whether or not there's a possible autocall expansion). This avoids
spurious (and very confusing) geattr() accesses. | If the 'rest' of the line begins with a function call or pretty much
any python operator, we should simply execute the line (regardless of
whether or not there's a possible autocall expansion). This avoids
spurious (and very confusing) geattr() accesses. | [
"If",
"the",
"rest",
"of",
"the",
"line",
"begins",
"with",
"a",
"function",
"call",
"or",
"pretty",
"much",
"any",
"python",
"operator",
"we",
"should",
"simply",
"execute",
"the",
"line",
"(",
"regardless",
"of",
"whether",
"or",
"not",
"there",
"s",
"a",
"possible",
"autocall",
"expansion",
")",
".",
"This",
"avoids",
"spurious",
"(",
"and",
"very",
"confusing",
")",
"geattr",
"()",
"accesses",
"."
] | def check(self, line_info):
"""If the 'rest' of the line begins with a function call or pretty much
any python operator, we should simply execute the line (regardless of
whether or not there's a possible autocall expansion). This avoids
spurious (and very confusing) geattr() accesses."""
if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
return self.prefilter_manager.get_handler_by_name('normal')
else:
return None | [
"def",
"check",
"(",
"self",
",",
"line_info",
")",
":",
"if",
"line_info",
".",
"the_rest",
"and",
"line_info",
".",
"the_rest",
"[",
"0",
"]",
"in",
"'!=()<>,+*/%^&|'",
":",
"return",
"self",
".",
"prefilter_manager",
".",
"get_handler_by_name",
"(",
"'normal'",
")",
"else",
":",
"return",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/prefilter.py#L482-L490 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/asinh.py | python | _asinh_tbe | () | return | Asinh TBE register | Asinh TBE register | [
"Asinh",
"TBE",
"register"
] | def _asinh_tbe():
"""Asinh TBE register"""
return | [
"def",
"_asinh_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/asinh.py#L35-L37 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/resource_variable_ops.py | python | BaseResourceVariable.__init__ | ( # pylint: disable=super-init-not-called
self,
trainable=None,
shape=None,
dtype=None,
handle=None,
constraint=None,
synchronization=None,
aggregation=None,
distribute_strategy=None,
name=None,
unique_id=None,
handle_name=None,
graph_element=None,
initial_value=None,
initializer_op=None,
is_initialized_op=None,
cached_value=None,
save_slice_info=None,
handle_deleter=None,
caching_device=None,
in_graph_mode=None,
**unused_kwargs) | Creates a variable from a handle.
Args:
trainable: If `True`, GradientTapes automatically watch uses of this
Variable.
shape: The variable's shape. This shape can be set to tf.TensorShape(None)
in order to assign values of different shapes to this variable.
Otherwise (i.e. if the shape is fully determined), it will trigger run
time checks to ensure that each assignment is of the same shape.
dtype: The variable's dtype.
handle: The variable's handle
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
distribute_strategy: The distribution strategy this variable was created
under.
name: The name for this variable.
unique_id: Internal. Unique ID for this variable's handle.
handle_name: The name for the variable's handle.
graph_element: Optional, required only in session.run-mode. Pre-created
tensor which reads this variable's value.
initial_value: Optional. Variable's initial value.
initializer_op: Operation which assigns the variable's initial value.
is_initialized_op: Pre-created operation to check whether this variable is
initialized.
cached_value: Pre-created operation to read this variable in a specific
device.
save_slice_info: Metadata for variable partitioning.
handle_deleter: EagerResourceDeleter responsible for cleaning up the
handle.
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
in_graph_mode: whether we are executing in TF1 graph mode. If None, will
detect within the function. This is to avoid repeated init_scope()
conetxt entrances which can add up. | Creates a variable from a handle. | [
"Creates",
"a",
"variable",
"from",
"a",
"handle",
"."
] | def __init__( # pylint: disable=super-init-not-called
self,
trainable=None,
shape=None,
dtype=None,
handle=None,
constraint=None,
synchronization=None,
aggregation=None,
distribute_strategy=None,
name=None,
unique_id=None,
handle_name=None,
graph_element=None,
initial_value=None,
initializer_op=None,
is_initialized_op=None,
cached_value=None,
save_slice_info=None,
handle_deleter=None,
caching_device=None,
in_graph_mode=None,
**unused_kwargs):
"""Creates a variable from a handle.
Args:
trainable: If `True`, GradientTapes automatically watch uses of this
Variable.
shape: The variable's shape. This shape can be set to tf.TensorShape(None)
in order to assign values of different shapes to this variable.
Otherwise (i.e. if the shape is fully determined), it will trigger run
time checks to ensure that each assignment is of the same shape.
dtype: The variable's dtype.
handle: The variable's handle
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
distribute_strategy: The distribution strategy this variable was created
under.
name: The name for this variable.
unique_id: Internal. Unique ID for this variable's handle.
handle_name: The name for the variable's handle.
graph_element: Optional, required only in session.run-mode. Pre-created
tensor which reads this variable's value.
initial_value: Optional. Variable's initial value.
initializer_op: Operation which assigns the variable's initial value.
is_initialized_op: Pre-created operation to check whether this variable is
initialized.
cached_value: Pre-created operation to read this variable in a specific
device.
save_slice_info: Metadata for variable partitioning.
handle_deleter: EagerResourceDeleter responsible for cleaning up the
handle.
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
in_graph_mode: whether we are executing in TF1 graph mode. If None, will
detect within the function. This is to avoid repeated init_scope()
conetxt entrances which can add up.
"""
if in_graph_mode is None:
with ops.init_scope():
self._in_graph_mode = not context.executing_eagerly()
else:
self._in_graph_mode = in_graph_mode
synchronization, aggregation, trainable = (
variables.validate_synchronization_aggregation_trainable(
synchronization, aggregation, trainable, name))
self._trainable = trainable
self._synchronization = synchronization
self._aggregation = aggregation
self._save_slice_info = save_slice_info
self._initial_value = initial_value
self._initializer_op = initializer_op
self._is_initialized_op = is_initialized_op
self._graph_element = graph_element
self._caching_device = caching_device
self._cached_value = cached_value
self._distribute_strategy = distribute_strategy
# Store the graph key so optimizers know how to only retrieve variables from
# this graph. Guaranteed to be the same as the eager graph_key.
self._graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access
self._shape = tensor_shape.as_shape(shape)
self._dtype = dtypes.as_dtype(dtype)
self._handle = handle
self._unique_id = unique_id
self._handle_name = handle_name + ":0"
self._constraint = constraint
# After the handle has been created, set up a way to clean it up when
# executing eagerly. We'll hold the only reference to the deleter, so that
# when this object is garbage collected the deleter will be too. This
# means ResourceVariables can be part of reference cycles without those
# cycles being uncollectable.
if not self._in_graph_mode:
if handle_deleter is None:
handle_deleter = EagerResourceDeleter(
handle=self._handle, handle_device=self._handle.device)
self._handle_deleter = handle_deleter
self._cached_shape_as_list = None | [
"def",
"__init__",
"(",
"# pylint: disable=super-init-not-called",
"self",
",",
"trainable",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"handle",
"=",
"None",
",",
"constraint",
"=",
"None",
",",
"synchronization",
"=",
"None",
",",
"aggregation",
"=",
"None",
",",
"distribute_strategy",
"=",
"None",
",",
"name",
"=",
"None",
",",
"unique_id",
"=",
"None",
",",
"handle_name",
"=",
"None",
",",
"graph_element",
"=",
"None",
",",
"initial_value",
"=",
"None",
",",
"initializer_op",
"=",
"None",
",",
"is_initialized_op",
"=",
"None",
",",
"cached_value",
"=",
"None",
",",
"save_slice_info",
"=",
"None",
",",
"handle_deleter",
"=",
"None",
",",
"caching_device",
"=",
"None",
",",
"in_graph_mode",
"=",
"None",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"if",
"in_graph_mode",
"is",
"None",
":",
"with",
"ops",
".",
"init_scope",
"(",
")",
":",
"self",
".",
"_in_graph_mode",
"=",
"not",
"context",
".",
"executing_eagerly",
"(",
")",
"else",
":",
"self",
".",
"_in_graph_mode",
"=",
"in_graph_mode",
"synchronization",
",",
"aggregation",
",",
"trainable",
"=",
"(",
"variables",
".",
"validate_synchronization_aggregation_trainable",
"(",
"synchronization",
",",
"aggregation",
",",
"trainable",
",",
"name",
")",
")",
"self",
".",
"_trainable",
"=",
"trainable",
"self",
".",
"_synchronization",
"=",
"synchronization",
"self",
".",
"_aggregation",
"=",
"aggregation",
"self",
".",
"_save_slice_info",
"=",
"save_slice_info",
"self",
".",
"_initial_value",
"=",
"initial_value",
"self",
".",
"_initializer_op",
"=",
"initializer_op",
"self",
".",
"_is_initialized_op",
"=",
"is_initialized_op",
"self",
".",
"_graph_element",
"=",
"graph_element",
"self",
".",
"_caching_device",
"=",
"caching_device",
"self",
".",
"_cached_value",
"=",
"cached_value",
"self",
".",
"_distribute_strategy",
"=",
"distribute_strategy",
"# Store the graph key so optimizers know how to only retrieve variables from",
"# this graph. Guaranteed to be the same as the eager graph_key.",
"self",
".",
"_graph_key",
"=",
"ops",
".",
"get_default_graph",
"(",
")",
".",
"_graph_key",
"# pylint: disable=protected-access",
"self",
".",
"_shape",
"=",
"tensor_shape",
".",
"as_shape",
"(",
"shape",
")",
"self",
".",
"_dtype",
"=",
"dtypes",
".",
"as_dtype",
"(",
"dtype",
")",
"self",
".",
"_handle",
"=",
"handle",
"self",
".",
"_unique_id",
"=",
"unique_id",
"self",
".",
"_handle_name",
"=",
"handle_name",
"+",
"\":0\"",
"self",
".",
"_constraint",
"=",
"constraint",
"# After the handle has been created, set up a way to clean it up when",
"# executing eagerly. We'll hold the only reference to the deleter, so that",
"# when this object is garbage collected the deleter will be too. This",
"# means ResourceVariables can be part of reference cycles without those",
"# cycles being uncollectable.",
"if",
"not",
"self",
".",
"_in_graph_mode",
":",
"if",
"handle_deleter",
"is",
"None",
":",
"handle_deleter",
"=",
"EagerResourceDeleter",
"(",
"handle",
"=",
"self",
".",
"_handle",
",",
"handle_device",
"=",
"self",
".",
"_handle",
".",
"device",
")",
"self",
".",
"_handle_deleter",
"=",
"handle_deleter",
"self",
".",
"_cached_shape_as_list",
"=",
"None"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/resource_variable_ops.py#L359-L471 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/run.py | python | main | (del_exitfunc=False) | Start the Python execution server in a subprocess
In the Python subprocess, RPCServer is instantiated with handlerclass
MyHandler, which inherits register/unregister methods from RPCHandler via
the mix-in class SocketIO.
When the RPCServer 'server' is instantiated, the TCPServer initialization
creates an instance of run.MyHandler and calls its handle() method.
handle() instantiates a run.Executive object, passing it a reference to the
MyHandler object. That reference is saved as attribute rpchandler of the
Executive instance. The Executive methods have access to the reference and
can pass it on to entities that they command
(e.g. RemoteDebugger.Debugger.start_debugger()). The latter, in turn, can
call MyHandler(SocketIO) register/unregister methods via the reference to
register and unregister themselves. | Start the Python execution server in a subprocess | [
"Start",
"the",
"Python",
"execution",
"server",
"in",
"a",
"subprocess"
] | def main(del_exitfunc=False):
"""Start the Python execution server in a subprocess
In the Python subprocess, RPCServer is instantiated with handlerclass
MyHandler, which inherits register/unregister methods from RPCHandler via
the mix-in class SocketIO.
When the RPCServer 'server' is instantiated, the TCPServer initialization
creates an instance of run.MyHandler and calls its handle() method.
handle() instantiates a run.Executive object, passing it a reference to the
MyHandler object. That reference is saved as attribute rpchandler of the
Executive instance. The Executive methods have access to the reference and
can pass it on to entities that they command
(e.g. RemoteDebugger.Debugger.start_debugger()). The latter, in turn, can
call MyHandler(SocketIO) register/unregister methods via the reference to
register and unregister themselves.
"""
global exit_now
global quitting
global no_exitfunc
no_exitfunc = del_exitfunc
#time.sleep(15) # test subprocess not responding
try:
assert(len(sys.argv) > 1)
port = int(sys.argv[-1])
except:
print>>sys.stderr, "IDLE Subprocess: no IP port passed in sys.argv."
return
sys.argv[:] = [""]
sockthread = threading.Thread(target=manage_socket,
name='SockThread',
args=((LOCALHOST, port),))
sockthread.setDaemon(True)
sockthread.start()
while 1:
try:
if exit_now:
try:
exit()
except KeyboardInterrupt:
# exiting but got an extra KBI? Try again!
continue
try:
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
except Queue.Empty:
continue
method, args, kwargs = request
ret = method(*args, **kwargs)
rpc.response_queue.put((seq, ret))
except KeyboardInterrupt:
if quitting:
exit_now = True
continue
except SystemExit:
raise
except:
type, value, tb = sys.exc_info()
try:
print_exception()
rpc.response_queue.put((seq, None))
except:
# Link didn't work, print same exception to __stderr__
traceback.print_exception(type, value, tb, file=sys.__stderr__)
exit()
else:
continue | [
"def",
"main",
"(",
"del_exitfunc",
"=",
"False",
")",
":",
"global",
"exit_now",
"global",
"quitting",
"global",
"no_exitfunc",
"no_exitfunc",
"=",
"del_exitfunc",
"#time.sleep(15) # test subprocess not responding",
"try",
":",
"assert",
"(",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
")",
"port",
"=",
"int",
"(",
"sys",
".",
"argv",
"[",
"-",
"1",
"]",
")",
"except",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"IDLE Subprocess: no IP port passed in sys.argv.\"",
"return",
"sys",
".",
"argv",
"[",
":",
"]",
"=",
"[",
"\"\"",
"]",
"sockthread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"manage_socket",
",",
"name",
"=",
"'SockThread'",
",",
"args",
"=",
"(",
"(",
"LOCALHOST",
",",
"port",
")",
",",
")",
")",
"sockthread",
".",
"setDaemon",
"(",
"True",
")",
"sockthread",
".",
"start",
"(",
")",
"while",
"1",
":",
"try",
":",
"if",
"exit_now",
":",
"try",
":",
"exit",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"# exiting but got an extra KBI? Try again!",
"continue",
"try",
":",
"seq",
",",
"request",
"=",
"rpc",
".",
"request_queue",
".",
"get",
"(",
"block",
"=",
"True",
",",
"timeout",
"=",
"0.05",
")",
"except",
"Queue",
".",
"Empty",
":",
"continue",
"method",
",",
"args",
",",
"kwargs",
"=",
"request",
"ret",
"=",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"rpc",
".",
"response_queue",
".",
"put",
"(",
"(",
"seq",
",",
"ret",
")",
")",
"except",
"KeyboardInterrupt",
":",
"if",
"quitting",
":",
"exit_now",
"=",
"True",
"continue",
"except",
"SystemExit",
":",
"raise",
"except",
":",
"type",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"try",
":",
"print_exception",
"(",
")",
"rpc",
".",
"response_queue",
".",
"put",
"(",
"(",
"seq",
",",
"None",
")",
")",
"except",
":",
"# Link didn't work, print same exception to __stderr__",
"traceback",
".",
"print_exception",
"(",
"type",
",",
"value",
",",
"tb",
",",
"file",
"=",
"sys",
".",
"__stderr__",
")",
"exit",
"(",
")",
"else",
":",
"continue"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/run.py#L52-L118 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/util.py | python | execute | (func, args, msg=None, verbose=0, dry_run=0) | Perform some action that affects the outside world (eg. by
writing to the filesystem). Such actions are special because they
are disabled by the 'dry_run' flag. This method takes care of all
that bureaucracy for you; all you have to do is supply the
function to call and an argument tuple for it (to embody the
"external action" being performed), and an optional message to
print. | Perform some action that affects the outside world (eg. by
writing to the filesystem). Such actions are special because they
are disabled by the 'dry_run' flag. This method takes care of all
that bureaucracy for you; all you have to do is supply the
function to call and an argument tuple for it (to embody the
"external action" being performed), and an optional message to
print. | [
"Perform",
"some",
"action",
"that",
"affects",
"the",
"outside",
"world",
"(",
"eg",
".",
"by",
"writing",
"to",
"the",
"filesystem",
")",
".",
"Such",
"actions",
"are",
"special",
"because",
"they",
"are",
"disabled",
"by",
"the",
"dry_run",
"flag",
".",
"This",
"method",
"takes",
"care",
"of",
"all",
"that",
"bureaucracy",
"for",
"you",
";",
"all",
"you",
"have",
"to",
"do",
"is",
"supply",
"the",
"function",
"to",
"call",
"and",
"an",
"argument",
"tuple",
"for",
"it",
"(",
"to",
"embody",
"the",
"external",
"action",
"being",
"performed",
")",
"and",
"an",
"optional",
"message",
"to",
"print",
"."
] | def execute (func, args, msg=None, verbose=0, dry_run=0):
"""Perform some action that affects the outside world (eg. by
writing to the filesystem). Such actions are special because they
are disabled by the 'dry_run' flag. This method takes care of all
that bureaucracy for you; all you have to do is supply the
function to call and an argument tuple for it (to embody the
"external action" being performed), and an optional message to
print.
"""
if msg is None:
msg = "%s%r" % (func.__name__, args)
if msg[-2:] == ',)': # correct for singleton tuple
msg = msg[0:-2] + ')'
log.info(msg)
if not dry_run:
func(*args) | [
"def",
"execute",
"(",
"func",
",",
"args",
",",
"msg",
"=",
"None",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
")",
":",
"if",
"msg",
"is",
"None",
":",
"msg",
"=",
"\"%s%r\"",
"%",
"(",
"func",
".",
"__name__",
",",
"args",
")",
"if",
"msg",
"[",
"-",
"2",
":",
"]",
"==",
"',)'",
":",
"# correct for singleton tuple",
"msg",
"=",
"msg",
"[",
"0",
":",
"-",
"2",
"]",
"+",
"')'",
"log",
".",
"info",
"(",
"msg",
")",
"if",
"not",
"dry_run",
":",
"func",
"(",
"*",
"args",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/util.py#L288-L304 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/more-itertools/py2/more_itertools/more.py | python | rlocate | (iterable, pred=bool, window_size=None) | return reversed(list(locate(iterable, pred, window_size))) | Yield the index of each item in *iterable* for which *pred* returns
``True``, starting from the right and moving left.
*pred* defaults to :func:`bool`, which will select truthy items:
>>> list(rlocate([0, 1, 1, 0, 1, 0, 0])) # Truthy at 1, 2, and 4
[4, 2, 1]
Set *pred* to a custom function to, e.g., find the indexes for a particular
item:
>>> iterable = iter('abcb')
>>> pred = lambda x: x == 'b'
>>> list(rlocate(iterable, pred))
[3, 1]
If *window_size* is given, then the *pred* function will be called with
that many items. This enables searching for sub-sequences:
>>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
>>> pred = lambda *args: args == (1, 2, 3)
>>> list(rlocate(iterable, pred=pred, window_size=3))
[9, 5, 1]
Beware, this function won't return anything for infinite iterables.
If *iterable* is reversible, ``rlocate`` will reverse it and search from
the right. Otherwise, it will search from the left and return the results
in reverse order.
See :func:`locate` to for other example applications. | Yield the index of each item in *iterable* for which *pred* returns
``True``, starting from the right and moving left. | [
"Yield",
"the",
"index",
"of",
"each",
"item",
"in",
"*",
"iterable",
"*",
"for",
"which",
"*",
"pred",
"*",
"returns",
"True",
"starting",
"from",
"the",
"right",
"and",
"moving",
"left",
"."
] | def rlocate(iterable, pred=bool, window_size=None):
"""Yield the index of each item in *iterable* for which *pred* returns
``True``, starting from the right and moving left.
*pred* defaults to :func:`bool`, which will select truthy items:
>>> list(rlocate([0, 1, 1, 0, 1, 0, 0])) # Truthy at 1, 2, and 4
[4, 2, 1]
Set *pred* to a custom function to, e.g., find the indexes for a particular
item:
>>> iterable = iter('abcb')
>>> pred = lambda x: x == 'b'
>>> list(rlocate(iterable, pred))
[3, 1]
If *window_size* is given, then the *pred* function will be called with
that many items. This enables searching for sub-sequences:
>>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
>>> pred = lambda *args: args == (1, 2, 3)
>>> list(rlocate(iterable, pred=pred, window_size=3))
[9, 5, 1]
Beware, this function won't return anything for infinite iterables.
If *iterable* is reversible, ``rlocate`` will reverse it and search from
the right. Otherwise, it will search from the left and return the results
in reverse order.
See :func:`locate` to for other example applications.
"""
if window_size is None:
try:
len_iter = len(iterable)
return (
len_iter - i - 1 for i in locate(reversed(iterable), pred)
)
except TypeError:
pass
return reversed(list(locate(iterable, pred, window_size))) | [
"def",
"rlocate",
"(",
"iterable",
",",
"pred",
"=",
"bool",
",",
"window_size",
"=",
"None",
")",
":",
"if",
"window_size",
"is",
"None",
":",
"try",
":",
"len_iter",
"=",
"len",
"(",
"iterable",
")",
"return",
"(",
"len_iter",
"-",
"i",
"-",
"1",
"for",
"i",
"in",
"locate",
"(",
"reversed",
"(",
"iterable",
")",
",",
"pred",
")",
")",
"except",
"TypeError",
":",
"pass",
"return",
"reversed",
"(",
"list",
"(",
"locate",
"(",
"iterable",
",",
"pred",
",",
"window_size",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py2/more_itertools/more.py#L2229-L2271 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/graphics.py | python | GraphicsContext.StrokeLineSegments | (self, beginPoints, endPoints) | Stroke a series of lines using the current pen. For each line
the begin point is taken from the beginPoints sequence and the
ending point is taken from the endPoints sequence. | Stroke a series of lines using the current pen. For each line
the begin point is taken from the beginPoints sequence and the
ending point is taken from the endPoints sequence. | [
"Stroke",
"a",
"series",
"of",
"lines",
"using",
"the",
"current",
"pen",
".",
"For",
"each",
"line",
"the",
"begin",
"point",
"is",
"taken",
"from",
"the",
"beginPoints",
"sequence",
"and",
"the",
"ending",
"point",
"is",
"taken",
"from",
"the",
"endPoints",
"sequence",
"."
] | def StrokeLineSegments(self, beginPoints, endPoints):
"""
Stroke a series of lines using the current pen. For each line
the begin point is taken from the beginPoints sequence and the
ending point is taken from the endPoints sequence.
"""
path = GraphicsPath()
for begin, end in zip(beginPoints, endPoints):
path.MoveToPoint(begin[0], begin[1])
path.AddLineToPoint(end[0], end[1])
self.StrokePath(path) | [
"def",
"StrokeLineSegments",
"(",
"self",
",",
"beginPoints",
",",
"endPoints",
")",
":",
"path",
"=",
"GraphicsPath",
"(",
")",
"for",
"begin",
",",
"end",
"in",
"zip",
"(",
"beginPoints",
",",
"endPoints",
")",
":",
"path",
".",
"MoveToPoint",
"(",
"begin",
"[",
"0",
"]",
",",
"begin",
"[",
"1",
"]",
")",
"path",
".",
"AddLineToPoint",
"(",
"end",
"[",
"0",
"]",
",",
"end",
"[",
"1",
"]",
")",
"self",
".",
"StrokePath",
"(",
"path",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/graphics.py#L1498-L1508 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/websocket-client/websocket.py | python | _parse_url | (url) | return (hostname, port, resource, is_secure) | parse url and the result is tuple of
(hostname, port, resource path and the flag of secure mode)
url: url string. | parse url and the result is tuple of
(hostname, port, resource path and the flag of secure mode) | [
"parse",
"url",
"and",
"the",
"result",
"is",
"tuple",
"of",
"(",
"hostname",
"port",
"resource",
"path",
"and",
"the",
"flag",
"of",
"secure",
"mode",
")"
] | def _parse_url(url):
"""
parse url and the result is tuple of
(hostname, port, resource path and the flag of secure mode)
url: url string.
"""
if ":" not in url:
raise ValueError("url is invalid")
scheme, url = url.split(":", 1)
parsed = urlparse(url, scheme="http")
if parsed.hostname:
hostname = parsed.hostname
else:
raise ValueError("hostname is invalid")
port = 0
if parsed.port:
port = parsed.port
is_secure = False
if scheme == "ws":
if not port:
port = 80
elif scheme == "wss":
is_secure = True
if not port:
port = 443
else:
raise ValueError("scheme %s is invalid" % scheme)
if parsed.path:
resource = parsed.path
else:
resource = "/"
if parsed.query:
resource += "?" + parsed.query
return (hostname, port, resource, is_secure) | [
"def",
"_parse_url",
"(",
"url",
")",
":",
"if",
"\":\"",
"not",
"in",
"url",
":",
"raise",
"ValueError",
"(",
"\"url is invalid\"",
")",
"scheme",
",",
"url",
"=",
"url",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"parsed",
"=",
"urlparse",
"(",
"url",
",",
"scheme",
"=",
"\"http\"",
")",
"if",
"parsed",
".",
"hostname",
":",
"hostname",
"=",
"parsed",
".",
"hostname",
"else",
":",
"raise",
"ValueError",
"(",
"\"hostname is invalid\"",
")",
"port",
"=",
"0",
"if",
"parsed",
".",
"port",
":",
"port",
"=",
"parsed",
".",
"port",
"is_secure",
"=",
"False",
"if",
"scheme",
"==",
"\"ws\"",
":",
"if",
"not",
"port",
":",
"port",
"=",
"80",
"elif",
"scheme",
"==",
"\"wss\"",
":",
"is_secure",
"=",
"True",
"if",
"not",
"port",
":",
"port",
"=",
"443",
"else",
":",
"raise",
"ValueError",
"(",
"\"scheme %s is invalid\"",
"%",
"scheme",
")",
"if",
"parsed",
".",
"path",
":",
"resource",
"=",
"parsed",
".",
"path",
"else",
":",
"resource",
"=",
"\"/\"",
"if",
"parsed",
".",
"query",
":",
"resource",
"+=",
"\"?\"",
"+",
"parsed",
".",
"query",
"return",
"(",
"hostname",
",",
"port",
",",
"resource",
",",
"is_secure",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/websocket-client/websocket.py#L133-L173 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/examples/python/gdbremote.py | python | RegisterInfo.get_value_from_hex_string | (self, hex_str) | return '%s' % (value_str) | Dump the register value given a native byte order encoded hex ASCII byte string. | Dump the register value given a native byte order encoded hex ASCII byte string. | [
"Dump",
"the",
"register",
"value",
"given",
"a",
"native",
"byte",
"order",
"encoded",
"hex",
"ASCII",
"byte",
"string",
"."
] | def get_value_from_hex_string(self, hex_str):
'''Dump the register value given a native byte order encoded hex ASCII byte string.'''
encoding = self.info['encoding']
bit_size = self.bit_size()
packet = Packet(hex_str)
if encoding == 'uint':
uval = packet.get_hex_uint(g_byte_order)
if bit_size == 8:
return '0x%2.2x' % (uval)
elif bit_size == 16:
return '0x%4.4x' % (uval)
elif bit_size == 32:
return '0x%8.8x' % (uval)
elif bit_size == 64:
return '0x%16.16x' % (uval)
bytes = list()
uval = packet.get_hex_uint8()
while uval is not None:
bytes.append(uval)
uval = packet.get_hex_uint8()
value_str = '0x'
if g_byte_order == 'little':
bytes.reverse()
for byte in bytes:
value_str += '%2.2x' % byte
return '%s' % (value_str) | [
"def",
"get_value_from_hex_string",
"(",
"self",
",",
"hex_str",
")",
":",
"encoding",
"=",
"self",
".",
"info",
"[",
"'encoding'",
"]",
"bit_size",
"=",
"self",
".",
"bit_size",
"(",
")",
"packet",
"=",
"Packet",
"(",
"hex_str",
")",
"if",
"encoding",
"==",
"'uint'",
":",
"uval",
"=",
"packet",
".",
"get_hex_uint",
"(",
"g_byte_order",
")",
"if",
"bit_size",
"==",
"8",
":",
"return",
"'0x%2.2x'",
"%",
"(",
"uval",
")",
"elif",
"bit_size",
"==",
"16",
":",
"return",
"'0x%4.4x'",
"%",
"(",
"uval",
")",
"elif",
"bit_size",
"==",
"32",
":",
"return",
"'0x%8.8x'",
"%",
"(",
"uval",
")",
"elif",
"bit_size",
"==",
"64",
":",
"return",
"'0x%16.16x'",
"%",
"(",
"uval",
")",
"bytes",
"=",
"list",
"(",
")",
"uval",
"=",
"packet",
".",
"get_hex_uint8",
"(",
")",
"while",
"uval",
"is",
"not",
"None",
":",
"bytes",
".",
"append",
"(",
"uval",
")",
"uval",
"=",
"packet",
".",
"get_hex_uint8",
"(",
")",
"value_str",
"=",
"'0x'",
"if",
"g_byte_order",
"==",
"'little'",
":",
"bytes",
".",
"reverse",
"(",
")",
"for",
"byte",
"in",
"bytes",
":",
"value_str",
"+=",
"'%2.2x'",
"%",
"byte",
"return",
"'%s'",
"%",
"(",
"value_str",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/examples/python/gdbremote.py#L356-L381 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/sdata.py | python | SDataByAngle.set_angle_data | (self, angle_index: int, sdata: SData,
add_to_existing: bool = False) | Set data for one angle from SData object
Args:
angle_index:
Index (in self.angles) of angle corresponding to data
sdata:
New S values to replace current content at given angle
add_to_existing:
Instead of replacing existing data, values are summed together | Set data for one angle from SData object | [
"Set",
"data",
"for",
"one",
"angle",
"from",
"SData",
"object"
] | def set_angle_data(self, angle_index: int, sdata: SData,
add_to_existing: bool = False) -> None:
"""Set data for one angle from SData object
Args:
angle_index:
Index (in self.angles) of angle corresponding to data
sdata:
New S values to replace current content at given angle
add_to_existing:
Instead of replacing existing data, values are summed together
"""
data = sdata.extract()
if 'frequencies' in data:
del data['frequencies']
self.set_angle_data_from_dict(angle_index, data,
add_to_existing=add_to_existing) | [
"def",
"set_angle_data",
"(",
"self",
",",
"angle_index",
":",
"int",
",",
"sdata",
":",
"SData",
",",
"add_to_existing",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"data",
"=",
"sdata",
".",
"extract",
"(",
")",
"if",
"'frequencies'",
"in",
"data",
":",
"del",
"data",
"[",
"'frequencies'",
"]",
"self",
".",
"set_angle_data_from_dict",
"(",
"angle_index",
",",
"data",
",",
"add_to_existing",
"=",
"add_to_existing",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/sdata.py#L509-L531 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/query.py | python | CustomRun.entry_ok | (self) | return None if cli_args is None else (cli_args, restart) | Return apparently valid (cli_args, restart) or None | Return apparently valid (cli_args, restart) or None | [
"Return",
"apparently",
"valid",
"(",
"cli_args",
"restart",
")",
"or",
"None"
] | def entry_ok(self):
"Return apparently valid (cli_args, restart) or None"
cli_args = self.cli_args_ok()
restart = self.restartvar.get()
return None if cli_args is None else (cli_args, restart) | [
"def",
"entry_ok",
"(",
"self",
")",
":",
"cli_args",
"=",
"self",
".",
"cli_args_ok",
"(",
")",
"restart",
"=",
"self",
".",
"restartvar",
".",
"get",
"(",
")",
"return",
"None",
"if",
"cli_args",
"is",
"None",
"else",
"(",
"cli_args",
",",
"restart",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/query.py#L377-L381 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | LoadResponse.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(LoadResponse) | Returns new LoadResponse object constructed from its marshaled
representation in the given byte buffer | Returns new LoadResponse object constructed from its marshaled
representation in the given byte buffer | [
"Returns",
"new",
"LoadResponse",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new LoadResponse object constructed from its marshaled
representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(LoadResponse) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"LoadResponse",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9648-L9652 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/mindrecord/shardsegment.py | python | ShardSegment.set_category_field | (self, category_field) | return self._segment.set_category_field(category_field) | Select one category field to use. | Select one category field to use. | [
"Select",
"one",
"category",
"field",
"to",
"use",
"."
] | def set_category_field(self, category_field):
"""Select one category field to use."""
return self._segment.set_category_field(category_field) | [
"def",
"set_category_field",
"(",
"self",
",",
"category_field",
")",
":",
"return",
"self",
".",
"_segment",
".",
"set_category_field",
"(",
"category_field",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/shardsegment.py#L78-L80 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/webbrowser.py | python | open_new | (url) | return open(url, 1) | Open url in a new window of the default browser.
If not possible, then open url in the only browser window. | Open url in a new window of the default browser. | [
"Open",
"url",
"in",
"a",
"new",
"window",
"of",
"the",
"default",
"browser",
"."
] | def open_new(url):
"""Open url in a new window of the default browser.
If not possible, then open url in the only browser window.
"""
return open(url, 1) | [
"def",
"open_new",
"(",
"url",
")",
":",
"return",
"open",
"(",
"url",
",",
"1",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/webbrowser.py#L90-L95 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/android/device_utils.py | python | DeviceUtils.GetClientCache | (self, client_name) | return self._client_caches[client_name] | Returns client cache. | Returns client cache. | [
"Returns",
"client",
"cache",
"."
] | def GetClientCache(self, client_name):
"""Returns client cache."""
if client_name not in self._client_caches:
self._client_caches[client_name] = {}
return self._client_caches[client_name] | [
"def",
"GetClientCache",
"(",
"self",
",",
"client_name",
")",
":",
"if",
"client_name",
"not",
"in",
"self",
".",
"_client_caches",
":",
"self",
".",
"_client_caches",
"[",
"client_name",
"]",
"=",
"{",
"}",
"return",
"self",
".",
"_client_caches",
"[",
"client_name",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/device_utils.py#L2205-L2209 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.ScrollToLine | (*args, **kwargs) | return _stc.StyledTextCtrl_ScrollToLine(*args, **kwargs) | ScrollToLine(self, int line)
Scroll enough to make the given line visible. | ScrollToLine(self, int line) | [
"ScrollToLine",
"(",
"self",
"int",
"line",
")"
] | def ScrollToLine(*args, **kwargs):
"""
ScrollToLine(self, int line)
Scroll enough to make the given line visible.
"""
return _stc.StyledTextCtrl_ScrollToLine(*args, **kwargs) | [
"def",
"ScrollToLine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_ScrollToLine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L6605-L6611 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | GBSpan.__init__ | (self, *args, **kwargs) | __init__(self, int rowspan=1, int colspan=1) -> GBSpan
Construct a new wxGBSpan, optionally setting the rowspan and
colspan. The default is (1,1). (Meaning that the item occupies one
cell in each direction. | __init__(self, int rowspan=1, int colspan=1) -> GBSpan | [
"__init__",
"(",
"self",
"int",
"rowspan",
"=",
"1",
"int",
"colspan",
"=",
"1",
")",
"-",
">",
"GBSpan"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, int rowspan=1, int colspan=1) -> GBSpan
Construct a new wxGBSpan, optionally setting the rowspan and
colspan. The default is (1,1). (Meaning that the item occupies one
cell in each direction.
"""
_core_.GBSpan_swiginit(self,_core_.new_GBSpan(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_core_",
".",
"GBSpan_swiginit",
"(",
"self",
",",
"_core_",
".",
"new_GBSpan",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L15645-L15653 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | PyScrolledWindow.DoSetSize | (*args, **kwargs) | return _windows_.PyScrolledWindow_DoSetSize(*args, **kwargs) | DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO) | DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO) | [
"DoSetSize",
"(",
"self",
"int",
"x",
"int",
"y",
"int",
"width",
"int",
"height",
"int",
"sizeFlags",
"=",
"SIZE_AUTO",
")"
] | def DoSetSize(*args, **kwargs):
"""DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO)"""
return _windows_.PyScrolledWindow_DoSetSize(*args, **kwargs) | [
"def",
"DoSetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PyScrolledWindow_DoSetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L4516-L4518 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/binary-tree-postorder-traversal.py | python | Solution.postorderTraversal | (self, root) | return result | :type root: TreeNode
:rtype: List[int] | :type root: TreeNode
:rtype: List[int] | [
":",
"type",
"root",
":",
"TreeNode",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
dummy = TreeNode(0)
dummy.left = root
result, cur = [], dummy
while cur:
if cur.left is None:
cur = cur.right
else:
node = cur.left
while node.right and node.right != cur:
node = node.right
if node.right is None:
node.right = cur
cur = cur.left
else:
result += self.traceBack(cur.left, node)
node.right = None
cur = cur.right
return result | [
"def",
"postorderTraversal",
"(",
"self",
",",
"root",
")",
":",
"dummy",
"=",
"TreeNode",
"(",
"0",
")",
"dummy",
".",
"left",
"=",
"root",
"result",
",",
"cur",
"=",
"[",
"]",
",",
"dummy",
"while",
"cur",
":",
"if",
"cur",
".",
"left",
"is",
"None",
":",
"cur",
"=",
"cur",
".",
"right",
"else",
":",
"node",
"=",
"cur",
".",
"left",
"while",
"node",
".",
"right",
"and",
"node",
".",
"right",
"!=",
"cur",
":",
"node",
"=",
"node",
".",
"right",
"if",
"node",
".",
"right",
"is",
"None",
":",
"node",
".",
"right",
"=",
"cur",
"cur",
"=",
"cur",
".",
"left",
"else",
":",
"result",
"+=",
"self",
".",
"traceBack",
"(",
"cur",
".",
"left",
",",
"node",
")",
"node",
".",
"right",
"=",
"None",
"cur",
"=",
"cur",
".",
"right",
"return",
"result"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/binary-tree-postorder-traversal.py#L13-L37 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/retdec-3.2/scripts/type_extractor/type_extractor/header_text_filters.py | python | filter_out_comments | (text) | return text | Removes one-line and multi-line comments. | Removes one-line and multi-line comments. | [
"Removes",
"one",
"-",
"line",
"and",
"multi",
"-",
"line",
"comments",
"."
] | def filter_out_comments(text):
"""Removes one-line and multi-line comments."""
text = re.sub(r'//(?:(?!\*/).)*$', '', text, flags=re.M)
text = re.sub(r'(?<!/)/\*.*?\*/', ' ', text, flags=re.S)
text = re.sub(r'//.*?$', '', text, flags=re.M)
return text | [
"def",
"filter_out_comments",
"(",
"text",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r'//(?:(?!\\*/).)*$'",
",",
"''",
",",
"text",
",",
"flags",
"=",
"re",
".",
"M",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'(?<!/)/\\*.*?\\*/'",
",",
"' '",
",",
"text",
",",
"flags",
"=",
"re",
".",
"S",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'//.*?$'",
",",
"''",
",",
"text",
",",
"flags",
"=",
"re",
".",
"M",
")",
"return",
"text"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/retdec-3.2/scripts/type_extractor/type_extractor/header_text_filters.py#L82-L87 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | clang/tools/scan-build-py/lib/libscanbuild/arguments.py | python | normalize_args_for_analyze | (args, from_build_command) | Normalize parsed arguments for analyze-build and scan-build.
:param args: Parsed argument object. (Will be mutated.)
:param from_build_command: Boolean value tells is the command suppose
to run the analyzer against a build command or a compilation db. | Normalize parsed arguments for analyze-build and scan-build. | [
"Normalize",
"parsed",
"arguments",
"for",
"analyze",
"-",
"build",
"and",
"scan",
"-",
"build",
"."
] | def normalize_args_for_analyze(args, from_build_command):
""" Normalize parsed arguments for analyze-build and scan-build.
:param args: Parsed argument object. (Will be mutated.)
:param from_build_command: Boolean value tells is the command suppose
to run the analyzer against a build command or a compilation db. """
# make plugins always a list. (it might be None when not specified.)
if args.plugins is None:
args.plugins = []
# make exclude directory list unique and absolute.
uniq_excludes = set(os.path.abspath(entry) for entry in args.excludes)
args.excludes = list(uniq_excludes)
# because shared codes for all tools, some common used methods are
# expecting some argument to be present. so, instead of query the args
# object about the presence of the flag, we fake it here. to make those
# methods more readable. (it's an arguable choice, took it only for those
# which have good default value.)
if from_build_command:
# add cdb parameter invisibly to make report module working.
args.cdb = 'compile_commands.json'
# Make ctu_dir an abspath as it is needed inside clang
if not from_build_command and hasattr(args, 'ctu_phases') \
and hasattr(args.ctu_phases, 'dir'):
args.ctu_dir = os.path.abspath(args.ctu_dir) | [
"def",
"normalize_args_for_analyze",
"(",
"args",
",",
"from_build_command",
")",
":",
"# make plugins always a list. (it might be None when not specified.)",
"if",
"args",
".",
"plugins",
"is",
"None",
":",
"args",
".",
"plugins",
"=",
"[",
"]",
"# make exclude directory list unique and absolute.",
"uniq_excludes",
"=",
"set",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"entry",
")",
"for",
"entry",
"in",
"args",
".",
"excludes",
")",
"args",
".",
"excludes",
"=",
"list",
"(",
"uniq_excludes",
")",
"# because shared codes for all tools, some common used methods are",
"# expecting some argument to be present. so, instead of query the args",
"# object about the presence of the flag, we fake it here. to make those",
"# methods more readable. (it's an arguable choice, took it only for those",
"# which have good default value.)",
"if",
"from_build_command",
":",
"# add cdb parameter invisibly to make report module working.",
"args",
".",
"cdb",
"=",
"'compile_commands.json'",
"# Make ctu_dir an abspath as it is needed inside clang",
"if",
"not",
"from_build_command",
"and",
"hasattr",
"(",
"args",
",",
"'ctu_phases'",
")",
"and",
"hasattr",
"(",
"args",
".",
"ctu_phases",
",",
"'dir'",
")",
":",
"args",
".",
"ctu_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"args",
".",
"ctu_dir",
")"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/tools/scan-build-py/lib/libscanbuild/arguments.py#L77-L104 | ||
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/ansic/cparse.py | python | p_labeled_statement_1 | (t) | labeled_statement : ID COLON statement | labeled_statement : ID COLON statement | [
"labeled_statement",
":",
"ID",
"COLON",
"statement"
] | def p_labeled_statement_1(t):
'labeled_statement : ID COLON statement'
pass | [
"def",
"p_labeled_statement_1",
"(",
"t",
")",
":",
"pass"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L466-L468 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/png/png.py | python | Test.testPalExpand | (self) | Test that bitdepth can be used to fiddle with pallete image. | Test that bitdepth can be used to fiddle with pallete image. | [
"Test",
"that",
"bitdepth",
"can",
"be",
"used",
"to",
"fiddle",
"with",
"pallete",
"image",
"."
] | def testPalExpand(self):
"""Test that bitdepth can be used to fiddle with pallete image."""
r = Reader(bytes=_pngsuite['basn3p04'])
x,y,pixels,info = r.read()
pixels = [list(row) for row in pixels]
info['bitdepth'] = 8
w = Writer(**info)
o = BytesIO()
w.write(o, pixels)
o.flush()
o.seek(0)
r = Reader(file=o)
_,_,again_pixels,again_info = r.read()
# Same pixels
again_pixels = [list(row) for row in again_pixels]
self.assertEqual(again_pixels, pixels) | [
"def",
"testPalExpand",
"(",
"self",
")",
":",
"r",
"=",
"Reader",
"(",
"bytes",
"=",
"_pngsuite",
"[",
"'basn3p04'",
"]",
")",
"x",
",",
"y",
",",
"pixels",
",",
"info",
"=",
"r",
".",
"read",
"(",
")",
"pixels",
"=",
"[",
"list",
"(",
"row",
")",
"for",
"row",
"in",
"pixels",
"]",
"info",
"[",
"'bitdepth'",
"]",
"=",
"8",
"w",
"=",
"Writer",
"(",
"*",
"*",
"info",
")",
"o",
"=",
"BytesIO",
"(",
")",
"w",
".",
"write",
"(",
"o",
",",
"pixels",
")",
"o",
".",
"flush",
"(",
")",
"o",
".",
"seek",
"(",
"0",
")",
"r",
"=",
"Reader",
"(",
"file",
"=",
"o",
")",
"_",
",",
"_",
",",
"again_pixels",
",",
"again_info",
"=",
"r",
".",
"read",
"(",
")",
"# Same pixels",
"again_pixels",
"=",
"[",
"list",
"(",
"row",
")",
"for",
"row",
"in",
"again_pixels",
"]",
"self",
".",
"assertEqual",
"(",
"again_pixels",
",",
"pixels",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/png/png.py#L2711-L2726 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/connectionpool.py | python | HTTPConnectionPool._make_request | (
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
) | return httplib_response | Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts. | Perform a request on a given urllib connection object taken from our
pool. | [
"Perform",
"a",
"request",
"on",
"a",
"given",
"urllib",
"connection",
"object",
"taken",
"from",
"our",
"pool",
"."
] | def _make_request(
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts.
"""
self.num_requests += 1
timeout_obj = self._get_timeout(timeout)
timeout_obj.start_connect()
conn.timeout = timeout_obj.connect_timeout
# Trigger any extra validation we need to do.
try:
self._validate_conn(conn)
except (SocketTimeout, BaseSSLError) as e:
# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
raise
# conn.request() calls http.client.*.request, not the method in
# urllib3.request. It also calls makefile (recv) on the socket.
try:
if chunked:
conn.request_chunked(method, url, **httplib_request_kw)
else:
conn.request(method, url, **httplib_request_kw)
# We are swallowing BrokenPipeError (errno.EPIPE) since the server is
# legitimately able to close the connection after sending a valid response.
# With this behaviour, the received response is still readable.
except BrokenPipeError:
# Python 3
pass
except IOError as e:
# Python 2 and macOS/Linux
# EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE is needed on macOS
# https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
if e.errno not in {
errno.EPIPE,
errno.ESHUTDOWN,
errno.EPROTOTYPE,
}:
raise
# Reset the timeout for the recv() on the socket
read_timeout = timeout_obj.read_timeout
# App Engine doesn't have a sock attr
if getattr(conn, "sock", None):
# In Python 3 socket.py will catch EAGAIN and return None when you
# try and read into the file pointer created by http.client, which
# instead raises a BadStatusLine exception. Instead of catching
# the exception and assuming all BadStatusLine exceptions are read
# timeouts, check for a zero timeout before making the request.
if read_timeout == 0:
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % read_timeout
)
if read_timeout is Timeout.DEFAULT_TIMEOUT:
conn.sock.settimeout(socket.getdefaulttimeout())
else: # None or a value
conn.sock.settimeout(read_timeout)
# Receive the response from the server
try:
try:
# Python 2.7, use buffering of HTTP responses
httplib_response = conn.getresponse(buffering=True)
except TypeError:
# Python 3
try:
httplib_response = conn.getresponse()
except BaseException as e:
# Remove the TypeError from the exception chain in
# Python 3 (including for exceptions like SystemExit).
# Otherwise it looks like a bug in the code.
six.raise_from(e, None)
except (SocketTimeout, BaseSSLError, SocketError) as e:
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
raise
# AppEngine doesn't have a version attr.
http_version = getattr(conn, "_http_vsn_str", "HTTP/?")
log.debug(
'%s://%s:%s "%s %s %s" %s %s',
self.scheme,
self.host,
self.port,
method,
url,
http_version,
httplib_response.status,
httplib_response.length,
)
try:
assert_header_parsing(httplib_response.msg)
except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3
log.warning(
"Failed to parse headers (url=%s): %s",
self._absolute_url(url),
hpe,
exc_info=True,
)
return httplib_response | [
"def",
"_make_request",
"(",
"self",
",",
"conn",
",",
"method",
",",
"url",
",",
"timeout",
"=",
"_Default",
",",
"chunked",
"=",
"False",
",",
"*",
"*",
"httplib_request_kw",
")",
":",
"self",
".",
"num_requests",
"+=",
"1",
"timeout_obj",
"=",
"self",
".",
"_get_timeout",
"(",
"timeout",
")",
"timeout_obj",
".",
"start_connect",
"(",
")",
"conn",
".",
"timeout",
"=",
"timeout_obj",
".",
"connect_timeout",
"# Trigger any extra validation we need to do.",
"try",
":",
"self",
".",
"_validate_conn",
"(",
"conn",
")",
"except",
"(",
"SocketTimeout",
",",
"BaseSSLError",
")",
"as",
"e",
":",
"# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.",
"self",
".",
"_raise_timeout",
"(",
"err",
"=",
"e",
",",
"url",
"=",
"url",
",",
"timeout_value",
"=",
"conn",
".",
"timeout",
")",
"raise",
"# conn.request() calls http.client.*.request, not the method in",
"# urllib3.request. It also calls makefile (recv) on the socket.",
"try",
":",
"if",
"chunked",
":",
"conn",
".",
"request_chunked",
"(",
"method",
",",
"url",
",",
"*",
"*",
"httplib_request_kw",
")",
"else",
":",
"conn",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"httplib_request_kw",
")",
"# We are swallowing BrokenPipeError (errno.EPIPE) since the server is",
"# legitimately able to close the connection after sending a valid response.",
"# With this behaviour, the received response is still readable.",
"except",
"BrokenPipeError",
":",
"# Python 3",
"pass",
"except",
"IOError",
"as",
"e",
":",
"# Python 2 and macOS/Linux",
"# EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE is needed on macOS",
"# https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/",
"if",
"e",
".",
"errno",
"not",
"in",
"{",
"errno",
".",
"EPIPE",
",",
"errno",
".",
"ESHUTDOWN",
",",
"errno",
".",
"EPROTOTYPE",
",",
"}",
":",
"raise",
"# Reset the timeout for the recv() on the socket",
"read_timeout",
"=",
"timeout_obj",
".",
"read_timeout",
"# App Engine doesn't have a sock attr",
"if",
"getattr",
"(",
"conn",
",",
"\"sock\"",
",",
"None",
")",
":",
"# In Python 3 socket.py will catch EAGAIN and return None when you",
"# try and read into the file pointer created by http.client, which",
"# instead raises a BadStatusLine exception. Instead of catching",
"# the exception and assuming all BadStatusLine exceptions are read",
"# timeouts, check for a zero timeout before making the request.",
"if",
"read_timeout",
"==",
"0",
":",
"raise",
"ReadTimeoutError",
"(",
"self",
",",
"url",
",",
"\"Read timed out. (read timeout=%s)\"",
"%",
"read_timeout",
")",
"if",
"read_timeout",
"is",
"Timeout",
".",
"DEFAULT_TIMEOUT",
":",
"conn",
".",
"sock",
".",
"settimeout",
"(",
"socket",
".",
"getdefaulttimeout",
"(",
")",
")",
"else",
":",
"# None or a value",
"conn",
".",
"sock",
".",
"settimeout",
"(",
"read_timeout",
")",
"# Receive the response from the server",
"try",
":",
"try",
":",
"# Python 2.7, use buffering of HTTP responses",
"httplib_response",
"=",
"conn",
".",
"getresponse",
"(",
"buffering",
"=",
"True",
")",
"except",
"TypeError",
":",
"# Python 3",
"try",
":",
"httplib_response",
"=",
"conn",
".",
"getresponse",
"(",
")",
"except",
"BaseException",
"as",
"e",
":",
"# Remove the TypeError from the exception chain in",
"# Python 3 (including for exceptions like SystemExit).",
"# Otherwise it looks like a bug in the code.",
"six",
".",
"raise_from",
"(",
"e",
",",
"None",
")",
"except",
"(",
"SocketTimeout",
",",
"BaseSSLError",
",",
"SocketError",
")",
"as",
"e",
":",
"self",
".",
"_raise_timeout",
"(",
"err",
"=",
"e",
",",
"url",
"=",
"url",
",",
"timeout_value",
"=",
"read_timeout",
")",
"raise",
"# AppEngine doesn't have a version attr.",
"http_version",
"=",
"getattr",
"(",
"conn",
",",
"\"_http_vsn_str\"",
",",
"\"HTTP/?\"",
")",
"log",
".",
"debug",
"(",
"'%s://%s:%s \"%s %s %s\" %s %s'",
",",
"self",
".",
"scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"method",
",",
"url",
",",
"http_version",
",",
"httplib_response",
".",
"status",
",",
"httplib_response",
".",
"length",
",",
")",
"try",
":",
"assert_header_parsing",
"(",
"httplib_response",
".",
"msg",
")",
"except",
"(",
"HeaderParsingError",
",",
"TypeError",
")",
"as",
"hpe",
":",
"# Platform-specific: Python 3",
"log",
".",
"warning",
"(",
"\"Failed to parse headers (url=%s): %s\"",
",",
"self",
".",
"_absolute_url",
"(",
"url",
")",
",",
"hpe",
",",
"exc_info",
"=",
"True",
",",
")",
"return",
"httplib_response"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/connectionpool.py#L357-L474 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/docs/tools/dump_ast_matchers.py | python | add_matcher | (result_type, name, args, comment, is_dyncast=False) | Adds a matcher to one of our categories. | Adds a matcher to one of our categories. | [
"Adds",
"a",
"matcher",
"to",
"one",
"of",
"our",
"categories",
"."
] | def add_matcher(result_type, name, args, comment, is_dyncast=False):
"""Adds a matcher to one of our categories."""
if name == 'id':
# FIXME: Figure out whether we want to support the 'id' matcher.
return
matcher_id = '%s%d' % (name, ids[name])
ids[name] += 1
args = unify_arguments(args)
result_type = unify_type(result_type)
docs_result_type = esc('Matcher<%s>' % result_type);
if name == 'mapAnyOf':
args = "nodeMatcherFunction..."
docs_result_type = "<em>unspecified</em>"
matcher_html = TD_TEMPLATE % {
'result': docs_result_type,
'name': name,
'args': esc(args),
'comment': esc(strip_doxygen(comment)),
'id': matcher_id,
}
if is_dyncast:
dict = node_matchers
lookup = result_type + name
# Use a heuristic to figure out whether a matcher is a narrowing or
# traversal matcher. By default, matchers that take other matchers as
# arguments (and are not node matchers) do traversal. We specifically
# exclude known narrowing matchers that also take other matchers as
# arguments.
elif ('Matcher<' not in args or
name in ['allOf', 'anyOf', 'anything', 'unless', 'mapAnyOf']):
dict = narrowing_matchers
lookup = result_type + name + esc(args)
else:
dict = traversal_matchers
lookup = result_type + name + esc(args)
if dict.get(lookup) is None or len(dict.get(lookup)) < len(matcher_html):
dict[lookup] = matcher_html | [
"def",
"add_matcher",
"(",
"result_type",
",",
"name",
",",
"args",
",",
"comment",
",",
"is_dyncast",
"=",
"False",
")",
":",
"if",
"name",
"==",
"'id'",
":",
"# FIXME: Figure out whether we want to support the 'id' matcher.",
"return",
"matcher_id",
"=",
"'%s%d'",
"%",
"(",
"name",
",",
"ids",
"[",
"name",
"]",
")",
"ids",
"[",
"name",
"]",
"+=",
"1",
"args",
"=",
"unify_arguments",
"(",
"args",
")",
"result_type",
"=",
"unify_type",
"(",
"result_type",
")",
"docs_result_type",
"=",
"esc",
"(",
"'Matcher<%s>'",
"%",
"result_type",
")",
"if",
"name",
"==",
"'mapAnyOf'",
":",
"args",
"=",
"\"nodeMatcherFunction...\"",
"docs_result_type",
"=",
"\"<em>unspecified</em>\"",
"matcher_html",
"=",
"TD_TEMPLATE",
"%",
"{",
"'result'",
":",
"docs_result_type",
",",
"'name'",
":",
"name",
",",
"'args'",
":",
"esc",
"(",
"args",
")",
",",
"'comment'",
":",
"esc",
"(",
"strip_doxygen",
"(",
"comment",
")",
")",
",",
"'id'",
":",
"matcher_id",
",",
"}",
"if",
"is_dyncast",
":",
"dict",
"=",
"node_matchers",
"lookup",
"=",
"result_type",
"+",
"name",
"# Use a heuristic to figure out whether a matcher is a narrowing or",
"# traversal matcher. By default, matchers that take other matchers as",
"# arguments (and are not node matchers) do traversal. We specifically",
"# exclude known narrowing matchers that also take other matchers as",
"# arguments.",
"elif",
"(",
"'Matcher<'",
"not",
"in",
"args",
"or",
"name",
"in",
"[",
"'allOf'",
",",
"'anyOf'",
",",
"'anything'",
",",
"'unless'",
",",
"'mapAnyOf'",
"]",
")",
":",
"dict",
"=",
"narrowing_matchers",
"lookup",
"=",
"result_type",
"+",
"name",
"+",
"esc",
"(",
"args",
")",
"else",
":",
"dict",
"=",
"traversal_matchers",
"lookup",
"=",
"result_type",
"+",
"name",
"+",
"esc",
"(",
"args",
")",
"if",
"dict",
".",
"get",
"(",
"lookup",
")",
"is",
"None",
"or",
"len",
"(",
"dict",
".",
"get",
"(",
"lookup",
")",
")",
"<",
"len",
"(",
"matcher_html",
")",
":",
"dict",
"[",
"lookup",
"]",
"=",
"matcher_html"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/docs/tools/dump_ast_matchers.py#L113-L153 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/column/string.py | python | StringColumn.find_and_replace | (
self,
to_replace: ColumnLike,
replacement: ColumnLike,
all_nan: bool = False,
) | return libcudf.replace.replace(res, df._data["old"], df._data["new"]) | Return col with *to_replace* replaced with *value* | Return col with *to_replace* replaced with *value* | [
"Return",
"col",
"with",
"*",
"to_replace",
"*",
"replaced",
"with",
"*",
"value",
"*"
] | def find_and_replace(
self,
to_replace: ColumnLike,
replacement: ColumnLike,
all_nan: bool = False,
) -> StringColumn:
"""
Return col with *to_replace* replaced with *value*
"""
to_replace_col = column.as_column(to_replace)
replacement_col = column.as_column(replacement)
if type(to_replace_col) != type(replacement_col):
raise TypeError(
f"to_replace and value should be of same types,"
f"got to_replace dtype: {to_replace_col.dtype} and "
f"value dtype: {replacement_col.dtype}"
)
if (
to_replace_col.dtype != self.dtype
and replacement_col.dtype != self.dtype
):
return self.copy()
df = cudf.DataFrame({"old": to_replace_col, "new": replacement_col})
df = df.drop_duplicates(subset=["old"], keep="last", ignore_index=True)
if df._data["old"].null_count == 1:
res = self.fillna(df._data["new"][df._data["old"].isnull()][0])
df = df.dropna(subset=["old"])
else:
res = self
return libcudf.replace.replace(res, df._data["old"], df._data["new"]) | [
"def",
"find_and_replace",
"(",
"self",
",",
"to_replace",
":",
"ColumnLike",
",",
"replacement",
":",
"ColumnLike",
",",
"all_nan",
":",
"bool",
"=",
"False",
",",
")",
"->",
"StringColumn",
":",
"to_replace_col",
"=",
"column",
".",
"as_column",
"(",
"to_replace",
")",
"replacement_col",
"=",
"column",
".",
"as_column",
"(",
"replacement",
")",
"if",
"type",
"(",
"to_replace_col",
")",
"!=",
"type",
"(",
"replacement_col",
")",
":",
"raise",
"TypeError",
"(",
"f\"to_replace and value should be of same types,\"",
"f\"got to_replace dtype: {to_replace_col.dtype} and \"",
"f\"value dtype: {replacement_col.dtype}\"",
")",
"if",
"(",
"to_replace_col",
".",
"dtype",
"!=",
"self",
".",
"dtype",
"and",
"replacement_col",
".",
"dtype",
"!=",
"self",
".",
"dtype",
")",
":",
"return",
"self",
".",
"copy",
"(",
")",
"df",
"=",
"cudf",
".",
"DataFrame",
"(",
"{",
"\"old\"",
":",
"to_replace_col",
",",
"\"new\"",
":",
"replacement_col",
"}",
")",
"df",
"=",
"df",
".",
"drop_duplicates",
"(",
"subset",
"=",
"[",
"\"old\"",
"]",
",",
"keep",
"=",
"\"last\"",
",",
"ignore_index",
"=",
"True",
")",
"if",
"df",
".",
"_data",
"[",
"\"old\"",
"]",
".",
"null_count",
"==",
"1",
":",
"res",
"=",
"self",
".",
"fillna",
"(",
"df",
".",
"_data",
"[",
"\"new\"",
"]",
"[",
"df",
".",
"_data",
"[",
"\"old\"",
"]",
".",
"isnull",
"(",
")",
"]",
"[",
"0",
"]",
")",
"df",
"=",
"df",
".",
"dropna",
"(",
"subset",
"=",
"[",
"\"old\"",
"]",
")",
"else",
":",
"res",
"=",
"self",
"return",
"libcudf",
".",
"replace",
".",
"replace",
"(",
"res",
",",
"df",
".",
"_data",
"[",
"\"old\"",
"]",
",",
"df",
".",
"_data",
"[",
"\"new\"",
"]",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/string.py#L5317-L5349 | |
sfzhang15/RefineDet | 52b6fe23dc1a160fe710b7734576dca509bf4fae | scripts/cpp_lint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=[]) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = _NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// marker so line numbers end in a known way'",
"]",
")",
"include_state",
"=",
"_IncludeState",
"(",
")",
"function_state",
"=",
"_FunctionState",
"(",
")",
"nesting_state",
"=",
"_NestingState",
"(",
")",
"ResetNolintSuppressions",
"(",
")",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"CheckForHeaderGuard",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"clean_lines",
"=",
"CleansedLines",
"(",
"lines",
")",
"for",
"line",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
")",
"nesting_state",
".",
"CheckCompletedBlocks",
"(",
"filename",
",",
"error",
")",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
")",
"# We check here rather than inside ProcessLine so that we see raw",
"# lines rather than \"cleaned\" lines.",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")"
] | https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/scripts/cpp_lint.py#L4648-L4691 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py | python | Session.options | (self, url, **kwargs) | return self.request('OPTIONS', url, **kwargs) | r"""Sends a OPTIONS request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response | r"""Sends a OPTIONS request. Returns :class:`Response` object. | [
"r",
"Sends",
"a",
"OPTIONS",
"request",
".",
"Returns",
":",
"class",
":",
"Response",
"object",
"."
] | def options(self, url, **kwargs):
r"""Sends a OPTIONS request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return self.request('OPTIONS', url, **kwargs) | [
"def",
"options",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'allow_redirects'",
",",
"True",
")",
"return",
"self",
".",
"request",
"(",
"'OPTIONS'",
",",
"url",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py#L545-L554 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/fixes/fix_import.py | python | traverse_imports | (names) | Walks over all the names imported in a dotted_as_names node. | Walks over all the names imported in a dotted_as_names node. | [
"Walks",
"over",
"all",
"the",
"names",
"imported",
"in",
"a",
"dotted_as_names",
"node",
"."
] | def traverse_imports(names):
"""
Walks over all the names imported in a dotted_as_names node.
"""
pending = [names]
while pending:
node = pending.pop()
if node.type == token.NAME:
yield node.value
elif node.type == syms.dotted_name:
yield "".join([ch.value for ch in node.children])
elif node.type == syms.dotted_as_name:
pending.append(node.children[0])
elif node.type == syms.dotted_as_names:
pending.extend(node.children[::-2])
else:
raise AssertionError("unkown node type") | [
"def",
"traverse_imports",
"(",
"names",
")",
":",
"pending",
"=",
"[",
"names",
"]",
"while",
"pending",
":",
"node",
"=",
"pending",
".",
"pop",
"(",
")",
"if",
"node",
".",
"type",
"==",
"token",
".",
"NAME",
":",
"yield",
"node",
".",
"value",
"elif",
"node",
".",
"type",
"==",
"syms",
".",
"dotted_name",
":",
"yield",
"\"\"",
".",
"join",
"(",
"[",
"ch",
".",
"value",
"for",
"ch",
"in",
"node",
".",
"children",
"]",
")",
"elif",
"node",
".",
"type",
"==",
"syms",
".",
"dotted_as_name",
":",
"pending",
".",
"append",
"(",
"node",
".",
"children",
"[",
"0",
"]",
")",
"elif",
"node",
".",
"type",
"==",
"syms",
".",
"dotted_as_names",
":",
"pending",
".",
"extend",
"(",
"node",
".",
"children",
"[",
":",
":",
"-",
"2",
"]",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"\"unkown node type\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/fixes/fix_import.py#L19-L35 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py | python | Decimal._isinteger | (self) | return rest == '0'*len(rest) | Returns whether self is an integer | Returns whether self is an integer | [
"Returns",
"whether",
"self",
"is",
"an",
"integer"
] | def _isinteger(self):
"""Returns whether self is an integer"""
if self._is_special:
return False
if self._exp >= 0:
return True
rest = self._int[self._exp:]
return rest == '0'*len(rest) | [
"def",
"_isinteger",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_special",
":",
"return",
"False",
"if",
"self",
".",
"_exp",
">=",
"0",
":",
"return",
"True",
"rest",
"=",
"self",
".",
"_int",
"[",
"self",
".",
"_exp",
":",
"]",
"return",
"rest",
"==",
"'0'",
"*",
"len",
"(",
"rest",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py#L2788-L2795 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudformation/connection.py | python | CloudFormationConnection.list_stack_resources | (self, stack_name_or_id, next_token=None) | return self.get_list('ListStackResources', params,
[('member', StackResourceSummary)]) | Returns descriptions of all resources of the specified stack.
For deleted stacks, ListStackResources returns resource
information for up to 90 days after the stack has been
deleted.
:type stack_name_or_id: string
:param stack_name_or_id: The name or the unique identifier associated
with the stack, which are not always interchangeable:
+ Running stacks: You can specify either the stack's name or its unique
stack ID.
+ Deleted stacks: You must specify the unique stack ID.
Default: There is no default value.
:type next_token: string
:param next_token: String that identifies the start of the next list of
stack resource summaries, if there is one.
Default: There is no default value. | Returns descriptions of all resources of the specified stack. | [
"Returns",
"descriptions",
"of",
"all",
"resources",
"of",
"the",
"specified",
"stack",
"."
] | def list_stack_resources(self, stack_name_or_id, next_token=None):
"""
Returns descriptions of all resources of the specified stack.
For deleted stacks, ListStackResources returns resource
information for up to 90 days after the stack has been
deleted.
:type stack_name_or_id: string
:param stack_name_or_id: The name or the unique identifier associated
with the stack, which are not always interchangeable:
+ Running stacks: You can specify either the stack's name or its unique
stack ID.
+ Deleted stacks: You must specify the unique stack ID.
Default: There is no default value.
:type next_token: string
:param next_token: String that identifies the start of the next list of
stack resource summaries, if there is one.
Default: There is no default value.
"""
params = {'StackName': stack_name_or_id}
if next_token:
params['NextToken'] = next_token
return self.get_list('ListStackResources', params,
[('member', StackResourceSummary)]) | [
"def",
"list_stack_resources",
"(",
"self",
",",
"stack_name_or_id",
",",
"next_token",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'StackName'",
":",
"stack_name_or_id",
"}",
"if",
"next_token",
":",
"params",
"[",
"'NextToken'",
"]",
"=",
"next_token",
"return",
"self",
".",
"get_list",
"(",
"'ListStackResources'",
",",
"params",
",",
"[",
"(",
"'member'",
",",
"StackResourceSummary",
")",
"]",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudformation/connection.py#L717-L746 | |
bundy-dns/bundy | 3d41934996b82b0cd2fe22dd74d2abc1daba835d | src/lib/python/bundy/config/cfgmgr.py | python | ConfigManager.get_statistics_spec | (self, name = None) | return statistics | Returns a dict containing 'module_name': statistics_spec for
all modules. If name is specified, only that module will
be included | Returns a dict containing 'module_name': statistics_spec for
all modules. If name is specified, only that module will
be included | [
"Returns",
"a",
"dict",
"containing",
"module_name",
":",
"statistics_spec",
"for",
"all",
"modules",
".",
"If",
"name",
"is",
"specified",
"only",
"that",
"module",
"will",
"be",
"included"
] | def get_statistics_spec(self, name = None):
"""Returns a dict containing 'module_name': statistics_spec for
all modules. If name is specified, only that module will
be included"""
statistics = {}
if name:
if name in self.module_specs:
statistics[name] = self.module_specs[name].get_statistics_spec()
else:
for module_name in self.module_specs.keys():
statistics[module_name] = self.module_specs[module_name].get_statistics_spec()
return statistics | [
"def",
"get_statistics_spec",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"statistics",
"=",
"{",
"}",
"if",
"name",
":",
"if",
"name",
"in",
"self",
".",
"module_specs",
":",
"statistics",
"[",
"name",
"]",
"=",
"self",
".",
"module_specs",
"[",
"name",
"]",
".",
"get_statistics_spec",
"(",
")",
"else",
":",
"for",
"module_name",
"in",
"self",
".",
"module_specs",
".",
"keys",
"(",
")",
":",
"statistics",
"[",
"module_name",
"]",
"=",
"self",
".",
"module_specs",
"[",
"module_name",
"]",
".",
"get_statistics_spec",
"(",
")",
"return",
"statistics"
] | https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/config/cfgmgr.py#L358-L369 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | ConfigBase.GetNumberOfEntries | (*args, **kwargs) | return _misc_.ConfigBase_GetNumberOfEntries(*args, **kwargs) | GetNumberOfEntries(self, bool recursive=False) -> size_t
Get the number of entries in the current group, with or without its
subgroups. | GetNumberOfEntries(self, bool recursive=False) -> size_t | [
"GetNumberOfEntries",
"(",
"self",
"bool",
"recursive",
"=",
"False",
")",
"-",
">",
"size_t"
] | def GetNumberOfEntries(*args, **kwargs):
"""
GetNumberOfEntries(self, bool recursive=False) -> size_t
Get the number of entries in the current group, with or without its
subgroups.
"""
return _misc_.ConfigBase_GetNumberOfEntries(*args, **kwargs) | [
"def",
"GetNumberOfEntries",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"ConfigBase_GetNumberOfEntries",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L3205-L3212 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/metrics/histograms/extract_histograms.py | python | ExtractHistograms | (filename) | Load histogram definitions from a disk file.
Args:
filename: a file path to load data from.
Returns:
a dictionary of histogram descriptions.
Raises:
Error: if the file is not well-formatted. | Load histogram definitions from a disk file. | [
"Load",
"histogram",
"definitions",
"from",
"a",
"disk",
"file",
"."
] | def ExtractHistograms(filename):
"""Load histogram definitions from a disk file.
Args:
filename: a file path to load data from.
Returns:
a dictionary of histogram descriptions.
Raises:
Error: if the file is not well-formatted.
"""
with open(filename, 'r') as f:
histograms, had_errors = ExtractHistogramsFromFile(f)
if had_errors:
logging.error('Error parsing %s', filename)
raise Error()
return histograms | [
"def",
"ExtractHistograms",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"histograms",
",",
"had_errors",
"=",
"ExtractHistogramsFromFile",
"(",
"f",
")",
"if",
"had_errors",
":",
"logging",
".",
"error",
"(",
"'Error parsing %s'",
",",
"filename",
")",
"raise",
"Error",
"(",
")",
"return",
"histograms"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/metrics/histograms/extract_histograms.py#L466-L483 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/revnet.py | python | RevNet.get_moving_stats | (self) | Get moving averages of batch normalization. | Get moving averages of batch normalization. | [
"Get",
"moving",
"averages",
"of",
"batch",
"normalization",
"."
] | def get_moving_stats(self):
"""Get moving averages of batch normalization."""
device = "/gpu:0" if tf.test.is_gpu_available() else "/cpu:0"
with tf.device(device):
return [v.read_value() for v in self.moving_average_variables] | [
"def",
"get_moving_stats",
"(",
"self",
")",
":",
"device",
"=",
"\"/gpu:0\"",
"if",
"tf",
".",
"test",
".",
"is_gpu_available",
"(",
")",
"else",
"\"/cpu:0\"",
"with",
"tf",
".",
"device",
"(",
"device",
")",
":",
"return",
"[",
"v",
".",
"read_value",
"(",
")",
"for",
"v",
"in",
"self",
".",
"moving_average_variables",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/revnet.py#L194-L198 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction_gui/reduction/sans/hfir_options_script.py | python | ReductionOptions.get_this_class_variables | (self) | return pairs | Just for debug purposes
Return: pairs of (var_name,var_value) | Just for debug purposes
Return: pairs of (var_name,var_value) | [
"Just",
"for",
"debug",
"purposes",
"Return",
":",
"pairs",
"of",
"(",
"var_name",
"var_value",
")"
] | def get_this_class_variables(self):
'''
Just for debug purposes
Return: pairs of (var_name,var_value)
'''
attributes = inspect.getmembers(
self, lambda a: not inspect.isroutine(a))
pairs = [a for a in attributes if not(
a[0].startswith('__') and a[0].endswith('__'))]
return pairs | [
"def",
"get_this_class_variables",
"(",
"self",
")",
":",
"attributes",
"=",
"inspect",
".",
"getmembers",
"(",
"self",
",",
"lambda",
"a",
":",
"not",
"inspect",
".",
"isroutine",
"(",
"a",
")",
")",
"pairs",
"=",
"[",
"a",
"for",
"a",
"in",
"attributes",
"if",
"not",
"(",
"a",
"[",
"0",
"]",
".",
"startswith",
"(",
"'__'",
")",
"and",
"a",
"[",
"0",
"]",
".",
"endswith",
"(",
"'__'",
")",
")",
"]",
"return",
"pairs"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/sans/hfir_options_script.py#L111-L120 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/scroll.py | python | scroll_half_page_down | (event: E) | Same as ControlF, but only scroll half a page. | Same as ControlF, but only scroll half a page. | [
"Same",
"as",
"ControlF",
"but",
"only",
"scroll",
"half",
"a",
"page",
"."
] | def scroll_half_page_down(event: E) -> None:
"""
Same as ControlF, but only scroll half a page.
"""
scroll_forward(event, half=True) | [
"def",
"scroll_half_page_down",
"(",
"event",
":",
"E",
")",
"->",
"None",
":",
"scroll_forward",
"(",
"event",
",",
"half",
"=",
"True",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/scroll.py#L83-L87 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.