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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ucbrise/clipper | 9f25e3fc7f8edc891615e81c5b80d3d8aed72608 | clipper_admin/clipper_admin/clipper_admin.py | python | ClipperConnection.get_num_replicas | (self, name, version=None) | return self.cm.get_num_replicas(name, version) | Gets the current number of model container replicas for a model.
Parameters
----------
name : str
The name of the model
version : str, optional
The version of the model. If no version is provided,
the currently deployed version will be used.
Returns
-------
int
The number of active replicas
Raises
------
:py:exc:`clipper.UnconnectedException`
:py:exc:`clipper.ClipperException` | Gets the current number of model container replicas for a model. | [
"Gets",
"the",
"current",
"number",
"of",
"model",
"container",
"replicas",
"for",
"a",
"model",
"."
] | def get_num_replicas(self, name, version=None):
"""Gets the current number of model container replicas for a model.
Parameters
----------
name : str
The name of the model
version : str, optional
The version of the model. If no version is provided,
the currently deployed version will be used.
Returns
-------
int
The number of active replicas
Raises
------
:py:exc:`clipper.UnconnectedException`
:py:exc:`clipper.ClipperException`
"""
if not self.connected:
raise UnconnectedException()
if version is None:
version = self.get_current_model_version(name)
else:
version = str(version)
return self.cm.get_num_replicas(name, version) | [
"def",
"get_num_replicas",
"(",
"self",
",",
"name",
",",
"version",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"UnconnectedException",
"(",
")",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"self",
".",
"get_current_model_version",
"(",
"name",
")",
"else",
":",
"version",
"=",
"str",
"(",
"version",
")",
"return",
"self",
".",
"cm",
".",
"get_num_replicas",
"(",
"name",
",",
"version",
")"
] | https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/clipper_admin.py#L758-L785 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py | python | Context.to_eng_string | (self, a) | return a.to_eng_string(context=self) | Convert to a string, using engineering notation if an exponent is needed.
Engineering notation has an exponent which is a multiple of 3. This
can leave up to 3 digits to the left of the decimal place and may
require the addition of either one or two trailing zeros.
The operation is not affected by the context.
>>> ExtendedContext.to_eng_string(Decimal('123E+1'))
'1.23E+3'
>>> ExtendedContext.to_eng_string(Decimal('123E+3'))
'123E+3'
>>> ExtendedContext.to_eng_string(Decimal('123E-10'))
'12.3E-9'
>>> ExtendedContext.to_eng_string(Decimal('-123E-12'))
'-123E-12'
>>> ExtendedContext.to_eng_string(Decimal('7E-7'))
'700E-9'
>>> ExtendedContext.to_eng_string(Decimal('7E+1'))
'70'
>>> ExtendedContext.to_eng_string(Decimal('0E+1'))
'0.00E+3' | Convert to a string, using engineering notation if an exponent is needed. | [
"Convert",
"to",
"a",
"string",
"using",
"engineering",
"notation",
"if",
"an",
"exponent",
"is",
"needed",
"."
] | def to_eng_string(self, a):
"""Convert to a string, using engineering notation if an exponent is needed.
Engineering notation has an exponent which is a multiple of 3. This
can leave up to 3 digits to the left of the decimal place and may
require the addition of either one or two trailing zeros.
The operation is not affected by the context.
>>> ExtendedContext.to_eng_string(Decimal('123E+1'))
'1.23E+3'
>>> ExtendedContext.to_eng_string(Decimal('123E+3'))
'123E+3'
>>> ExtendedContext.to_eng_string(Decimal('123E-10'))
'12.3E-9'
>>> ExtendedContext.to_eng_string(Decimal('-123E-12'))
'-123E-12'
>>> ExtendedContext.to_eng_string(Decimal('7E-7'))
'700E-9'
>>> ExtendedContext.to_eng_string(Decimal('7E+1'))
'70'
>>> ExtendedContext.to_eng_string(Decimal('0E+1'))
'0.00E+3'
"""
a = _convert_other(a, raiseit=True)
return a.to_eng_string(context=self) | [
"def",
"to_eng_string",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"to_eng_string",
"(",
"context",
"=",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L5516-L5542 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/arrayprint.py | python | _formatArray | (a, format_function, rank, max_line_len,
next_line_prefix, separator, edge_items, summary_insert) | return s | formatArray is designed for two modes of operation:
1. Full output
2. Summarized output | formatArray is designed for two modes of operation: | [
"formatArray",
"is",
"designed",
"for",
"two",
"modes",
"of",
"operation",
":"
] | def _formatArray(a, format_function, rank, max_line_len,
next_line_prefix, separator, edge_items, summary_insert):
"""formatArray is designed for two modes of operation:
1. Full output
2. Summarized output
"""
if rank == 0:
obj = a.item()
if isinstance(obj, tuple):
obj = _convert_arrays(obj)
return str(obj)
if summary_insert and 2*edge_items < len(a):
leading_items, trailing_items, summary_insert1 = \
edge_items, edge_items, summary_insert
else:
leading_items, trailing_items, summary_insert1 = 0, len(a), ""
if rank == 1:
s = ""
line = next_line_prefix
for i in range(leading_items):
word = format_function(a[i]) + separator
s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
if summary_insert1:
s, line = _extendLine(s, line, summary_insert1, max_line_len, next_line_prefix)
for i in range(trailing_items, 1, -1):
word = format_function(a[-i]) + separator
s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
word = format_function(a[-1])
s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
s += line + "]\n"
s = '[' + s[len(next_line_prefix):]
else:
s = '['
sep = separator.rstrip()
for i in range(leading_items):
if i > 0:
s += next_line_prefix
s += _formatArray(a[i], format_function, rank-1, max_line_len,
" " + next_line_prefix, separator, edge_items,
summary_insert)
s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1)
if summary_insert1:
s += next_line_prefix + summary_insert1 + "\n"
for i in range(trailing_items, 1, -1):
if leading_items or i != trailing_items:
s += next_line_prefix
s += _formatArray(a[-i], format_function, rank-1, max_line_len,
" " + next_line_prefix, separator, edge_items,
summary_insert)
s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1)
if leading_items or trailing_items > 1:
s += next_line_prefix
s += _formatArray(a[-1], format_function, rank-1, max_line_len,
" " + next_line_prefix, separator, edge_items,
summary_insert).rstrip()+']\n'
return s | [
"def",
"_formatArray",
"(",
"a",
",",
"format_function",
",",
"rank",
",",
"max_line_len",
",",
"next_line_prefix",
",",
"separator",
",",
"edge_items",
",",
"summary_insert",
")",
":",
"if",
"rank",
"==",
"0",
":",
"obj",
"=",
"a",
".",
"item",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"obj",
"=",
"_convert_arrays",
"(",
"obj",
")",
"return",
"str",
"(",
"obj",
")",
"if",
"summary_insert",
"and",
"2",
"*",
"edge_items",
"<",
"len",
"(",
"a",
")",
":",
"leading_items",
",",
"trailing_items",
",",
"summary_insert1",
"=",
"edge_items",
",",
"edge_items",
",",
"summary_insert",
"else",
":",
"leading_items",
",",
"trailing_items",
",",
"summary_insert1",
"=",
"0",
",",
"len",
"(",
"a",
")",
",",
"\"\"",
"if",
"rank",
"==",
"1",
":",
"s",
"=",
"\"\"",
"line",
"=",
"next_line_prefix",
"for",
"i",
"in",
"range",
"(",
"leading_items",
")",
":",
"word",
"=",
"format_function",
"(",
"a",
"[",
"i",
"]",
")",
"+",
"separator",
"s",
",",
"line",
"=",
"_extendLine",
"(",
"s",
",",
"line",
",",
"word",
",",
"max_line_len",
",",
"next_line_prefix",
")",
"if",
"summary_insert1",
":",
"s",
",",
"line",
"=",
"_extendLine",
"(",
"s",
",",
"line",
",",
"summary_insert1",
",",
"max_line_len",
",",
"next_line_prefix",
")",
"for",
"i",
"in",
"range",
"(",
"trailing_items",
",",
"1",
",",
"-",
"1",
")",
":",
"word",
"=",
"format_function",
"(",
"a",
"[",
"-",
"i",
"]",
")",
"+",
"separator",
"s",
",",
"line",
"=",
"_extendLine",
"(",
"s",
",",
"line",
",",
"word",
",",
"max_line_len",
",",
"next_line_prefix",
")",
"word",
"=",
"format_function",
"(",
"a",
"[",
"-",
"1",
"]",
")",
"s",
",",
"line",
"=",
"_extendLine",
"(",
"s",
",",
"line",
",",
"word",
",",
"max_line_len",
",",
"next_line_prefix",
")",
"s",
"+=",
"line",
"+",
"\"]\\n\"",
"s",
"=",
"'['",
"+",
"s",
"[",
"len",
"(",
"next_line_prefix",
")",
":",
"]",
"else",
":",
"s",
"=",
"'['",
"sep",
"=",
"separator",
".",
"rstrip",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"leading_items",
")",
":",
"if",
"i",
">",
"0",
":",
"s",
"+=",
"next_line_prefix",
"s",
"+=",
"_formatArray",
"(",
"a",
"[",
"i",
"]",
",",
"format_function",
",",
"rank",
"-",
"1",
",",
"max_line_len",
",",
"\" \"",
"+",
"next_line_prefix",
",",
"separator",
",",
"edge_items",
",",
"summary_insert",
")",
"s",
"=",
"s",
".",
"rstrip",
"(",
")",
"+",
"sep",
".",
"rstrip",
"(",
")",
"+",
"'\\n'",
"*",
"max",
"(",
"rank",
"-",
"1",
",",
"1",
")",
"if",
"summary_insert1",
":",
"s",
"+=",
"next_line_prefix",
"+",
"summary_insert1",
"+",
"\"\\n\"",
"for",
"i",
"in",
"range",
"(",
"trailing_items",
",",
"1",
",",
"-",
"1",
")",
":",
"if",
"leading_items",
"or",
"i",
"!=",
"trailing_items",
":",
"s",
"+=",
"next_line_prefix",
"s",
"+=",
"_formatArray",
"(",
"a",
"[",
"-",
"i",
"]",
",",
"format_function",
",",
"rank",
"-",
"1",
",",
"max_line_len",
",",
"\" \"",
"+",
"next_line_prefix",
",",
"separator",
",",
"edge_items",
",",
"summary_insert",
")",
"s",
"=",
"s",
".",
"rstrip",
"(",
")",
"+",
"sep",
".",
"rstrip",
"(",
")",
"+",
"'\\n'",
"*",
"max",
"(",
"rank",
"-",
"1",
",",
"1",
")",
"if",
"leading_items",
"or",
"trailing_items",
">",
"1",
":",
"s",
"+=",
"next_line_prefix",
"s",
"+=",
"_formatArray",
"(",
"a",
"[",
"-",
"1",
"]",
",",
"format_function",
",",
"rank",
"-",
"1",
",",
"max_line_len",
",",
"\" \"",
"+",
"next_line_prefix",
",",
"separator",
",",
"edge_items",
",",
"summary_insert",
")",
".",
"rstrip",
"(",
")",
"+",
"']\\n'",
"return",
"s"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/arrayprint.py#L465-L530 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py | python | class_t.__init__ | (
self,
name='',
class_type=CLASS_TYPES.CLASS,
is_abstract=False) | creates class that describes C++ class definition | creates class that describes C++ class definition | [
"creates",
"class",
"that",
"describes",
"C",
"++",
"class",
"definition"
] | def __init__(
self,
name='',
class_type=CLASS_TYPES.CLASS,
is_abstract=False):
"""creates class that describes C++ class definition"""
scopedef.scopedef_t.__init__(self, name)
byte_info.byte_info.__init__(self)
elaborated_info.elaborated_info.__init__(self, class_type)
if class_type:
assert class_type in CLASS_TYPES.ALL
self._class_type = class_type
self._bases = []
self._derived = []
self._is_abstract = is_abstract
self._public_members = []
self._private_members = []
self._protected_members = []
self._aliases = []
self._recursive_bases = None
self._recursive_derived = None | [
"def",
"__init__",
"(",
"self",
",",
"name",
"=",
"''",
",",
"class_type",
"=",
"CLASS_TYPES",
".",
"CLASS",
",",
"is_abstract",
"=",
"False",
")",
":",
"scopedef",
".",
"scopedef_t",
".",
"__init__",
"(",
"self",
",",
"name",
")",
"byte_info",
".",
"byte_info",
".",
"__init__",
"(",
"self",
")",
"elaborated_info",
".",
"elaborated_info",
".",
"__init__",
"(",
"self",
",",
"class_type",
")",
"if",
"class_type",
":",
"assert",
"class_type",
"in",
"CLASS_TYPES",
".",
"ALL",
"self",
".",
"_class_type",
"=",
"class_type",
"self",
".",
"_bases",
"=",
"[",
"]",
"self",
".",
"_derived",
"=",
"[",
"]",
"self",
".",
"_is_abstract",
"=",
"is_abstract",
"self",
".",
"_public_members",
"=",
"[",
"]",
"self",
".",
"_private_members",
"=",
"[",
"]",
"self",
".",
"_protected_members",
"=",
"[",
"]",
"self",
".",
"_aliases",
"=",
"[",
"]",
"self",
".",
"_recursive_bases",
"=",
"None",
"self",
".",
"_recursive_derived",
"=",
"None"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py#L191-L211 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/jpsro.py | python | _approx_mgce | (meta_game, per_player_repeats, ignore_repeats=False,
epsilon=0.01) | return dist, dict() | Approximate Maximum Gini CE. | Approximate Maximum Gini CE. | [
"Approximate",
"Maximum",
"Gini",
"CE",
"."
] | def _approx_mgce(meta_game, per_player_repeats, ignore_repeats=False,
epsilon=0.01):
"""Approximate Maximum Gini CE."""
a_mat, e_vec, meta = _ace_constraints(
meta_game, [0.0] * len(per_player_repeats), remove_null=True,
zero_tolerance=1e-8)
max_ab = 0.0
if a_mat.size:
max_ab = np.max(a_mat.mean(axis=1))
a_mat, e_vec, meta = _ace_constraints(
meta_game, [epsilon * max_ab] * len(per_player_repeats), remove_null=True,
zero_tolerance=1e-8)
a_mats = _partition_by_player(
a_mat, meta["p_vec"], len(per_player_repeats))
e_vecs = _partition_by_player(
e_vec, meta["p_vec"], len(per_player_repeats))
dist, _ = _try_two_solvers(
_qp_ce,
meta_game, a_mats, e_vecs,
action_repeats=(None if ignore_repeats else per_player_repeats))
return dist, dict() | [
"def",
"_approx_mgce",
"(",
"meta_game",
",",
"per_player_repeats",
",",
"ignore_repeats",
"=",
"False",
",",
"epsilon",
"=",
"0.01",
")",
":",
"a_mat",
",",
"e_vec",
",",
"meta",
"=",
"_ace_constraints",
"(",
"meta_game",
",",
"[",
"0.0",
"]",
"*",
"len",
"(",
"per_player_repeats",
")",
",",
"remove_null",
"=",
"True",
",",
"zero_tolerance",
"=",
"1e-8",
")",
"max_ab",
"=",
"0.0",
"if",
"a_mat",
".",
"size",
":",
"max_ab",
"=",
"np",
".",
"max",
"(",
"a_mat",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
")",
"a_mat",
",",
"e_vec",
",",
"meta",
"=",
"_ace_constraints",
"(",
"meta_game",
",",
"[",
"epsilon",
"*",
"max_ab",
"]",
"*",
"len",
"(",
"per_player_repeats",
")",
",",
"remove_null",
"=",
"True",
",",
"zero_tolerance",
"=",
"1e-8",
")",
"a_mats",
"=",
"_partition_by_player",
"(",
"a_mat",
",",
"meta",
"[",
"\"p_vec\"",
"]",
",",
"len",
"(",
"per_player_repeats",
")",
")",
"e_vecs",
"=",
"_partition_by_player",
"(",
"e_vec",
",",
"meta",
"[",
"\"p_vec\"",
"]",
",",
"len",
"(",
"per_player_repeats",
")",
")",
"dist",
",",
"_",
"=",
"_try_two_solvers",
"(",
"_qp_ce",
",",
"meta_game",
",",
"a_mats",
",",
"e_vecs",
",",
"action_repeats",
"=",
"(",
"None",
"if",
"ignore_repeats",
"else",
"per_player_repeats",
")",
")",
"return",
"dist",
",",
"dict",
"(",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/jpsro.py#L838-L858 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/legendre.py | python | leggrid2d | (x, y, c) | return pu._gridnd(legval, c, x, y) | Evaluate a 2-D Legendre series on the Cartesian product of x and y.
This function returns the values:
.. math:: p(a,b) = \\sum_{i,j} c_{i,j} * L_i(a) * L_j(b)
where the points `(a, b)` consist of all pairs formed by taking
`a` from `x` and `b` from `y`. The resulting points form a grid with
`x` in the first dimension and `y` in the second.
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars. In either
case, either `x` and `y` or their elements must support multiplication
and addition both with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape + y.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points in the
Cartesian product of `x` and `y`. If `x` or `y` is a list or
tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term of
multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional Chebyshev series at points in the
Cartesian product of `x` and `y`.
See Also
--------
legval, legval2d, legval3d, leggrid3d
Notes
-----
.. versionadded:: 1.7.0 | Evaluate a 2-D Legendre series on the Cartesian product of x and y. | [
"Evaluate",
"a",
"2",
"-",
"D",
"Legendre",
"series",
"on",
"the",
"Cartesian",
"product",
"of",
"x",
"and",
"y",
"."
] | def leggrid2d(x, y, c):
"""
Evaluate a 2-D Legendre series on the Cartesian product of x and y.
This function returns the values:
.. math:: p(a,b) = \\sum_{i,j} c_{i,j} * L_i(a) * L_j(b)
where the points `(a, b)` consist of all pairs formed by taking
`a` from `x` and `b` from `y`. The resulting points form a grid with
`x` in the first dimension and `y` in the second.
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars. In either
case, either `x` and `y` or their elements must support multiplication
and addition both with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape + y.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points in the
Cartesian product of `x` and `y`. If `x` or `y` is a list or
tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term of
multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional Chebyshev series at points in the
Cartesian product of `x` and `y`.
See Also
--------
legval, legval2d, legval3d, leggrid3d
Notes
-----
.. versionadded:: 1.7.0
"""
return pu._gridnd(legval, c, x, y) | [
"def",
"leggrid2d",
"(",
"x",
",",
"y",
",",
"c",
")",
":",
"return",
"pu",
".",
"_gridnd",
"(",
"legval",
",",
"c",
",",
"x",
",",
"y",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/legendre.py#L969-L1019 | |
cathywu/Sentiment-Analysis | eb501fd1375c0c3f3ab430f963255f1bb858e659 | PyML-0.7.9/PyML/containers/vectorDatasets.py | python | BaseCVectorDataSet.addFeatures | (self, other) | Add features to a dataset using the features in another dataset
:Parameters:
- `other` - the other dataset | Add features to a dataset using the features in another dataset | [
"Add",
"features",
"to",
"a",
"dataset",
"using",
"the",
"features",
"in",
"another",
"dataset"
] | def addFeatures(self, other) :
"""
Add features to a dataset using the features in another dataset
:Parameters:
- `other` - the other dataset
"""
if len(other) != len(self) :
raise ValueError, 'number of examples does not match'
if not hasattr(self, 'featureKeyDict') :
self.addFeatureKeyDict()
for id in other.featureID :
if hash(id) in self.featureKeyDict :
raise ValueError, 'Feature already exists, or hash clash'
self.container.addFeatures(self, other)
self.updateFeatureDict(other) | [
"def",
"addFeatures",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"other",
")",
"!=",
"len",
"(",
"self",
")",
":",
"raise",
"ValueError",
",",
"'number of examples does not match'",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'featureKeyDict'",
")",
":",
"self",
".",
"addFeatureKeyDict",
"(",
")",
"for",
"id",
"in",
"other",
".",
"featureID",
":",
"if",
"hash",
"(",
"id",
")",
"in",
"self",
".",
"featureKeyDict",
":",
"raise",
"ValueError",
",",
"'Feature already exists, or hash clash'",
"self",
".",
"container",
".",
"addFeatures",
"(",
"self",
",",
"other",
")",
"self",
".",
"updateFeatureDict",
"(",
"other",
")"
] | https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/containers/vectorDatasets.py#L75-L91 | ||
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/extras/ticgt.py | python | create_compiled_task | (self, name, node) | return task | Overrides ccroot.create_compiled_task to support ti_c | Overrides ccroot.create_compiled_task to support ti_c | [
"Overrides",
"ccroot",
".",
"create_compiled_task",
"to",
"support",
"ti_c"
] | def create_compiled_task(self, name, node):
"""
Overrides ccroot.create_compiled_task to support ti_c
"""
out = '%s' % (node.change_ext('.obj').name)
if self.env.CC_NAME == 'ticc':
name = 'ti_c'
task = self.create_task(name, node, node.parent.find_or_declare(out))
self.env.OUT = '-fr%s' % (node.parent.get_bld().abspath())
try:
self.compiled_tasks.append(task)
except AttributeError:
self.compiled_tasks = [task]
return task | [
"def",
"create_compiled_task",
"(",
"self",
",",
"name",
",",
"node",
")",
":",
"out",
"=",
"'%s'",
"%",
"(",
"node",
".",
"change_ext",
"(",
"'.obj'",
")",
".",
"name",
")",
"if",
"self",
".",
"env",
".",
"CC_NAME",
"==",
"'ticc'",
":",
"name",
"=",
"'ti_c'",
"task",
"=",
"self",
".",
"create_task",
"(",
"name",
",",
"node",
",",
"node",
".",
"parent",
".",
"find_or_declare",
"(",
"out",
")",
")",
"self",
".",
"env",
".",
"OUT",
"=",
"'-fr%s'",
"%",
"(",
"node",
".",
"parent",
".",
"get_bld",
"(",
")",
".",
"abspath",
"(",
")",
")",
"try",
":",
"self",
".",
"compiled_tasks",
".",
"append",
"(",
"task",
")",
"except",
"AttributeError",
":",
"self",
".",
"compiled_tasks",
"=",
"[",
"task",
"]",
"return",
"task"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/ticgt.py#L202-L215 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Configuration/Generator/python/relval_generation_module.py | python | _generate_RS1GG | (step, evt_type, energy, evtnumber) | return generator | Here the settings for the RS1 graviton into gamma gamma. | Here the settings for the RS1 graviton into gamma gamma. | [
"Here",
"the",
"settings",
"for",
"the",
"RS1",
"graviton",
"into",
"gamma",
"gamma",
"."
] | def _generate_RS1GG(step, evt_type, energy, evtnumber):
"""
Here the settings for the RS1 graviton into gamma gamma.
"""
func_id=mod_id+"["+sys._getframe().f_code.co_name+"]"
common.log( func_id+" Entering... ")
# Build the process source
generator = cms.EDFilter('Pythia6GeneratorFilter',
pythiaPylistVerbosity=cms.untracked.int32(0),
pythiaHepMCVerbosity=cms.untracked.bool(False),
maxEventsToPrint = cms.untracked.int32(0),
filterEfficiency = cms.untracked.double(1),
PythiaParameters = cms.PSet\
(parameterSets = cms.vstring('PythiaUESettings','processParameters'),
PythiaUESettings=user_pythia_ue_settings(),
processParameters=\
cms.vstring('MSEL=0 ',
'MSUB(391) =1 ',
'MSUB(392) =1 ',
'PMAS(347,1) = %s ' %energy,# ! minv ',
'PARP(50) = 0.54 ',# ! 0.54 == c=0.1',
'MDME(4158,1)=0 ',
'MDME(4159,1)=0 ',
'MDME(4160,1)=0 ',
'MDME(4161,1)=0 ',
'MDME(4162,1)=0 ',
'MDME(4163,1)=0 ',
'MDME(4164,1)=0 ',
'MDME(4165,1)=0 ',
'MDME(4166,1)=0 ',
'MDME(4167,1)=0 ',
'MDME(4168,1)=0 ',
'MDME(4169,1)=0 ',
'MDME(4170,1)=0 ',
'MDME(4170,1)=0 ',
'MDME(4171,1)=0 ',
'MDME(4172,1)=0 ',
'MDME(4173,1)=0 ',
'MDME(4174,1)=0 ',
'MDME(4175,1)=1 ',#! gamma gamma ',
'MDME(4176,1)=0 ',
'MDME(4177,1)=0 ',
'MDME(4178,1)=0 ',
'CKIN(3)=20. ',#! minimum pt hat for hard interactions',
'CKIN(4)=-1. '#! maximum pt hat for hard interactions'
)
)
)
common.log(func_id+" Returning Generator...")
return generator | [
"def",
"_generate_RS1GG",
"(",
"step",
",",
"evt_type",
",",
"energy",
",",
"evtnumber",
")",
":",
"func_id",
"=",
"mod_id",
"+",
"\"[\"",
"+",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_code",
".",
"co_name",
"+",
"\"]\"",
"common",
".",
"log",
"(",
"func_id",
"+",
"\" Entering... \"",
")",
"# Build the process source",
"generator",
"=",
"cms",
".",
"EDFilter",
"(",
"'Pythia6GeneratorFilter'",
",",
"pythiaPylistVerbosity",
"=",
"cms",
".",
"untracked",
".",
"int32",
"(",
"0",
")",
",",
"pythiaHepMCVerbosity",
"=",
"cms",
".",
"untracked",
".",
"bool",
"(",
"False",
")",
",",
"maxEventsToPrint",
"=",
"cms",
".",
"untracked",
".",
"int32",
"(",
"0",
")",
",",
"filterEfficiency",
"=",
"cms",
".",
"untracked",
".",
"double",
"(",
"1",
")",
",",
"PythiaParameters",
"=",
"cms",
".",
"PSet",
"(",
"parameterSets",
"=",
"cms",
".",
"vstring",
"(",
"'PythiaUESettings'",
",",
"'processParameters'",
")",
",",
"PythiaUESettings",
"=",
"user_pythia_ue_settings",
"(",
")",
",",
"processParameters",
"=",
"cms",
".",
"vstring",
"(",
"'MSEL=0 '",
",",
"'MSUB(391) =1 '",
",",
"'MSUB(392) =1 '",
",",
"'PMAS(347,1) = %s '",
"%",
"energy",
",",
"# ! minv ', ",
"'PARP(50) = 0.54 '",
",",
"# ! 0.54 == c=0.1', ",
"'MDME(4158,1)=0 '",
",",
"'MDME(4159,1)=0 '",
",",
"'MDME(4160,1)=0 '",
",",
"'MDME(4161,1)=0 '",
",",
"'MDME(4162,1)=0 '",
",",
"'MDME(4163,1)=0 '",
",",
"'MDME(4164,1)=0 '",
",",
"'MDME(4165,1)=0 '",
",",
"'MDME(4166,1)=0 '",
",",
"'MDME(4167,1)=0 '",
",",
"'MDME(4168,1)=0 '",
",",
"'MDME(4169,1)=0 '",
",",
"'MDME(4170,1)=0 '",
",",
"'MDME(4170,1)=0 '",
",",
"'MDME(4171,1)=0 '",
",",
"'MDME(4172,1)=0 '",
",",
"'MDME(4173,1)=0 '",
",",
"'MDME(4174,1)=0 '",
",",
"'MDME(4175,1)=1 '",
",",
"#! gamma gamma ', ",
"'MDME(4176,1)=0 '",
",",
"'MDME(4177,1)=0 '",
",",
"'MDME(4178,1)=0 '",
",",
"'CKIN(3)=20. '",
",",
"#! minimum pt hat for hard interactions', ",
"'CKIN(4)=-1. '",
"#! maximum pt hat for hard interactions'",
")",
")",
")",
"common",
".",
"log",
"(",
"func_id",
"+",
"\" Returning Generator...\"",
")",
"return",
"generator"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Configuration/Generator/python/relval_generation_module.py#L651-L704 | |
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | third_party/cpplint.py | python | ResetNolintSuppressions | () | Resets the set of NOLINT suppressions to empty. | Resets the set of NOLINT suppressions to empty. | [
"Resets",
"the",
"set",
"of",
"NOLINT",
"suppressions",
"to",
"empty",
"."
] | def ResetNolintSuppressions():
"""Resets the set of NOLINT suppressions to empty."""
_error_suppressions.clear()
_global_error_suppressions.clear() | [
"def",
"ResetNolintSuppressions",
"(",
")",
":",
"_error_suppressions",
".",
"clear",
"(",
")",
"_global_error_suppressions",
".",
"clear",
"(",
")"
] | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/third_party/cpplint.py#L631-L634 | ||
Stellarium/stellarium | f289cda0d618180bbd3afe82f23d86ec0ac3c5e9 | skycultures/western_SnT/generate_constellationship.py | python | get_hip | (ra, dec, mag) | return None | Given an RA (in hours and decimals), and Dec (in
degrees and decimals), and a magnitude (in
visual magnitudes), queries VizieR and attempts
to locate a Hipparcos star ID at the location.
Returns an integer HIP ID if found, or None otherwise
Maintains a .hip_cache file to speed up lookups;
you can delete the .hip_cache file to perform
fresh lookups. | Given an RA (in hours and decimals), and Dec (in
degrees and decimals), and a magnitude (in
visual magnitudes), queries VizieR and attempts
to locate a Hipparcos star ID at the location. | [
"Given",
"an",
"RA",
"(",
"in",
"hours",
"and",
"decimals",
")",
"and",
"Dec",
"(",
"in",
"degrees",
"and",
"decimals",
")",
"and",
"a",
"magnitude",
"(",
"in",
"visual",
"magnitudes",
")",
"queries",
"VizieR",
"and",
"attempts",
"to",
"locate",
"a",
"Hipparcos",
"star",
"ID",
"at",
"the",
"location",
"."
] | def get_hip(ra, dec, mag):
"""
Given an RA (in hours and decimals), and Dec (in
degrees and decimals), and a magnitude (in
visual magnitudes), queries VizieR and attempts
to locate a Hipparcos star ID at the location.
Returns an integer HIP ID if found, or None otherwise
Maintains a .hip_cache file to speed up lookups;
you can delete the .hip_cache file to perform
fresh lookups.
"""
coord = SkyCoord(ra=Angle("{} hours".format(ra)),
dec=Angle("{} degree".format(dec)),
obstime="J2000.0")
# Search the Hipparcos catalog, and only return results that include
# a HIP (Hipparcos) column, sorting the results by magnitude. The
# top result is almost certainly the star we want.
v = Vizier(catalog='I/239/hip_main', columns=["HIP", "+Vmag"])
# Constrain the search to stars within 1 Vmag of our target
v.query_constraints(Vmag="{}..{}".format(mag - 0.5, mag + 0.5))
# Start with a targeted search, which returns more quickly from the
# API. If that fails to find a star, query a 3 degree diameter circle
# around the ra/dec. This is because Sky & Telescope has a convention
# of stopping their constellation lines a degree or so away from the
# star, if that star isn't actually part of the constellation
# (example: Alpheratz, which is part of the Pegasus figure, but the
# star is in Andromeda)
for radius in (0.05, 1.5):
result = v.query_region(coord, radius=radius*u.deg)
try:
table = result['I/239/hip_main']
except TypeError:
# A TypeError means that the results didn't include anything from
# the I/239/hip_main catalog. The "in" operator doesn't seem to
# work with Table objects.
continue
else:
return table['HIP'][0]
return None | [
"def",
"get_hip",
"(",
"ra",
",",
"dec",
",",
"mag",
")",
":",
"coord",
"=",
"SkyCoord",
"(",
"ra",
"=",
"Angle",
"(",
"\"{} hours\"",
".",
"format",
"(",
"ra",
")",
")",
",",
"dec",
"=",
"Angle",
"(",
"\"{} degree\"",
".",
"format",
"(",
"dec",
")",
")",
",",
"obstime",
"=",
"\"J2000.0\"",
")",
"# Search the Hipparcos catalog, and only return results that include",
"# a HIP (Hipparcos) column, sorting the results by magnitude. The",
"# top result is almost certainly the star we want.",
"v",
"=",
"Vizier",
"(",
"catalog",
"=",
"'I/239/hip_main'",
",",
"columns",
"=",
"[",
"\"HIP\"",
",",
"\"+Vmag\"",
"]",
")",
"# Constrain the search to stars within 1 Vmag of our target",
"v",
".",
"query_constraints",
"(",
"Vmag",
"=",
"\"{}..{}\"",
".",
"format",
"(",
"mag",
"-",
"0.5",
",",
"mag",
"+",
"0.5",
")",
")",
"# Start with a targeted search, which returns more quickly from the",
"# API. If that fails to find a star, query a 3 degree diameter circle",
"# around the ra/dec. This is because Sky & Telescope has a convention",
"# of stopping their constellation lines a degree or so away from the",
"# star, if that star isn't actually part of the constellation",
"# (example: Alpheratz, which is part of the Pegasus figure, but the",
"# star is in Andromeda)",
"for",
"radius",
"in",
"(",
"0.05",
",",
"1.5",
")",
":",
"result",
"=",
"v",
".",
"query_region",
"(",
"coord",
",",
"radius",
"=",
"radius",
"*",
"u",
".",
"deg",
")",
"try",
":",
"table",
"=",
"result",
"[",
"'I/239/hip_main'",
"]",
"except",
"TypeError",
":",
"# A TypeError means that the results didn't include anything from",
"# the I/239/hip_main catalog. The \"in\" operator doesn't seem to",
"# work with Table objects.",
"continue",
"else",
":",
"return",
"table",
"[",
"'HIP'",
"]",
"[",
"0",
"]",
"return",
"None"
] | https://github.com/Stellarium/stellarium/blob/f289cda0d618180bbd3afe82f23d86ec0ac3c5e9/skycultures/western_SnT/generate_constellationship.py#L55-L97 | |
facebookarchive/LogDevice | ce7726050edc49a1e15d9160e81c890736b779e2 | build/fbcode_builder/getdeps/manifest.py | python | ManifestParser.is_first_party_project | (self) | return self.shipit_project is not None | returns true if this is an FB first-party project | returns true if this is an FB first-party project | [
"returns",
"true",
"if",
"this",
"is",
"an",
"FB",
"first",
"-",
"party",
"project"
] | def is_first_party_project(self):
""" returns true if this is an FB first-party project """
return self.shipit_project is not None | [
"def",
"is_first_party_project",
"(",
"self",
")",
":",
"return",
"self",
".",
"shipit_project",
"is",
"not",
"None"
] | https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/build/fbcode_builder/getdeps/manifest.py#L331-L333 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | relaxNgValidCtxt.relaxNGValidatePopElement | (self, doc, elem) | return ret | Pop the element end from the RelaxNG validation stack. | Pop the element end from the RelaxNG validation stack. | [
"Pop",
"the",
"element",
"end",
"from",
"the",
"RelaxNG",
"validation",
"stack",
"."
] | def relaxNGValidatePopElement(self, doc, elem):
"""Pop the element end from the RelaxNG validation stack. """
if doc is None: doc__o = None
else: doc__o = doc._o
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlRelaxNGValidatePopElement(self._o, doc__o, elem__o)
return ret | [
"def",
"relaxNGValidatePopElement",
"(",
"self",
",",
"doc",
",",
"elem",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"else",
":",
"elem__o",
"=",
"elem",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlRelaxNGValidatePopElement",
"(",
"self",
".",
"_o",
",",
"doc__o",
",",
"elem__o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L6317-L6324 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/copier.py | python | FileRegistry.__iter__ | (self) | return self._files.iteritems() | Iterate over all (path, BaseFile instance) pairs from the container.
for path, file in registry:
(...) | Iterate over all (path, BaseFile instance) pairs from the container.
for path, file in registry:
(...) | [
"Iterate",
"over",
"all",
"(",
"path",
"BaseFile",
"instance",
")",
"pairs",
"from",
"the",
"container",
".",
"for",
"path",
"file",
"in",
"registry",
":",
"(",
"...",
")"
] | def __iter__(self):
'''
Iterate over all (path, BaseFile instance) pairs from the container.
for path, file in registry:
(...)
'''
return self._files.iteritems() | [
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_files",
".",
"iteritems",
"(",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/copier.py#L129-L135 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/android_platform/development/scripts/symbol.py | python | GetCrazyLib | (apk_filename) | Returns the name of the first crazy library from this APK.
Args:
apk_filename: name of an APK file.
Returns:
Name of the first library which would be crazy loaded from this APK. | Returns the name of the first crazy library from this APK. | [
"Returns",
"the",
"name",
"of",
"the",
"first",
"crazy",
"library",
"from",
"this",
"APK",
"."
] | def GetCrazyLib(apk_filename):
"""Returns the name of the first crazy library from this APK.
Args:
apk_filename: name of an APK file.
Returns:
Name of the first library which would be crazy loaded from this APK.
"""
zip_file = zipfile.ZipFile(apk_filename, 'r')
for filename in zip_file.namelist():
match = re.match('lib/[^/]*/crazy.(lib.*[.]so)', filename)
if match:
return match.group(1) | [
"def",
"GetCrazyLib",
"(",
"apk_filename",
")",
":",
"zip_file",
"=",
"zipfile",
".",
"ZipFile",
"(",
"apk_filename",
",",
"'r'",
")",
"for",
"filename",
"in",
"zip_file",
".",
"namelist",
"(",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"'lib/[^/]*/crazy.(lib.*[.]so)'",
",",
"filename",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"1",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/android_platform/development/scripts/symbol.py#L249-L262 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/suncc.py | python | scc_common_flags | (conf) | Flags required for executing the sun C compiler | Flags required for executing the sun C compiler | [
"Flags",
"required",
"for",
"executing",
"the",
"sun",
"C",
"compiler"
] | def scc_common_flags(conf):
"""
Flags required for executing the sun C compiler
"""
v = conf.env
v['CC_SRC_F'] = []
v['CC_TGT_F'] = ['-c', '-o']
# linker
if not v['LINK_CC']: v['LINK_CC'] = v['CC']
v['CCLNK_SRC_F'] = ''
v['CCLNK_TGT_F'] = ['-o']
v['CPPPATH_ST'] = '-I%s'
v['DEFINES_ST'] = '-D%s'
v['LIB_ST'] = '-l%s' # template for adding libs
v['LIBPATH_ST'] = '-L%s' # template for adding libpaths
v['STLIB_ST'] = '-l%s'
v['STLIBPATH_ST'] = '-L%s'
v['SONAME_ST'] = '-Wl,-h,%s'
v['SHLIB_MARKER'] = '-Bdynamic'
v['STLIB_MARKER'] = '-Bstatic'
# program
v['cprogram_PATTERN'] = '%s'
# shared library
v['CFLAGS_cshlib'] = ['-Kpic', '-DPIC']
v['LINKFLAGS_cshlib'] = ['-G']
v['cshlib_PATTERN'] = 'lib%s.so'
# static lib
v['LINKFLAGS_cstlib'] = ['-Bstatic']
v['cstlib_PATTERN'] = 'lib%s.a' | [
"def",
"scc_common_flags",
"(",
"conf",
")",
":",
"v",
"=",
"conf",
".",
"env",
"v",
"[",
"'CC_SRC_F'",
"]",
"=",
"[",
"]",
"v",
"[",
"'CC_TGT_F'",
"]",
"=",
"[",
"'-c'",
",",
"'-o'",
"]",
"# linker",
"if",
"not",
"v",
"[",
"'LINK_CC'",
"]",
":",
"v",
"[",
"'LINK_CC'",
"]",
"=",
"v",
"[",
"'CC'",
"]",
"v",
"[",
"'CCLNK_SRC_F'",
"]",
"=",
"''",
"v",
"[",
"'CCLNK_TGT_F'",
"]",
"=",
"[",
"'-o'",
"]",
"v",
"[",
"'CPPPATH_ST'",
"]",
"=",
"'-I%s'",
"v",
"[",
"'DEFINES_ST'",
"]",
"=",
"'-D%s'",
"v",
"[",
"'LIB_ST'",
"]",
"=",
"'-l%s'",
"# template for adding libs",
"v",
"[",
"'LIBPATH_ST'",
"]",
"=",
"'-L%s'",
"# template for adding libpaths",
"v",
"[",
"'STLIB_ST'",
"]",
"=",
"'-l%s'",
"v",
"[",
"'STLIBPATH_ST'",
"]",
"=",
"'-L%s'",
"v",
"[",
"'SONAME_ST'",
"]",
"=",
"'-Wl,-h,%s'",
"v",
"[",
"'SHLIB_MARKER'",
"]",
"=",
"'-Bdynamic'",
"v",
"[",
"'STLIB_MARKER'",
"]",
"=",
"'-Bstatic'",
"# program",
"v",
"[",
"'cprogram_PATTERN'",
"]",
"=",
"'%s'",
"# shared library",
"v",
"[",
"'CFLAGS_cshlib'",
"]",
"=",
"[",
"'-Kpic'",
",",
"'-DPIC'",
"]",
"v",
"[",
"'LINKFLAGS_cshlib'",
"]",
"=",
"[",
"'-G'",
"]",
"v",
"[",
"'cshlib_PATTERN'",
"]",
"=",
"'lib%s.so'",
"# static lib",
"v",
"[",
"'LINKFLAGS_cstlib'",
"]",
"=",
"[",
"'-Bstatic'",
"]",
"v",
"[",
"'cstlib_PATTERN'",
"]",
"=",
"'lib%s.a'"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/suncc.py#L35-L70 | ||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/bindings/python/clang/cindex.py | python | TranslationUnit.get_tokens | (self, locations=None, extent=None) | return TokenGroup.get_tokens(self, extent) | Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined. | Obtain tokens in this translation unit. | [
"Obtain",
"tokens",
"in",
"this",
"translation",
"unit",
"."
] | def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined.
"""
if locations is not None:
extent = SourceRange(start=locations[0], end=locations[1])
return TokenGroup.get_tokens(self, extent) | [
"def",
"get_tokens",
"(",
"self",
",",
"locations",
"=",
"None",
",",
"extent",
"=",
"None",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"extent",
"=",
"SourceRange",
"(",
"start",
"=",
"locations",
"[",
"0",
"]",
",",
"end",
"=",
"locations",
"[",
"1",
"]",
")",
"return",
"TokenGroup",
".",
"get_tokens",
"(",
"self",
",",
"extent",
")"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L3078-L3089 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/metric.py | python | EvalMetric.reset_local | (self) | Resets the local portion of the internal evaluation results
to initial state. | Resets the local portion of the internal evaluation results
to initial state. | [
"Resets",
"the",
"local",
"portion",
"of",
"the",
"internal",
"evaluation",
"results",
"to",
"initial",
"state",
"."
] | def reset_local(self):
"""Resets the local portion of the internal evaluation results
to initial state."""
self.num_inst = 0
self.sum_metric = 0.0 | [
"def",
"reset_local",
"(",
"self",
")",
":",
"self",
".",
"num_inst",
"=",
"0",
"self",
".",
"sum_metric",
"=",
"0.0"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/metric.py#L155-L159 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/timeseries/python/timeseries/model.py | python | TimeSeriesModel.initialize_graph | (self, input_statistics=None) | Define ops for the model, not depending on any previously defined ops.
Args:
input_statistics: A math_utils.InputStatistics object containing input
statistics. If None, data-independent defaults are used, which may
result in longer or unstable training. | Define ops for the model, not depending on any previously defined ops. | [
"Define",
"ops",
"for",
"the",
"model",
"not",
"depending",
"on",
"any",
"previously",
"defined",
"ops",
"."
] | def initialize_graph(self, input_statistics=None):
"""Define ops for the model, not depending on any previously defined ops.
Args:
input_statistics: A math_utils.InputStatistics object containing input
statistics. If None, data-independent defaults are used, which may
result in longer or unstable training.
"""
self._graph_initialized = True
self._input_statistics = input_statistics
if self._input_statistics:
self._stats_means, variances = (
self._input_statistics.overall_feature_moments)
self._stats_sigmas = math_ops.sqrt(variances) | [
"def",
"initialize_graph",
"(",
"self",
",",
"input_statistics",
"=",
"None",
")",
":",
"self",
".",
"_graph_initialized",
"=",
"True",
"self",
".",
"_input_statistics",
"=",
"input_statistics",
"if",
"self",
".",
"_input_statistics",
":",
"self",
".",
"_stats_means",
",",
"variances",
"=",
"(",
"self",
".",
"_input_statistics",
".",
"overall_feature_moments",
")",
"self",
".",
"_stats_sigmas",
"=",
"math_ops",
".",
"sqrt",
"(",
"variances",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/timeseries/python/timeseries/model.py#L115-L128 | ||
Cisco-Talos/moflow | ed71dfb0540d9e0d7a4c72f0881b58958d573728 | BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py | python | _DefaultValueConstructorForField | (field) | return MakeScalarDefault | Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in turn returns a default value for this field. The default
value may refer back to |message| via a weak reference. | Returns a function which returns a default value for a field. | [
"Returns",
"a",
"function",
"which",
"returns",
"a",
"default",
"value",
"for",
"a",
"field",
"."
] | def _DefaultValueConstructorForField(field):
"""Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in turn returns a default value for this field. The default
value may refer back to |message| via a weak reference.
"""
if field.label == _FieldDescriptor.LABEL_REPEATED:
if field.default_value != []:
raise ValueError('Repeated field default value not empty list: %s' % (
field.default_value))
if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
# We can't look at _concrete_class yet since it might not have
# been set. (Depends on order in which we initialize the classes).
message_type = field.message_type
def MakeRepeatedMessageDefault(message):
return containers.RepeatedCompositeFieldContainer(
message._listener_for_children, field.message_type)
return MakeRepeatedMessageDefault
else:
type_checker = type_checkers.GetTypeChecker(field.cpp_type, field.type)
def MakeRepeatedScalarDefault(message):
return containers.RepeatedScalarFieldContainer(
message._listener_for_children, type_checker)
return MakeRepeatedScalarDefault
if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
# _concrete_class may not yet be initialized.
message_type = field.message_type
def MakeSubMessageDefault(message):
result = message_type._concrete_class()
result._SetListener(message._listener_for_children)
return result
return MakeSubMessageDefault
def MakeScalarDefault(message):
return field.default_value
return MakeScalarDefault | [
"def",
"_DefaultValueConstructorForField",
"(",
"field",
")",
":",
"if",
"field",
".",
"label",
"==",
"_FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"if",
"field",
".",
"default_value",
"!=",
"[",
"]",
":",
"raise",
"ValueError",
"(",
"'Repeated field default value not empty list: %s'",
"%",
"(",
"field",
".",
"default_value",
")",
")",
"if",
"field",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"# We can't look at _concrete_class yet since it might not have",
"# been set. (Depends on order in which we initialize the classes).",
"message_type",
"=",
"field",
".",
"message_type",
"def",
"MakeRepeatedMessageDefault",
"(",
"message",
")",
":",
"return",
"containers",
".",
"RepeatedCompositeFieldContainer",
"(",
"message",
".",
"_listener_for_children",
",",
"field",
".",
"message_type",
")",
"return",
"MakeRepeatedMessageDefault",
"else",
":",
"type_checker",
"=",
"type_checkers",
".",
"GetTypeChecker",
"(",
"field",
".",
"cpp_type",
",",
"field",
".",
"type",
")",
"def",
"MakeRepeatedScalarDefault",
"(",
"message",
")",
":",
"return",
"containers",
".",
"RepeatedScalarFieldContainer",
"(",
"message",
".",
"_listener_for_children",
",",
"type_checker",
")",
"return",
"MakeRepeatedScalarDefault",
"if",
"field",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"# _concrete_class may not yet be initialized.",
"message_type",
"=",
"field",
".",
"message_type",
"def",
"MakeSubMessageDefault",
"(",
"message",
")",
":",
"result",
"=",
"message_type",
".",
"_concrete_class",
"(",
")",
"result",
".",
"_SetListener",
"(",
"message",
".",
"_listener_for_children",
")",
"return",
"result",
"return",
"MakeSubMessageDefault",
"def",
"MakeScalarDefault",
"(",
"message",
")",
":",
"return",
"field",
".",
"default_value",
"return",
"MakeScalarDefault"
] | https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py#L236-L280 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/thrift/server/TNonblockingServer.py | python | Connection.write | (self) | Writes data from socket and switch state. | Writes data from socket and switch state. | [
"Writes",
"data",
"from",
"socket",
"and",
"switch",
"state",
"."
] | def write(self):
"""Writes data from socket and switch state."""
assert self.status == SEND_ANSWER
sent = self.socket.send(self._wbuf)
if sent == len(self._wbuf):
self.status = WAIT_LEN
self._wbuf = b''
self.len = 0
else:
self._wbuf = self._wbuf[sent:] | [
"def",
"write",
"(",
"self",
")",
":",
"assert",
"self",
".",
"status",
"==",
"SEND_ANSWER",
"sent",
"=",
"self",
".",
"socket",
".",
"send",
"(",
"self",
".",
"_wbuf",
")",
"if",
"sent",
"==",
"len",
"(",
"self",
".",
"_wbuf",
")",
":",
"self",
".",
"status",
"=",
"WAIT_LEN",
"self",
".",
"_wbuf",
"=",
"b''",
"self",
".",
"len",
"=",
"0",
"else",
":",
"self",
".",
"_wbuf",
"=",
"self",
".",
"_wbuf",
"[",
"sent",
":",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/thrift/server/TNonblockingServer.py#L168-L177 | ||
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/importers/CNTK/lib/cntk_utilities.py | python | Utilities.get_padding_for_layer_with_sliding_window | (cntk_attributes,
window_size=3, scheme=ell.neural.PaddingScheme.zeros) | return {"size": padding, "scheme": scheme} | Returns padding for a cntk node that uses sliding windows like
Convolution and Pooling | Returns padding for a cntk node that uses sliding windows like
Convolution and Pooling | [
"Returns",
"padding",
"for",
"a",
"cntk",
"node",
"that",
"uses",
"sliding",
"windows",
"like",
"Convolution",
"and",
"Pooling"
] | def get_padding_for_layer_with_sliding_window(cntk_attributes,
window_size=3, scheme=ell.neural.PaddingScheme.zeros):
"""
Returns padding for a cntk node that uses sliding windows like
Convolution and Pooling
"""
if 'autoPadding' in cntk_attributes:
if cntk_attributes['autoPadding'][1]:
padding = int((window_size - 1) / 2)
else:
padding = cntk_attributes['upperPad'][0]
else:
padding = cntk_attributes['upperPad'][0]
return {"size": padding, "scheme": scheme} | [
"def",
"get_padding_for_layer_with_sliding_window",
"(",
"cntk_attributes",
",",
"window_size",
"=",
"3",
",",
"scheme",
"=",
"ell",
".",
"neural",
".",
"PaddingScheme",
".",
"zeros",
")",
":",
"if",
"'autoPadding'",
"in",
"cntk_attributes",
":",
"if",
"cntk_attributes",
"[",
"'autoPadding'",
"]",
"[",
"1",
"]",
":",
"padding",
"=",
"int",
"(",
"(",
"window_size",
"-",
"1",
")",
"/",
"2",
")",
"else",
":",
"padding",
"=",
"cntk_attributes",
"[",
"'upperPad'",
"]",
"[",
"0",
"]",
"else",
":",
"padding",
"=",
"cntk_attributes",
"[",
"'upperPad'",
"]",
"[",
"0",
"]",
"return",
"{",
"\"size\"",
":",
"padding",
",",
"\"scheme\"",
":",
"scheme",
"}"
] | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/CNTK/lib/cntk_utilities.py#L298-L311 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/inline_response200.py | python | InlineResponse200.__ne__ | (self, other) | return not self == other | Returns true if both objects are not equal | Returns true if both objects are not equal | [
"Returns",
"true",
"if",
"both",
"objects",
"are",
"not",
"equal"
] | def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | [
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":",
"return",
"not",
"self",
"==",
"other"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/inline_response200.py#L113-L115 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextBuffer.BeginSuppressUndo | (*args, **kwargs) | return _richtext.RichTextBuffer_BeginSuppressUndo(*args, **kwargs) | BeginSuppressUndo(self) -> bool | BeginSuppressUndo(self) -> bool | [
"BeginSuppressUndo",
"(",
"self",
")",
"-",
">",
"bool"
] | def BeginSuppressUndo(*args, **kwargs):
"""BeginSuppressUndo(self) -> bool"""
return _richtext.RichTextBuffer_BeginSuppressUndo(*args, **kwargs) | [
"def",
"BeginSuppressUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_BeginSuppressUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L2289-L2291 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | samples/networking/03-distributed-node/AIDGameObjectAI.py | python | AIDGameObjectAI.d_messageRoundtripToClient | (self, data, requesterId) | Send the given data to the requesting client | Send the given data to the requesting client | [
"Send",
"the",
"given",
"data",
"to",
"the",
"requesting",
"client"
] | def d_messageRoundtripToClient(self, data, requesterId):
""" Send the given data to the requesting client """
print("Send message to back to:", requesterId)
self.sendUpdateToAvatarId(requesterId, 'messageRoundtripToClient', [data]) | [
"def",
"d_messageRoundtripToClient",
"(",
"self",
",",
"data",
",",
"requesterId",
")",
":",
"print",
"(",
"\"Send message to back to:\"",
",",
"requesterId",
")",
"self",
".",
"sendUpdateToAvatarId",
"(",
"requesterId",
",",
"'messageRoundtripToClient'",
",",
"[",
"data",
"]",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/samples/networking/03-distributed-node/AIDGameObjectAI.py#L22-L25 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | build/android/pylib/perf/surface_stats_collector.py | python | SurfaceStatsCollector._GetSurfaceFlingerFrameData | (self) | return (refresh_period, timestamps) | Returns collected SurfaceFlinger frame timing data.
Returns:
A tuple containing:
- The display's nominal refresh period in seconds.
- A list of timestamps signifying frame presentation times in seconds.
The return value may be (None, None) if there was no data collected (for
example, if the app was closed before the collector thread has finished). | Returns collected SurfaceFlinger frame timing data. | [
"Returns",
"collected",
"SurfaceFlinger",
"frame",
"timing",
"data",
"."
] | def _GetSurfaceFlingerFrameData(self):
"""Returns collected SurfaceFlinger frame timing data.
Returns:
A tuple containing:
- The display's nominal refresh period in seconds.
- A list of timestamps signifying frame presentation times in seconds.
The return value may be (None, None) if there was no data collected (for
example, if the app was closed before the collector thread has finished).
"""
# adb shell dumpsys SurfaceFlinger --latency <window name>
# prints some information about the last 128 frames displayed in
# that window.
# The data returned looks like this:
# 16954612
# 7657467895508 7657482691352 7657493499756
# 7657484466553 7657499645964 7657511077881
# 7657500793457 7657516600576 7657527404785
# (...)
#
# The first line is the refresh period (here 16.95 ms), it is followed
# by 128 lines w/ 3 timestamps in nanosecond each:
# A) when the app started to draw
# B) the vsync immediately preceding SF submitting the frame to the h/w
# C) timestamp immediately after SF submitted that frame to the h/w
#
# The difference between the 1st and 3rd timestamp is the frame-latency.
# An interesting data is when the frame latency crosses a refresh period
# boundary, this can be calculated this way:
#
# ceil((C - A) / refresh-period)
#
# (each time the number above changes, we have a "jank").
# If this happens a lot during an animation, the animation appears
# janky, even if it runs at 60 fps in average.
#
# We use the special "SurfaceView" window name because the statistics for
# the activity's main window are not updated when the main web content is
# composited into a SurfaceView.
results = self._adb.RunShellCommand(
'dumpsys SurfaceFlinger --latency SurfaceView',
log_result=logging.getLogger().isEnabledFor(logging.DEBUG))
if not len(results):
return (None, None)
timestamps = []
nanoseconds_per_second = 1e9
refresh_period = long(results[0]) / nanoseconds_per_second
# If a fence associated with a frame is still pending when we query the
# latency data, SurfaceFlinger gives the frame a timestamp of INT64_MAX.
# Since we only care about completed frames, we will ignore any timestamps
# with this value.
pending_fence_timestamp = (1 << 63) - 1
for line in results[1:]:
fields = line.split()
if len(fields) != 3:
continue
timestamp = long(fields[1])
if timestamp == pending_fence_timestamp:
continue
timestamp /= nanoseconds_per_second
timestamps.append(timestamp)
return (refresh_period, timestamps) | [
"def",
"_GetSurfaceFlingerFrameData",
"(",
"self",
")",
":",
"# adb shell dumpsys SurfaceFlinger --latency <window name>",
"# prints some information about the last 128 frames displayed in",
"# that window.",
"# The data returned looks like this:",
"# 16954612",
"# 7657467895508 7657482691352 7657493499756",
"# 7657484466553 7657499645964 7657511077881",
"# 7657500793457 7657516600576 7657527404785",
"# (...)",
"#",
"# The first line is the refresh period (here 16.95 ms), it is followed",
"# by 128 lines w/ 3 timestamps in nanosecond each:",
"# A) when the app started to draw",
"# B) the vsync immediately preceding SF submitting the frame to the h/w",
"# C) timestamp immediately after SF submitted that frame to the h/w",
"#",
"# The difference between the 1st and 3rd timestamp is the frame-latency.",
"# An interesting data is when the frame latency crosses a refresh period",
"# boundary, this can be calculated this way:",
"#",
"# ceil((C - A) / refresh-period)",
"#",
"# (each time the number above changes, we have a \"jank\").",
"# If this happens a lot during an animation, the animation appears",
"# janky, even if it runs at 60 fps in average.",
"#",
"# We use the special \"SurfaceView\" window name because the statistics for",
"# the activity's main window are not updated when the main web content is",
"# composited into a SurfaceView.",
"results",
"=",
"self",
".",
"_adb",
".",
"RunShellCommand",
"(",
"'dumpsys SurfaceFlinger --latency SurfaceView'",
",",
"log_result",
"=",
"logging",
".",
"getLogger",
"(",
")",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
")",
"if",
"not",
"len",
"(",
"results",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"timestamps",
"=",
"[",
"]",
"nanoseconds_per_second",
"=",
"1e9",
"refresh_period",
"=",
"long",
"(",
"results",
"[",
"0",
"]",
")",
"/",
"nanoseconds_per_second",
"# If a fence associated with a frame is still pending when we query the",
"# latency data, SurfaceFlinger gives the frame a timestamp of INT64_MAX.",
"# Since we only care about completed frames, we will ignore any timestamps",
"# with this value.",
"pending_fence_timestamp",
"=",
"(",
"1",
"<<",
"63",
")",
"-",
"1",
"for",
"line",
"in",
"results",
"[",
"1",
":",
"]",
":",
"fields",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"fields",
")",
"!=",
"3",
":",
"continue",
"timestamp",
"=",
"long",
"(",
"fields",
"[",
"1",
"]",
")",
"if",
"timestamp",
"==",
"pending_fence_timestamp",
":",
"continue",
"timestamp",
"/=",
"nanoseconds_per_second",
"timestamps",
".",
"append",
"(",
"timestamp",
")",
"return",
"(",
"refresh_period",
",",
"timestamps",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/perf/surface_stats_collector.py#L216-L281 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/cookies.py | python | create_cookie | (name, value, **kwargs) | return cookielib.Cookie(**result) | Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie"). | Make a cookie from underspecified parameters. | [
"Make",
"a",
"cookie",
"from",
"underspecified",
"parameters",
"."
] | def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = dict(
version=0,
name=name,
value=value,
port=None,
domain='',
path='/',
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': None},
rfc2109=False,)
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
return cookielib.Cookie(**result) | [
"def",
"create_cookie",
"(",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"dict",
"(",
"version",
"=",
"0",
",",
"name",
"=",
"name",
",",
"value",
"=",
"value",
",",
"port",
"=",
"None",
",",
"domain",
"=",
"''",
",",
"path",
"=",
"'/'",
",",
"secure",
"=",
"False",
",",
"expires",
"=",
"None",
",",
"discard",
"=",
"True",
",",
"comment",
"=",
"None",
",",
"comment_url",
"=",
"None",
",",
"rest",
"=",
"{",
"'HttpOnly'",
":",
"None",
"}",
",",
"rfc2109",
"=",
"False",
",",
")",
"badargs",
"=",
"set",
"(",
"kwargs",
")",
"-",
"set",
"(",
"result",
")",
"if",
"badargs",
":",
"err",
"=",
"'create_cookie() got unexpected keyword arguments: %s'",
"raise",
"TypeError",
"(",
"err",
"%",
"list",
"(",
"badargs",
")",
")",
"result",
".",
"update",
"(",
"kwargs",
")",
"result",
"[",
"'port_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'port'",
"]",
")",
"result",
"[",
"'domain_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'domain'",
"]",
")",
"result",
"[",
"'domain_initial_dot'",
"]",
"=",
"result",
"[",
"'domain'",
"]",
".",
"startswith",
"(",
"'.'",
")",
"result",
"[",
"'path_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'path'",
"]",
")",
"return",
"cookielib",
".",
"Cookie",
"(",
"*",
"*",
"result",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/cookies.py#L353-L385 | |
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/google/protobuf/descriptor.py | python | EnumDescriptor.CopyToProto | (self, proto) | Copies this to a descriptor_pb2.EnumDescriptorProto.
Args:
proto: An empty descriptor_pb2.EnumDescriptorProto. | Copies this to a descriptor_pb2.EnumDescriptorProto. | [
"Copies",
"this",
"to",
"a",
"descriptor_pb2",
".",
"EnumDescriptorProto",
"."
] | def CopyToProto(self, proto):
"""Copies this to a descriptor_pb2.EnumDescriptorProto.
Args:
proto: An empty descriptor_pb2.EnumDescriptorProto.
"""
# This function is overriden to give a better doc comment.
super(EnumDescriptor, self).CopyToProto(proto) | [
"def",
"CopyToProto",
"(",
"self",
",",
"proto",
")",
":",
"# This function is overriden to give a better doc comment.",
"super",
"(",
"EnumDescriptor",
",",
"self",
")",
".",
"CopyToProto",
"(",
"proto",
")"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/descriptor.py#L536-L543 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextObject.ConvertTenthsMMToPixels | (*args, **kwargs) | return _richtext.RichTextObject_ConvertTenthsMMToPixels(*args, **kwargs) | ConvertTenthsMMToPixels(int ppi, int units, double scale=1.0) -> int | ConvertTenthsMMToPixels(int ppi, int units, double scale=1.0) -> int | [
"ConvertTenthsMMToPixels",
"(",
"int",
"ppi",
"int",
"units",
"double",
"scale",
"=",
"1",
".",
"0",
")",
"-",
">",
"int"
] | def ConvertTenthsMMToPixels(*args, **kwargs):
"""ConvertTenthsMMToPixels(int ppi, int units, double scale=1.0) -> int"""
return _richtext.RichTextObject_ConvertTenthsMMToPixels(*args, **kwargs) | [
"def",
"ConvertTenthsMMToPixels",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextObject_ConvertTenthsMMToPixels",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L1395-L1397 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/integration/AsyncStateMachine.py | python | AsyncStateMachine.setHandshakeOp | (self, handshaker) | Start a handshake operation.
@type handshaker: generator
@param handshaker: A generator created by using one of the
asynchronous handshake functions (i.e. handshakeServerAsync, or
handshakeClientxxx(..., async=True). | Start a handshake operation. | [
"Start",
"a",
"handshake",
"operation",
"."
] | def setHandshakeOp(self, handshaker):
"""Start a handshake operation.
@type handshaker: generator
@param handshaker: A generator created by using one of the
asynchronous handshake functions (i.e. handshakeServerAsync, or
handshakeClientxxx(..., async=True).
"""
try:
self._checkAssert(0)
self.handshaker = handshaker
self._doHandshakeOp()
except:
self._clear()
raise | [
"def",
"setHandshakeOp",
"(",
"self",
",",
"handshaker",
")",
":",
"try",
":",
"self",
".",
"_checkAssert",
"(",
"0",
")",
"self",
".",
"handshaker",
"=",
"handshaker",
"self",
".",
"_doHandshakeOp",
"(",
")",
"except",
":",
"self",
".",
"_clear",
"(",
")",
"raise"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/integration/AsyncStateMachine.py#L186-L200 | ||
eomahony/Numberjack | 53fa9e994a36f881ffd320d8d04158097190aad8 | Numberjack/__init__.py | python | NBJ_STD_Solver.setOption | (self,func,param=None) | Sets an option in Toulbar2 whose name is passed as the first parameter,
and value as a second one. | Sets an option in Toulbar2 whose name is passed as the first parameter,
and value as a second one. | [
"Sets",
"an",
"option",
"in",
"Toulbar2",
"whose",
"name",
"is",
"passed",
"as",
"the",
"first",
"parameter",
"and",
"value",
"as",
"a",
"second",
"one",
"."
] | def setOption(self,func,param=None):
"""
Sets an option in Toulbar2 whose name is passed as the first parameter,
and value as a second one.
"""
try:
function = getattr(self.solver,func)
except AttributeError:
print("Warning: "+func+" option does not exist in this solver!")
else:
if param is None:
function()
else:
function(param) | [
"def",
"setOption",
"(",
"self",
",",
"func",
",",
"param",
"=",
"None",
")",
":",
"try",
":",
"function",
"=",
"getattr",
"(",
"self",
".",
"solver",
",",
"func",
")",
"except",
"AttributeError",
":",
"print",
"(",
"\"Warning: \"",
"+",
"func",
"+",
"\" option does not exist in this solver!\"",
")",
"else",
":",
"if",
"param",
"is",
"None",
":",
"function",
"(",
")",
"else",
":",
"function",
"(",
"param",
")"
] | https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/__init__.py#L3635-L3648 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/telnetlib.py | python | Telnet.sock_avail | (self) | return select.select([self], [], [], 0) == ([self], [], []) | Test whether data is available on the socket. | Test whether data is available on the socket. | [
"Test",
"whether",
"data",
"is",
"available",
"on",
"the",
"socket",
"."
] | def sock_avail(self):
"""Test whether data is available on the socket."""
return select.select([self], [], [], 0) == ([self], [], []) | [
"def",
"sock_avail",
"(",
"self",
")",
":",
"return",
"select",
".",
"select",
"(",
"[",
"self",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"0",
")",
"==",
"(",
"[",
"self",
"]",
",",
"[",
"]",
",",
"[",
"]",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/telnetlib.py#L578-L580 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/cgi.py | python | parse | (fp=None, environ=os.environ, keep_blank_values=0,
strict_parsing=0, separator='&') | return urllib.parse.parse_qs(qs, keep_blank_values, strict_parsing,
encoding=encoding, separator=separator) | Parse a query in the environment or from a file (default stdin)
Arguments, all optional:
fp : file pointer; default: sys.stdin.buffer
environ : environment dictionary; default: os.environ
keep_blank_values: flag indicating whether blank values in
percent-encoded forms should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
not included.
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
separator: str. The symbol to use for separating the query arguments.
Defaults to &. | Parse a query in the environment or from a file (default stdin) | [
"Parse",
"a",
"query",
"in",
"the",
"environment",
"or",
"from",
"a",
"file",
"(",
"default",
"stdin",
")"
] | def parse(fp=None, environ=os.environ, keep_blank_values=0,
strict_parsing=0, separator='&'):
"""Parse a query in the environment or from a file (default stdin)
Arguments, all optional:
fp : file pointer; default: sys.stdin.buffer
environ : environment dictionary; default: os.environ
keep_blank_values: flag indicating whether blank values in
percent-encoded forms should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
not included.
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
separator: str. The symbol to use for separating the query arguments.
Defaults to &.
"""
if fp is None:
fp = sys.stdin
# field keys and values (except for files) are returned as strings
# an encoding is required to decode the bytes read from self.fp
if hasattr(fp,'encoding'):
encoding = fp.encoding
else:
encoding = 'latin-1'
# fp.read() must return bytes
if isinstance(fp, TextIOWrapper):
fp = fp.buffer
if not 'REQUEST_METHOD' in environ:
environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone
if environ['REQUEST_METHOD'] == 'POST':
ctype, pdict = parse_header(environ['CONTENT_TYPE'])
if ctype == 'multipart/form-data':
return parse_multipart(fp, pdict, separator=separator)
elif ctype == 'application/x-www-form-urlencoded':
clength = int(environ['CONTENT_LENGTH'])
if maxlen and clength > maxlen:
raise ValueError('Maximum content length exceeded')
qs = fp.read(clength).decode(encoding)
else:
qs = '' # Unknown content-type
if 'QUERY_STRING' in environ:
if qs: qs = qs + '&'
qs = qs + environ['QUERY_STRING']
elif sys.argv[1:]:
if qs: qs = qs + '&'
qs = qs + sys.argv[1]
environ['QUERY_STRING'] = qs # XXX Shouldn't, really
elif 'QUERY_STRING' in environ:
qs = environ['QUERY_STRING']
else:
if sys.argv[1:]:
qs = sys.argv[1]
else:
qs = ""
environ['QUERY_STRING'] = qs # XXX Shouldn't, really
return urllib.parse.parse_qs(qs, keep_blank_values, strict_parsing,
encoding=encoding, separator=separator) | [
"def",
"parse",
"(",
"fp",
"=",
"None",
",",
"environ",
"=",
"os",
".",
"environ",
",",
"keep_blank_values",
"=",
"0",
",",
"strict_parsing",
"=",
"0",
",",
"separator",
"=",
"'&'",
")",
":",
"if",
"fp",
"is",
"None",
":",
"fp",
"=",
"sys",
".",
"stdin",
"# field keys and values (except for files) are returned as strings",
"# an encoding is required to decode the bytes read from self.fp",
"if",
"hasattr",
"(",
"fp",
",",
"'encoding'",
")",
":",
"encoding",
"=",
"fp",
".",
"encoding",
"else",
":",
"encoding",
"=",
"'latin-1'",
"# fp.read() must return bytes",
"if",
"isinstance",
"(",
"fp",
",",
"TextIOWrapper",
")",
":",
"fp",
"=",
"fp",
".",
"buffer",
"if",
"not",
"'REQUEST_METHOD'",
"in",
"environ",
":",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"=",
"'GET'",
"# For testing stand-alone",
"if",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"==",
"'POST'",
":",
"ctype",
",",
"pdict",
"=",
"parse_header",
"(",
"environ",
"[",
"'CONTENT_TYPE'",
"]",
")",
"if",
"ctype",
"==",
"'multipart/form-data'",
":",
"return",
"parse_multipart",
"(",
"fp",
",",
"pdict",
",",
"separator",
"=",
"separator",
")",
"elif",
"ctype",
"==",
"'application/x-www-form-urlencoded'",
":",
"clength",
"=",
"int",
"(",
"environ",
"[",
"'CONTENT_LENGTH'",
"]",
")",
"if",
"maxlen",
"and",
"clength",
">",
"maxlen",
":",
"raise",
"ValueError",
"(",
"'Maximum content length exceeded'",
")",
"qs",
"=",
"fp",
".",
"read",
"(",
"clength",
")",
".",
"decode",
"(",
"encoding",
")",
"else",
":",
"qs",
"=",
"''",
"# Unknown content-type",
"if",
"'QUERY_STRING'",
"in",
"environ",
":",
"if",
"qs",
":",
"qs",
"=",
"qs",
"+",
"'&'",
"qs",
"=",
"qs",
"+",
"environ",
"[",
"'QUERY_STRING'",
"]",
"elif",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
":",
"if",
"qs",
":",
"qs",
"=",
"qs",
"+",
"'&'",
"qs",
"=",
"qs",
"+",
"sys",
".",
"argv",
"[",
"1",
"]",
"environ",
"[",
"'QUERY_STRING'",
"]",
"=",
"qs",
"# XXX Shouldn't, really",
"elif",
"'QUERY_STRING'",
"in",
"environ",
":",
"qs",
"=",
"environ",
"[",
"'QUERY_STRING'",
"]",
"else",
":",
"if",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
":",
"qs",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"else",
":",
"qs",
"=",
"\"\"",
"environ",
"[",
"'QUERY_STRING'",
"]",
"=",
"qs",
"# XXX Shouldn't, really",
"return",
"urllib",
".",
"parse",
".",
"parse_qs",
"(",
"qs",
",",
"keep_blank_values",
",",
"strict_parsing",
",",
"encoding",
"=",
"encoding",
",",
"separator",
"=",
"separator",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/cgi.py#L120-L187 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/http/cookiejar.py | python | split_header_words | (header_values) | return result | r"""Parse header values into a list of lists containing key,value pairs.
The function knows how to deal with ",", ";" and "=" as well as quoted
values after "=". A list of space separated tokens are parsed as if they
were separated by ";".
If the header_values passed as argument contains multiple values, then they
are treated as if they were a single value separated by comma ",".
This means that this function is useful for parsing header fields that
follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
the requirement for tokens).
headers = #header
header = (token | parameter) *( [";"] (token | parameter))
token = 1*<any CHAR except CTLs or separators>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
qdtext = <any TEXT except <">>
quoted-pair = "\" CHAR
parameter = attribute "=" value
attribute = token
value = token | quoted-string
Each header is represented by a list of key/value pairs. The value for a
simple token (not part of a parameter) is None. Syntactically incorrect
headers will not necessarily be parsed as you would want.
This is easier to describe with some examples:
>>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz'])
[[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]]
>>> split_header_words(['text/html; charset="iso-8859-1"'])
[[('text/html', None), ('charset', 'iso-8859-1')]]
>>> split_header_words([r'Basic realm="\"foo\bar\""'])
[[('Basic', None), ('realm', '"foobar"')]] | r"""Parse header values into a list of lists containing key,value pairs. | [
"r",
"Parse",
"header",
"values",
"into",
"a",
"list",
"of",
"lists",
"containing",
"key",
"value",
"pairs",
"."
] | def split_header_words(header_values):
r"""Parse header values into a list of lists containing key,value pairs.
The function knows how to deal with ",", ";" and "=" as well as quoted
values after "=". A list of space separated tokens are parsed as if they
were separated by ";".
If the header_values passed as argument contains multiple values, then they
are treated as if they were a single value separated by comma ",".
This means that this function is useful for parsing header fields that
follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
the requirement for tokens).
headers = #header
header = (token | parameter) *( [";"] (token | parameter))
token = 1*<any CHAR except CTLs or separators>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
qdtext = <any TEXT except <">>
quoted-pair = "\" CHAR
parameter = attribute "=" value
attribute = token
value = token | quoted-string
Each header is represented by a list of key/value pairs. The value for a
simple token (not part of a parameter) is None. Syntactically incorrect
headers will not necessarily be parsed as you would want.
This is easier to describe with some examples:
>>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz'])
[[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]]
>>> split_header_words(['text/html; charset="iso-8859-1"'])
[[('text/html', None), ('charset', 'iso-8859-1')]]
>>> split_header_words([r'Basic realm="\"foo\bar\""'])
[[('Basic', None), ('realm', '"foobar"')]]
"""
assert not isinstance(header_values, str)
result = []
for text in header_values:
orig_text = text
pairs = []
while text:
m = HEADER_TOKEN_RE.search(text)
if m:
text = unmatched(m)
name = m.group(1)
m = HEADER_QUOTED_VALUE_RE.search(text)
if m: # quoted value
text = unmatched(m)
value = m.group(1)
value = HEADER_ESCAPE_RE.sub(r"\1", value)
else:
m = HEADER_VALUE_RE.search(text)
if m: # unquoted value
text = unmatched(m)
value = m.group(1)
value = value.rstrip()
else:
# no value, a lone token
value = None
pairs.append((name, value))
elif text.lstrip().startswith(","):
# concatenated headers, as per RFC 2616 section 4.2
text = text.lstrip()[1:]
if pairs: result.append(pairs)
pairs = []
else:
# skip junk
non_junk, nr_junk_chars = re.subn(r"^[=\s;]*", "", text)
assert nr_junk_chars > 0, (
"split_header_words bug: '%s', '%s', %s" %
(orig_text, text, pairs))
text = non_junk
if pairs: result.append(pairs)
return result | [
"def",
"split_header_words",
"(",
"header_values",
")",
":",
"assert",
"not",
"isinstance",
"(",
"header_values",
",",
"str",
")",
"result",
"=",
"[",
"]",
"for",
"text",
"in",
"header_values",
":",
"orig_text",
"=",
"text",
"pairs",
"=",
"[",
"]",
"while",
"text",
":",
"m",
"=",
"HEADER_TOKEN_RE",
".",
"search",
"(",
"text",
")",
"if",
"m",
":",
"text",
"=",
"unmatched",
"(",
"m",
")",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"m",
"=",
"HEADER_QUOTED_VALUE_RE",
".",
"search",
"(",
"text",
")",
"if",
"m",
":",
"# quoted value",
"text",
"=",
"unmatched",
"(",
"m",
")",
"value",
"=",
"m",
".",
"group",
"(",
"1",
")",
"value",
"=",
"HEADER_ESCAPE_RE",
".",
"sub",
"(",
"r\"\\1\"",
",",
"value",
")",
"else",
":",
"m",
"=",
"HEADER_VALUE_RE",
".",
"search",
"(",
"text",
")",
"if",
"m",
":",
"# unquoted value",
"text",
"=",
"unmatched",
"(",
"m",
")",
"value",
"=",
"m",
".",
"group",
"(",
"1",
")",
"value",
"=",
"value",
".",
"rstrip",
"(",
")",
"else",
":",
"# no value, a lone token",
"value",
"=",
"None",
"pairs",
".",
"append",
"(",
"(",
"name",
",",
"value",
")",
")",
"elif",
"text",
".",
"lstrip",
"(",
")",
".",
"startswith",
"(",
"\",\"",
")",
":",
"# concatenated headers, as per RFC 2616 section 4.2",
"text",
"=",
"text",
".",
"lstrip",
"(",
")",
"[",
"1",
":",
"]",
"if",
"pairs",
":",
"result",
".",
"append",
"(",
"pairs",
")",
"pairs",
"=",
"[",
"]",
"else",
":",
"# skip junk",
"non_junk",
",",
"nr_junk_chars",
"=",
"re",
".",
"subn",
"(",
"r\"^[=\\s;]*\"",
",",
"\"\"",
",",
"text",
")",
"assert",
"nr_junk_chars",
">",
"0",
",",
"(",
"\"split_header_words bug: '%s', '%s', %s\"",
"%",
"(",
"orig_text",
",",
"text",
",",
"pairs",
")",
")",
"text",
"=",
"non_junk",
"if",
"pairs",
":",
"result",
".",
"append",
"(",
"pairs",
")",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/http/cookiejar.py#L341-L424 | |
google/shaka-player-embedded | dabbeb5b47cc257b37b9a254661546352aaf0afe | shaka/tools/parse_makefile.py | python | _Split | (s) | return re.split(' +', s.strip()) | Splits a string on white space.
This is used to split similar to argument lists, which is used for Make
variables. However, this doesn't support using quoted arguments. | Splits a string on white space. | [
"Splits",
"a",
"string",
"on",
"white",
"space",
"."
] | def _Split(s):
"""Splits a string on white space.
This is used to split similar to argument lists, which is used for Make
variables. However, this doesn't support using quoted arguments.
"""
assert '"' not in s
if not s.strip():
return []
return re.split(' +', s.strip()) | [
"def",
"_Split",
"(",
"s",
")",
":",
"assert",
"'\"'",
"not",
"in",
"s",
"if",
"not",
"s",
".",
"strip",
"(",
")",
":",
"return",
"[",
"]",
"return",
"re",
".",
"split",
"(",
"' +'",
",",
"s",
".",
"strip",
"(",
")",
")"
] | https://github.com/google/shaka-player-embedded/blob/dabbeb5b47cc257b37b9a254661546352aaf0afe/shaka/tools/parse_makefile.py#L31-L40 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/numbers.py | python | Real.real | (self) | return +self | Real numbers are their real component. | Real numbers are their real component. | [
"Real",
"numbers",
"are",
"their",
"real",
"component",
"."
] | def real(self):
"""Real numbers are their real component."""
return +self | [
"def",
"real",
"(",
"self",
")",
":",
"return",
"+",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/numbers.py#L251-L253 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlBookRecord.SetContentsRange | (*args, **kwargs) | return _html.HtmlBookRecord_SetContentsRange(*args, **kwargs) | SetContentsRange(self, int start, int end) | SetContentsRange(self, int start, int end) | [
"SetContentsRange",
"(",
"self",
"int",
"start",
"int",
"end",
")"
] | def SetContentsRange(*args, **kwargs):
"""SetContentsRange(self, int start, int end)"""
return _html.HtmlBookRecord_SetContentsRange(*args, **kwargs) | [
"def",
"SetContentsRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlBookRecord_SetContentsRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1427-L1429 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/ftplib.py | python | FTP.dir | (self, *args) | List a directory in long form.
By default list current directory to stdout.
Optional last argument is callback function; all
non-empty arguments before it are concatenated to the
LIST command. (This *should* only be used for a pathname.) | List a directory in long form.
By default list current directory to stdout.
Optional last argument is callback function; all
non-empty arguments before it are concatenated to the
LIST command. (This *should* only be used for a pathname.) | [
"List",
"a",
"directory",
"in",
"long",
"form",
".",
"By",
"default",
"list",
"current",
"directory",
"to",
"stdout",
".",
"Optional",
"last",
"argument",
"is",
"callback",
"function",
";",
"all",
"non",
"-",
"empty",
"arguments",
"before",
"it",
"are",
"concatenated",
"to",
"the",
"LIST",
"command",
".",
"(",
"This",
"*",
"should",
"*",
"only",
"be",
"used",
"for",
"a",
"pathname",
".",
")"
] | def dir(self, *args):
'''List a directory in long form.
By default list current directory to stdout.
Optional last argument is callback function; all
non-empty arguments before it are concatenated to the
LIST command. (This *should* only be used for a pathname.)'''
cmd = 'LIST'
func = None
if args[-1:] and type(args[-1]) != type(''):
args, func = args[:-1], args[-1]
for arg in args:
if arg:
cmd = cmd + (' ' + arg)
self.retrlines(cmd, func) | [
"def",
"dir",
"(",
"self",
",",
"*",
"args",
")",
":",
"cmd",
"=",
"'LIST'",
"func",
"=",
"None",
"if",
"args",
"[",
"-",
"1",
":",
"]",
"and",
"type",
"(",
"args",
"[",
"-",
"1",
"]",
")",
"!=",
"type",
"(",
"''",
")",
":",
"args",
",",
"func",
"=",
"args",
"[",
":",
"-",
"1",
"]",
",",
"args",
"[",
"-",
"1",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
":",
"cmd",
"=",
"cmd",
"+",
"(",
"' '",
"+",
"arg",
")",
"self",
".",
"retrlines",
"(",
"cmd",
",",
"func",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/ftplib.py#L533-L546 | ||
ClickHouse/ClickHouse | 66386aab1b14e4386b9a218ae92861fa8579285a | utils/github/query.py | python | Query.get_pull_requests | (self, before_commit) | return pull_requests | Get all merged pull-requests from the HEAD of default branch to the last commit (excluding) | Get all merged pull-requests from the HEAD of default branch to the last commit (excluding) | [
"Get",
"all",
"merged",
"pull",
"-",
"requests",
"from",
"the",
"HEAD",
"of",
"default",
"branch",
"to",
"the",
"last",
"commit",
"(",
"excluding",
")"
] | def get_pull_requests(self, before_commit):
'''
Get all merged pull-requests from the HEAD of default branch to the last commit (excluding)
'''
_QUERY = '''
repository(owner: "{owner}" name: "{name}") {{
defaultBranchRef {{
target {{
... on Commit {{
history(first: {max_page_size} {next}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
oid
associatedPullRequests(first: {min_page_size}) {{
totalCount
nodes {{
... on PullRequest {{
{pull_request_data}
labels(first: {min_page_size}) {{
totalCount
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
name
color
}}
}}
}}
}}
}}
}}
}}
}}
}}
}}
}}
'''
pull_requests = []
not_end = True
query = _QUERY.format(owner=self._owner, name=self._name,
max_page_size=self._max_page_size,
min_page_size=self._min_page_size,
pull_request_data=self._PULL_REQUEST,
next='')
while not_end:
result = self._run(query)['repository']['defaultBranchRef']['target']['history']
not_end = result['pageInfo']['hasNextPage']
query = _QUERY.format(owner=self._owner, name=self._name,
max_page_size=self._max_page_size,
min_page_size=self._min_page_size,
pull_request_data=self._PULL_REQUEST,
next='after: "{}"'.format(result["pageInfo"]["endCursor"]))
for commit in result['nodes']:
# FIXME: maybe include `before_commit`?
if str(commit['oid']) == str(before_commit):
not_end = False
break
# TODO: fetch all pull-requests that were merged in a single commit.
assert commit['associatedPullRequests']['totalCount'] <= self._min_page_size
for pull_request in commit['associatedPullRequests']['nodes']:
if(pull_request['baseRepository']['nameWithOwner'] == '{}/{}'.format(self._owner, self._name) and
pull_request['baseRefName'] == self.default_branch and
pull_request['mergeCommit']['oid'] == commit['oid']):
pull_requests.append(pull_request)
return pull_requests | [
"def",
"get_pull_requests",
"(",
"self",
",",
"before_commit",
")",
":",
"_QUERY",
"=",
"'''\n repository(owner: \"{owner}\" name: \"{name}\") {{\n defaultBranchRef {{\n target {{\n ... on Commit {{\n history(first: {max_page_size} {next}) {{\n pageInfo {{\n hasNextPage\n endCursor\n }}\n nodes {{\n oid\n associatedPullRequests(first: {min_page_size}) {{\n totalCount\n nodes {{\n ... on PullRequest {{\n {pull_request_data}\n\n labels(first: {min_page_size}) {{\n totalCount\n pageInfo {{\n hasNextPage\n endCursor\n }}\n nodes {{\n name\n color\n }}\n }}\n }}\n }}\n }}\n }}\n }}\n }}\n }}\n }}\n }}\n '''",
"pull_requests",
"=",
"[",
"]",
"not_end",
"=",
"True",
"query",
"=",
"_QUERY",
".",
"format",
"(",
"owner",
"=",
"self",
".",
"_owner",
",",
"name",
"=",
"self",
".",
"_name",
",",
"max_page_size",
"=",
"self",
".",
"_max_page_size",
",",
"min_page_size",
"=",
"self",
".",
"_min_page_size",
",",
"pull_request_data",
"=",
"self",
".",
"_PULL_REQUEST",
",",
"next",
"=",
"''",
")",
"while",
"not_end",
":",
"result",
"=",
"self",
".",
"_run",
"(",
"query",
")",
"[",
"'repository'",
"]",
"[",
"'defaultBranchRef'",
"]",
"[",
"'target'",
"]",
"[",
"'history'",
"]",
"not_end",
"=",
"result",
"[",
"'pageInfo'",
"]",
"[",
"'hasNextPage'",
"]",
"query",
"=",
"_QUERY",
".",
"format",
"(",
"owner",
"=",
"self",
".",
"_owner",
",",
"name",
"=",
"self",
".",
"_name",
",",
"max_page_size",
"=",
"self",
".",
"_max_page_size",
",",
"min_page_size",
"=",
"self",
".",
"_min_page_size",
",",
"pull_request_data",
"=",
"self",
".",
"_PULL_REQUEST",
",",
"next",
"=",
"'after: \"{}\"'",
".",
"format",
"(",
"result",
"[",
"\"pageInfo\"",
"]",
"[",
"\"endCursor\"",
"]",
")",
")",
"for",
"commit",
"in",
"result",
"[",
"'nodes'",
"]",
":",
"# FIXME: maybe include `before_commit`?",
"if",
"str",
"(",
"commit",
"[",
"'oid'",
"]",
")",
"==",
"str",
"(",
"before_commit",
")",
":",
"not_end",
"=",
"False",
"break",
"# TODO: fetch all pull-requests that were merged in a single commit.",
"assert",
"commit",
"[",
"'associatedPullRequests'",
"]",
"[",
"'totalCount'",
"]",
"<=",
"self",
".",
"_min_page_size",
"for",
"pull_request",
"in",
"commit",
"[",
"'associatedPullRequests'",
"]",
"[",
"'nodes'",
"]",
":",
"if",
"(",
"pull_request",
"[",
"'baseRepository'",
"]",
"[",
"'nameWithOwner'",
"]",
"==",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"_owner",
",",
"self",
".",
"_name",
")",
"and",
"pull_request",
"[",
"'baseRefName'",
"]",
"==",
"self",
".",
"default_branch",
"and",
"pull_request",
"[",
"'mergeCommit'",
"]",
"[",
"'oid'",
"]",
"==",
"commit",
"[",
"'oid'",
"]",
")",
":",
"pull_requests",
".",
"append",
"(",
"pull_request",
")",
"return",
"pull_requests"
] | https://github.com/ClickHouse/ClickHouse/blob/66386aab1b14e4386b9a218ae92861fa8579285a/utils/github/query.py#L180-L257 | |
qboticslabs/mastering_ros | d83e78f30acc45b0f18522c1d5fae3a7f52974b9 | chapter_3_codes/seven_dof_arm_gazebo/scripts/pick_and_place_working_1.py | python | CokeCanPickAndPlace._generate_places | (self, target) | return places | Generate places (place locations), based on
https://github.com/davetcoleman/baxter_cpp/blob/hydro-devel/
baxter_pick_place/src/block_pick_place.cpp | Generate places (place locations), based on
https://github.com/davetcoleman/baxter_cpp/blob/hydro-devel/
baxter_pick_place/src/block_pick_place.cpp | [
"Generate",
"places",
"(",
"place",
"locations",
")",
"based",
"on",
"https",
":",
"//",
"github",
".",
"com",
"/",
"davetcoleman",
"/",
"baxter_cpp",
"/",
"blob",
"/",
"hydro",
"-",
"devel",
"/",
"baxter_pick_place",
"/",
"src",
"/",
"block_pick_place",
".",
"cpp"
] | def _generate_places(self, target):
"""
Generate places (place locations), based on
https://github.com/davetcoleman/baxter_cpp/blob/hydro-devel/
baxter_pick_place/src/block_pick_place.cpp
"""
# Generate places:
places = []
now = rospy.Time.now()
for angle in numpy.arange(0.0, numpy.deg2rad(360.0), numpy.deg2rad(1.0)):
# Create place location:
place = PlaceLocation()
place.place_pose.header.stamp = now
place.place_pose.header.frame_id = self._robot.get_planning_frame()
# Set target position:
place.place_pose.pose = copy.deepcopy(target)
# Generate orientation (wrt Z axis):
q = quaternion_from_euler(0.0, 0.0, angle)
place.place_pose.pose.orientation = Quaternion(*q)
# Generate pre place approach:
place.pre_place_approach.desired_distance = self._approach_retreat_desired_dist
place.pre_place_approach.min_distance = self._approach_retreat_min_dist
place.pre_place_approach.direction.header.stamp = now
place.pre_place_approach.direction.header.frame_id = self._robot.get_planning_frame()
place.pre_place_approach.direction.vector.x = 0
place.pre_place_approach.direction.vector.y = 0
place.pre_place_approach.direction.vector.z = -1
# Generate post place approach:
place.post_place_retreat.direction.header.stamp = now
place.post_place_retreat.direction.header.frame_id = self._robot.get_planning_frame()
place.post_place_retreat.desired_distance = self._approach_retreat_desired_dist
place.post_place_retreat.min_distance = self._approach_retreat_min_dist
place.post_place_retreat.direction.vector.x = 0
place.post_place_retreat.direction.vector.y = 0
place.post_place_retreat.direction.vector.z = 1
# Add place:
places.append(place)
# Publish places (for debugging/visualization purposes):
self._publish_places(places)
return places | [
"def",
"_generate_places",
"(",
"self",
",",
"target",
")",
":",
"# Generate places:",
"places",
"=",
"[",
"]",
"now",
"=",
"rospy",
".",
"Time",
".",
"now",
"(",
")",
"for",
"angle",
"in",
"numpy",
".",
"arange",
"(",
"0.0",
",",
"numpy",
".",
"deg2rad",
"(",
"360.0",
")",
",",
"numpy",
".",
"deg2rad",
"(",
"1.0",
")",
")",
":",
"# Create place location:",
"place",
"=",
"PlaceLocation",
"(",
")",
"place",
".",
"place_pose",
".",
"header",
".",
"stamp",
"=",
"now",
"place",
".",
"place_pose",
".",
"header",
".",
"frame_id",
"=",
"self",
".",
"_robot",
".",
"get_planning_frame",
"(",
")",
"# Set target position:",
"place",
".",
"place_pose",
".",
"pose",
"=",
"copy",
".",
"deepcopy",
"(",
"target",
")",
"# Generate orientation (wrt Z axis):",
"q",
"=",
"quaternion_from_euler",
"(",
"0.0",
",",
"0.0",
",",
"angle",
")",
"place",
".",
"place_pose",
".",
"pose",
".",
"orientation",
"=",
"Quaternion",
"(",
"*",
"q",
")",
"# Generate pre place approach:",
"place",
".",
"pre_place_approach",
".",
"desired_distance",
"=",
"self",
".",
"_approach_retreat_desired_dist",
"place",
".",
"pre_place_approach",
".",
"min_distance",
"=",
"self",
".",
"_approach_retreat_min_dist",
"place",
".",
"pre_place_approach",
".",
"direction",
".",
"header",
".",
"stamp",
"=",
"now",
"place",
".",
"pre_place_approach",
".",
"direction",
".",
"header",
".",
"frame_id",
"=",
"self",
".",
"_robot",
".",
"get_planning_frame",
"(",
")",
"place",
".",
"pre_place_approach",
".",
"direction",
".",
"vector",
".",
"x",
"=",
"0",
"place",
".",
"pre_place_approach",
".",
"direction",
".",
"vector",
".",
"y",
"=",
"0",
"place",
".",
"pre_place_approach",
".",
"direction",
".",
"vector",
".",
"z",
"=",
"-",
"1",
"# Generate post place approach:",
"place",
".",
"post_place_retreat",
".",
"direction",
".",
"header",
".",
"stamp",
"=",
"now",
"place",
".",
"post_place_retreat",
".",
"direction",
".",
"header",
".",
"frame_id",
"=",
"self",
".",
"_robot",
".",
"get_planning_frame",
"(",
")",
"place",
".",
"post_place_retreat",
".",
"desired_distance",
"=",
"self",
".",
"_approach_retreat_desired_dist",
"place",
".",
"post_place_retreat",
".",
"min_distance",
"=",
"self",
".",
"_approach_retreat_min_dist",
"place",
".",
"post_place_retreat",
".",
"direction",
".",
"vector",
".",
"x",
"=",
"0",
"place",
".",
"post_place_retreat",
".",
"direction",
".",
"vector",
".",
"y",
"=",
"0",
"place",
".",
"post_place_retreat",
".",
"direction",
".",
"vector",
".",
"z",
"=",
"1",
"# Add place:",
"places",
".",
"append",
"(",
"place",
")",
"# Publish places (for debugging/visualization purposes):",
"self",
".",
"_publish_places",
"(",
"places",
")",
"return",
"places"
] | https://github.com/qboticslabs/mastering_ros/blob/d83e78f30acc45b0f18522c1d5fae3a7f52974b9/chapter_3_codes/seven_dof_arm_gazebo/scripts/pick_and_place_working_1.py#L191-L243 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBDebugger.SetCurrentPlatform | (self, *args) | return _lldb.SBDebugger_SetCurrentPlatform(self, *args) | SetCurrentPlatform(self, str platform_name) -> SBError | SetCurrentPlatform(self, str platform_name) -> SBError | [
"SetCurrentPlatform",
"(",
"self",
"str",
"platform_name",
")",
"-",
">",
"SBError"
] | def SetCurrentPlatform(self, *args):
"""SetCurrentPlatform(self, str platform_name) -> SBError"""
return _lldb.SBDebugger_SetCurrentPlatform(self, *args) | [
"def",
"SetCurrentPlatform",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_SetCurrentPlatform",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3334-L3336 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/dist.py | python | Distribution.reinitialize_command | (self, command, reinit_subcommands=0) | return command | Reinitializes a command to the state it was in when first
returned by 'get_command_obj()': ie., initialized but not yet
finalized. This provides the opportunity to sneak option
values in programmatically, overriding or supplementing
user-supplied values from the config files and command line.
You'll have to re-finalize the command object (by calling
'finalize_options()' or 'ensure_finalized()') before using it for
real.
'command' should be a command name (string) or command object. If
'reinit_subcommands' is true, also reinitializes the command's
sub-commands, as declared by the 'sub_commands' class attribute (if
it has one). See the "install" command for an example. Only
reinitializes the sub-commands that actually matter, ie. those
whose test predicates return true.
Returns the reinitialized command object. | Reinitializes a command to the state it was in when first
returned by 'get_command_obj()': ie., initialized but not yet
finalized. This provides the opportunity to sneak option
values in programmatically, overriding or supplementing
user-supplied values from the config files and command line.
You'll have to re-finalize the command object (by calling
'finalize_options()' or 'ensure_finalized()') before using it for
real. | [
"Reinitializes",
"a",
"command",
"to",
"the",
"state",
"it",
"was",
"in",
"when",
"first",
"returned",
"by",
"get_command_obj",
"()",
":",
"ie",
".",
"initialized",
"but",
"not",
"yet",
"finalized",
".",
"This",
"provides",
"the",
"opportunity",
"to",
"sneak",
"option",
"values",
"in",
"programmatically",
"overriding",
"or",
"supplementing",
"user",
"-",
"supplied",
"values",
"from",
"the",
"config",
"files",
"and",
"command",
"line",
".",
"You",
"ll",
"have",
"to",
"re",
"-",
"finalize",
"the",
"command",
"object",
"(",
"by",
"calling",
"finalize_options",
"()",
"or",
"ensure_finalized",
"()",
")",
"before",
"using",
"it",
"for",
"real",
"."
] | def reinitialize_command(self, command, reinit_subcommands=0):
"""Reinitializes a command to the state it was in when first
returned by 'get_command_obj()': ie., initialized but not yet
finalized. This provides the opportunity to sneak option
values in programmatically, overriding or supplementing
user-supplied values from the config files and command line.
You'll have to re-finalize the command object (by calling
'finalize_options()' or 'ensure_finalized()') before using it for
real.
'command' should be a command name (string) or command object. If
'reinit_subcommands' is true, also reinitializes the command's
sub-commands, as declared by the 'sub_commands' class attribute (if
it has one). See the "install" command for an example. Only
reinitializes the sub-commands that actually matter, ie. those
whose test predicates return true.
Returns the reinitialized command object.
"""
from distutils.cmd import Command
if not isinstance(command, Command):
command_name = command
command = self.get_command_obj(command_name)
else:
command_name = command.get_command_name()
if not command.finalized:
return command
command.initialize_options()
command.finalized = 0
self.have_run[command_name] = 0
self._set_command_options(command)
if reinit_subcommands:
for sub in command.get_sub_commands():
self.reinitialize_command(sub, reinit_subcommands)
return command | [
"def",
"reinitialize_command",
"(",
"self",
",",
"command",
",",
"reinit_subcommands",
"=",
"0",
")",
":",
"from",
"distutils",
".",
"cmd",
"import",
"Command",
"if",
"not",
"isinstance",
"(",
"command",
",",
"Command",
")",
":",
"command_name",
"=",
"command",
"command",
"=",
"self",
".",
"get_command_obj",
"(",
"command_name",
")",
"else",
":",
"command_name",
"=",
"command",
".",
"get_command_name",
"(",
")",
"if",
"not",
"command",
".",
"finalized",
":",
"return",
"command",
"command",
".",
"initialize_options",
"(",
")",
"command",
".",
"finalized",
"=",
"0",
"self",
".",
"have_run",
"[",
"command_name",
"]",
"=",
"0",
"self",
".",
"_set_command_options",
"(",
"command",
")",
"if",
"reinit_subcommands",
":",
"for",
"sub",
"in",
"command",
".",
"get_sub_commands",
"(",
")",
":",
"self",
".",
"reinitialize_command",
"(",
"sub",
",",
"reinit_subcommands",
")",
"return",
"command"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/dist.py#L916-L953 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_cmdbar.py | python | PopupList.ActivateParent | (self) | Activate the parent window
@postcondition: parent window is raised | Activate the parent window
@postcondition: parent window is raised | [
"Activate",
"the",
"parent",
"window",
"@postcondition",
":",
"parent",
"window",
"is",
"raised"
] | def ActivateParent(self):
"""Activate the parent window
@postcondition: parent window is raised
"""
parent = self.GetParent()
parent.Raise()
parent.SetFocus() | [
"def",
"ActivateParent",
"(",
"self",
")",
":",
"parent",
"=",
"self",
".",
"GetParent",
"(",
")",
"parent",
".",
"Raise",
"(",
")",
"parent",
".",
"SetFocus",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_cmdbar.py#L1152-L1159 | ||
mysql/mysql-router | cc0179f982bb9739a834eb6fd205a56224616133 | ext/gmock/scripts/generator/cpp/ast.py | python | Node.IsDefinition | (self) | return False | Returns bool if this node is a definition. | Returns bool if this node is a definition. | [
"Returns",
"bool",
"if",
"this",
"node",
"is",
"a",
"definition",
"."
] | def IsDefinition(self):
"""Returns bool if this node is a definition."""
return False | [
"def",
"IsDefinition",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/mysql/mysql-router/blob/cc0179f982bb9739a834eb6fd205a56224616133/ext/gmock/scripts/generator/cpp/ast.py#L119-L121 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/ltisys.py | python | lti.__new__ | (cls, *system) | return super(lti, cls).__new__(cls) | Create an instance of the appropriate subclass. | Create an instance of the appropriate subclass. | [
"Create",
"an",
"instance",
"of",
"the",
"appropriate",
"subclass",
"."
] | def __new__(cls, *system):
"""Create an instance of the appropriate subclass."""
if cls is lti:
N = len(system)
if N == 2:
return TransferFunctionContinuous.__new__(
TransferFunctionContinuous, *system)
elif N == 3:
return ZerosPolesGainContinuous.__new__(
ZerosPolesGainContinuous, *system)
elif N == 4:
return StateSpaceContinuous.__new__(StateSpaceContinuous,
*system)
else:
raise ValueError("`system` needs to be an instance of `lti` "
"or have 2, 3 or 4 arguments.")
# __new__ was called from a subclass, let it call its own functions
return super(lti, cls).__new__(cls) | [
"def",
"__new__",
"(",
"cls",
",",
"*",
"system",
")",
":",
"if",
"cls",
"is",
"lti",
":",
"N",
"=",
"len",
"(",
"system",
")",
"if",
"N",
"==",
"2",
":",
"return",
"TransferFunctionContinuous",
".",
"__new__",
"(",
"TransferFunctionContinuous",
",",
"*",
"system",
")",
"elif",
"N",
"==",
"3",
":",
"return",
"ZerosPolesGainContinuous",
".",
"__new__",
"(",
"ZerosPolesGainContinuous",
",",
"*",
"system",
")",
"elif",
"N",
"==",
"4",
":",
"return",
"StateSpaceContinuous",
".",
"__new__",
"(",
"StateSpaceContinuous",
",",
"*",
"system",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"`system` needs to be an instance of `lti` \"",
"\"or have 2, 3 or 4 arguments.\"",
")",
"# __new__ was called from a subclass, let it call its own functions",
"return",
"super",
"(",
"lti",
",",
"cls",
")",
".",
"__new__",
"(",
"cls",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L204-L221 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/recommender/util.py | python | precision_recall_by_user | (observed_user_items, recommendations, cutoffs=[10]) | return sf.sort([user_id, "cutoff"]) | Compute precision and recall at a given cutoff for each user. In information
retrieval terms, precision represents the ratio of relevant, retrieved items
to the number of relevant items. Recall represents the ratio of relevant,
retrieved items to the number of relevant items.
Let :math:`p_k` be a vector of the first :math:`k` elements in the
recommendations for a particular user, and let :math:`a` be the set of items
in ``observed_user_items`` for that user. The "precision at cutoff k" for
this user is defined as
.. math::
P(k) = \\frac{ | a \cap p_k | }{k},
while "recall at cutoff k" is defined as
.. math::
R(k) = \\frac{ | a \cap p_k | }{|a|}
The order of the elements in the recommendations affects the returned
precision and recall scores.
Parameters
----------
observed_user_items : SFrame
An SFrame containing observed user item pairs, where the first
column contains user ids and the second column contains item ids.
recommendations : SFrame
An SFrame containing columns pertaining to the user id, the item id,
the score given to that pair, and the rank of that item among the
recommendations made for user id. For example, see the output of
recommend() produced by any turicreate.recommender model.
cutoffs : list[int], optional
The cutoffs to use when computing precision and recall.
Returns
-------
out : SFrame
An SFrame containing columns user id, cutoff, precision, recall, and
count where the precision and recall are reported for each user at
each requested cutoff, and count is the number of observations for
that user id.
Notes
-----
The corner cases that involve empty lists were chosen to be consistent
with the feasible set of precision-recall curves, which start at
(precision, recall) = (1,0) and end at (0,1). However, we do not believe
there is a well-known consensus on this choice.
Examples
--------
Given SFrames ``train_data`` and ``test_data`` with columns user_id
and item_id:
>>> from turicreate.toolkits.recommender.util import precision_recall_by_user
>>> m = turicreate.recommender.create(train_data)
>>> recs = m.recommend()
>>> precision_recall_by_user(test_data, recs, cutoffs=[5, 10]) | Compute precision and recall at a given cutoff for each user. In information
retrieval terms, precision represents the ratio of relevant, retrieved items
to the number of relevant items. Recall represents the ratio of relevant,
retrieved items to the number of relevant items. | [
"Compute",
"precision",
"and",
"recall",
"at",
"a",
"given",
"cutoff",
"for",
"each",
"user",
".",
"In",
"information",
"retrieval",
"terms",
"precision",
"represents",
"the",
"ratio",
"of",
"relevant",
"retrieved",
"items",
"to",
"the",
"number",
"of",
"relevant",
"items",
".",
"Recall",
"represents",
"the",
"ratio",
"of",
"relevant",
"retrieved",
"items",
"to",
"the",
"number",
"of",
"relevant",
"items",
"."
] | def precision_recall_by_user(observed_user_items, recommendations, cutoffs=[10]):
"""
Compute precision and recall at a given cutoff for each user. In information
retrieval terms, precision represents the ratio of relevant, retrieved items
to the number of relevant items. Recall represents the ratio of relevant,
retrieved items to the number of relevant items.
Let :math:`p_k` be a vector of the first :math:`k` elements in the
recommendations for a particular user, and let :math:`a` be the set of items
in ``observed_user_items`` for that user. The "precision at cutoff k" for
this user is defined as
.. math::
P(k) = \\frac{ | a \cap p_k | }{k},
while "recall at cutoff k" is defined as
.. math::
R(k) = \\frac{ | a \cap p_k | }{|a|}
The order of the elements in the recommendations affects the returned
precision and recall scores.
Parameters
----------
observed_user_items : SFrame
An SFrame containing observed user item pairs, where the first
column contains user ids and the second column contains item ids.
recommendations : SFrame
An SFrame containing columns pertaining to the user id, the item id,
the score given to that pair, and the rank of that item among the
recommendations made for user id. For example, see the output of
recommend() produced by any turicreate.recommender model.
cutoffs : list[int], optional
The cutoffs to use when computing precision and recall.
Returns
-------
out : SFrame
An SFrame containing columns user id, cutoff, precision, recall, and
count where the precision and recall are reported for each user at
each requested cutoff, and count is the number of observations for
that user id.
Notes
-----
The corner cases that involve empty lists were chosen to be consistent
with the feasible set of precision-recall curves, which start at
(precision, recall) = (1,0) and end at (0,1). However, we do not believe
there is a well-known consensus on this choice.
Examples
--------
Given SFrames ``train_data`` and ``test_data`` with columns user_id
and item_id:
>>> from turicreate.toolkits.recommender.util import precision_recall_by_user
>>> m = turicreate.recommender.create(train_data)
>>> recs = m.recommend()
>>> precision_recall_by_user(test_data, recs, cutoffs=[5, 10])
"""
assert type(observed_user_items) == _SFrame
assert type(recommendations) == _SFrame
assert type(cutoffs) == list
assert min(cutoffs) > 0, "All cutoffs must be positive integers."
assert recommendations.num_columns() >= 2
user_id = recommendations.column_names()[0]
item_id = recommendations.column_names()[1]
assert observed_user_items.num_rows() > 0, (
"Evaluating precision and recall requires a non-empty " + "observed_user_items."
)
assert (
user_id in observed_user_items.column_names()
), "User column required in observed_user_items."
assert (
item_id in observed_user_items.column_names()
), "Item column required in observed_user_items."
assert (
observed_user_items[user_id].dtype == recommendations[user_id].dtype
), "The user column in the two provided SFrames must have the same type."
assert (
observed_user_items[item_id].dtype == recommendations[item_id].dtype
), "The user column in the two provided SFrames must have the same type."
cutoffs = _array.array("f", cutoffs)
opts = {
"data": observed_user_items,
"recommendations": recommendations,
"cutoffs": cutoffs,
}
response = _turicreate.toolkits._main.run(
"evaluation_precision_recall_by_user", opts
)
sf = _SFrame(None, _proxy=response["pr"])
return sf.sort([user_id, "cutoff"]) | [
"def",
"precision_recall_by_user",
"(",
"observed_user_items",
",",
"recommendations",
",",
"cutoffs",
"=",
"[",
"10",
"]",
")",
":",
"assert",
"type",
"(",
"observed_user_items",
")",
"==",
"_SFrame",
"assert",
"type",
"(",
"recommendations",
")",
"==",
"_SFrame",
"assert",
"type",
"(",
"cutoffs",
")",
"==",
"list",
"assert",
"min",
"(",
"cutoffs",
")",
">",
"0",
",",
"\"All cutoffs must be positive integers.\"",
"assert",
"recommendations",
".",
"num_columns",
"(",
")",
">=",
"2",
"user_id",
"=",
"recommendations",
".",
"column_names",
"(",
")",
"[",
"0",
"]",
"item_id",
"=",
"recommendations",
".",
"column_names",
"(",
")",
"[",
"1",
"]",
"assert",
"observed_user_items",
".",
"num_rows",
"(",
")",
">",
"0",
",",
"(",
"\"Evaluating precision and recall requires a non-empty \"",
"+",
"\"observed_user_items.\"",
")",
"assert",
"(",
"user_id",
"in",
"observed_user_items",
".",
"column_names",
"(",
")",
")",
",",
"\"User column required in observed_user_items.\"",
"assert",
"(",
"item_id",
"in",
"observed_user_items",
".",
"column_names",
"(",
")",
")",
",",
"\"Item column required in observed_user_items.\"",
"assert",
"(",
"observed_user_items",
"[",
"user_id",
"]",
".",
"dtype",
"==",
"recommendations",
"[",
"user_id",
"]",
".",
"dtype",
")",
",",
"\"The user column in the two provided SFrames must have the same type.\"",
"assert",
"(",
"observed_user_items",
"[",
"item_id",
"]",
".",
"dtype",
"==",
"recommendations",
"[",
"item_id",
"]",
".",
"dtype",
")",
",",
"\"The user column in the two provided SFrames must have the same type.\"",
"cutoffs",
"=",
"_array",
".",
"array",
"(",
"\"f\"",
",",
"cutoffs",
")",
"opts",
"=",
"{",
"\"data\"",
":",
"observed_user_items",
",",
"\"recommendations\"",
":",
"recommendations",
",",
"\"cutoffs\"",
":",
"cutoffs",
",",
"}",
"response",
"=",
"_turicreate",
".",
"toolkits",
".",
"_main",
".",
"run",
"(",
"\"evaluation_precision_recall_by_user\"",
",",
"opts",
")",
"sf",
"=",
"_SFrame",
"(",
"None",
",",
"_proxy",
"=",
"response",
"[",
"\"pr\"",
"]",
")",
"return",
"sf",
".",
"sort",
"(",
"[",
"user_id",
",",
"\"cutoff\"",
"]",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/recommender/util.py#L357-L457 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/MythTV/mythproto.py | python | findfile | (filename, sgroup, db=None) | return None | findfile(filename, sgroup, db=None) -> StorageGroup object
Will search through all matching storage groups, searching for file.
Returns matching storage group upon success. | findfile(filename, sgroup, db=None) -> StorageGroup object | [
"findfile",
"(",
"filename",
"sgroup",
"db",
"=",
"None",
")",
"-",
">",
"StorageGroup",
"object"
] | def findfile(filename, sgroup, db=None):
"""
findfile(filename, sgroup, db=None) -> StorageGroup object
Will search through all matching storage groups, searching for file.
Returns matching storage group upon success.
"""
db = DBCache(db)
for sg in db.getStorageGroup(groupname=sgroup):
# search given group
if sg.local:
if os.access(os.path.join(sg.dirname, filename), os.F_OK):
return sg
for sg in db.getStorageGroup():
# not found, search all other groups
if sg.local:
if os.access(os.path.join(sg.dirname, filename), os.F_OK):
return sg
return None | [
"def",
"findfile",
"(",
"filename",
",",
"sgroup",
",",
"db",
"=",
"None",
")",
":",
"db",
"=",
"DBCache",
"(",
"db",
")",
"for",
"sg",
"in",
"db",
".",
"getStorageGroup",
"(",
"groupname",
"=",
"sgroup",
")",
":",
"# search given group",
"if",
"sg",
".",
"local",
":",
"if",
"os",
".",
"access",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sg",
".",
"dirname",
",",
"filename",
")",
",",
"os",
".",
"F_OK",
")",
":",
"return",
"sg",
"for",
"sg",
"in",
"db",
".",
"getStorageGroup",
"(",
")",
":",
"# not found, search all other groups",
"if",
"sg",
".",
"local",
":",
"if",
"os",
".",
"access",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sg",
".",
"dirname",
",",
"filename",
")",
",",
"os",
".",
"F_OK",
")",
":",
"return",
"sg",
"return",
"None"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/mythproto.py#L175-L193 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/ML/Cluster/Standardize.py | python | StdDev | (mat) | return Stats.StandardizeMatrix(mat) | the standard deviation classifier
This uses _ML.Data.Stats.StandardizeMatrix()_ to do the work | the standard deviation classifier | [
"the",
"standard",
"deviation",
"classifier"
] | def StdDev(mat):
""" the standard deviation classifier
This uses _ML.Data.Stats.StandardizeMatrix()_ to do the work
"""
return Stats.StandardizeMatrix(mat) | [
"def",
"StdDev",
"(",
"mat",
")",
":",
"return",
"Stats",
".",
"StandardizeMatrix",
"(",
"mat",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/Cluster/Standardize.py#L18-L24 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchPanel.py | python | makePanelSheet | (panels=[],name="PanelSheet") | return sheet | makePanelSheet([panels]) : Creates a sheet with the given panel cuts
in the 3D space, positioned at the origin. | makePanelSheet([panels]) : Creates a sheet with the given panel cuts
in the 3D space, positioned at the origin. | [
"makePanelSheet",
"(",
"[",
"panels",
"]",
")",
":",
"Creates",
"a",
"sheet",
"with",
"the",
"given",
"panel",
"cuts",
"in",
"the",
"3D",
"space",
"positioned",
"at",
"the",
"origin",
"."
] | def makePanelSheet(panels=[],name="PanelSheet"):
"""makePanelSheet([panels]) : Creates a sheet with the given panel cuts
in the 3D space, positioned at the origin."""
sheet = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name)
PanelSheet(sheet)
if panels:
sheet.Group = panels
if FreeCAD.GuiUp:
ViewProviderPanelSheet(sheet.ViewObject)
return sheet | [
"def",
"makePanelSheet",
"(",
"panels",
"=",
"[",
"]",
",",
"name",
"=",
"\"PanelSheet\"",
")",
":",
"sheet",
"=",
"FreeCAD",
".",
"ActiveDocument",
".",
"addObject",
"(",
"\"Part::FeaturePython\"",
",",
"name",
")",
"PanelSheet",
"(",
"sheet",
")",
"if",
"panels",
":",
"sheet",
".",
"Group",
"=",
"panels",
"if",
"FreeCAD",
".",
"GuiUp",
":",
"ViewProviderPanelSheet",
"(",
"sheet",
".",
"ViewObject",
")",
"return",
"sheet"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchPanel.py#L127-L138 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py | python | CodeWarrior_suite_Events.run_target | (self, _no_object=None, _attributes={}, **_arguments) | run target: run a project or target
Keyword argument _attributes: AppleEvent attribute dictionary | run target: run a project or target
Keyword argument _attributes: AppleEvent attribute dictionary | [
"run",
"target",
":",
"run",
"a",
"project",
"or",
"target",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary"
] | def run_target(self, _no_object=None, _attributes={}, **_arguments):
"""run target: run a project or target
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'CWIE'
_subcode = 'RUN '
if _arguments: raise TypeError, 'No optional args expected'
if _no_object is not None: raise TypeError, 'No direct arg expected'
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"run_target",
"(",
"self",
",",
"_no_object",
"=",
"None",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'CWIE'",
"_subcode",
"=",
"'RUN '",
"if",
"_arguments",
":",
"raise",
"TypeError",
",",
"'No optional args expected'",
"if",
"_no_object",
"is",
"not",
"None",
":",
"raise",
"TypeError",
",",
"'No direct arg expected'",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py#L188-L205 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Scale.identify | (self, x, y) | return self.tk.call(self._w, 'identify', x, y) | Return where the point X,Y lies. Valid return values are "slider",
"though1" and "though2". | Return where the point X,Y lies. Valid return values are "slider",
"though1" and "though2". | [
"Return",
"where",
"the",
"point",
"X",
"Y",
"lies",
".",
"Valid",
"return",
"values",
"are",
"slider",
"though1",
"and",
"though2",
"."
] | def identify(self, x, y):
"""Return where the point X,Y lies. Valid return values are "slider",
"though1" and "though2"."""
return self.tk.call(self._w, 'identify', x, y) | [
"def",
"identify",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'identify'",
",",
"x",
",",
"y",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3027-L3030 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/cr/cr/visitor.py | python | Visitor.root_node | (self) | return self.stack[0] | Returns the variable at the root of the current traversal. | Returns the variable at the root of the current traversal. | [
"Returns",
"the",
"variable",
"at",
"the",
"root",
"of",
"the",
"current",
"traversal",
"."
] | def root_node(self):
"""Returns the variable at the root of the current traversal."""
return self.stack[0] | [
"def",
"root_node",
"(",
"self",
")",
":",
"return",
"self",
".",
"stack",
"[",
"0",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cr/cr/visitor.py#L64-L66 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Tools/CryVersionSelector/cryselect.py | python | error_engine_not_found | (args) | Error to specify that the .cryengine file couldn't be found. | Error to specify that the .cryengine file couldn't be found. | [
"Error",
"to",
"specify",
"that",
"the",
".",
"cryengine",
"file",
"couldn",
"t",
"be",
"found",
"."
] | def error_engine_not_found(args):
"""
Error to specify that the .cryengine file couldn't be found.
"""
message = "'{}' not found.\n".format(args.engine_file)
if not args.silent and HAS_WIN_MODULES:
MESSAGEBOX(None, message, command_title(args),
win32con.MB_OK | win32con.MB_ICONERROR)
else:
sys.stderr.write(message)
sys.exit(600) | [
"def",
"error_engine_not_found",
"(",
"args",
")",
":",
"message",
"=",
"\"'{}' not found.\\n\"",
".",
"format",
"(",
"args",
".",
"engine_file",
")",
"if",
"not",
"args",
".",
"silent",
"and",
"HAS_WIN_MODULES",
":",
"MESSAGEBOX",
"(",
"None",
",",
"message",
",",
"command_title",
"(",
"args",
")",
",",
"win32con",
".",
"MB_OK",
"|",
"win32con",
".",
"MB_ICONERROR",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
")",
"sys",
".",
"exit",
"(",
"600",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Tools/CryVersionSelector/cryselect.py#L87-L97 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction/command_interface.py | python | ReductionSingleton.__init__ | (self) | Create singleton instance | Create singleton instance | [
"Create",
"singleton",
"instance"
] | def __init__(self):
""" Create singleton instance """
# Check whether we already have an instance
if ReductionSingleton.__instance is None:
# Create and remember instance
ReductionSingleton.__instance = Reducer()
# Store instance reference as the only member in the handle
self.__dict__['_ReductionSingleton__instance'] = ReductionSingleton.__instance | [
"def",
"__init__",
"(",
"self",
")",
":",
"# Check whether we already have an instance",
"if",
"ReductionSingleton",
".",
"__instance",
"is",
"None",
":",
"# Create and remember instance",
"ReductionSingleton",
".",
"__instance",
"=",
"Reducer",
"(",
")",
"# Store instance reference as the only member in the handle",
"self",
".",
"__dict__",
"[",
"'_ReductionSingleton__instance'",
"]",
"=",
"ReductionSingleton",
".",
"__instance"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction/command_interface.py#L20-L28 | ||
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/tomviz/io/ser.py | python | FileSER.readHeader | (self, verbose=False) | return head | Read and return the SER files header.
Parameters
----------
verbose: bool
True to get extensive output while reading the file.
Returns
-------
: dict
The header of the SER file as dict. | Read and return the SER files header. | [
"Read",
"and",
"return",
"the",
"SER",
"files",
"header",
"."
] | def readHeader(self, verbose=False): # noqa: C901
"""Read and return the SER files header.
Parameters
----------
verbose: bool
True to get extensive output while reading the file.
Returns
-------
: dict
The header of the SER file as dict.
"""
# prepare empty dict to be populated while reading
head = {}
# go back to beginning of file
self._file_hdl.seek(0, 0)
# read 3 int16
data = np.fromfile(self._file_hdl, dtype='<i2', count=3)
# ByteOrder (only little Endian expected)
if not data[0] in self._dictByteOrder:
raise RuntimeError('Only little Endian implemented for SER files')
head['ByteOrder'] = data[0]
# SeriesID, check whether TIA Series Data File
if not data[1] == 0x0197:
raise NotSERError('This is not a TIA Series Data File (SER)')
head['SeriesID'] = data[1]
if verbose:
print('SeriesID:\t"{:#06x},\tTIA Series Data File'.format(data[1]))
# SeriesVersion
if not data[2] in self._dictSeriesVersion:
raise RuntimeError('Unknown TIA version: "{:#06x}"'.format(data[2]))
head['SeriesVersion'] = data[2]
# version dependent file format for below
if head['SeriesVersion'] == 0x0210:
offset_dtype = '<i4'
else:
# head['SeriesVersion']==0x220:
offset_dtype = '<i8'
# read 4 int32
data = np.fromfile(self._file_hdl, dtype='<i4', count=4)
# DataTypeID
if not data[0] in self._dictDataTypeID:
raise RuntimeError('Unknown DataTypeID: "{:#06x}"'.format(data[0]))
head['DataTypeID'] = data[0]
# TagTypeID
if not data[1] in self._dictTagTypeID:
raise RuntimeError('Unknown TagTypeID: "{:#06x}"'.format(data[1]))
head['TagTypeID'] = data[1]
# TotalNumberElements
if not data[2] >= 0:
raise RuntimeError('Negative total number \
of elements: {}'.format(data[2]))
head['TotalNumberElements'] = data[2]
if verbose:
print('TotalNumberElements:\t{}'.format(data[2]))
# ValidNumberElements
if not data[3] >= 0:
raise RuntimeError('Negative valid number \
of elements: {}'.format(data[3]))
head['ValidNumberElements'] = data[3]
if verbose:
print('ValidNumberElements:\t{}'.format(data[3]))
# OffsetArrayOffset, sensitive to SeriesVersion
data = np.fromfile(self._file_hdl, dtype=offset_dtype, count=1)
head['OffsetArrayOffset'] = data[0]
if verbose:
print('OffsetArrayOffset:\t{}'.format(data[0]))
# NumberDimensions
data = np.fromfile(self._file_hdl, dtype='<i4', count=1)
if not data[0] >= 0:
raise RuntimeError('Negative number of dimensions')
head['NumberDimensions'] = data[0]
if verbose:
print('NumberDimensions:\t{}'.format(data[0]))
# Dimensions array
dimensions = []
for i in range(head['NumberDimensions']):
if verbose:
print('reading Dimension {}'.format(i))
this_dim = {}
# DimensionSize
data = np.fromfile(self._file_hdl, dtype='<i4', count=1)
this_dim['DimensionSize'] = data[0]
if verbose:
print('DimensionSize:\t{}'.format(data[0]))
data = np.fromfile(self._file_hdl, dtype='<f8', count=2)
# CalibrationOffset
this_dim['CalibrationOffset'] = data[0]
if verbose:
print('CalibrationOffset:\t{}'.format(data[0]))
# CalibrationDelta
this_dim['CalibrationDelta'] = data[1]
if verbose:
print('CalibrationDelta:\t{}'.format(data[1]))
data = np.fromfile(self._file_hdl, dtype='<i4', count=2)
# CalibrationElement
this_dim['CalibrationElement'] = data[0]
if verbose:
print('CalibrationElement:\t{}'.format(data[0]))
# DescriptionLength
n = data[1]
# Description
data = np.fromfile(self._file_hdl, dtype='<i1', count=n)
data = ''.join(map(chr, data))
this_dim['Description'] = data
if verbose:
print('Description:\t{}'.format(data))
# UnitsLength
data = np.fromfile(self._file_hdl, dtype='<i4', count=1)
n = data[0]
# Units
data = np.fromfile(self._file_hdl, dtype='<i1', count=n)
data = ''.join(map(chr, data))
this_dim['Units'] = data
if verbose:
print('Units:\t{}'.format(data))
dimensions.append(this_dim)
# save dimensions array as tuple of dicts in head dict
head['Dimensions'] = tuple(dimensions)
# Offset array
self._file_hdl.seek(head['OffsetArrayOffset'], 0)
# DataOffsetArray
data = np.fromfile(self._file_hdl, dtype=offset_dtype,
count=head['ValidNumberElements'])
head['DataOffsetArray'] = data.tolist()
if verbose:
print('reading in DataOffsetArray')
# TagOffsetArray
data = np.fromfile(self._file_hdl, dtype=offset_dtype,
count=head['ValidNumberElements'])
head['TagOffsetArray'] = data.tolist()
if verbose:
print('reading in TagOffsetArray')
return head | [
"def",
"readHeader",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"# noqa: C901",
"# prepare empty dict to be populated while reading",
"head",
"=",
"{",
"}",
"# go back to beginning of file",
"self",
".",
"_file_hdl",
".",
"seek",
"(",
"0",
",",
"0",
")",
"# read 3 int16",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<i2'",
",",
"count",
"=",
"3",
")",
"# ByteOrder (only little Endian expected)",
"if",
"not",
"data",
"[",
"0",
"]",
"in",
"self",
".",
"_dictByteOrder",
":",
"raise",
"RuntimeError",
"(",
"'Only little Endian implemented for SER files'",
")",
"head",
"[",
"'ByteOrder'",
"]",
"=",
"data",
"[",
"0",
"]",
"# SeriesID, check whether TIA Series Data File",
"if",
"not",
"data",
"[",
"1",
"]",
"==",
"0x0197",
":",
"raise",
"NotSERError",
"(",
"'This is not a TIA Series Data File (SER)'",
")",
"head",
"[",
"'SeriesID'",
"]",
"=",
"data",
"[",
"1",
"]",
"if",
"verbose",
":",
"print",
"(",
"'SeriesID:\\t\"{:#06x},\\tTIA Series Data File'",
".",
"format",
"(",
"data",
"[",
"1",
"]",
")",
")",
"# SeriesVersion",
"if",
"not",
"data",
"[",
"2",
"]",
"in",
"self",
".",
"_dictSeriesVersion",
":",
"raise",
"RuntimeError",
"(",
"'Unknown TIA version: \"{:#06x}\"'",
".",
"format",
"(",
"data",
"[",
"2",
"]",
")",
")",
"head",
"[",
"'SeriesVersion'",
"]",
"=",
"data",
"[",
"2",
"]",
"# version dependent file format for below",
"if",
"head",
"[",
"'SeriesVersion'",
"]",
"==",
"0x0210",
":",
"offset_dtype",
"=",
"'<i4'",
"else",
":",
"# head['SeriesVersion']==0x220:",
"offset_dtype",
"=",
"'<i8'",
"# read 4 int32",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<i4'",
",",
"count",
"=",
"4",
")",
"# DataTypeID",
"if",
"not",
"data",
"[",
"0",
"]",
"in",
"self",
".",
"_dictDataTypeID",
":",
"raise",
"RuntimeError",
"(",
"'Unknown DataTypeID: \"{:#06x}\"'",
".",
"format",
"(",
"data",
"[",
"0",
"]",
")",
")",
"head",
"[",
"'DataTypeID'",
"]",
"=",
"data",
"[",
"0",
"]",
"# TagTypeID",
"if",
"not",
"data",
"[",
"1",
"]",
"in",
"self",
".",
"_dictTagTypeID",
":",
"raise",
"RuntimeError",
"(",
"'Unknown TagTypeID: \"{:#06x}\"'",
".",
"format",
"(",
"data",
"[",
"1",
"]",
")",
")",
"head",
"[",
"'TagTypeID'",
"]",
"=",
"data",
"[",
"1",
"]",
"# TotalNumberElements",
"if",
"not",
"data",
"[",
"2",
"]",
">=",
"0",
":",
"raise",
"RuntimeError",
"(",
"'Negative total number \\\n of elements: {}'",
".",
"format",
"(",
"data",
"[",
"2",
"]",
")",
")",
"head",
"[",
"'TotalNumberElements'",
"]",
"=",
"data",
"[",
"2",
"]",
"if",
"verbose",
":",
"print",
"(",
"'TotalNumberElements:\\t{}'",
".",
"format",
"(",
"data",
"[",
"2",
"]",
")",
")",
"# ValidNumberElements",
"if",
"not",
"data",
"[",
"3",
"]",
">=",
"0",
":",
"raise",
"RuntimeError",
"(",
"'Negative valid number \\\n of elements: {}'",
".",
"format",
"(",
"data",
"[",
"3",
"]",
")",
")",
"head",
"[",
"'ValidNumberElements'",
"]",
"=",
"data",
"[",
"3",
"]",
"if",
"verbose",
":",
"print",
"(",
"'ValidNumberElements:\\t{}'",
".",
"format",
"(",
"data",
"[",
"3",
"]",
")",
")",
"# OffsetArrayOffset, sensitive to SeriesVersion",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"offset_dtype",
",",
"count",
"=",
"1",
")",
"head",
"[",
"'OffsetArrayOffset'",
"]",
"=",
"data",
"[",
"0",
"]",
"if",
"verbose",
":",
"print",
"(",
"'OffsetArrayOffset:\\t{}'",
".",
"format",
"(",
"data",
"[",
"0",
"]",
")",
")",
"# NumberDimensions",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<i4'",
",",
"count",
"=",
"1",
")",
"if",
"not",
"data",
"[",
"0",
"]",
">=",
"0",
":",
"raise",
"RuntimeError",
"(",
"'Negative number of dimensions'",
")",
"head",
"[",
"'NumberDimensions'",
"]",
"=",
"data",
"[",
"0",
"]",
"if",
"verbose",
":",
"print",
"(",
"'NumberDimensions:\\t{}'",
".",
"format",
"(",
"data",
"[",
"0",
"]",
")",
")",
"# Dimensions array",
"dimensions",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"head",
"[",
"'NumberDimensions'",
"]",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"'reading Dimension {}'",
".",
"format",
"(",
"i",
")",
")",
"this_dim",
"=",
"{",
"}",
"# DimensionSize",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<i4'",
",",
"count",
"=",
"1",
")",
"this_dim",
"[",
"'DimensionSize'",
"]",
"=",
"data",
"[",
"0",
"]",
"if",
"verbose",
":",
"print",
"(",
"'DimensionSize:\\t{}'",
".",
"format",
"(",
"data",
"[",
"0",
"]",
")",
")",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<f8'",
",",
"count",
"=",
"2",
")",
"# CalibrationOffset",
"this_dim",
"[",
"'CalibrationOffset'",
"]",
"=",
"data",
"[",
"0",
"]",
"if",
"verbose",
":",
"print",
"(",
"'CalibrationOffset:\\t{}'",
".",
"format",
"(",
"data",
"[",
"0",
"]",
")",
")",
"# CalibrationDelta",
"this_dim",
"[",
"'CalibrationDelta'",
"]",
"=",
"data",
"[",
"1",
"]",
"if",
"verbose",
":",
"print",
"(",
"'CalibrationDelta:\\t{}'",
".",
"format",
"(",
"data",
"[",
"1",
"]",
")",
")",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<i4'",
",",
"count",
"=",
"2",
")",
"# CalibrationElement",
"this_dim",
"[",
"'CalibrationElement'",
"]",
"=",
"data",
"[",
"0",
"]",
"if",
"verbose",
":",
"print",
"(",
"'CalibrationElement:\\t{}'",
".",
"format",
"(",
"data",
"[",
"0",
"]",
")",
")",
"# DescriptionLength",
"n",
"=",
"data",
"[",
"1",
"]",
"# Description",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<i1'",
",",
"count",
"=",
"n",
")",
"data",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"chr",
",",
"data",
")",
")",
"this_dim",
"[",
"'Description'",
"]",
"=",
"data",
"if",
"verbose",
":",
"print",
"(",
"'Description:\\t{}'",
".",
"format",
"(",
"data",
")",
")",
"# UnitsLength",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<i4'",
",",
"count",
"=",
"1",
")",
"n",
"=",
"data",
"[",
"0",
"]",
"# Units",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"'<i1'",
",",
"count",
"=",
"n",
")",
"data",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"chr",
",",
"data",
")",
")",
"this_dim",
"[",
"'Units'",
"]",
"=",
"data",
"if",
"verbose",
":",
"print",
"(",
"'Units:\\t{}'",
".",
"format",
"(",
"data",
")",
")",
"dimensions",
".",
"append",
"(",
"this_dim",
")",
"# save dimensions array as tuple of dicts in head dict",
"head",
"[",
"'Dimensions'",
"]",
"=",
"tuple",
"(",
"dimensions",
")",
"# Offset array",
"self",
".",
"_file_hdl",
".",
"seek",
"(",
"head",
"[",
"'OffsetArrayOffset'",
"]",
",",
"0",
")",
"# DataOffsetArray",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"offset_dtype",
",",
"count",
"=",
"head",
"[",
"'ValidNumberElements'",
"]",
")",
"head",
"[",
"'DataOffsetArray'",
"]",
"=",
"data",
".",
"tolist",
"(",
")",
"if",
"verbose",
":",
"print",
"(",
"'reading in DataOffsetArray'",
")",
"# TagOffsetArray",
"data",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"_file_hdl",
",",
"dtype",
"=",
"offset_dtype",
",",
"count",
"=",
"head",
"[",
"'ValidNumberElements'",
"]",
")",
"head",
"[",
"'TagOffsetArray'",
"]",
"=",
"data",
".",
"tolist",
"(",
")",
"if",
"verbose",
":",
"print",
"(",
"'reading in TagOffsetArray'",
")",
"return",
"head"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/io/ser.py#L162-L328 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py | python | _list_from_statespec | (stuple) | return [_flatten(spec) for spec in zip(it, it)] | Construct a list from the given statespec tuple according to the
accepted statespec accepted by _format_mapdict. | Construct a list from the given statespec tuple according to the
accepted statespec accepted by _format_mapdict. | [
"Construct",
"a",
"list",
"from",
"the",
"given",
"statespec",
"tuple",
"according",
"to",
"the",
"accepted",
"statespec",
"accepted",
"by",
"_format_mapdict",
"."
] | def _list_from_statespec(stuple):
"""Construct a list from the given statespec tuple according to the
accepted statespec accepted by _format_mapdict."""
nval = []
for val in stuple:
typename = getattr(val, 'typename', None)
if typename is None:
nval.append(val)
else: # this is a Tcl object
val = str(val)
if typename == 'StateSpec':
val = val.split()
nval.append(val)
it = iter(nval)
return [_flatten(spec) for spec in zip(it, it)] | [
"def",
"_list_from_statespec",
"(",
"stuple",
")",
":",
"nval",
"=",
"[",
"]",
"for",
"val",
"in",
"stuple",
":",
"typename",
"=",
"getattr",
"(",
"val",
",",
"'typename'",
",",
"None",
")",
"if",
"typename",
"is",
"None",
":",
"nval",
".",
"append",
"(",
"val",
")",
"else",
":",
"# this is a Tcl object",
"val",
"=",
"str",
"(",
"val",
")",
"if",
"typename",
"==",
"'StateSpec'",
":",
"val",
"=",
"val",
".",
"split",
"(",
")",
"nval",
".",
"append",
"(",
"val",
")",
"it",
"=",
"iter",
"(",
"nval",
")",
"return",
"[",
"_flatten",
"(",
"spec",
")",
"for",
"spec",
"in",
"zip",
"(",
"it",
",",
"it",
")",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py#L260-L275 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/help_about.py | python | build_bits | () | Return bits for platform. | Return bits for platform. | [
"Return",
"bits",
"for",
"platform",
"."
] | def build_bits():
"Return bits for platform."
if sys.platform == 'darwin':
return '64' if sys.maxsize > 2**32 else '32'
else:
return architecture()[0][:2] | [
"def",
"build_bits",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"return",
"'64'",
"if",
"sys",
".",
"maxsize",
">",
"2",
"**",
"32",
"else",
"'32'",
"else",
":",
"return",
"architecture",
"(",
")",
"[",
"0",
"]",
"[",
":",
"2",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/help_about.py#L14-L19 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Tools/MakeMacBundleRelocatable.py | python | DepsGraph.visit | (self, operation, op_args=[]) | Perform a depth first visit of the graph, calling operation
on each node. | Perform a depth first visit of the graph, calling operation
on each node. | [
"Perform",
"a",
"depth",
"first",
"visit",
"of",
"the",
"graph",
"calling",
"operation",
"on",
"each",
"node",
"."
] | def visit(self, operation, op_args=[]):
""""
Perform a depth first visit of the graph, calling operation
on each node.
"""
stack = []
for k in self.graph.keys():
self.graph[k]._marked = False
for k in self.graph.keys():
if not self.graph[k]._marked:
stack.append(k)
while stack:
node_key = stack.pop()
self.graph[node_key]._marked = True
for ck in self.graph[node_key].children:
if not self.graph[ck]._marked:
stack.append(ck)
operation(self, self.graph[node_key], *op_args) | [
"def",
"visit",
"(",
"self",
",",
"operation",
",",
"op_args",
"=",
"[",
"]",
")",
":",
"stack",
"=",
"[",
"]",
"for",
"k",
"in",
"self",
".",
"graph",
".",
"keys",
"(",
")",
":",
"self",
".",
"graph",
"[",
"k",
"]",
".",
"_marked",
"=",
"False",
"for",
"k",
"in",
"self",
".",
"graph",
".",
"keys",
"(",
")",
":",
"if",
"not",
"self",
".",
"graph",
"[",
"k",
"]",
".",
"_marked",
":",
"stack",
".",
"append",
"(",
"k",
")",
"while",
"stack",
":",
"node_key",
"=",
"stack",
".",
"pop",
"(",
")",
"self",
".",
"graph",
"[",
"node_key",
"]",
".",
"_marked",
"=",
"True",
"for",
"ck",
"in",
"self",
".",
"graph",
"[",
"node_key",
"]",
".",
"children",
":",
"if",
"not",
"self",
".",
"graph",
"[",
"ck",
"]",
".",
"_marked",
":",
"stack",
".",
"append",
"(",
"ck",
")",
"operation",
"(",
"self",
",",
"self",
".",
"graph",
"[",
"node_key",
"]",
",",
"*",
"op_args",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Tools/MakeMacBundleRelocatable.py#L64-L83 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset13.py | python | convert_logsoftmax | (node, **kwargs) | return [node] | Map MXNet's log_softmax operator attributes to onnx's LogSoftMax operator
and return the created node. | Map MXNet's log_softmax operator attributes to onnx's LogSoftMax operator
and return the created node. | [
"Map",
"MXNet",
"s",
"log_softmax",
"operator",
"attributes",
"to",
"onnx",
"s",
"LogSoftMax",
"operator",
"and",
"return",
"the",
"created",
"node",
"."
] | def convert_logsoftmax(node, **kwargs):
"""Map MXNet's log_softmax operator attributes to onnx's LogSoftMax operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to int
axis = int(attrs.get("axis", -1))
temp = attrs.get('temperature', 'None')
use_length = attrs.get('use_length', 'False')
if temp != 'None':
raise AttributeError('LogSoftMax currently does not support temperature!=None')
if use_length in ['1', 'True']:
raise AttributeError('LogSoftMax currently does not support use_length==True')
node = onnx.helper.make_node(
'LogSoftmax',
input_nodes,
[name],
axis=axis,
name=name
)
return [node] | [
"def",
"convert_logsoftmax",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"# Converting to int",
"axis",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"\"axis\"",
",",
"-",
"1",
")",
")",
"temp",
"=",
"attrs",
".",
"get",
"(",
"'temperature'",
",",
"'None'",
")",
"use_length",
"=",
"attrs",
".",
"get",
"(",
"'use_length'",
",",
"'False'",
")",
"if",
"temp",
"!=",
"'None'",
":",
"raise",
"AttributeError",
"(",
"'LogSoftMax currently does not support temperature!=None'",
")",
"if",
"use_length",
"in",
"[",
"'1'",
",",
"'True'",
"]",
":",
"raise",
"AttributeError",
"(",
"'LogSoftMax currently does not support use_length==True'",
")",
"node",
"=",
"onnx",
".",
"helper",
".",
"make_node",
"(",
"'LogSoftmax'",
",",
"input_nodes",
",",
"[",
"name",
"]",
",",
"axis",
"=",
"axis",
",",
"name",
"=",
"name",
")",
"return",
"[",
"node",
"]"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset13.py#L1769-L1794 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/xml/sax/_exceptions.py | python | SAXException.getMessage | (self) | return self._msg | Return a message for this exception. | Return a message for this exception. | [
"Return",
"a",
"message",
"for",
"this",
"exception",
"."
] | def getMessage(self):
"Return a message for this exception."
return self._msg | [
"def",
"getMessage",
"(",
"self",
")",
":",
"return",
"self",
".",
"_msg"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/xml/sax/_exceptions.py#L26-L28 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/importlib/__init__.py | python | reload | (module) | Reload the module and return it.
The module must have been successfully imported before. | Reload the module and return it. | [
"Reload",
"the",
"module",
"and",
"return",
"it",
"."
] | def reload(module):
"""Reload the module and return it.
The module must have been successfully imported before.
"""
if not module or not isinstance(module, types.ModuleType):
raise TypeError("reload() argument must be a module")
try:
name = module.__spec__.name
except AttributeError:
name = module.__name__
if sys.modules.get(name) is not module:
msg = "module {} not in sys.modules"
raise ImportError(msg.format(name), name=name)
if name in _RELOADING:
return _RELOADING[name]
_RELOADING[name] = module
try:
parent_name = name.rpartition('.')[0]
if parent_name:
try:
parent = sys.modules[parent_name]
except KeyError:
msg = "parent {!r} not in sys.modules"
raise ImportError(msg.format(parent_name),
name=parent_name) from None
else:
pkgpath = parent.__path__
else:
pkgpath = None
target = module
spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
if spec is None:
raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name)
_bootstrap._exec(spec, module)
# The module may have replaced itself in sys.modules!
return sys.modules[name]
finally:
try:
del _RELOADING[name]
except KeyError:
pass | [
"def",
"reload",
"(",
"module",
")",
":",
"if",
"not",
"module",
"or",
"not",
"isinstance",
"(",
"module",
",",
"types",
".",
"ModuleType",
")",
":",
"raise",
"TypeError",
"(",
"\"reload() argument must be a module\"",
")",
"try",
":",
"name",
"=",
"module",
".",
"__spec__",
".",
"name",
"except",
"AttributeError",
":",
"name",
"=",
"module",
".",
"__name__",
"if",
"sys",
".",
"modules",
".",
"get",
"(",
"name",
")",
"is",
"not",
"module",
":",
"msg",
"=",
"\"module {} not in sys.modules\"",
"raise",
"ImportError",
"(",
"msg",
".",
"format",
"(",
"name",
")",
",",
"name",
"=",
"name",
")",
"if",
"name",
"in",
"_RELOADING",
":",
"return",
"_RELOADING",
"[",
"name",
"]",
"_RELOADING",
"[",
"name",
"]",
"=",
"module",
"try",
":",
"parent_name",
"=",
"name",
".",
"rpartition",
"(",
"'.'",
")",
"[",
"0",
"]",
"if",
"parent_name",
":",
"try",
":",
"parent",
"=",
"sys",
".",
"modules",
"[",
"parent_name",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"\"parent {!r} not in sys.modules\"",
"raise",
"ImportError",
"(",
"msg",
".",
"format",
"(",
"parent_name",
")",
",",
"name",
"=",
"parent_name",
")",
"from",
"None",
"else",
":",
"pkgpath",
"=",
"parent",
".",
"__path__",
"else",
":",
"pkgpath",
"=",
"None",
"target",
"=",
"module",
"spec",
"=",
"module",
".",
"__spec__",
"=",
"_bootstrap",
".",
"_find_spec",
"(",
"name",
",",
"pkgpath",
",",
"target",
")",
"if",
"spec",
"is",
"None",
":",
"raise",
"ModuleNotFoundError",
"(",
"f\"spec not found for the module {name!r}\"",
",",
"name",
"=",
"name",
")",
"_bootstrap",
".",
"_exec",
"(",
"spec",
",",
"module",
")",
"# The module may have replaced itself in sys.modules!",
"return",
"sys",
".",
"modules",
"[",
"name",
"]",
"finally",
":",
"try",
":",
"del",
"_RELOADING",
"[",
"name",
"]",
"except",
"KeyError",
":",
"pass"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/__init__.py#L133-L176 | ||
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/core/tensor.py | python | Tensor.__call__ | (self, *args, **kwargs) | return self.PrintExpressions() | Print the expressions.
Returns
-------
None | Print the expressions. | [
"Print",
"the",
"expressions",
"."
] | def __call__(self, *args, **kwargs):
"""Print the expressions.
Returns
-------
None
"""
return self.PrintExpressions() | [
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"PrintExpressions",
"(",
")"
] | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/core/tensor.py#L679-L687 | |
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/tree.py | python | RewriteRuleSubtreeStream.nextNode | (self) | return el | Treat next element as a single node even if it's a subtree.
This is used instead of next() when the result has to be a
tree root node. Also prevents us from duplicating recently-added
children; e.g., ^(type ID)+ adds ID to type and then 2nd iteration
must dup the type node, but ID has been added.
Referencing a rule result twice is ok; dup entire tree as
we can't be adding trees as root; e.g., expr expr.
Hideous code duplication here with super.next(). Can't think of
a proper way to refactor. This needs to always call dup node
and super.next() doesn't know which to call: dup node or dup tree. | Treat next element as a single node even if it's a subtree.
This is used instead of next() when the result has to be a
tree root node. Also prevents us from duplicating recently-added
children; e.g., ^(type ID)+ adds ID to type and then 2nd iteration
must dup the type node, but ID has been added. | [
"Treat",
"next",
"element",
"as",
"a",
"single",
"node",
"even",
"if",
"it",
"s",
"a",
"subtree",
".",
"This",
"is",
"used",
"instead",
"of",
"next",
"()",
"when",
"the",
"result",
"has",
"to",
"be",
"a",
"tree",
"root",
"node",
".",
"Also",
"prevents",
"us",
"from",
"duplicating",
"recently",
"-",
"added",
"children",
";",
"e",
".",
"g",
".",
"^",
"(",
"type",
"ID",
")",
"+",
"adds",
"ID",
"to",
"type",
"and",
"then",
"2nd",
"iteration",
"must",
"dup",
"the",
"type",
"node",
"but",
"ID",
"has",
"been",
"added",
"."
] | def nextNode(self):
"""
Treat next element as a single node even if it's a subtree.
This is used instead of next() when the result has to be a
tree root node. Also prevents us from duplicating recently-added
children; e.g., ^(type ID)+ adds ID to type and then 2nd iteration
must dup the type node, but ID has been added.
Referencing a rule result twice is ok; dup entire tree as
we can't be adding trees as root; e.g., expr expr.
Hideous code duplication here with super.next(). Can't think of
a proper way to refactor. This needs to always call dup node
and super.next() doesn't know which to call: dup node or dup tree.
"""
if (self.dirty
or (self.cursor >= len(self) and len(self) == 1)
):
# if out of elements and size is 1, dup (at most a single node
# since this is for making root nodes).
el = self._next()
return self.adaptor.dupNode(el)
# test size above then fetch
el = self._next()
return el | [
"def",
"nextNode",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"dirty",
"or",
"(",
"self",
".",
"cursor",
">=",
"len",
"(",
"self",
")",
"and",
"len",
"(",
"self",
")",
"==",
"1",
")",
")",
":",
"# if out of elements and size is 1, dup (at most a single node",
"# since this is for making root nodes).",
"el",
"=",
"self",
".",
"_next",
"(",
")",
"return",
"self",
".",
"adaptor",
".",
"dupNode",
"(",
"el",
")",
"# test size above then fetch",
"el",
"=",
"self",
".",
"_next",
"(",
")",
"return",
"el"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/tree.py#L2375-L2401 | |
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/faster-rcnn/lib/datasets/voc_eval.py | python | voc_ap | (rec, prec, use_07_metric=False) | return ap | ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False). | ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False). | [
"ap",
"=",
"voc_ap",
"(",
"rec",
"prec",
"[",
"use_07_metric",
"]",
")",
"Compute",
"VOC",
"AP",
"given",
"precision",
"and",
"recall",
".",
"If",
"use_07_metric",
"is",
"true",
"uses",
"the",
"VOC",
"07",
"11",
"point",
"method",
"(",
"default",
":",
"False",
")",
"."
] | def voc_ap(rec, prec, use_07_metric=False):
""" ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
# 11 point metric
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(prec[rec >= t])
ap = ap + p / 11.
else:
# correct AP calculation
# first append sentinel values at the end
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# to calculate area under PR curve, look for points
# where X axis (recall) changes value
i = np.where(mrec[1:] != mrec[:-1])[0]
# and sum (\Delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap | [
"def",
"voc_ap",
"(",
"rec",
",",
"prec",
",",
"use_07_metric",
"=",
"False",
")",
":",
"if",
"use_07_metric",
":",
"# 11 point metric",
"ap",
"=",
"0.",
"for",
"t",
"in",
"np",
".",
"arange",
"(",
"0.",
",",
"1.1",
",",
"0.1",
")",
":",
"if",
"np",
".",
"sum",
"(",
"rec",
">=",
"t",
")",
"==",
"0",
":",
"p",
"=",
"0",
"else",
":",
"p",
"=",
"np",
".",
"max",
"(",
"prec",
"[",
"rec",
">=",
"t",
"]",
")",
"ap",
"=",
"ap",
"+",
"p",
"/",
"11.",
"else",
":",
"# correct AP calculation",
"# first append sentinel values at the end",
"mrec",
"=",
"np",
".",
"concatenate",
"(",
"(",
"[",
"0.",
"]",
",",
"rec",
",",
"[",
"1.",
"]",
")",
")",
"mpre",
"=",
"np",
".",
"concatenate",
"(",
"(",
"[",
"0.",
"]",
",",
"prec",
",",
"[",
"0.",
"]",
")",
")",
"# compute the precision envelope",
"for",
"i",
"in",
"range",
"(",
"mpre",
".",
"size",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"mpre",
"[",
"i",
"-",
"1",
"]",
"=",
"np",
".",
"maximum",
"(",
"mpre",
"[",
"i",
"-",
"1",
"]",
",",
"mpre",
"[",
"i",
"]",
")",
"# to calculate area under PR curve, look for points",
"# where X axis (recall) changes value",
"i",
"=",
"np",
".",
"where",
"(",
"mrec",
"[",
"1",
":",
"]",
"!=",
"mrec",
"[",
":",
"-",
"1",
"]",
")",
"[",
"0",
"]",
"# and sum (\\Delta recall) * prec",
"ap",
"=",
"np",
".",
"sum",
"(",
"(",
"mrec",
"[",
"i",
"+",
"1",
"]",
"-",
"mrec",
"[",
"i",
"]",
")",
"*",
"mpre",
"[",
"i",
"+",
"1",
"]",
")",
"return",
"ap"
] | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/faster-rcnn/lib/datasets/voc_eval.py#L31-L62 | |
facebookresearch/faiss | eb8781557f556505ca93f6f21fff932e17f0d9e0 | contrib/factory_tools.py | python | reverse_index_factory | (index) | attempts to get the factory string the index was built with | attempts to get the factory string the index was built with | [
"attempts",
"to",
"get",
"the",
"factory",
"string",
"the",
"index",
"was",
"built",
"with"
] | def reverse_index_factory(index):
"""
attempts to get the factory string the index was built with
"""
index = faiss.downcast_index(index)
if isinstance(index, faiss.IndexFlat):
return "Flat"
if isinstance(index, faiss.IndexIVF):
quantizer = faiss.downcast_index(index.quantizer)
if isinstance(quantizer, faiss.IndexFlat):
prefix = "IVF%d" % index.nlist
elif isinstance(quantizer, faiss.MultiIndexQuantizer):
prefix = "IMI%dx%d" % (quantizer.pq.M, quantizer.pq.nbit)
elif isinstance(quantizer, faiss.IndexHNSW):
prefix = "IVF%d_HNSW%d" % (index.nlist, quantizer.hnsw.M)
else:
prefix = "IVF%d(%s)" % (index.nlist, reverse_index_factory(quantizer))
if isinstance(index, faiss.IndexIVFFlat):
return prefix + ",Flat"
if isinstance(index, faiss.IndexIVFScalarQuantizer):
return prefix + ",SQ8"
raise NotImplementedError() | [
"def",
"reverse_index_factory",
"(",
"index",
")",
":",
"index",
"=",
"faiss",
".",
"downcast_index",
"(",
"index",
")",
"if",
"isinstance",
"(",
"index",
",",
"faiss",
".",
"IndexFlat",
")",
":",
"return",
"\"Flat\"",
"if",
"isinstance",
"(",
"index",
",",
"faiss",
".",
"IndexIVF",
")",
":",
"quantizer",
"=",
"faiss",
".",
"downcast_index",
"(",
"index",
".",
"quantizer",
")",
"if",
"isinstance",
"(",
"quantizer",
",",
"faiss",
".",
"IndexFlat",
")",
":",
"prefix",
"=",
"\"IVF%d\"",
"%",
"index",
".",
"nlist",
"elif",
"isinstance",
"(",
"quantizer",
",",
"faiss",
".",
"MultiIndexQuantizer",
")",
":",
"prefix",
"=",
"\"IMI%dx%d\"",
"%",
"(",
"quantizer",
".",
"pq",
".",
"M",
",",
"quantizer",
".",
"pq",
".",
"nbit",
")",
"elif",
"isinstance",
"(",
"quantizer",
",",
"faiss",
".",
"IndexHNSW",
")",
":",
"prefix",
"=",
"\"IVF%d_HNSW%d\"",
"%",
"(",
"index",
".",
"nlist",
",",
"quantizer",
".",
"hnsw",
".",
"M",
")",
"else",
":",
"prefix",
"=",
"\"IVF%d(%s)\"",
"%",
"(",
"index",
".",
"nlist",
",",
"reverse_index_factory",
"(",
"quantizer",
")",
")",
"if",
"isinstance",
"(",
"index",
",",
"faiss",
".",
"IndexIVFFlat",
")",
":",
"return",
"prefix",
"+",
"\",Flat\"",
"if",
"isinstance",
"(",
"index",
",",
"faiss",
".",
"IndexIVFScalarQuantizer",
")",
":",
"return",
"prefix",
"+",
"\",SQ8\"",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/facebookresearch/faiss/blob/eb8781557f556505ca93f6f21fff932e17f0d9e0/contrib/factory_tools.py#L76-L100 | ||
Z3Prover/z3 | d745d03afdfdf638d66093e2bfbacaf87187f35b | src/api/python/z3/z3.py | python | SubSeq | (s, offset, length) | return Extract(s, offset, length) | Extract substring or subsequence starting at offset | Extract substring or subsequence starting at offset | [
"Extract",
"substring",
"or",
"subsequence",
"starting",
"at",
"offset"
] | def SubSeq(s, offset, length):
"""Extract substring or subsequence starting at offset"""
return Extract(s, offset, length) | [
"def",
"SubSeq",
"(",
"s",
",",
"offset",
",",
"length",
")",
":",
"return",
"Extract",
"(",
"s",
",",
"offset",
",",
"length",
")"
] | https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L10820-L10822 | |
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | scripts/cpp_lint.py | python | ResetNolintSuppressions | () | Resets the set of NOLINT suppressions to empty. | Resets the set of NOLINT suppressions to empty. | [
"Resets",
"the",
"set",
"of",
"NOLINT",
"suppressions",
"to",
"empty",
"."
] | def ResetNolintSuppressions():
"Resets the set of NOLINT suppressions to empty."
_error_suppressions.clear() | [
"def",
"ResetNolintSuppressions",
"(",
")",
":",
"_error_suppressions",
".",
"clear",
"(",
")"
] | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L499-L501 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/genericmessagedialog.py | python | GenericMessageDialog.__init__ | (self, parent, message, caption, agwStyle,
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.DEFAULT_DIALOG_STYLE|wx.WANTS_CHARS,
wrap=-1) | Default class constructor. Use :meth:`~GenericMessageDialog.ShowModal` to show the dialog.
:param `parent`: the :class:`GenericMessageDialog` parent (if any);
:param `message`: the message in the main body of the dialog;
:param `caption`: the dialog title;
:param `agwStyle`: the AGW-specific dialog style; it can be one of the
following bits:
=========================== =========== ==================================================
Window Styles Hex Value Description
=========================== =========== ==================================================
``GMD_DEFAULT`` 0 Uses normal generic buttons
``GMD_USE_AQUABUTTONS`` 0x20 Uses :class:`AquaButton` buttons instead of generic buttons.
``GMD_USE_GRADIENTBUTTONS`` 0x40 Uses :class:`GradientButton` buttons instead of generic buttons.
=========================== =========== ==================================================
The styles above are mutually exclusive. The style chosen above can be combined with a
bitlist containing flags chosen from the following:
=========================== =========== ==================================================
Window Styles Hex Value Description
=========================== =========== ==================================================
``wx.OK`` 0x4 Shows an ``OK`` button.
``wx.CANCEL`` 0x10 Shows a ``Cancel`` button.
``wx.YES_NO`` 0xA Show ``Yes`` and ``No`` buttons.
``wx.YES_DEFAULT`` 0x0 Used with ``wx.YES_NO``, makes ``Yes`` button the default - which is the default behaviour.
``wx.NO_DEFAULT`` 0x80 Used with ``wx.YES_NO``, makes ``No`` button the default.
``wx.ICON_EXCLAMATION`` 0x100 Shows an exclamation mark icon.
``wx.ICON_HAND`` 0x200 Shows an error icon.
``wx.ICON_ERROR`` 0x200 Shows an error icon - the same as ``wx.ICON_HAND``.
``wx.ICON_QUESTION`` 0x400 Shows a question mark icon.
``wx.ICON_INFORMATION`` 0x800 Shows an information icon.
=========================== =========== ==================================================
:param `pos`: the dialog position on screen;
:param `size`: the dialog size;
:param `style`: the underlying :class:`Dialog` style;
:param `wrap`: if set greater than zero, wraps the string in `message` so that
every line is at most `wrap` pixels long.
:note: Notice that not all styles are compatible: only one of ``wx.OK`` and ``wx.YES_NO`` may be
specified (and one of them must be specified) and at most one default button style can be used
and it is only valid if the corresponding button is shown in the message box. | Default class constructor. Use :meth:`~GenericMessageDialog.ShowModal` to show the dialog. | [
"Default",
"class",
"constructor",
".",
"Use",
":",
"meth",
":",
"~GenericMessageDialog",
".",
"ShowModal",
"to",
"show",
"the",
"dialog",
"."
] | def __init__(self, parent, message, caption, agwStyle,
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.DEFAULT_DIALOG_STYLE|wx.WANTS_CHARS,
wrap=-1):
"""
Default class constructor. Use :meth:`~GenericMessageDialog.ShowModal` to show the dialog.
:param `parent`: the :class:`GenericMessageDialog` parent (if any);
:param `message`: the message in the main body of the dialog;
:param `caption`: the dialog title;
:param `agwStyle`: the AGW-specific dialog style; it can be one of the
following bits:
=========================== =========== ==================================================
Window Styles Hex Value Description
=========================== =========== ==================================================
``GMD_DEFAULT`` 0 Uses normal generic buttons
``GMD_USE_AQUABUTTONS`` 0x20 Uses :class:`AquaButton` buttons instead of generic buttons.
``GMD_USE_GRADIENTBUTTONS`` 0x40 Uses :class:`GradientButton` buttons instead of generic buttons.
=========================== =========== ==================================================
The styles above are mutually exclusive. The style chosen above can be combined with a
bitlist containing flags chosen from the following:
=========================== =========== ==================================================
Window Styles Hex Value Description
=========================== =========== ==================================================
``wx.OK`` 0x4 Shows an ``OK`` button.
``wx.CANCEL`` 0x10 Shows a ``Cancel`` button.
``wx.YES_NO`` 0xA Show ``Yes`` and ``No`` buttons.
``wx.YES_DEFAULT`` 0x0 Used with ``wx.YES_NO``, makes ``Yes`` button the default - which is the default behaviour.
``wx.NO_DEFAULT`` 0x80 Used with ``wx.YES_NO``, makes ``No`` button the default.
``wx.ICON_EXCLAMATION`` 0x100 Shows an exclamation mark icon.
``wx.ICON_HAND`` 0x200 Shows an error icon.
``wx.ICON_ERROR`` 0x200 Shows an error icon - the same as ``wx.ICON_HAND``.
``wx.ICON_QUESTION`` 0x400 Shows a question mark icon.
``wx.ICON_INFORMATION`` 0x800 Shows an information icon.
=========================== =========== ==================================================
:param `pos`: the dialog position on screen;
:param `size`: the dialog size;
:param `style`: the underlying :class:`Dialog` style;
:param `wrap`: if set greater than zero, wraps the string in `message` so that
every line is at most `wrap` pixels long.
:note: Notice that not all styles are compatible: only one of ``wx.OK`` and ``wx.YES_NO`` may be
specified (and one of them must be specified) and at most one default button style can be used
and it is only valid if the corresponding button is shown in the message box.
"""
wx.Dialog.__init__(self, parent, wx.ID_ANY, caption, pos, size, style)
self._message = message
self._agwStyle = agwStyle
self._wrap = wrap
# The extended message placeholder
self._extendedMessage = ''
# Labels for the buttons, initially empty meaning that the defaults should
# be used, use GetYes/No/OK/CancelLabel() to access them
self._yes = self._no = self._ok = self._cancel = self._help = ''
# Icons for the buttons, initially empty meaning that the defaults should
# be used, use GetYes/No/OK/CancelBitmap() to access them
self._yesBitmap = self._noBitmap = self._okBitmap = self._cancelBitmap = self._helpBitmap = None
self._created = False | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"message",
",",
"caption",
",",
"agwStyle",
",",
"pos",
"=",
"wx",
".",
"DefaultPosition",
",",
"size",
"=",
"wx",
".",
"DefaultSize",
",",
"style",
"=",
"wx",
".",
"DEFAULT_DIALOG_STYLE",
"|",
"wx",
".",
"WANTS_CHARS",
",",
"wrap",
"=",
"-",
"1",
")",
":",
"wx",
".",
"Dialog",
".",
"__init__",
"(",
"self",
",",
"parent",
",",
"wx",
".",
"ID_ANY",
",",
"caption",
",",
"pos",
",",
"size",
",",
"style",
")",
"self",
".",
"_message",
"=",
"message",
"self",
".",
"_agwStyle",
"=",
"agwStyle",
"self",
".",
"_wrap",
"=",
"wrap",
"# The extended message placeholder",
"self",
".",
"_extendedMessage",
"=",
"''",
"# Labels for the buttons, initially empty meaning that the defaults should",
"# be used, use GetYes/No/OK/CancelLabel() to access them ",
"self",
".",
"_yes",
"=",
"self",
".",
"_no",
"=",
"self",
".",
"_ok",
"=",
"self",
".",
"_cancel",
"=",
"self",
".",
"_help",
"=",
"''",
"# Icons for the buttons, initially empty meaning that the defaults should",
"# be used, use GetYes/No/OK/CancelBitmap() to access them ",
"self",
".",
"_yesBitmap",
"=",
"self",
".",
"_noBitmap",
"=",
"self",
".",
"_okBitmap",
"=",
"self",
".",
"_cancelBitmap",
"=",
"self",
".",
"_helpBitmap",
"=",
"None",
"self",
".",
"_created",
"=",
"False"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/genericmessagedialog.py#L606-L673 | ||
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | data/prep/create_pretraining_data.py | python | create_training_instances | (input_files, tokenizer, max_seq_length,
dupe_factor, short_seq_prob, masked_lm_prob,
max_predictions_per_seq, rng) | return instances | Create `TrainingInstance`s from raw text. | Create `TrainingInstance`s from raw text. | [
"Create",
"TrainingInstance",
"s",
"from",
"raw",
"text",
"."
] | def create_training_instances(input_files, tokenizer, max_seq_length,
dupe_factor, short_seq_prob, masked_lm_prob,
max_predictions_per_seq, rng):
"""Create `TrainingInstance`s from raw text."""
all_documents = [[]]
# Input file format:
# (1) One sentence per line. These should ideally be actual sentences, not
# entire paragraphs or arbitrary spans of text. (Because we use the
# sentence boundaries for the "next sentence prediction" task).
# (2) Blank lines between documents. Document boundaries are needed so
# that the "next sentence prediction" task doesn't span between documents.
for input_file in input_files:
with tf.gfile.GFile(input_file, "r") as reader:
while True:
line = tokenization.convert_to_unicode(reader.readline())
if not line:
break
line = line.strip()
# Empty lines are used as document delimiters
if not line:
all_documents.append([])
tokens = tokenizer.tokenize(line)
if tokens:
all_documents[-1].append(tokens)
# Remove empty documents
all_documents = [x for x in all_documents if x]
rng.shuffle(all_documents)
vocab_words = list(tokenizer.vocab.keys())
instances = []
for _ in range(dupe_factor):
for document_index in range(len(all_documents)):
instances.extend(
create_instances_from_document(
all_documents, document_index, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, vocab_words, rng))
rng.shuffle(instances)
return instances | [
"def",
"create_training_instances",
"(",
"input_files",
",",
"tokenizer",
",",
"max_seq_length",
",",
"dupe_factor",
",",
"short_seq_prob",
",",
"masked_lm_prob",
",",
"max_predictions_per_seq",
",",
"rng",
")",
":",
"all_documents",
"=",
"[",
"[",
"]",
"]",
"# Input file format:",
"# (1) One sentence per line. These should ideally be actual sentences, not",
"# entire paragraphs or arbitrary spans of text. (Because we use the",
"# sentence boundaries for the \"next sentence prediction\" task).",
"# (2) Blank lines between documents. Document boundaries are needed so",
"# that the \"next sentence prediction\" task doesn't span between documents.",
"for",
"input_file",
"in",
"input_files",
":",
"with",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"input_file",
",",
"\"r\"",
")",
"as",
"reader",
":",
"while",
"True",
":",
"line",
"=",
"tokenization",
".",
"convert_to_unicode",
"(",
"reader",
".",
"readline",
"(",
")",
")",
"if",
"not",
"line",
":",
"break",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"# Empty lines are used as document delimiters",
"if",
"not",
"line",
":",
"all_documents",
".",
"append",
"(",
"[",
"]",
")",
"tokens",
"=",
"tokenizer",
".",
"tokenize",
"(",
"line",
")",
"if",
"tokens",
":",
"all_documents",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"tokens",
")",
"# Remove empty documents",
"all_documents",
"=",
"[",
"x",
"for",
"x",
"in",
"all_documents",
"if",
"x",
"]",
"rng",
".",
"shuffle",
"(",
"all_documents",
")",
"vocab_words",
"=",
"list",
"(",
"tokenizer",
".",
"vocab",
".",
"keys",
"(",
")",
")",
"instances",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"dupe_factor",
")",
":",
"for",
"document_index",
"in",
"range",
"(",
"len",
"(",
"all_documents",
")",
")",
":",
"instances",
".",
"extend",
"(",
"create_instances_from_document",
"(",
"all_documents",
",",
"document_index",
",",
"max_seq_length",
",",
"short_seq_prob",
",",
"masked_lm_prob",
",",
"max_predictions_per_seq",
",",
"vocab_words",
",",
"rng",
")",
")",
"rng",
".",
"shuffle",
"(",
"instances",
")",
"return",
"instances"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/data/prep/create_pretraining_data.py#L183-L224 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/internal/python_message.py | python | _AddMergeFromStringMethod | (message_descriptor, cls) | Helper for _AddMessageMethods(). | Helper for _AddMessageMethods(). | [
"Helper",
"for",
"_AddMessageMethods",
"()",
"."
] | def _AddMergeFromStringMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def MergeFromString(self, serialized):
length = len(serialized)
try:
if self._InternalParse(serialized, 0, length) != length:
# The only reason _InternalParse would return early is if it
# encountered an end-group tag.
raise message_mod.DecodeError('Unexpected end-group tag.')
except IndexError:
raise message_mod.DecodeError('Truncated message.')
except struct.error, e:
raise message_mod.DecodeError(e)
return length # Return this for legacy reasons.
cls.MergeFromString = MergeFromString
local_ReadTag = decoder.ReadTag
local_SkipField = decoder.SkipField
decoders_by_tag = cls._decoders_by_tag
def InternalParse(self, buffer, pos, end):
self._Modified()
field_dict = self._fields
while pos != end:
(tag_bytes, new_pos) = local_ReadTag(buffer, pos)
field_decoder = decoders_by_tag.get(tag_bytes)
if field_decoder is None:
new_pos = local_SkipField(buffer, new_pos, end, tag_bytes)
if new_pos == -1:
return pos
pos = new_pos
else:
pos = field_decoder(buffer, new_pos, end, self, field_dict)
return pos
cls._InternalParse = InternalParse | [
"def",
"_AddMergeFromStringMethod",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"def",
"MergeFromString",
"(",
"self",
",",
"serialized",
")",
":",
"length",
"=",
"len",
"(",
"serialized",
")",
"try",
":",
"if",
"self",
".",
"_InternalParse",
"(",
"serialized",
",",
"0",
",",
"length",
")",
"!=",
"length",
":",
"# The only reason _InternalParse would return early is if it",
"# encountered an end-group tag.",
"raise",
"message_mod",
".",
"DecodeError",
"(",
"'Unexpected end-group tag.'",
")",
"except",
"IndexError",
":",
"raise",
"message_mod",
".",
"DecodeError",
"(",
"'Truncated message.'",
")",
"except",
"struct",
".",
"error",
",",
"e",
":",
"raise",
"message_mod",
".",
"DecodeError",
"(",
"e",
")",
"return",
"length",
"# Return this for legacy reasons.",
"cls",
".",
"MergeFromString",
"=",
"MergeFromString",
"local_ReadTag",
"=",
"decoder",
".",
"ReadTag",
"local_SkipField",
"=",
"decoder",
".",
"SkipField",
"decoders_by_tag",
"=",
"cls",
".",
"_decoders_by_tag",
"def",
"InternalParse",
"(",
"self",
",",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"self",
".",
"_Modified",
"(",
")",
"field_dict",
"=",
"self",
".",
"_fields",
"while",
"pos",
"!=",
"end",
":",
"(",
"tag_bytes",
",",
"new_pos",
")",
"=",
"local_ReadTag",
"(",
"buffer",
",",
"pos",
")",
"field_decoder",
"=",
"decoders_by_tag",
".",
"get",
"(",
"tag_bytes",
")",
"if",
"field_decoder",
"is",
"None",
":",
"new_pos",
"=",
"local_SkipField",
"(",
"buffer",
",",
"new_pos",
",",
"end",
",",
"tag_bytes",
")",
"if",
"new_pos",
"==",
"-",
"1",
":",
"return",
"pos",
"pos",
"=",
"new_pos",
"else",
":",
"pos",
"=",
"field_decoder",
"(",
"buffer",
",",
"new_pos",
",",
"end",
",",
"self",
",",
"field_dict",
")",
"return",
"pos",
"cls",
".",
"_InternalParse",
"=",
"InternalParse"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/internal/python_message.py#L749-L783 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/layer1.py | python | DynamoDBConnection.delete_table | (self, table_name) | return self.make_request(action='DeleteTable',
body=json.dumps(params)) | The DeleteTable operation deletes a table and all of its
items. After a DeleteTable request, the specified table is in
the `DELETING` state until DynamoDB completes the deletion. If
the table is in the `ACTIVE` state, you can delete it. If a
table is in `CREATING` or `UPDATING` states, then DynamoDB
returns a ResourceInUseException . If the specified table does
not exist, DynamoDB returns a ResourceNotFoundException . If
table is already in the `DELETING` state, no error is
returned.
DynamoDB might continue to accept data read and write
operations, such as GetItem and PutItem , on a table in the
`DELETING` state until the table deletion is complete.
When you delete a table, any indexes on that table are also
deleted.
Use the DescribeTable API to check the status of the table.
:type table_name: string
:param table_name: The name of the table to delete. | The DeleteTable operation deletes a table and all of its
items. After a DeleteTable request, the specified table is in
the `DELETING` state until DynamoDB completes the deletion. If
the table is in the `ACTIVE` state, you can delete it. If a
table is in `CREATING` or `UPDATING` states, then DynamoDB
returns a ResourceInUseException . If the specified table does
not exist, DynamoDB returns a ResourceNotFoundException . If
table is already in the `DELETING` state, no error is
returned. | [
"The",
"DeleteTable",
"operation",
"deletes",
"a",
"table",
"and",
"all",
"of",
"its",
"items",
".",
"After",
"a",
"DeleteTable",
"request",
"the",
"specified",
"table",
"is",
"in",
"the",
"DELETING",
"state",
"until",
"DynamoDB",
"completes",
"the",
"deletion",
".",
"If",
"the",
"table",
"is",
"in",
"the",
"ACTIVE",
"state",
"you",
"can",
"delete",
"it",
".",
"If",
"a",
"table",
"is",
"in",
"CREATING",
"or",
"UPDATING",
"states",
"then",
"DynamoDB",
"returns",
"a",
"ResourceInUseException",
".",
"If",
"the",
"specified",
"table",
"does",
"not",
"exist",
"DynamoDB",
"returns",
"a",
"ResourceNotFoundException",
".",
"If",
"table",
"is",
"already",
"in",
"the",
"DELETING",
"state",
"no",
"error",
"is",
"returned",
"."
] | def delete_table(self, table_name):
"""
The DeleteTable operation deletes a table and all of its
items. After a DeleteTable request, the specified table is in
the `DELETING` state until DynamoDB completes the deletion. If
the table is in the `ACTIVE` state, you can delete it. If a
table is in `CREATING` or `UPDATING` states, then DynamoDB
returns a ResourceInUseException . If the specified table does
not exist, DynamoDB returns a ResourceNotFoundException . If
table is already in the `DELETING` state, no error is
returned.
DynamoDB might continue to accept data read and write
operations, such as GetItem and PutItem , on a table in the
`DELETING` state until the table deletion is complete.
When you delete a table, any indexes on that table are also
deleted.
Use the DescribeTable API to check the status of the table.
:type table_name: string
:param table_name: The name of the table to delete.
"""
params = {'TableName': table_name, }
return self.make_request(action='DeleteTable',
body=json.dumps(params)) | [
"def",
"delete_table",
"(",
"self",
",",
"table_name",
")",
":",
"params",
"=",
"{",
"'TableName'",
":",
"table_name",
",",
"}",
"return",
"self",
".",
"make_request",
"(",
"action",
"=",
"'DeleteTable'",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"params",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/layer1.py#L927-L956 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/engine/atoms.py | python | Atom.__init__ | (self, system, index) | Initializes Atom.
Args:
system: An Atoms object containing the required atom.
index: An integer giving the index of the required atom in the atoms
list. Note that indices start from 0. | Initializes Atom. | [
"Initializes",
"Atom",
"."
] | def __init__(self, system, index):
"""Initializes Atom.
Args:
system: An Atoms object containing the required atom.
index: An integer giving the index of the required atom in the atoms
list. Note that indices start from 0.
"""
dset(self,"p",system.p[3*index:3*index+3])
dset(self,"q",system.q[3*index:3*index+3])
dset(self,"m",system.m[index:index+1])
dset(self,"name",system.names[index:index+1])
dset(self,"m3",system.m3[3*index:3*index+3]) | [
"def",
"__init__",
"(",
"self",
",",
"system",
",",
"index",
")",
":",
"dset",
"(",
"self",
",",
"\"p\"",
",",
"system",
".",
"p",
"[",
"3",
"*",
"index",
":",
"3",
"*",
"index",
"+",
"3",
"]",
")",
"dset",
"(",
"self",
",",
"\"q\"",
",",
"system",
".",
"q",
"[",
"3",
"*",
"index",
":",
"3",
"*",
"index",
"+",
"3",
"]",
")",
"dset",
"(",
"self",
",",
"\"m\"",
",",
"system",
".",
"m",
"[",
"index",
":",
"index",
"+",
"1",
"]",
")",
"dset",
"(",
"self",
",",
"\"name\"",
",",
"system",
".",
"names",
"[",
"index",
":",
"index",
"+",
"1",
"]",
")",
"dset",
"(",
"self",
",",
"\"m3\"",
",",
"system",
".",
"m3",
"[",
"3",
"*",
"index",
":",
"3",
"*",
"index",
"+",
"3",
"]",
")"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/atoms.py#L53-L66 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/linear_model/ransac.py | python | RANSACRegressor.score | (self, X, y) | return self.estimator_.score(X, y) | Returns the score of the prediction.
This is a wrapper for `estimator_.score(X, y)`.
Parameters
----------
X : numpy array or sparse matrix of shape [n_samples, n_features]
Training data.
y : array, shape = [n_samples] or [n_samples, n_targets]
Target values.
Returns
-------
z : float
Score of the prediction. | Returns the score of the prediction. | [
"Returns",
"the",
"score",
"of",
"the",
"prediction",
"."
] | def score(self, X, y):
"""Returns the score of the prediction.
This is a wrapper for `estimator_.score(X, y)`.
Parameters
----------
X : numpy array or sparse matrix of shape [n_samples, n_features]
Training data.
y : array, shape = [n_samples] or [n_samples, n_targets]
Target values.
Returns
-------
z : float
Score of the prediction.
"""
check_is_fitted(self, 'estimator_')
return self.estimator_.score(X, y) | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"'estimator_'",
")",
"return",
"self",
".",
"estimator_",
".",
"score",
"(",
"X",
",",
"y",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/ransac.py#L430-L450 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/math_ops.py | python | sqrt | (x, name=None) | r"""Computes square root of x element-wise.
I.e., \\(y = \sqrt{x} = x^{1/2}\\).
Args:
x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`,
`float32`, `float64`, `complex64`, `complex128`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. | r"""Computes square root of x element-wise. | [
"r",
"Computes",
"square",
"root",
"of",
"x",
"element",
"-",
"wise",
"."
] | def sqrt(x, name=None):
r"""Computes square root of x element-wise.
I.e., \\(y = \sqrt{x} = x^{1/2}\\).
Args:
x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`,
`float32`, `float64`, `complex64`, `complex128`.
name: A name for the operation (optional).
Returns:
A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.
"""
with ops.name_scope(name, "Sqrt", [x]) as name:
if isinstance(x, sparse_tensor.SparseTensor):
x_sqrt = gen_math_ops.sqrt(x.values, name=name)
return sparse_tensor.SparseTensor(
indices=x.indices, values=x_sqrt, dense_shape=x.dense_shape)
else:
return gen_math_ops.sqrt(x, name=name) | [
"def",
"sqrt",
"(",
"x",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"Sqrt\"",
",",
"[",
"x",
"]",
")",
"as",
"name",
":",
"if",
"isinstance",
"(",
"x",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
":",
"x_sqrt",
"=",
"gen_math_ops",
".",
"sqrt",
"(",
"x",
".",
"values",
",",
"name",
"=",
"name",
")",
"return",
"sparse_tensor",
".",
"SparseTensor",
"(",
"indices",
"=",
"x",
".",
"indices",
",",
"values",
"=",
"x_sqrt",
",",
"dense_shape",
"=",
"x",
".",
"dense_shape",
")",
"else",
":",
"return",
"gen_math_ops",
".",
"sqrt",
"(",
"x",
",",
"name",
"=",
"name",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_ops.py#L452-L471 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/config.py | python | IdleConf.LoadCfgFiles | (self) | Load all configuration files. | Load all configuration files. | [
"Load",
"all",
"configuration",
"files",
"."
] | def LoadCfgFiles(self):
"Load all configuration files."
for key in self.defaultCfg:
self.defaultCfg[key].Load()
self.userCfg[key].Load() | [
"def",
"LoadCfgFiles",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"defaultCfg",
":",
"self",
".",
"defaultCfg",
"[",
"key",
"]",
".",
"Load",
"(",
")",
"self",
".",
"userCfg",
"[",
"key",
"]",
".",
"Load",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/config.py#L754-L758 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/extras.py | python | masked_all | (shape, dtype=float) | return a | Empty masked array with all elements masked.
Return an empty masked array of the given shape and dtype, where all the
data are masked.
Parameters
----------
shape : tuple
Shape of the required MaskedArray.
dtype : dtype, optional
Data type of the output.
Returns
-------
a : MaskedArray
A masked array with all data masked.
See Also
--------
masked_all_like : Empty masked array modelled on an existing array.
Examples
--------
>>> import numpy.ma as ma
>>> ma.masked_all((3, 3))
masked_array(
data=[[--, --, --],
[--, --, --],
[--, --, --]],
mask=[[ True, True, True],
[ True, True, True],
[ True, True, True]],
fill_value=1e+20,
dtype=float64)
The `dtype` parameter defines the underlying data type.
>>> a = ma.masked_all((3, 3))
>>> a.dtype
dtype('float64')
>>> a = ma.masked_all((3, 3), dtype=np.int32)
>>> a.dtype
dtype('int32') | Empty masked array with all elements masked. | [
"Empty",
"masked",
"array",
"with",
"all",
"elements",
"masked",
"."
] | def masked_all(shape, dtype=float):
"""
Empty masked array with all elements masked.
Return an empty masked array of the given shape and dtype, where all the
data are masked.
Parameters
----------
shape : tuple
Shape of the required MaskedArray.
dtype : dtype, optional
Data type of the output.
Returns
-------
a : MaskedArray
A masked array with all data masked.
See Also
--------
masked_all_like : Empty masked array modelled on an existing array.
Examples
--------
>>> import numpy.ma as ma
>>> ma.masked_all((3, 3))
masked_array(
data=[[--, --, --],
[--, --, --],
[--, --, --]],
mask=[[ True, True, True],
[ True, True, True],
[ True, True, True]],
fill_value=1e+20,
dtype=float64)
The `dtype` parameter defines the underlying data type.
>>> a = ma.masked_all((3, 3))
>>> a.dtype
dtype('float64')
>>> a = ma.masked_all((3, 3), dtype=np.int32)
>>> a.dtype
dtype('int32')
"""
a = masked_array(np.empty(shape, dtype),
mask=np.ones(shape, make_mask_descr(dtype)))
return a | [
"def",
"masked_all",
"(",
"shape",
",",
"dtype",
"=",
"float",
")",
":",
"a",
"=",
"masked_array",
"(",
"np",
".",
"empty",
"(",
"shape",
",",
"dtype",
")",
",",
"mask",
"=",
"np",
".",
"ones",
"(",
"shape",
",",
"make_mask_descr",
"(",
"dtype",
")",
")",
")",
"return",
"a"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/extras.py#L107-L156 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/mooseutils/MooseSourceParser.py | python | MooseSourceParser.method | (self, name) | return decl, defn | Retrieve a class declaration and definition by name.
Args:
name[str]: The name of the method to extract.
Returns:
decl[str], defn[str]: A string containing the declaration and definition of the desired method. | Retrieve a class declaration and definition by name. | [
"Retrieve",
"a",
"class",
"declaration",
"and",
"definition",
"by",
"name",
"."
] | def method(self, name):
"""
Retrieve a class declaration and definition by name.
Args:
name[str]: The name of the method to extract.
Returns:
decl[str], defn[str]: A string containing the declaration and definition of the desired method.
"""
decl = None
defn = None
cursors = self.find(clang.cindex.CursorKind.CXX_METHOD, name=name)
for c in cursors:
if c.is_definition():
defn = self.content(c)
else:
decl = self.content(c)
return decl, defn | [
"def",
"method",
"(",
"self",
",",
"name",
")",
":",
"decl",
"=",
"None",
"defn",
"=",
"None",
"cursors",
"=",
"self",
".",
"find",
"(",
"clang",
".",
"cindex",
".",
"CursorKind",
".",
"CXX_METHOD",
",",
"name",
"=",
"name",
")",
"for",
"c",
"in",
"cursors",
":",
"if",
"c",
".",
"is_definition",
"(",
")",
":",
"defn",
"=",
"self",
".",
"content",
"(",
"c",
")",
"else",
":",
"decl",
"=",
"self",
".",
"content",
"(",
"c",
")",
"return",
"decl",
",",
"defn"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mooseutils/MooseSourceParser.py#L74-L94 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/detail/exportnow.py | python | CinemaDHelper.WriteNow | (self) | For Catalyst, we don't generally have a Final state, so we call this every CoProcess call and fixup the table if we have to. | For Catalyst, we don't generally have a Final state, so we call this every CoProcess call and fixup the table if we have to. | [
"For",
"Catalyst",
"we",
"don",
"t",
"generally",
"have",
"a",
"Final",
"state",
"so",
"we",
"call",
"this",
"every",
"CoProcess",
"call",
"and",
"fixup",
"the",
"table",
"if",
"we",
"have",
"to",
"."
] | def WriteNow(self):
""" For Catalyst, we don't generally have a Final state, so we call this every CoProcess call and fixup the table if we have to. """
if not self.__EnableCinemaDTable:
return
indexfilename, datafilename = self.__MakeCinDFileNamesUnderRootDir()
if self.KeysWritten == self.Keys:
# phew nothing new, we can just append a record
f = open(indexfilename, "a+")
for l in self.Contents:
f.write("%s,"%l['timestep'])
f.write("%s,"%l['producer'])
for k in self.Keys:
if k != 'timestep' and k != 'producer' and k != 'FILE':
v = ''
if k in l:
v = l[k]
f.write("%s,"%v)
f.write("%s\n"%self.__StripRootDir(l['FILE']))
f.close()
self.Contents = []
return
#dang, whatever we wrote recently had a new variable
#we may have to extend and rewrite the old output file
readKeys = None
readContents = []
if os.path.exists(indexfilename):
#yep we have to do it
#parse the old file
f = open(indexfilename, "r")
for line in f:
read = line[0:-1].split(",") #-1 to skip trailing\n
if readKeys is None:
readKeys = read
else:
entry = {}
for idx in range(0,len(read)):
entry.update({readKeys[idx]:read[idx]})
readContents.append(entry)
#combine contents
if readKeys is not None:
self.Keys = self.Keys.union(readKeys)
readContents.extend(self.Contents)
self.Contents = readContents
#finally, write
self.Finalize()
self.KeysWritten = self.Keys.copy()
self.Contents = [] | [
"def",
"WriteNow",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__EnableCinemaDTable",
":",
"return",
"indexfilename",
",",
"datafilename",
"=",
"self",
".",
"__MakeCinDFileNamesUnderRootDir",
"(",
")",
"if",
"self",
".",
"KeysWritten",
"==",
"self",
".",
"Keys",
":",
"# phew nothing new, we can just append a record",
"f",
"=",
"open",
"(",
"indexfilename",
",",
"\"a+\"",
")",
"for",
"l",
"in",
"self",
".",
"Contents",
":",
"f",
".",
"write",
"(",
"\"%s,\"",
"%",
"l",
"[",
"'timestep'",
"]",
")",
"f",
".",
"write",
"(",
"\"%s,\"",
"%",
"l",
"[",
"'producer'",
"]",
")",
"for",
"k",
"in",
"self",
".",
"Keys",
":",
"if",
"k",
"!=",
"'timestep'",
"and",
"k",
"!=",
"'producer'",
"and",
"k",
"!=",
"'FILE'",
":",
"v",
"=",
"''",
"if",
"k",
"in",
"l",
":",
"v",
"=",
"l",
"[",
"k",
"]",
"f",
".",
"write",
"(",
"\"%s,\"",
"%",
"v",
")",
"f",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"self",
".",
"__StripRootDir",
"(",
"l",
"[",
"'FILE'",
"]",
")",
")",
"f",
".",
"close",
"(",
")",
"self",
".",
"Contents",
"=",
"[",
"]",
"return",
"#dang, whatever we wrote recently had a new variable",
"#we may have to extend and rewrite the old output file",
"readKeys",
"=",
"None",
"readContents",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"indexfilename",
")",
":",
"#yep we have to do it",
"#parse the old file",
"f",
"=",
"open",
"(",
"indexfilename",
",",
"\"r\"",
")",
"for",
"line",
"in",
"f",
":",
"read",
"=",
"line",
"[",
"0",
":",
"-",
"1",
"]",
".",
"split",
"(",
"\",\"",
")",
"#-1 to skip trailing\\n",
"if",
"readKeys",
"is",
"None",
":",
"readKeys",
"=",
"read",
"else",
":",
"entry",
"=",
"{",
"}",
"for",
"idx",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"read",
")",
")",
":",
"entry",
".",
"update",
"(",
"{",
"readKeys",
"[",
"idx",
"]",
":",
"read",
"[",
"idx",
"]",
"}",
")",
"readContents",
".",
"append",
"(",
"entry",
")",
"#combine contents",
"if",
"readKeys",
"is",
"not",
"None",
":",
"self",
".",
"Keys",
"=",
"self",
".",
"Keys",
".",
"union",
"(",
"readKeys",
")",
"readContents",
".",
"extend",
"(",
"self",
".",
"Contents",
")",
"self",
".",
"Contents",
"=",
"readContents",
"#finally, write",
"self",
".",
"Finalize",
"(",
")",
"self",
".",
"KeysWritten",
"=",
"self",
".",
"Keys",
".",
"copy",
"(",
")",
"self",
".",
"Contents",
"=",
"[",
"]"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/detail/exportnow.py#L99-L146 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatmenu.py | python | FlatMenuButton.GetTimer | (self) | return self._timer | Returns the timer object. | Returns the timer object. | [
"Returns",
"the",
"timer",
"object",
"."
] | def GetTimer(self):
""" Returns the timer object. """
return self._timer | [
"def",
"GetTimer",
"(",
"self",
")",
":",
"return",
"self",
".",
"_timer"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L4076-L4079 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/adidas_utils/solvers/symmetric/qre_anneal_noaux.py | python | Solver.euc_descent_step | (self, params, grads, t) | return new_params | Projected gradient descent on exploitability using Euclidean projection.
Args:
params: tuple of variables to be updated (dist, anneal_steps)
grads: tuple of variable gradients (grad_dist, grad_anneal_steps)
t: int, solver iteration
Returns:
new_params: tuple of update params (new_dist, new_anneal_steps) | Projected gradient descent on exploitability using Euclidean projection. | [
"Projected",
"gradient",
"descent",
"on",
"exploitability",
"using",
"Euclidean",
"projection",
"."
] | def euc_descent_step(self, params, grads, t):
"""Projected gradient descent on exploitability using Euclidean projection.
Args:
params: tuple of variables to be updated (dist, anneal_steps)
grads: tuple of variable gradients (grad_dist, grad_anneal_steps)
t: int, solver iteration
Returns:
new_params: tuple of update params (new_dist, new_anneal_steps)
"""
del t
lr_dist = self.lrs[0]
new_params = [params[0] - lr_dist * grads[0]]
new_params = euc_project(*new_params)
new_params += (params[1] + grads[1],)
return new_params | [
"def",
"euc_descent_step",
"(",
"self",
",",
"params",
",",
"grads",
",",
"t",
")",
":",
"del",
"t",
"lr_dist",
"=",
"self",
".",
"lrs",
"[",
"0",
"]",
"new_params",
"=",
"[",
"params",
"[",
"0",
"]",
"-",
"lr_dist",
"*",
"grads",
"[",
"0",
"]",
"]",
"new_params",
"=",
"euc_project",
"(",
"*",
"new_params",
")",
"new_params",
"+=",
"(",
"params",
"[",
"1",
"]",
"+",
"grads",
"[",
"1",
"]",
",",
")",
"return",
"new_params"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/adidas_utils/solvers/symmetric/qre_anneal_noaux.py#L301-L316 | |
kungfu-origin/kungfu | 90c84b2b590855654cb9a6395ed050e0f7763512 | core/deps/SQLiteCpp-2.3.0/cpplint.py | python | CleanseRawStrings | (raw_lines) | return lines_without_raw_strings | Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings. | Removes C++11 raw strings from lines. | [
"Removes",
"C",
"++",
"11",
"raw",
"strings",
"from",
"lines",
"."
] | def CleanseRawStrings(raw_lines):
"""Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings.
"""
delimiter = None
lines_without_raw_strings = []
for line in raw_lines:
if delimiter:
# Inside a raw string, look for the end
end = line.find(delimiter)
if end >= 0:
# Found the end of the string, match leading space for this
# line and resume copying the original lines, and also insert
# a "" on the last line.
leading_space = Match(r'^(\s*)\S', line)
line = leading_space.group(1) + '""' + line[end + len(delimiter):]
delimiter = None
else:
# Haven't found the end yet, append a blank line.
line = ''
else:
# Look for beginning of a raw string.
# See 2.14.15 [lex.string] for syntax.
matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
if matched:
delimiter = ')' + matched.group(2) + '"'
end = matched.group(3).find(delimiter)
if end >= 0:
# Raw string ended on same line
line = (matched.group(1) + '""' +
matched.group(3)[end + len(delimiter):])
delimiter = None
else:
# Start of a multi-line raw string
line = matched.group(1) + '""'
lines_without_raw_strings.append(line)
# TODO(unknown): if delimiter is not None here, we might want to
# emit a warning for unterminated string.
return lines_without_raw_strings | [
"def",
"CleanseRawStrings",
"(",
"raw_lines",
")",
":",
"delimiter",
"=",
"None",
"lines_without_raw_strings",
"=",
"[",
"]",
"for",
"line",
"in",
"raw_lines",
":",
"if",
"delimiter",
":",
"# Inside a raw string, look for the end",
"end",
"=",
"line",
".",
"find",
"(",
"delimiter",
")",
"if",
"end",
">=",
"0",
":",
"# Found the end of the string, match leading space for this",
"# line and resume copying the original lines, and also insert",
"# a \"\" on the last line.",
"leading_space",
"=",
"Match",
"(",
"r'^(\\s*)\\S'",
",",
"line",
")",
"line",
"=",
"leading_space",
".",
"group",
"(",
"1",
")",
"+",
"'\"\"'",
"+",
"line",
"[",
"end",
"+",
"len",
"(",
"delimiter",
")",
":",
"]",
"delimiter",
"=",
"None",
"else",
":",
"# Haven't found the end yet, append a blank line.",
"line",
"=",
"''",
"else",
":",
"# Look for beginning of a raw string.",
"# See 2.14.15 [lex.string] for syntax.",
"matched",
"=",
"Match",
"(",
"r'^(.*)\\b(?:R|u8R|uR|UR|LR)\"([^\\s\\\\()]*)\\((.*)$'",
",",
"line",
")",
"if",
"matched",
":",
"delimiter",
"=",
"')'",
"+",
"matched",
".",
"group",
"(",
"2",
")",
"+",
"'\"'",
"end",
"=",
"matched",
".",
"group",
"(",
"3",
")",
".",
"find",
"(",
"delimiter",
")",
"if",
"end",
">=",
"0",
":",
"# Raw string ended on same line",
"line",
"=",
"(",
"matched",
".",
"group",
"(",
"1",
")",
"+",
"'\"\"'",
"+",
"matched",
".",
"group",
"(",
"3",
")",
"[",
"end",
"+",
"len",
"(",
"delimiter",
")",
":",
"]",
")",
"delimiter",
"=",
"None",
"else",
":",
"# Start of a multi-line raw string",
"line",
"=",
"matched",
".",
"group",
"(",
"1",
")",
"+",
"'\"\"'",
"lines_without_raw_strings",
".",
"append",
"(",
"line",
")",
"# TODO(unknown): if delimiter is not None here, we might want to",
"# emit a warning for unterminated string.",
"return",
"lines_without_raw_strings"
] | https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L1066-L1124 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Scanner/__init__.py | python | Base.__call__ | (self, node, env, path=()) | return nodes | Scans a single object.
Args:
node: the node that will be passed to the scanner function
env: the environment that will be passed to the scanner function.
Returns:
A list of direct dependency nodes for the specified node. | Scans a single object. | [
"Scans",
"a",
"single",
"object",
"."
] | def __call__(self, node, env, path=()):
"""Scans a single object.
Args:
node: the node that will be passed to the scanner function
env: the environment that will be passed to the scanner function.
Returns:
A list of direct dependency nodes for the specified node.
"""
if self.scan_check and not self.scan_check(node, env):
return []
self = self.select(node)
if self.argument is not _null:
node_list = self.function(node, env, path, self.argument)
else:
node_list = self.function(node, env, path)
kw = {}
if hasattr(node, 'dir'):
kw['directory'] = node.dir
node_factory = env.get_factory(self.node_factory)
nodes = []
for l in node_list:
if self.node_class and not isinstance(l, self.node_class):
l = node_factory(l, **kw)
nodes.append(l)
return nodes | [
"def",
"__call__",
"(",
"self",
",",
"node",
",",
"env",
",",
"path",
"=",
"(",
")",
")",
":",
"if",
"self",
".",
"scan_check",
"and",
"not",
"self",
".",
"scan_check",
"(",
"node",
",",
"env",
")",
":",
"return",
"[",
"]",
"self",
"=",
"self",
".",
"select",
"(",
"node",
")",
"if",
"self",
".",
"argument",
"is",
"not",
"_null",
":",
"node_list",
"=",
"self",
".",
"function",
"(",
"node",
",",
"env",
",",
"path",
",",
"self",
".",
"argument",
")",
"else",
":",
"node_list",
"=",
"self",
".",
"function",
"(",
"node",
",",
"env",
",",
"path",
")",
"kw",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"node",
",",
"'dir'",
")",
":",
"kw",
"[",
"'directory'",
"]",
"=",
"node",
".",
"dir",
"node_factory",
"=",
"env",
".",
"get_factory",
"(",
"self",
".",
"node_factory",
")",
"nodes",
"=",
"[",
"]",
"for",
"l",
"in",
"node_list",
":",
"if",
"self",
".",
"node_class",
"and",
"not",
"isinstance",
"(",
"l",
",",
"self",
".",
"node_class",
")",
":",
"l",
"=",
"node_factory",
"(",
"l",
",",
"*",
"*",
"kw",
")",
"nodes",
".",
"append",
"(",
"l",
")",
"return",
"nodes"
] | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Scanner/__init__.py#L190-L220 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/check_ops.py | python | assert_rank | (x, rank, data=None, summarize=None, message=None, name=None) | return assert_op | Assert `x` has rank equal to `rank`.
Example of adding a dependency to an operation:
```python
with tf.control_dependencies([tf.assert_rank(x, 2)]):
output = tf.reduce_sum(x)
```
Example of adding dependency to the tensor being checked:
```python
x = tf.with_dependencies([tf.assert_rank(x, 2)], x)
```
Args:
x: Numeric `Tensor`.
rank: Scalar integer `Tensor`.
data: The tensors to print out if the condition is False. Defaults to
error message and first few entries of `x`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name: A name for this operation (optional). Defaults to "assert_rank".
Returns:
Op raising `InvalidArgumentError` unless `x` has specified rank.
If static checks determine `x` has correct rank, a `no_op` is returned.
Raises:
ValueError: If static checks determine `x` has wrong rank. | Assert `x` has rank equal to `rank`. | [
"Assert",
"x",
"has",
"rank",
"equal",
"to",
"rank",
"."
] | def assert_rank(x, rank, data=None, summarize=None, message=None, name=None):
"""Assert `x` has rank equal to `rank`.
Example of adding a dependency to an operation:
```python
with tf.control_dependencies([tf.assert_rank(x, 2)]):
output = tf.reduce_sum(x)
```
Example of adding dependency to the tensor being checked:
```python
x = tf.with_dependencies([tf.assert_rank(x, 2)], x)
```
Args:
x: Numeric `Tensor`.
rank: Scalar integer `Tensor`.
data: The tensors to print out if the condition is False. Defaults to
error message and first few entries of `x`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name: A name for this operation (optional). Defaults to "assert_rank".
Returns:
Op raising `InvalidArgumentError` unless `x` has specified rank.
If static checks determine `x` has correct rank, a `no_op` is returned.
Raises:
ValueError: If static checks determine `x` has wrong rank.
"""
message = message or ''
static_condition = lambda actual_rank, given_rank: actual_rank == given_rank
dynamic_condition = math_ops.equal
if data is None:
data = [
message,
'Tensor %s must have rank' % x.name, rank, 'Received shape: ',
array_ops.shape(x)
]
try:
assert_op = _assert_rank_condition(x, rank, static_condition,
dynamic_condition, data, summarize, name)
except ValueError as e:
if e.args[0] == 'Static rank condition failed':
raise ValueError(
'%s. Tensor %s must have rank %d. Received rank %d, shape %s' %
(message, x.name, e.args[2], e.args[1], x.get_shape()))
else:
raise
return assert_op | [
"def",
"assert_rank",
"(",
"x",
",",
"rank",
",",
"data",
"=",
"None",
",",
"summarize",
"=",
"None",
",",
"message",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"message",
"=",
"message",
"or",
"''",
"static_condition",
"=",
"lambda",
"actual_rank",
",",
"given_rank",
":",
"actual_rank",
"==",
"given_rank",
"dynamic_condition",
"=",
"math_ops",
".",
"equal",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"[",
"message",
",",
"'Tensor %s must have rank'",
"%",
"x",
".",
"name",
",",
"rank",
",",
"'Received shape: '",
",",
"array_ops",
".",
"shape",
"(",
"x",
")",
"]",
"try",
":",
"assert_op",
"=",
"_assert_rank_condition",
"(",
"x",
",",
"rank",
",",
"static_condition",
",",
"dynamic_condition",
",",
"data",
",",
"summarize",
",",
"name",
")",
"except",
"ValueError",
"as",
"e",
":",
"if",
"e",
".",
"args",
"[",
"0",
"]",
"==",
"'Static rank condition failed'",
":",
"raise",
"ValueError",
"(",
"'%s. Tensor %s must have rank %d. Received rank %d, shape %s'",
"%",
"(",
"message",
",",
"x",
".",
"name",
",",
"e",
".",
"args",
"[",
"2",
"]",
",",
"e",
".",
"args",
"[",
"1",
"]",
",",
"x",
".",
"get_shape",
"(",
")",
")",
")",
"else",
":",
"raise",
"return",
"assert_op"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/check_ops.py#L458-L514 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/inspector_protocol/jinja2/utils.py | python | urlize | (text, trim_url_limit=None, rel=None, target=None) | return u''.join(words) | Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_limit characters.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If target is not None, a target attribute will be added to the link. | Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing. | [
"Converts",
"any",
"URLs",
"in",
"text",
"into",
"clickable",
"links",
".",
"Works",
"on",
"http",
":",
"//",
"https",
":",
"//",
"and",
"www",
".",
"links",
".",
"Links",
"can",
"have",
"trailing",
"punctuation",
"(",
"periods",
"commas",
"close",
"-",
"parens",
")",
"and",
"leading",
"punctuation",
"(",
"opening",
"parens",
")",
"and",
"it",
"ll",
"still",
"do",
"the",
"right",
"thing",
"."
] | def urlize(text, trim_url_limit=None, rel=None, target=None):
"""Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_limit characters.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If target is not None, a target attribute will be added to the link.
"""
trim_url = lambda x, limit=trim_url_limit: limit is not None \
and (x[:limit] + (len(x) >=limit and '...'
or '')) or x
words = _word_split_re.split(text_type(escape(text)))
rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ''
target_attr = target and ' target="%s"' % escape(target) or ''
for i, word in enumerate(words):
match = _punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
if middle.startswith('www.') or (
'@' not in middle and
not middle.startswith('http://') and
not middle.startswith('https://') and
len(middle) > 0 and
middle[0] in _letters + _digits and (
middle.endswith('.org') or
middle.endswith('.net') or
middle.endswith('.com')
)):
middle = '<a href="http://%s"%s%s>%s</a>' % (middle,
rel_attr, target_attr, trim_url(middle))
if middle.startswith('http://') or \
middle.startswith('https://'):
middle = '<a href="%s"%s%s>%s</a>' % (middle,
rel_attr, target_attr, trim_url(middle))
if '@' in middle and not middle.startswith('www.') and \
not ':' in middle and _simple_email_re.match(middle):
middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
if lead + middle + trail != word:
words[i] = lead + middle + trail
return u''.join(words) | [
"def",
"urlize",
"(",
"text",
",",
"trim_url_limit",
"=",
"None",
",",
"rel",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"trim_url",
"=",
"lambda",
"x",
",",
"limit",
"=",
"trim_url_limit",
":",
"limit",
"is",
"not",
"None",
"and",
"(",
"x",
"[",
":",
"limit",
"]",
"+",
"(",
"len",
"(",
"x",
")",
">=",
"limit",
"and",
"'...'",
"or",
"''",
")",
")",
"or",
"x",
"words",
"=",
"_word_split_re",
".",
"split",
"(",
"text_type",
"(",
"escape",
"(",
"text",
")",
")",
")",
"rel_attr",
"=",
"rel",
"and",
"' rel=\"%s\"'",
"%",
"text_type",
"(",
"escape",
"(",
"rel",
")",
")",
"or",
"''",
"target_attr",
"=",
"target",
"and",
"' target=\"%s\"'",
"%",
"escape",
"(",
"target",
")",
"or",
"''",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"words",
")",
":",
"match",
"=",
"_punctuation_re",
".",
"match",
"(",
"word",
")",
"if",
"match",
":",
"lead",
",",
"middle",
",",
"trail",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"middle",
".",
"startswith",
"(",
"'www.'",
")",
"or",
"(",
"'@'",
"not",
"in",
"middle",
"and",
"not",
"middle",
".",
"startswith",
"(",
"'http://'",
")",
"and",
"not",
"middle",
".",
"startswith",
"(",
"'https://'",
")",
"and",
"len",
"(",
"middle",
")",
">",
"0",
"and",
"middle",
"[",
"0",
"]",
"in",
"_letters",
"+",
"_digits",
"and",
"(",
"middle",
".",
"endswith",
"(",
"'.org'",
")",
"or",
"middle",
".",
"endswith",
"(",
"'.net'",
")",
"or",
"middle",
".",
"endswith",
"(",
"'.com'",
")",
")",
")",
":",
"middle",
"=",
"'<a href=\"http://%s\"%s%s>%s</a>'",
"%",
"(",
"middle",
",",
"rel_attr",
",",
"target_attr",
",",
"trim_url",
"(",
"middle",
")",
")",
"if",
"middle",
".",
"startswith",
"(",
"'http://'",
")",
"or",
"middle",
".",
"startswith",
"(",
"'https://'",
")",
":",
"middle",
"=",
"'<a href=\"%s\"%s%s>%s</a>'",
"%",
"(",
"middle",
",",
"rel_attr",
",",
"target_attr",
",",
"trim_url",
"(",
"middle",
")",
")",
"if",
"'@'",
"in",
"middle",
"and",
"not",
"middle",
".",
"startswith",
"(",
"'www.'",
")",
"and",
"not",
"':'",
"in",
"middle",
"and",
"_simple_email_re",
".",
"match",
"(",
"middle",
")",
":",
"middle",
"=",
"'<a href=\"mailto:%s\">%s</a>'",
"%",
"(",
"middle",
",",
"middle",
")",
"if",
"lead",
"+",
"middle",
"+",
"trail",
"!=",
"word",
":",
"words",
"[",
"i",
"]",
"=",
"lead",
"+",
"middle",
"+",
"trail",
"return",
"u''",
".",
"join",
"(",
"words",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/utils.py#L189-L235 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/pydoc.py | python | HTMLDoc.heading | (self, title, fgcol, bgcol, extras='') | return '''
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="%s">
<td valign=bottom> <br>
<font color="%s" face="helvetica, arial"> <br>%s</font></td
><td align=right valign=bottom
><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
''' % (bgcol, fgcol, title, fgcol, extras or ' ') | Format a page heading. | Format a page heading. | [
"Format",
"a",
"page",
"heading",
"."
] | def heading(self, title, fgcol, bgcol, extras=''):
"""Format a page heading."""
return '''
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="%s">
<td valign=bottom> <br>
<font color="%s" face="helvetica, arial"> <br>%s</font></td
><td align=right valign=bottom
><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
''' % (bgcol, fgcol, title, fgcol, extras or ' ') | [
"def",
"heading",
"(",
"self",
",",
"title",
",",
"fgcol",
",",
"bgcol",
",",
"extras",
"=",
"''",
")",
":",
"return",
"'''\n<table width=\"100%%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">\n<tr bgcolor=\"%s\">\n<td valign=bottom> <br>\n<font color=\"%s\" face=\"helvetica, arial\"> <br>%s</font></td\n><td align=right valign=bottom\n><font color=\"%s\" face=\"helvetica, arial\">%s</font></td></tr></table>\n '''",
"%",
"(",
"bgcol",
",",
"fgcol",
",",
"title",
",",
"fgcol",
",",
"extras",
"or",
"' '",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pydoc.py#L577-L586 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_logic_parser.py | python | p_apps_app | (p) | apps : app | apps : app | [
"apps",
":",
"app"
] | def p_apps_app(p):
'apps : app'
p[0] = [p[1]] | [
"def",
"p_apps_app",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_logic_parser.py#L266-L268 | ||
omnisci/omniscidb | b9c95f1bd602b4ffc8b0edf18bfad61031e08d86 | python/omnisci/thrift/OmniSci.py | python | Iface.get_all_files_in_archive | (self, session, archive_path, copy_params) | Parameters:
- session
- archive_path
- copy_params | Parameters:
- session
- archive_path
- copy_params | [
"Parameters",
":",
"-",
"session",
"-",
"archive_path",
"-",
"copy_params"
] | def get_all_files_in_archive(self, session, archive_path, copy_params):
"""
Parameters:
- session
- archive_path
- copy_params
"""
pass | [
"def",
"get_all_files_in_archive",
"(",
"self",
",",
"session",
",",
"archive_path",
",",
"copy_params",
")",
":",
"pass"
] | https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/python/omnisci/thrift/OmniSci.py#L734-L742 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/lambda-code/ServiceLambda/resource_types/Custom_AccessControl.py | python | _get_permissions | (resource_info, problems) | return permissions | Looks for the following metadata in a stack template:
{
"Resources": {
"<logical-resource-id>": {
"Metadata": { # optional
"CloudCanvas": { # optional
"Permissions": [ # optional list or a single object
{
"AbstractRole": [ "<abstract-role-name>", ... ], # required list or single string
"Action": [ "<allowed-action>", ... ] # required list or single string
"ResourceSuffix": [ "<resource-suffix>", ... ] # required list or single string
},
...
]
}
}
},
...
}
}
Args:
resource_info - a StackInfo object representing the stack with the metadata. Can be of type ProjectInfo or ResourceGroupInfo
problems - A ProblemList object used to report problems
Returns:
A dictionary constructed from the resource metadata:
{
'<resource-arn>': [
{
"AbstractRole": [ ["<resource-group-name>", "<abstract-role-name>"], ... ],
"Action": [ "<allowed-action>", ... ],
"ResourceSuffix": [ "<resource-suffix>", ... ],
"LogicalResourceId": "<logical-resource-id>"
},
...
]
} | Looks for the following metadata in a stack template: | [
"Looks",
"for",
"the",
"following",
"metadata",
"in",
"a",
"stack",
"template",
":"
] | def _get_permissions(resource_info, problems):
"""Looks for the following metadata in a stack template:
{
"Resources": {
"<logical-resource-id>": {
"Metadata": { # optional
"CloudCanvas": { # optional
"Permissions": [ # optional list or a single object
{
"AbstractRole": [ "<abstract-role-name>", ... ], # required list or single string
"Action": [ "<allowed-action>", ... ] # required list or single string
"ResourceSuffix": [ "<resource-suffix>", ... ] # required list or single string
},
...
]
}
}
},
...
}
}
Args:
resource_info - a StackInfo object representing the stack with the metadata. Can be of type ProjectInfo or ResourceGroupInfo
problems - A ProblemList object used to report problems
Returns:
A dictionary constructed from the resource metadata:
{
'<resource-arn>': [
{
"AbstractRole": [ ["<resource-group-name>", "<abstract-role-name>"], ... ],
"Action": [ "<allowed-action>", ... ],
"ResourceSuffix": [ "<resource-suffix>", ... ],
"LogicalResourceId": "<logical-resource-id>"
},
...
]
}
"""
resource_definitions = resource_info.resource_definitions
permissions = {}
print('Permission context: {}'.format(resource_info.permission_context_name))
for resource in resource_info.resources:
permission_list = []
permission_metadata = resource.get_cloud_canvas_metadata('Permissions')
if permission_metadata is not None:
if reference_type_utils.is_reference_type(resource.type):
permission_metadata = _get_permissions_for_reference_type(resource, permission_metadata)
print('Found permission metadata on stack {} resource {}: {}.'.format(resource_info.stack_name, resource.logical_id, permission_metadata))
problems.push_prefix('Stack {} resource {} ', resource_info.stack_name, resource.logical_id)
permission_list.extend(_get_permission_list(resource_info.permission_context_name, resource.logical_id, permission_metadata, problems))
problems.pop_prefix()
resource_type = resource_definitions.get(resource.type, None)
permission_metadata = None if resource_type is None else resource_type.permission_metadata
default_role_mappings = None if permission_metadata is None else permission_metadata.get('DefaultRoleMappings', None)
if default_role_mappings:
print('Found default permission metadata for stack {} resource {} with type {}: {}.'.format(resource_info.stack_name, resource.logical_id,
resource.type, permission_metadata))
problems.push_prefix('Stack {} resource {} default ', resource_info.stack_name, resource.logical_id)
permission_list.extend(_get_permission_list(resource_info.permission_context_name, resource.logical_id, default_role_mappings, problems))
problems.pop_prefix()
if permission_list:
try:
# A type to ARN format mapping may not be available.
resource_arn_type = resource.resource_arn
existing_list = permissions.get(resource_arn_type, [])
existing_list.extend(permission_list)
permissions[resource_arn_type] = existing_list
except Exception as e:
problems.append('type {} is not supported by the Custom::AccessControl resource: {}'.format(resource.type, str(e)))
_check_restrictions(resource, permission_metadata, permission_list, problems)
return permissions | [
"def",
"_get_permissions",
"(",
"resource_info",
",",
"problems",
")",
":",
"resource_definitions",
"=",
"resource_info",
".",
"resource_definitions",
"permissions",
"=",
"{",
"}",
"print",
"(",
"'Permission context: {}'",
".",
"format",
"(",
"resource_info",
".",
"permission_context_name",
")",
")",
"for",
"resource",
"in",
"resource_info",
".",
"resources",
":",
"permission_list",
"=",
"[",
"]",
"permission_metadata",
"=",
"resource",
".",
"get_cloud_canvas_metadata",
"(",
"'Permissions'",
")",
"if",
"permission_metadata",
"is",
"not",
"None",
":",
"if",
"reference_type_utils",
".",
"is_reference_type",
"(",
"resource",
".",
"type",
")",
":",
"permission_metadata",
"=",
"_get_permissions_for_reference_type",
"(",
"resource",
",",
"permission_metadata",
")",
"print",
"(",
"'Found permission metadata on stack {} resource {}: {}.'",
".",
"format",
"(",
"resource_info",
".",
"stack_name",
",",
"resource",
".",
"logical_id",
",",
"permission_metadata",
")",
")",
"problems",
".",
"push_prefix",
"(",
"'Stack {} resource {} '",
",",
"resource_info",
".",
"stack_name",
",",
"resource",
".",
"logical_id",
")",
"permission_list",
".",
"extend",
"(",
"_get_permission_list",
"(",
"resource_info",
".",
"permission_context_name",
",",
"resource",
".",
"logical_id",
",",
"permission_metadata",
",",
"problems",
")",
")",
"problems",
".",
"pop_prefix",
"(",
")",
"resource_type",
"=",
"resource_definitions",
".",
"get",
"(",
"resource",
".",
"type",
",",
"None",
")",
"permission_metadata",
"=",
"None",
"if",
"resource_type",
"is",
"None",
"else",
"resource_type",
".",
"permission_metadata",
"default_role_mappings",
"=",
"None",
"if",
"permission_metadata",
"is",
"None",
"else",
"permission_metadata",
".",
"get",
"(",
"'DefaultRoleMappings'",
",",
"None",
")",
"if",
"default_role_mappings",
":",
"print",
"(",
"'Found default permission metadata for stack {} resource {} with type {}: {}.'",
".",
"format",
"(",
"resource_info",
".",
"stack_name",
",",
"resource",
".",
"logical_id",
",",
"resource",
".",
"type",
",",
"permission_metadata",
")",
")",
"problems",
".",
"push_prefix",
"(",
"'Stack {} resource {} default '",
",",
"resource_info",
".",
"stack_name",
",",
"resource",
".",
"logical_id",
")",
"permission_list",
".",
"extend",
"(",
"_get_permission_list",
"(",
"resource_info",
".",
"permission_context_name",
",",
"resource",
".",
"logical_id",
",",
"default_role_mappings",
",",
"problems",
")",
")",
"problems",
".",
"pop_prefix",
"(",
")",
"if",
"permission_list",
":",
"try",
":",
"# A type to ARN format mapping may not be available.",
"resource_arn_type",
"=",
"resource",
".",
"resource_arn",
"existing_list",
"=",
"permissions",
".",
"get",
"(",
"resource_arn_type",
",",
"[",
"]",
")",
"existing_list",
".",
"extend",
"(",
"permission_list",
")",
"permissions",
"[",
"resource_arn_type",
"]",
"=",
"existing_list",
"except",
"Exception",
"as",
"e",
":",
"problems",
".",
"append",
"(",
"'type {} is not supported by the Custom::AccessControl resource: {}'",
".",
"format",
"(",
"resource",
".",
"type",
",",
"str",
"(",
"e",
")",
")",
")",
"_check_restrictions",
"(",
"resource",
",",
"permission_metadata",
",",
"permission_list",
",",
"problems",
")",
"return",
"permissions"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/lambda-code/ServiceLambda/resource_types/Custom_AccessControl.py#L284-L370 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/PlanetUtilsAI.py | python | get_capital | () | return INVALID_ID | Return current empire capital id.
If no current capital returns planet with biggest population in first not empty group.
First check all planets with coloniser species, after that with ship builders and at last all inhabited planets. | Return current empire capital id. | [
"Return",
"current",
"empire",
"capital",
"id",
"."
] | def get_capital() -> PlanetId:
"""
Return current empire capital id.
If no current capital returns planet with biggest population in first not empty group.
First check all planets with coloniser species, after that with ship builders and at last all inhabited planets.
"""
universe = fo.getUniverse()
empire = fo.getEmpire()
empire_id = empire.empireID
capital_id = empire.capitalID
homeworld = universe.getPlanet(capital_id)
if homeworld:
if homeworld.owner == empire_id:
return capital_id
else:
debug(
"Nominal Capitol %s does not appear to be owned by empire %d %s"
% (homeworld.name, empire_id, empire.name)
)
empire_owned_planet_ids = get_owned_planets_by_empire(universe.planetIDs)
peopled_planets = get_populated_planet_ids(empire_owned_planet_ids)
if not peopled_planets:
if empire_owned_planet_ids:
return empire_owned_planet_ids[0]
else:
return INVALID_ID
try:
for spec_list in [get_colony_builders(), get_ship_builders(), None]:
population_id_pairs = []
for planet_id in peopled_planets:
planet = universe.getPlanet(planet_id)
if spec_list is None or planet.speciesName in spec_list:
population_id_pairs.append((planet.initialMeterValue(fo.meterType.population), planet_id))
if population_id_pairs:
return max(population_id_pairs)[-1]
except Exception as e:
error(e, exc_info=True)
return INVALID_ID | [
"def",
"get_capital",
"(",
")",
"->",
"PlanetId",
":",
"universe",
"=",
"fo",
".",
"getUniverse",
"(",
")",
"empire",
"=",
"fo",
".",
"getEmpire",
"(",
")",
"empire_id",
"=",
"empire",
".",
"empireID",
"capital_id",
"=",
"empire",
".",
"capitalID",
"homeworld",
"=",
"universe",
".",
"getPlanet",
"(",
"capital_id",
")",
"if",
"homeworld",
":",
"if",
"homeworld",
".",
"owner",
"==",
"empire_id",
":",
"return",
"capital_id",
"else",
":",
"debug",
"(",
"\"Nominal Capitol %s does not appear to be owned by empire %d %s\"",
"%",
"(",
"homeworld",
".",
"name",
",",
"empire_id",
",",
"empire",
".",
"name",
")",
")",
"empire_owned_planet_ids",
"=",
"get_owned_planets_by_empire",
"(",
"universe",
".",
"planetIDs",
")",
"peopled_planets",
"=",
"get_populated_planet_ids",
"(",
"empire_owned_planet_ids",
")",
"if",
"not",
"peopled_planets",
":",
"if",
"empire_owned_planet_ids",
":",
"return",
"empire_owned_planet_ids",
"[",
"0",
"]",
"else",
":",
"return",
"INVALID_ID",
"try",
":",
"for",
"spec_list",
"in",
"[",
"get_colony_builders",
"(",
")",
",",
"get_ship_builders",
"(",
")",
",",
"None",
"]",
":",
"population_id_pairs",
"=",
"[",
"]",
"for",
"planet_id",
"in",
"peopled_planets",
":",
"planet",
"=",
"universe",
".",
"getPlanet",
"(",
"planet_id",
")",
"if",
"spec_list",
"is",
"None",
"or",
"planet",
".",
"speciesName",
"in",
"spec_list",
":",
"population_id_pairs",
".",
"append",
"(",
"(",
"planet",
".",
"initialMeterValue",
"(",
"fo",
".",
"meterType",
".",
"population",
")",
",",
"planet_id",
")",
")",
"if",
"population_id_pairs",
":",
"return",
"max",
"(",
"population_id_pairs",
")",
"[",
"-",
"1",
"]",
"except",
"Exception",
"as",
"e",
":",
"error",
"(",
"e",
",",
"exc_info",
"=",
"True",
")",
"return",
"INVALID_ID"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/PlanetUtilsAI.py#L44-L82 | |
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | ctpn_crnn_ocr/CTPN/caffe/python/caffe/net_spec.py | python | to_proto | (*tops) | return net | Generate a NetParameter that contains all layers needed to compute
all arguments. | Generate a NetParameter that contains all layers needed to compute
all arguments. | [
"Generate",
"a",
"NetParameter",
"that",
"contains",
"all",
"layers",
"needed",
"to",
"compute",
"all",
"arguments",
"."
] | def to_proto(*tops):
"""Generate a NetParameter that contains all layers needed to compute
all arguments."""
layers = OrderedDict()
autonames = Counter()
for top in tops:
top.fn._to_proto(layers, {}, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net | [
"def",
"to_proto",
"(",
"*",
"tops",
")",
":",
"layers",
"=",
"OrderedDict",
"(",
")",
"autonames",
"=",
"Counter",
"(",
")",
"for",
"top",
"in",
"tops",
":",
"top",
".",
"fn",
".",
"_to_proto",
"(",
"layers",
",",
"{",
"}",
",",
"autonames",
")",
"net",
"=",
"caffe_pb2",
".",
"NetParameter",
"(",
")",
"net",
".",
"layer",
".",
"extend",
"(",
"layers",
".",
"values",
"(",
")",
")",
"return",
"net"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/ctpn_crnn_ocr/CTPN/caffe/python/caffe/net_spec.py#L43-L53 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/__init__.py | python | ZipManifests.build | (cls, path) | Build a dictionary similar to the zipimport directory
caches, except instead of tuples, store ZipInfo objects.
Use a platform-specific path separator (os.sep) for the path keys
for compatibility with pypy on Windows. | Build a dictionary similar to the zipimport directory
caches, except instead of tuples, store ZipInfo objects. | [
"Build",
"a",
"dictionary",
"similar",
"to",
"the",
"zipimport",
"directory",
"caches",
"except",
"instead",
"of",
"tuples",
"store",
"ZipInfo",
"objects",
"."
] | def build(cls, path):
"""
Build a dictionary similar to the zipimport directory
caches, except instead of tuples, store ZipInfo objects.
Use a platform-specific path separator (os.sep) for the path keys
for compatibility with pypy on Windows.
"""
with zipfile.ZipFile(path) as zfile:
items = (
(
name.replace('/', os.sep),
zfile.getinfo(name),
)
for name in zfile.namelist()
)
return dict(items) | [
"def",
"build",
"(",
"cls",
",",
"path",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"as",
"zfile",
":",
"items",
"=",
"(",
"(",
"name",
".",
"replace",
"(",
"'/'",
",",
"os",
".",
"sep",
")",
",",
"zfile",
".",
"getinfo",
"(",
"name",
")",
",",
")",
"for",
"name",
"in",
"zfile",
".",
"namelist",
"(",
")",
")",
"return",
"dict",
"(",
"items",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/__init__.py#L1658-L1674 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftviewproviders/view_layer.py | python | ViewProviderLayer.getDisplayModes | (self, vobj) | return ["Default"] | Return the display modes that this viewprovider supports. | Return the display modes that this viewprovider supports. | [
"Return",
"the",
"display",
"modes",
"that",
"this",
"viewprovider",
"supports",
"."
] | def getDisplayModes(self, vobj):
"""Return the display modes that this viewprovider supports."""
return ["Default"] | [
"def",
"getDisplayModes",
"(",
"self",
",",
"vobj",
")",
":",
"return",
"[",
"\"Default\"",
"]"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftviewproviders/view_layer.py#L194-L196 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/engine/training.py | python | _make_batches | (size, batch_size) | return [(i * batch_size, min(size, (i + 1) * batch_size))
for i in range(0, num_batches)] | Returns a list of batch indices (tuples of indices).
Arguments:
size: Integer, total size of the data to slice into batches.
batch_size: Integer, batch size.
Returns:
A list of tuples of array indices. | Returns a list of batch indices (tuples of indices). | [
"Returns",
"a",
"list",
"of",
"batch",
"indices",
"(",
"tuples",
"of",
"indices",
")",
"."
] | def _make_batches(size, batch_size):
"""Returns a list of batch indices (tuples of indices).
Arguments:
size: Integer, total size of the data to slice into batches.
batch_size: Integer, batch size.
Returns:
A list of tuples of array indices.
"""
num_batches = int(np.ceil(size / float(batch_size)))
return [(i * batch_size, min(size, (i + 1) * batch_size))
for i in range(0, num_batches)] | [
"def",
"_make_batches",
"(",
"size",
",",
"batch_size",
")",
":",
"num_batches",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"size",
"/",
"float",
"(",
"batch_size",
")",
")",
")",
"return",
"[",
"(",
"i",
"*",
"batch_size",
",",
"min",
"(",
"size",
",",
"(",
"i",
"+",
"1",
")",
"*",
"batch_size",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_batches",
")",
"]"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/engine/training.py#L356-L368 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/pyreadline/console/console.py | python | Console.getchar | (self) | Get next character from queue. | Get next character from queue. | [
"Get",
"next",
"character",
"from",
"queue",
"."
] | def getchar(self):
'''Get next character from queue.'''
Cevent = INPUT_RECORD()
count = c_int(0)
while 1:
status = self.ReadConsoleInputA(self.hin, byref(Cevent), 1, byref(count))
if (status and count.value==1 and Cevent.EventType == 1 and
Cevent.Event.KeyEvent.bKeyDown):
sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
if len(sym) == 0:
sym = Cevent.Event.KeyEvent.uChar.AsciiChar
return sym | [
"def",
"getchar",
"(",
"self",
")",
":",
"Cevent",
"=",
"INPUT_RECORD",
"(",
")",
"count",
"=",
"c_int",
"(",
"0",
")",
"while",
"1",
":",
"status",
"=",
"self",
".",
"ReadConsoleInputA",
"(",
"self",
".",
"hin",
",",
"byref",
"(",
"Cevent",
")",
",",
"1",
",",
"byref",
"(",
"count",
")",
")",
"if",
"(",
"status",
"and",
"count",
".",
"value",
"==",
"1",
"and",
"Cevent",
".",
"EventType",
"==",
"1",
"and",
"Cevent",
".",
"Event",
".",
"KeyEvent",
".",
"bKeyDown",
")",
":",
"sym",
"=",
"keysym",
"(",
"Cevent",
".",
"Event",
".",
"KeyEvent",
".",
"wVirtualKeyCode",
")",
"if",
"len",
"(",
"sym",
")",
"==",
"0",
":",
"sym",
"=",
"Cevent",
".",
"Event",
".",
"KeyEvent",
".",
"uChar",
".",
"AsciiChar",
"return",
"sym"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/console/console.py#L520-L532 | ||
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/argparse/argparse.py | python | _ActionsContainer.add_argument | (self, *args, **kwargs) | return self._add_action(action) | add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...) | add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...) | [
"add_argument",
"(",
"dest",
"...",
"name",
"=",
"value",
"...",
")",
"add_argument",
"(",
"option_string",
"option_string",
"...",
"name",
"=",
"value",
"...",
")"
] | def add_argument(self, *args, **kwargs):
"""
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
# if no positional args are supplied or only one is supplied and
# it doesn't look like an option string, parse a positional
# argument
chars = self.prefix_chars
if not args or len(args) == 1 and args[0][0] not in chars:
if args and 'dest' in kwargs:
raise ValueError('dest supplied twice for positional argument')
kwargs = self._get_positional_kwargs(*args, **kwargs)
# otherwise, we're adding an optional argument
else:
kwargs = self._get_optional_kwargs(*args, **kwargs)
# if no default was supplied, use the parser-level default
if 'default' not in kwargs:
dest = kwargs['dest']
if dest in self._defaults:
kwargs['default'] = self._defaults[dest]
elif self.argument_default is not None:
kwargs['default'] = self.argument_default
# create the action object, and add it to the parser
action_class = self._pop_action_class(kwargs)
if not _callable(action_class):
raise ValueError('unknown action "%s"' % action_class)
action = action_class(**kwargs)
# raise an error if the action type is not callable
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
raise ValueError('%r is not callable' % type_func)
return self._add_action(action) | [
"def",
"add_argument",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# if no positional args are supplied or only one is supplied and",
"# it doesn't look like an option string, parse a positional",
"# argument",
"chars",
"=",
"self",
".",
"prefix_chars",
"if",
"not",
"args",
"or",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"args",
"[",
"0",
"]",
"[",
"0",
"]",
"not",
"in",
"chars",
":",
"if",
"args",
"and",
"'dest'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'dest supplied twice for positional argument'",
")",
"kwargs",
"=",
"self",
".",
"_get_positional_kwargs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# otherwise, we're adding an optional argument",
"else",
":",
"kwargs",
"=",
"self",
".",
"_get_optional_kwargs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# if no default was supplied, use the parser-level default",
"if",
"'default'",
"not",
"in",
"kwargs",
":",
"dest",
"=",
"kwargs",
"[",
"'dest'",
"]",
"if",
"dest",
"in",
"self",
".",
"_defaults",
":",
"kwargs",
"[",
"'default'",
"]",
"=",
"self",
".",
"_defaults",
"[",
"dest",
"]",
"elif",
"self",
".",
"argument_default",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'default'",
"]",
"=",
"self",
".",
"argument_default",
"# create the action object, and add it to the parser",
"action_class",
"=",
"self",
".",
"_pop_action_class",
"(",
"kwargs",
")",
"if",
"not",
"_callable",
"(",
"action_class",
")",
":",
"raise",
"ValueError",
"(",
"'unknown action \"%s\"'",
"%",
"action_class",
")",
"action",
"=",
"action_class",
"(",
"*",
"*",
"kwargs",
")",
"# raise an error if the action type is not callable",
"type_func",
"=",
"self",
".",
"_registry_get",
"(",
"'type'",
",",
"action",
".",
"type",
",",
"action",
".",
"type",
")",
"if",
"not",
"_callable",
"(",
"type_func",
")",
":",
"raise",
"ValueError",
"(",
"'%r is not callable'",
"%",
"type_func",
")",
"return",
"self",
".",
"_add_action",
"(",
"action",
")"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/argparse/argparse.py#L1270-L1308 | |
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/daemon/daemon.py | python | DaemonContext._get_exclude_file_descriptors | (self) | return exclude_descriptors | Return the set of file descriptors to exclude closing.
Returns a set containing the file descriptors for the
items in `files_preserve`, and also each of `stdin`,
`stdout`, and `stderr`:
* If the item is ``None``, it is omitted from the return
set.
* If the item has a ``fileno()`` method, that method's
return value is in the return set.
* Otherwise, the item is in the return set verbatim. | Return the set of file descriptors to exclude closing. | [
"Return",
"the",
"set",
"of",
"file",
"descriptors",
"to",
"exclude",
"closing",
"."
] | def _get_exclude_file_descriptors(self):
""" Return the set of file descriptors to exclude closing.
Returns a set containing the file descriptors for the
items in `files_preserve`, and also each of `stdin`,
`stdout`, and `stderr`:
* If the item is ``None``, it is omitted from the return
set.
* If the item has a ``fileno()`` method, that method's
return value is in the return set.
* Otherwise, the item is in the return set verbatim.
"""
files_preserve = self.files_preserve
if files_preserve is None:
files_preserve = []
files_preserve.extend(
item for item in [self.stdin, self.stdout, self.stderr]
if hasattr(item, 'fileno'))
exclude_descriptors = set()
for item in files_preserve:
if item is None:
continue
if hasattr(item, 'fileno'):
exclude_descriptors.add(item.fileno())
else:
exclude_descriptors.add(item)
for fd in os.listdir("/proc/self/fd"):
file = os.path.join("/proc/self/fd", fd)
if not os.path.exists(file):
continue
file = os.readlink(file)
if file in {"/dev/urandom", "/dev/random"}:
exclude_descriptors.add(int(fd))
return exclude_descriptors | [
"def",
"_get_exclude_file_descriptors",
"(",
"self",
")",
":",
"files_preserve",
"=",
"self",
".",
"files_preserve",
"if",
"files_preserve",
"is",
"None",
":",
"files_preserve",
"=",
"[",
"]",
"files_preserve",
".",
"extend",
"(",
"item",
"for",
"item",
"in",
"[",
"self",
".",
"stdin",
",",
"self",
".",
"stdout",
",",
"self",
".",
"stderr",
"]",
"if",
"hasattr",
"(",
"item",
",",
"'fileno'",
")",
")",
"exclude_descriptors",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"files_preserve",
":",
"if",
"item",
"is",
"None",
":",
"continue",
"if",
"hasattr",
"(",
"item",
",",
"'fileno'",
")",
":",
"exclude_descriptors",
".",
"add",
"(",
"item",
".",
"fileno",
"(",
")",
")",
"else",
":",
"exclude_descriptors",
".",
"add",
"(",
"item",
")",
"for",
"fd",
"in",
"os",
".",
"listdir",
"(",
"\"/proc/self/fd\"",
")",
":",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"/proc/self/fd\"",
",",
"fd",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file",
")",
":",
"continue",
"file",
"=",
"os",
".",
"readlink",
"(",
"file",
")",
"if",
"file",
"in",
"{",
"\"/dev/urandom\"",
",",
"\"/dev/random\"",
"}",
":",
"exclude_descriptors",
".",
"add",
"(",
"int",
"(",
"fd",
")",
")",
"return",
"exclude_descriptors"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/daemon/daemon.py#L428-L465 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/lib/regutil.py | python | UnregisterNamedPath | (name) | Unregister a named path - ie, a named PythonPath entry. | Unregister a named path - ie, a named PythonPath entry. | [
"Unregister",
"a",
"named",
"path",
"-",
"ie",
"a",
"named",
"PythonPath",
"entry",
"."
] | def UnregisterNamedPath(name):
"""Unregister a named path - ie, a named PythonPath entry.
"""
keyStr = BuildDefaultPythonKey() + "\\PythonPath\\" + name
try:
win32api.RegDeleteKey(GetRootKey(), keyStr)
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
return | [
"def",
"UnregisterNamedPath",
"(",
"name",
")",
":",
"keyStr",
"=",
"BuildDefaultPythonKey",
"(",
")",
"+",
"\"\\\\PythonPath\\\\\"",
"+",
"name",
"try",
":",
"win32api",
".",
"RegDeleteKey",
"(",
"GetRootKey",
"(",
")",
",",
"keyStr",
")",
"except",
"win32api",
".",
"error",
",",
"exc",
":",
"import",
"winerror",
"if",
"exc",
".",
"winerror",
"!=",
"winerror",
".",
"ERROR_FILE_NOT_FOUND",
":",
"raise",
"return"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/lib/regutil.py#L103-L113 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | Colour.GetPixel | (*args, **kwargs) | return _gdi_.Colour_GetPixel(*args, **kwargs) | GetPixel(self) -> long
Returns a pixel value which is platform-dependent. On Windows, a
COLORREF is returned. On X, an allocated pixel value is returned. -1
is returned if the pixel is invalid (on X, unallocated). | GetPixel(self) -> long | [
"GetPixel",
"(",
"self",
")",
"-",
">",
"long"
] | def GetPixel(*args, **kwargs):
"""
GetPixel(self) -> long
Returns a pixel value which is platform-dependent. On Windows, a
COLORREF is returned. On X, an allocated pixel value is returned. -1
is returned if the pixel is invalid (on X, unallocated).
"""
return _gdi_.Colour_GetPixel(*args, **kwargs) | [
"def",
"GetPixel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Colour_GetPixel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L234-L242 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py | python | IMAP4.shutdown | (self) | Close I/O established in "open". | Close I/O established in "open". | [
"Close",
"I",
"/",
"O",
"established",
"in",
"open",
"."
] | def shutdown(self):
"""Close I/O established in "open"."""
self.file.close()
try:
self.sock.shutdown(socket.SHUT_RDWR)
except OSError as exc:
# The server might already have closed the connection.
# On Windows, this may result in WSAEINVAL (error 10022):
# An invalid operation was attempted.
if (exc.errno != errno.ENOTCONN
and getattr(exc, 'winerror', 0) != 10022):
raise
finally:
self.sock.close() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"file",
".",
"close",
"(",
")",
"try",
":",
"self",
".",
"sock",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"except",
"OSError",
"as",
"exc",
":",
"# The server might already have closed the connection.",
"# On Windows, this may result in WSAEINVAL (error 10022):",
"# An invalid operation was attempted.",
"if",
"(",
"exc",
".",
"errno",
"!=",
"errno",
".",
"ENOTCONN",
"and",
"getattr",
"(",
"exc",
",",
"'winerror'",
",",
"0",
")",
"!=",
"10022",
")",
":",
"raise",
"finally",
":",
"self",
".",
"sock",
".",
"close",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py#L321-L334 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchWall.py | python | _ViewProviderWall.setDisplayMode | (self,mode) | return ArchComponent.ViewProviderComponent.setDisplayMode(self,mode) | Method called when the display mode changes.
Called when the display mode changes, this method can be used to set
data that wasn't available when .attach() was called.
When Footprint is set as display mode, find the faces that make up the
footprint of the wall, and give them a lined texture. Then display
the wall as a wireframe.
Then pass the displaymode onto Arch Component's .setDisplayMode().
Parameters
----------
mode: str
The name of the display mode the view provider has switched to.
Returns
-------
str:
The name of the display mode the view provider has switched to. | Method called when the display mode changes. | [
"Method",
"called",
"when",
"the",
"display",
"mode",
"changes",
"."
] | def setDisplayMode(self,mode):
"""Method called when the display mode changes.
Called when the display mode changes, this method can be used to set
data that wasn't available when .attach() was called.
When Footprint is set as display mode, find the faces that make up the
footprint of the wall, and give them a lined texture. Then display
the wall as a wireframe.
Then pass the displaymode onto Arch Component's .setDisplayMode().
Parameters
----------
mode: str
The name of the display mode the view provider has switched to.
Returns
-------
str:
The name of the display mode the view provider has switched to.
"""
self.fset.coordIndex.deleteValues(0)
self.fcoords.point.deleteValues(0)
if mode == "Footprint":
if hasattr(self,"Object"):
faces = self.Object.Proxy.getFootprint(self.Object)
if faces:
verts = []
fdata = []
idx = 0
for face in faces:
tri = face.tessellate(1)
for v in tri[0]:
verts.append([v.x,v.y,v.z])
for f in tri[1]:
fdata.extend([f[0]+idx,f[1]+idx,f[2]+idx,-1])
idx += len(tri[0])
self.fcoords.point.setValues(verts)
self.fset.coordIndex.setValues(0,len(fdata),fdata)
return "Wireframe"
return ArchComponent.ViewProviderComponent.setDisplayMode(self,mode) | [
"def",
"setDisplayMode",
"(",
"self",
",",
"mode",
")",
":",
"self",
".",
"fset",
".",
"coordIndex",
".",
"deleteValues",
"(",
"0",
")",
"self",
".",
"fcoords",
".",
"point",
".",
"deleteValues",
"(",
"0",
")",
"if",
"mode",
"==",
"\"Footprint\"",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"Object\"",
")",
":",
"faces",
"=",
"self",
".",
"Object",
".",
"Proxy",
".",
"getFootprint",
"(",
"self",
".",
"Object",
")",
"if",
"faces",
":",
"verts",
"=",
"[",
"]",
"fdata",
"=",
"[",
"]",
"idx",
"=",
"0",
"for",
"face",
"in",
"faces",
":",
"tri",
"=",
"face",
".",
"tessellate",
"(",
"1",
")",
"for",
"v",
"in",
"tri",
"[",
"0",
"]",
":",
"verts",
".",
"append",
"(",
"[",
"v",
".",
"x",
",",
"v",
".",
"y",
",",
"v",
".",
"z",
"]",
")",
"for",
"f",
"in",
"tri",
"[",
"1",
"]",
":",
"fdata",
".",
"extend",
"(",
"[",
"f",
"[",
"0",
"]",
"+",
"idx",
",",
"f",
"[",
"1",
"]",
"+",
"idx",
",",
"f",
"[",
"2",
"]",
"+",
"idx",
",",
"-",
"1",
"]",
")",
"idx",
"+=",
"len",
"(",
"tri",
"[",
"0",
"]",
")",
"self",
".",
"fcoords",
".",
"point",
".",
"setValues",
"(",
"verts",
")",
"self",
".",
"fset",
".",
"coordIndex",
".",
"setValues",
"(",
"0",
",",
"len",
"(",
"fdata",
")",
",",
"fdata",
")",
"return",
"\"Wireframe\"",
"return",
"ArchComponent",
".",
"ViewProviderComponent",
".",
"setDisplayMode",
"(",
"self",
",",
"mode",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchWall.py#L1673-L1715 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.