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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/servermanager.py | python | ArrayListProperty.GetAvailable | (self) | return retVal | Returns the list of available arrays | Returns the list of available arrays | [
"Returns",
"the",
"list",
"of",
"available",
"arrays"
] | def GetAvailable(self):
"Returns the list of available arrays"
dm = self.SMProperty.FindDomain("vtkSMArraySelectionDomain")
if not dm:
dm = self.SMProperty.FindDomain("vtkSMChartSeriesSelectionDomain")
retVal = []
if dm:
for i in range(dm.GetNumberOfStrings()):
retVal.append(dm.GetString(i))
return retVal | [
"def",
"GetAvailable",
"(",
"self",
")",
":",
"dm",
"=",
"self",
".",
"SMProperty",
".",
"FindDomain",
"(",
"\"vtkSMArraySelectionDomain\"",
")",
"if",
"not",
"dm",
":",
"dm",
"=",
"self",
".",
"SMProperty",
".",
"FindDomain",
"(",
"\"vtkSMChartSeriesSelectionDomain\"",
")",
"retVal",
"=",
"[",
"]",
"if",
"dm",
":",
"for",
"i",
"in",
"range",
"(",
"dm",
".",
"GetNumberOfStrings",
"(",
")",
")",
":",
"retVal",
".",
"append",
"(",
"dm",
".",
"GetString",
"(",
"i",
")",
")",
"return",
"retVal"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/servermanager.py#L1119-L1128 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/math_ops.py | python | round | (x, name=None) | Rounds the values of a tensor to the nearest integer, element-wise.
For example:
```python
# 'a' is [0.9, 2.5, 2.3, -4.4]
tf.round(a) ==> [ 1.0, 3.0, 2.0, -4.0 ]
```
Args:
x: A `Tensor` of type `float32` or `float64`.
name: A name for the operation (optional).
Returns:
A `Tensor` of same shape and type as `x`. | Rounds the values of a tensor to the nearest integer, element-wise. | [
"Rounds",
"the",
"values",
"of",
"a",
"tensor",
"to",
"the",
"nearest",
"integer",
"element",
"-",
"wise",
"."
] | def round(x, name=None):
"""Rounds the values of a tensor to the nearest integer, element-wise.
For example:
```python
# 'a' is [0.9, 2.5, 2.3, -4.4]
tf.round(a) ==> [ 1.0, 3.0, 2.0, -4.0 ]
```
Args:
x: A `Tensor` of type `float32` or `float64`.
name: A name for the operation (optional).
Returns:
A `Tensor` of same shape and type as `x`.
"""
x = ops.convert_to_tensor(x, name="x")
if x.dtype.is_integer:
return x
else:
return gen_math_ops.floor(x + 0.5, name=name) | [
"def",
"round",
"(",
"x",
",",
"name",
"=",
"None",
")",
":",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
",",
"name",
"=",
"\"x\"",
")",
"if",
"x",
".",
"dtype",
".",
"is_integer",
":",
"return",
"x",
"else",
":",
"return",
"gen_math_ops",
".",
"floor",
"(",
"x",
"+",
"0.5",
",",
"name",
"=",
"name",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L563-L584 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/number-of-strings-that-appear-as-substrings-in-word.py | python | Solution.numOfStrings | (self, patterns, word) | return sum(len(trie.step(c)) for c in word) | :type patterns: List[str]
:type word: str
:rtype: int | :type patterns: List[str]
:type word: str
:rtype: int | [
":",
"type",
"patterns",
":",
"List",
"[",
"str",
"]",
":",
"type",
"word",
":",
"str",
":",
"rtype",
":",
"int"
] | def numOfStrings(self, patterns, word):
"""
:type patterns: List[str]
:type word: str
:rtype: int
"""
trie = AhoTrie(patterns)
return sum(len(trie.step(c)) for c in word) | [
"def",
"numOfStrings",
"(",
"self",
",",
"patterns",
",",
"word",
")",
":",
"trie",
"=",
"AhoTrie",
"(",
"patterns",
")",
"return",
"sum",
"(",
"len",
"(",
"trie",
".",
"step",
"(",
"c",
")",
")",
"for",
"c",
"in",
"word",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/number-of-strings-that-appear-as-substrings-in-word.py#L73-L80 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateSpan.GetTotalDays | (*args, **kwargs) | return _misc_.DateSpan_GetTotalDays(*args, **kwargs) | GetTotalDays(self) -> int | GetTotalDays(self) -> int | [
"GetTotalDays",
"(",
"self",
")",
"-",
">",
"int"
] | def GetTotalDays(*args, **kwargs):
"""GetTotalDays(self) -> int"""
return _misc_.DateSpan_GetTotalDays(*args, **kwargs) | [
"def",
"GetTotalDays",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_GetTotalDays",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4685-L4687 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | SizerItem.SetInitSize | (*args, **kwargs) | return _core_.SizerItem_SetInitSize(*args, **kwargs) | SetInitSize(self, int x, int y) | SetInitSize(self, int x, int y) | [
"SetInitSize",
"(",
"self",
"int",
"x",
"int",
"y",
")"
] | def SetInitSize(*args, **kwargs):
"""SetInitSize(self, int x, int y)"""
return _core_.SizerItem_SetInitSize(*args, **kwargs) | [
"def",
"SetInitSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SizerItem_SetInitSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L14113-L14115 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/prt/prt.py | python | PrtStrategy.preevaluate | (self, ids_person) | return preeval | Preevaluation strategies for person IDs in vector ids_person.
Returns a preevaluation vector with a preevaluation value
for each person ID. The values of the preevaluation vector are as follows:
-1 : Strategy cannot be applied
0 : Stategy can be applied, but the preferred mode is not used
1 : Stategy can be applied, and preferred mode is part of the strategy
2 : Strategy uses predomunantly preferred mode | Preevaluation strategies for person IDs in vector ids_person. | [
"Preevaluation",
"strategies",
"for",
"person",
"IDs",
"in",
"vector",
"ids_person",
"."
] | def preevaluate(self, ids_person):
"""
Preevaluation strategies for person IDs in vector ids_person.
Returns a preevaluation vector with a preevaluation value
for each person ID. The values of the preevaluation vector are as follows:
-1 : Strategy cannot be applied
0 : Stategy can be applied, but the preferred mode is not used
1 : Stategy can be applied, and preferred mode is part of the strategy
2 : Strategy uses predomunantly preferred mode
"""
n_pers = len(ids_person)
persons = self.get_virtualpop()
preeval = np.zeros(n_pers, dtype=np.int32)
# TODO: here we could exclude by age or distance facilities-stops
# put 0 for persons whose preference is not public transport
preeval[persons.ids_mode_preferred[ids_person] != self.prtservice.id_prtmode] = 0
# put 2 for persons with car access and who prefer cars
preeval[persons.ids_mode_preferred[ids_person] == self.prtservice.id_prtmode] = 2
print ' PrtStrategy.preevaluate', len(np.flatnonzero(preeval))
return preeval | [
"def",
"preevaluate",
"(",
"self",
",",
"ids_person",
")",
":",
"n_pers",
"=",
"len",
"(",
"ids_person",
")",
"persons",
"=",
"self",
".",
"get_virtualpop",
"(",
")",
"preeval",
"=",
"np",
".",
"zeros",
"(",
"n_pers",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"# TODO: here we could exclude by age or distance facilities-stops",
"# put 0 for persons whose preference is not public transport",
"preeval",
"[",
"persons",
".",
"ids_mode_preferred",
"[",
"ids_person",
"]",
"!=",
"self",
".",
"prtservice",
".",
"id_prtmode",
"]",
"=",
"0",
"# put 2 for persons with car access and who prefer cars",
"preeval",
"[",
"persons",
".",
"ids_mode_preferred",
"[",
"ids_person",
"]",
"==",
"self",
".",
"prtservice",
".",
"id_prtmode",
"]",
"=",
"2",
"print",
"' PrtStrategy.preevaluate'",
",",
"len",
"(",
"np",
".",
"flatnonzero",
"(",
"preeval",
")",
")",
"return",
"preeval"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/prt/prt.py#L4798-L4823 | |
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/containers.py | python | RepeatedCompositeFieldContainer.add | (self, **kwargs) | return new_element | Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element. | Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element. | [
"Adds",
"a",
"new",
"element",
"at",
"the",
"end",
"of",
"the",
"list",
"and",
"returns",
"it",
".",
"Keyword",
"arguments",
"may",
"be",
"used",
"to",
"initialize",
"the",
"element",
"."
] | def add(self, **kwargs):
"""Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element.
"""
new_element = self._message_descriptor._concrete_class(**kwargs)
new_element._SetListener(self._message_listener)
self._values.append(new_element)
if not self._message_listener.dirty:
self._message_listener.Modified()
return new_element | [
"def",
"add",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"new_element",
"=",
"self",
".",
"_message_descriptor",
".",
"_concrete_class",
"(",
"*",
"*",
"kwargs",
")",
"new_element",
".",
"_SetListener",
"(",
"self",
".",
"_message_listener",
")",
"self",
".",
"_values",
".",
"append",
"(",
"new_element",
")",
"if",
"not",
"self",
".",
"_message_listener",
".",
"dirty",
":",
"self",
".",
"_message_listener",
".",
"Modified",
"(",
")",
"return",
"new_element"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/containers.py#L212-L221 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/markupsafe/__init__.py | python | Markup.escape | (cls, s) | return rv | Escape the string. Works like :func:`escape` with the difference
that for subclasses of :class:`Markup` this function would return the
correct subclass. | Escape the string. Works like :func:`escape` with the difference
that for subclasses of :class:`Markup` this function would return the
correct subclass. | [
"Escape",
"the",
"string",
".",
"Works",
"like",
":",
"func",
":",
"escape",
"with",
"the",
"difference",
"that",
"for",
"subclasses",
"of",
":",
"class",
":",
"Markup",
"this",
"function",
"would",
"return",
"the",
"correct",
"subclass",
"."
] | def escape(cls, s):
"""Escape the string. Works like :func:`escape` with the difference
that for subclasses of :class:`Markup` this function would return the
correct subclass.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv | [
"def",
"escape",
"(",
"cls",
",",
"s",
")",
":",
"rv",
"=",
"escape",
"(",
"s",
")",
"if",
"rv",
".",
"__class__",
"is",
"not",
"cls",
":",
"return",
"cls",
"(",
"rv",
")",
"return",
"rv"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/markupsafe/__init__.py#L157-L165 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/quopri.py | python | needsquoting | (c, quotetabs, header) | return c == ESCAPE or not (' ' <= c <= '~') | Decide whether a particular character needs to be quoted.
The 'quotetabs' flag indicates whether embedded tabs and spaces should be
quoted. Note that line-ending tabs and spaces are always encoded, as per
RFC 1521. | Decide whether a particular character needs to be quoted. | [
"Decide",
"whether",
"a",
"particular",
"character",
"needs",
"to",
"be",
"quoted",
"."
] | def needsquoting(c, quotetabs, header):
"""Decide whether a particular character needs to be quoted.
The 'quotetabs' flag indicates whether embedded tabs and spaces should be
quoted. Note that line-ending tabs and spaces are always encoded, as per
RFC 1521.
"""
if c in ' \t':
return quotetabs
# if header, we have to escape _ because _ is used to escape space
if c == '_':
return header
return c == ESCAPE or not (' ' <= c <= '~') | [
"def",
"needsquoting",
"(",
"c",
",",
"quotetabs",
",",
"header",
")",
":",
"if",
"c",
"in",
"' \\t'",
":",
"return",
"quotetabs",
"# if header, we have to escape _ because _ is used to escape space",
"if",
"c",
"==",
"'_'",
":",
"return",
"header",
"return",
"c",
"==",
"ESCAPE",
"or",
"not",
"(",
"' '",
"<=",
"c",
"<=",
"'~'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/quopri.py#L21-L33 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/distributions/python/ops/bijectors/affine_impl.py | python | _TriLPlusVDVTLightweightOperatorPD.sqrt_matmul | (self, x) | return m_x + v_d_vt_x | Computes `matmul(self, x)`.
Doesn't actually do the sqrt! Named as such to agree with API.
Args:
x: `Tensor`
Returns:
self_times_x: `Tensor` | Computes `matmul(self, x)`. | [
"Computes",
"matmul",
"(",
"self",
"x",
")",
"."
] | def sqrt_matmul(self, x):
"""Computes `matmul(self, x)`.
Doesn't actually do the sqrt! Named as such to agree with API.
Args:
x: `Tensor`
Returns:
self_times_x: `Tensor`
"""
m_x = math_ops.matmul(self._m, x)
vt_x = math_ops.matmul(self._v, x, adjoint_a=True)
d_vt_x = self._d.matmul(vt_x)
v_d_vt_x = math_ops.matmul(self._v, d_vt_x)
return m_x + v_d_vt_x | [
"def",
"sqrt_matmul",
"(",
"self",
",",
"x",
")",
":",
"m_x",
"=",
"math_ops",
".",
"matmul",
"(",
"self",
".",
"_m",
",",
"x",
")",
"vt_x",
"=",
"math_ops",
".",
"matmul",
"(",
"self",
".",
"_v",
",",
"x",
",",
"adjoint_a",
"=",
"True",
")",
"d_vt_x",
"=",
"self",
".",
"_d",
".",
"matmul",
"(",
"vt_x",
")",
"v_d_vt_x",
"=",
"math_ops",
".",
"matmul",
"(",
"self",
".",
"_v",
",",
"d_vt_x",
")",
"return",
"m_x",
"+",
"v_d_vt_x"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/bijectors/affine_impl.py#L101-L116 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/py/py/_path/common.py | python | PathBase.dirname | (self) | return self._getbyspec('dirname')[0] | dirname part of path. | dirname part of path. | [
"dirname",
"part",
"of",
"path",
"."
] | def dirname(self):
""" dirname part of path. """
return self._getbyspec('dirname')[0] | [
"def",
"dirname",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getbyspec",
"(",
"'dirname'",
")",
"[",
"0",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_path/common.py#L144-L146 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_osx_support.py | python | _save_modified_value | (_config_vars, cv, newvalue) | Save modified and original unmodified value of configuration var | Save modified and original unmodified value of configuration var | [
"Save",
"modified",
"and",
"original",
"unmodified",
"value",
"of",
"configuration",
"var"
] | def _save_modified_value(_config_vars, cv, newvalue):
"""Save modified and original unmodified value of configuration var"""
oldvalue = _config_vars.get(cv, '')
if (oldvalue != newvalue) and (_INITPRE + cv not in _config_vars):
_config_vars[_INITPRE + cv] = oldvalue
_config_vars[cv] = newvalue | [
"def",
"_save_modified_value",
"(",
"_config_vars",
",",
"cv",
",",
"newvalue",
")",
":",
"oldvalue",
"=",
"_config_vars",
".",
"get",
"(",
"cv",
",",
"''",
")",
"if",
"(",
"oldvalue",
"!=",
"newvalue",
")",
"and",
"(",
"_INITPRE",
"+",
"cv",
"not",
"in",
"_config_vars",
")",
":",
"_config_vars",
"[",
"_INITPRE",
"+",
"cv",
"]",
"=",
"oldvalue",
"_config_vars",
"[",
"cv",
"]",
"=",
"newvalue"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_osx_support.py#L120-L126 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/filters.py | python | do_lower | (s: str) | return soft_str(s).lower() | Convert a value to lowercase. | Convert a value to lowercase. | [
"Convert",
"a",
"value",
"to",
"lowercase",
"."
] | def do_lower(s: str) -> str:
"""Convert a value to lowercase."""
return soft_str(s).lower() | [
"def",
"do_lower",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"return",
"soft_str",
"(",
"s",
")",
".",
"lower",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L269-L271 | |
amrayn/easyloggingpp | 8489989bb26c6371df103f6cbced3fbee1bc3c2f | tools/cpplint.py | python | CheckMakePairUsesDeduction | (filename, clean_lines, linenum, error) | Check that make_pair's template arguments are deduced.
G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Check that make_pair's template arguments are deduced. | [
"Check",
"that",
"make_pair",
"s",
"template",
"arguments",
"are",
"deduced",
"."
] | def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
"""Check that make_pair's template arguments are deduced.
G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4, # 4 = high confidence
'For C++11-compatibility, omit template arguments from make_pair'
' OR use pair directly OR if appropriate, construct a pair directly') | [
"def",
"CheckMakePairUsesDeduction",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"match",
"=",
"_RE_PATTERN_EXPLICIT_MAKEPAIR",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/explicit_make_pair'",
",",
"4",
",",
"# 4 = high confidence",
"'For C++11-compatibility, omit template arguments from make_pair'",
"' OR use pair directly OR if appropriate, construct a pair directly'",
")"
] | https://github.com/amrayn/easyloggingpp/blob/8489989bb26c6371df103f6cbced3fbee1bc3c2f/tools/cpplint.py#L4456-L4474 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/cluster/_feature_agglomeration.py | python | AgglomerationTransform.transform | (self, X) | return nX | Transform a new matrix using the built clustering
Parameters
----------
X : array-like of shape (n_samples, n_features) or (n_samples,)
A M by N array of M observations in N dimensions or a length
M array of M one-dimensional observations.
Returns
-------
Y : array, shape = [n_samples, n_clusters] or [n_clusters]
The pooled values for each feature cluster. | Transform a new matrix using the built clustering | [
"Transform",
"a",
"new",
"matrix",
"using",
"the",
"built",
"clustering"
] | def transform(self, X):
"""
Transform a new matrix using the built clustering
Parameters
----------
X : array-like of shape (n_samples, n_features) or (n_samples,)
A M by N array of M observations in N dimensions or a length
M array of M one-dimensional observations.
Returns
-------
Y : array, shape = [n_samples, n_clusters] or [n_clusters]
The pooled values for each feature cluster.
"""
check_is_fitted(self)
X = check_array(X)
if len(self.labels_) != X.shape[1]:
raise ValueError("X has a different number of features than "
"during fitting.")
if self.pooling_func == np.mean and not issparse(X):
size = np.bincount(self.labels_)
n_samples = X.shape[0]
# a fast way to compute the mean of grouped features
nX = np.array([np.bincount(self.labels_, X[i, :]) / size
for i in range(n_samples)])
else:
nX = [self.pooling_func(X[:, self.labels_ == l], axis=1)
for l in np.unique(self.labels_)]
nX = np.array(nX).T
return nX | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
")",
"X",
"=",
"check_array",
"(",
"X",
")",
"if",
"len",
"(",
"self",
".",
"labels_",
")",
"!=",
"X",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"X has a different number of features than \"",
"\"during fitting.\"",
")",
"if",
"self",
".",
"pooling_func",
"==",
"np",
".",
"mean",
"and",
"not",
"issparse",
"(",
"X",
")",
":",
"size",
"=",
"np",
".",
"bincount",
"(",
"self",
".",
"labels_",
")",
"n_samples",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"# a fast way to compute the mean of grouped features",
"nX",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"bincount",
"(",
"self",
".",
"labels_",
",",
"X",
"[",
"i",
",",
":",
"]",
")",
"/",
"size",
"for",
"i",
"in",
"range",
"(",
"n_samples",
")",
"]",
")",
"else",
":",
"nX",
"=",
"[",
"self",
".",
"pooling_func",
"(",
"X",
"[",
":",
",",
"self",
".",
"labels_",
"==",
"l",
"]",
",",
"axis",
"=",
"1",
")",
"for",
"l",
"in",
"np",
".",
"unique",
"(",
"self",
".",
"labels_",
")",
"]",
"nX",
"=",
"np",
".",
"array",
"(",
"nX",
")",
".",
"T",
"return",
"nX"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/cluster/_feature_agglomeration.py#L24-L55 | |
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/models/autoreg.py | python | _call | (model: AbstractARNN, inputs: Array) | return log_psi | Returns log_psi. | Returns log_psi. | [
"Returns",
"log_psi",
"."
] | def _call(model: AbstractARNN, inputs: Array) -> Array:
"""Returns log_psi."""
if inputs.ndim == 1:
inputs = jnp.expand_dims(inputs, axis=0)
idx = _local_states_to_numbers(model.hilbert, inputs)
idx = jnp.expand_dims(idx, axis=-1)
log_psi = _conditionals_log_psi(model, inputs)
log_psi = jnp.take_along_axis(log_psi, idx, axis=-1)
log_psi = log_psi.reshape((inputs.shape[0], -1)).sum(axis=1)
return log_psi | [
"def",
"_call",
"(",
"model",
":",
"AbstractARNN",
",",
"inputs",
":",
"Array",
")",
"->",
"Array",
":",
"if",
"inputs",
".",
"ndim",
"==",
"1",
":",
"inputs",
"=",
"jnp",
".",
"expand_dims",
"(",
"inputs",
",",
"axis",
"=",
"0",
")",
"idx",
"=",
"_local_states_to_numbers",
"(",
"model",
".",
"hilbert",
",",
"inputs",
")",
"idx",
"=",
"jnp",
".",
"expand_dims",
"(",
"idx",
",",
"axis",
"=",
"-",
"1",
")",
"log_psi",
"=",
"_conditionals_log_psi",
"(",
"model",
",",
"inputs",
")",
"log_psi",
"=",
"jnp",
".",
"take_along_axis",
"(",
"log_psi",
",",
"idx",
",",
"axis",
"=",
"-",
"1",
")",
"log_psi",
"=",
"log_psi",
".",
"reshape",
"(",
"(",
"inputs",
".",
"shape",
"[",
"0",
"]",
",",
"-",
"1",
")",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"return",
"log_psi"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/models/autoreg.py#L311-L324 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/json/__init__.py | python | loads | (s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw) | return cls(encoding=encoding, **kw).decode(s) | Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg. | Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object. | [
"Deserialize",
"s",
"(",
"a",
"str",
"or",
"unicode",
"instance",
"containing",
"a",
"JSON",
"document",
")",
"to",
"a",
"Python",
"object",
"."
] | def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if (cls is None and encoding is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
return cls(encoding=encoding, **kw).decode(s) | [
"def",
"loads",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"object_hook",
"=",
"None",
",",
"parse_float",
"=",
"None",
",",
"parse_int",
"=",
"None",
",",
"parse_constant",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"(",
"cls",
"is",
"None",
"and",
"encoding",
"is",
"None",
"and",
"object_hook",
"is",
"None",
"and",
"parse_int",
"is",
"None",
"and",
"parse_float",
"is",
"None",
"and",
"parse_constant",
"is",
"None",
"and",
"not",
"kw",
")",
":",
"return",
"_default_decoder",
".",
"decode",
"(",
"s",
")",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"JSONDecoder",
"if",
"object_hook",
"is",
"not",
"None",
":",
"kw",
"[",
"'object_hook'",
"]",
"=",
"object_hook",
"if",
"parse_float",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_float'",
"]",
"=",
"parse_float",
"if",
"parse_int",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_int'",
"]",
"=",
"parse_int",
"if",
"parse_constant",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_constant'",
"]",
"=",
"parse_constant",
"return",
"cls",
"(",
"encoding",
"=",
"encoding",
",",
"*",
"*",
"kw",
")",
".",
"decode",
"(",
"s",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/json/__init__.py#L270-L318 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PGChoices.RemoveAt | (*args, **kwargs) | return _propgrid.PGChoices_RemoveAt(*args, **kwargs) | RemoveAt(self, size_t nIndex, size_t count=1) | RemoveAt(self, size_t nIndex, size_t count=1) | [
"RemoveAt",
"(",
"self",
"size_t",
"nIndex",
"size_t",
"count",
"=",
"1",
")"
] | def RemoveAt(*args, **kwargs):
"""RemoveAt(self, size_t nIndex, size_t count=1)"""
return _propgrid.PGChoices_RemoveAt(*args, **kwargs) | [
"def",
"RemoveAt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGChoices_RemoveAt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L316-L318 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/word-abbreviation.py | python | Solution.wordsAbbreviation | (self, dict) | return [word_to_abbr[word] for word in dict] | :type dict: List[str]
:rtype: List[str] | :type dict: List[str]
:rtype: List[str] | [
":",
"type",
"dict",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"List",
"[",
"str",
"]"
] | def wordsAbbreviation(self, dict):
"""
:type dict: List[str]
:rtype: List[str]
"""
def isUnique(prefix, words):
return sum(word.startswith(prefix) for word in words) == 1
def toAbbr(prefix, word):
abbr = prefix + str(len(word) - 1 - len(prefix)) + word[-1]
return abbr if len(abbr) < len(word) else word
abbr_to_word = collections.defaultdict(set)
word_to_abbr = {}
for word in dict:
prefix = word[:1]
abbr_to_word[toAbbr(prefix, word)].add(word)
for abbr, conflicts in abbr_to_word.iteritems():
if len(conflicts) > 1:
for word in conflicts:
for i in xrange(2, len(word)):
prefix = word[:i]
if isUnique(prefix, conflicts):
word_to_abbr[word] = toAbbr(prefix, word)
break
else:
word_to_abbr[conflicts.pop()] = abbr
return [word_to_abbr[word] for word in dict] | [
"def",
"wordsAbbreviation",
"(",
"self",
",",
"dict",
")",
":",
"def",
"isUnique",
"(",
"prefix",
",",
"words",
")",
":",
"return",
"sum",
"(",
"word",
".",
"startswith",
"(",
"prefix",
")",
"for",
"word",
"in",
"words",
")",
"==",
"1",
"def",
"toAbbr",
"(",
"prefix",
",",
"word",
")",
":",
"abbr",
"=",
"prefix",
"+",
"str",
"(",
"len",
"(",
"word",
")",
"-",
"1",
"-",
"len",
"(",
"prefix",
")",
")",
"+",
"word",
"[",
"-",
"1",
"]",
"return",
"abbr",
"if",
"len",
"(",
"abbr",
")",
"<",
"len",
"(",
"word",
")",
"else",
"word",
"abbr_to_word",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"word_to_abbr",
"=",
"{",
"}",
"for",
"word",
"in",
"dict",
":",
"prefix",
"=",
"word",
"[",
":",
"1",
"]",
"abbr_to_word",
"[",
"toAbbr",
"(",
"prefix",
",",
"word",
")",
"]",
".",
"add",
"(",
"word",
")",
"for",
"abbr",
",",
"conflicts",
"in",
"abbr_to_word",
".",
"iteritems",
"(",
")",
":",
"if",
"len",
"(",
"conflicts",
")",
">",
"1",
":",
"for",
"word",
"in",
"conflicts",
":",
"for",
"i",
"in",
"xrange",
"(",
"2",
",",
"len",
"(",
"word",
")",
")",
":",
"prefix",
"=",
"word",
"[",
":",
"i",
"]",
"if",
"isUnique",
"(",
"prefix",
",",
"conflicts",
")",
":",
"word_to_abbr",
"[",
"word",
"]",
"=",
"toAbbr",
"(",
"prefix",
",",
"word",
")",
"break",
"else",
":",
"word_to_abbr",
"[",
"conflicts",
".",
"pop",
"(",
")",
"]",
"=",
"abbr",
"return",
"[",
"word_to_abbr",
"[",
"word",
"]",
"for",
"word",
"in",
"dict",
"]"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/word-abbreviation.py#L8-L38 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py | python | _mask_to_weights | (mask=None) | return weights | Converts a binary mask to a set of weights.
Args:
mask: A binary `Tensor`.
Returns:
The corresponding set of weights if `mask` is not `None`, otherwise `None`. | Converts a binary mask to a set of weights. | [
"Converts",
"a",
"binary",
"mask",
"to",
"a",
"set",
"of",
"weights",
"."
] | def _mask_to_weights(mask=None):
"""Converts a binary mask to a set of weights.
Args:
mask: A binary `Tensor`.
Returns:
The corresponding set of weights if `mask` is not `None`, otherwise `None`.
"""
if mask is not None:
check_ops.assert_type(mask, dtypes.bool)
weights = math_ops.logical_not(mask)
else:
weights = None
return weights | [
"def",
"_mask_to_weights",
"(",
"mask",
"=",
"None",
")",
":",
"if",
"mask",
"is",
"not",
"None",
":",
"check_ops",
".",
"assert_type",
"(",
"mask",
",",
"dtypes",
".",
"bool",
")",
"weights",
"=",
"math_ops",
".",
"logical_not",
"(",
"mask",
")",
"else",
":",
"weights",
"=",
"None",
"return",
"weights"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py#L43-L57 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Misc.bind_all | (self, sequence=None, func=None, add=None) | return self._bind(('bind', 'all'), sequence, func, add, 0) | Bind to all widgets at an event SEQUENCE a call to function FUNC.
An additional boolean parameter ADD specifies whether FUNC will
be called additionally to the other bound function or whether
it will replace the previous function. See bind for the return value. | Bind to all widgets at an event SEQUENCE a call to function FUNC.
An additional boolean parameter ADD specifies whether FUNC will
be called additionally to the other bound function or whether
it will replace the previous function. See bind for the return value. | [
"Bind",
"to",
"all",
"widgets",
"at",
"an",
"event",
"SEQUENCE",
"a",
"call",
"to",
"function",
"FUNC",
".",
"An",
"additional",
"boolean",
"parameter",
"ADD",
"specifies",
"whether",
"FUNC",
"will",
"be",
"called",
"additionally",
"to",
"the",
"other",
"bound",
"function",
"or",
"whether",
"it",
"will",
"replace",
"the",
"previous",
"function",
".",
"See",
"bind",
"for",
"the",
"return",
"value",
"."
] | def bind_all(self, sequence=None, func=None, add=None):
"""Bind to all widgets at an event SEQUENCE a call to function FUNC.
An additional boolean parameter ADD specifies whether FUNC will
be called additionally to the other bound function or whether
it will replace the previous function. See bind for the return value."""
return self._bind(('bind', 'all'), sequence, func, add, 0) | [
"def",
"bind_all",
"(",
"self",
",",
"sequence",
"=",
"None",
",",
"func",
"=",
"None",
",",
"add",
"=",
"None",
")",
":",
"return",
"self",
".",
"_bind",
"(",
"(",
"'bind'",
",",
"'all'",
")",
",",
"sequence",
",",
"func",
",",
"add",
",",
"0",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1258-L1263 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | ppapi/generators/idl_parser.py | python | IDLParser.p_optional | (self, p) | optional : OPTIONAL
| | optional : OPTIONAL
| | [
"optional",
":",
"OPTIONAL",
"|"
] | def p_optional(self, p):
"""optional : OPTIONAL
| """
if len(p) == 2:
p[0] = self.BuildAttribute('OPTIONAL', True) | [
"def",
"p_optional",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"BuildAttribute",
"(",
"'OPTIONAL'",
",",
"True",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/ppapi/generators/idl_parser.py#L562-L566 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/contrib/slim/quantization/imperative/fuse_utils.py | python | _fuse_linear_bn | (linear, bn) | fuse linear and bn | fuse linear and bn | [
"fuse",
"linear",
"and",
"bn"
] | def _fuse_linear_bn(linear, bn):
'''fuse linear and bn'''
assert (linear.training == bn.training),\
"Linear and BN both must be in the same mode (train or eval)."
if linear.training:
assert bn._num_features == linear.weight.shape[
1], 'Output channel of Linear must match num_features of BatchNorm'
raise NotImplementedError
else:
return _fuse_linear_bn_eval(linear, bn) | [
"def",
"_fuse_linear_bn",
"(",
"linear",
",",
"bn",
")",
":",
"assert",
"(",
"linear",
".",
"training",
"==",
"bn",
".",
"training",
")",
",",
"\"Linear and BN both must be in the same mode (train or eval).\"",
"if",
"linear",
".",
"training",
":",
"assert",
"bn",
".",
"_num_features",
"==",
"linear",
".",
"weight",
".",
"shape",
"[",
"1",
"]",
",",
"'Output channel of Linear must match num_features of BatchNorm'",
"raise",
"NotImplementedError",
"else",
":",
"return",
"_fuse_linear_bn_eval",
"(",
"linear",
",",
"bn",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/slim/quantization/imperative/fuse_utils.py#L131-L140 | ||
alibaba/graph-learn | 54cafee9db3054dc310a28b856be7f97c7d5aee9 | graphlearn/python/graph.py | python | Graph.neighbor_sampler | (self,
meta_path,
expand_factor,
strategy="random") | return getattr(samplers, sampler)(self,
meta_path,
expand_factor,
strategy=strategy) | Sampler for sample neighbors and edges along a meta path.
The neighbors of the seed nodes and edges between seed nodes and
neighbors are called layer.
Args:
meta_path (list): A list of edge_type.
expand_factor (int | list): Number of neighbors sampled from all
the dst nodes of the node along the corresponding meta_path.
int: indicates the number of neighbors sampled for each node.
list of int: indicates the number of neighbors sampled for each node of
each hop, and length of expand_factor is same with length of meta_path.
strategy (string): Indicates how to sample meta paths,
"edge_weight", "random", "in_degree" are supported.
"edge_weight": sample neighbor nodes by the edge weight between seed
node and dst node.
"random": randomly sample neighbor nodes.
"in_degree": sample neighbor nodes by the in degree of the neighbors.
Return:
A 'NeighborSampler' object. | Sampler for sample neighbors and edges along a meta path.
The neighbors of the seed nodes and edges between seed nodes and
neighbors are called layer. | [
"Sampler",
"for",
"sample",
"neighbors",
"and",
"edges",
"along",
"a",
"meta",
"path",
".",
"The",
"neighbors",
"of",
"the",
"seed",
"nodes",
"and",
"edges",
"between",
"seed",
"nodes",
"and",
"neighbors",
"are",
"called",
"layer",
"."
] | def neighbor_sampler(self,
meta_path,
expand_factor,
strategy="random"):
""" Sampler for sample neighbors and edges along a meta path.
The neighbors of the seed nodes and edges between seed nodes and
neighbors are called layer.
Args:
meta_path (list): A list of edge_type.
expand_factor (int | list): Number of neighbors sampled from all
the dst nodes of the node along the corresponding meta_path.
int: indicates the number of neighbors sampled for each node.
list of int: indicates the number of neighbors sampled for each node of
each hop, and length of expand_factor is same with length of meta_path.
strategy (string): Indicates how to sample meta paths,
"edge_weight", "random", "in_degree" are supported.
"edge_weight": sample neighbor nodes by the edge weight between seed
node and dst node.
"random": randomly sample neighbor nodes.
"in_degree": sample neighbor nodes by the in degree of the neighbors.
Return:
A 'NeighborSampler' object.
"""
sampler = utils.strategy2op(strategy, "NeighborSampler")
return getattr(samplers, sampler)(self,
meta_path,
expand_factor,
strategy=strategy) | [
"def",
"neighbor_sampler",
"(",
"self",
",",
"meta_path",
",",
"expand_factor",
",",
"strategy",
"=",
"\"random\"",
")",
":",
"sampler",
"=",
"utils",
".",
"strategy2op",
"(",
"strategy",
",",
"\"NeighborSampler\"",
")",
"return",
"getattr",
"(",
"samplers",
",",
"sampler",
")",
"(",
"self",
",",
"meta_path",
",",
"expand_factor",
",",
"strategy",
"=",
"strategy",
")"
] | https://github.com/alibaba/graph-learn/blob/54cafee9db3054dc310a28b856be7f97c7d5aee9/graphlearn/python/graph.py#L594-L623 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/linalg/_interpolative_backend.py | python | iddp_aid | (eps, A) | return k, idx, proj | Compute ID of a real matrix to a specified relative precision using random
sampling.
:param eps:
Relative precision.
:type eps: float
:param A:
Matrix.
:type A: :class:`numpy.ndarray`
:return:
Rank of ID.
:rtype: int
:return:
Column index array.
:rtype: :class:`numpy.ndarray`
:return:
Interpolation coefficients.
:rtype: :class:`numpy.ndarray` | Compute ID of a real matrix to a specified relative precision using random
sampling. | [
"Compute",
"ID",
"of",
"a",
"real",
"matrix",
"to",
"a",
"specified",
"relative",
"precision",
"using",
"random",
"sampling",
"."
] | def iddp_aid(eps, A):
"""
Compute ID of a real matrix to a specified relative precision using random
sampling.
:param eps:
Relative precision.
:type eps: float
:param A:
Matrix.
:type A: :class:`numpy.ndarray`
:return:
Rank of ID.
:rtype: int
:return:
Column index array.
:rtype: :class:`numpy.ndarray`
:return:
Interpolation coefficients.
:rtype: :class:`numpy.ndarray`
"""
A = np.asfortranarray(A)
m, n = A.shape
n2, w = idd_frmi(m)
proj = np.empty(n*(2*n2 + 1) + n2 + 1, order='F')
k, idx, proj = _id.iddp_aid(eps, A, w, proj)
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
return k, idx, proj | [
"def",
"iddp_aid",
"(",
"eps",
",",
"A",
")",
":",
"A",
"=",
"np",
".",
"asfortranarray",
"(",
"A",
")",
"m",
",",
"n",
"=",
"A",
".",
"shape",
"n2",
",",
"w",
"=",
"idd_frmi",
"(",
"m",
")",
"proj",
"=",
"np",
".",
"empty",
"(",
"n",
"*",
"(",
"2",
"*",
"n2",
"+",
"1",
")",
"+",
"n2",
"+",
"1",
",",
"order",
"=",
"'F'",
")",
"k",
",",
"idx",
",",
"proj",
"=",
"_id",
".",
"iddp_aid",
"(",
"eps",
",",
"A",
",",
"w",
",",
"proj",
")",
"proj",
"=",
"proj",
"[",
":",
"k",
"*",
"(",
"n",
"-",
"k",
")",
"]",
".",
"reshape",
"(",
"(",
"k",
",",
"n",
"-",
"k",
")",
",",
"order",
"=",
"'F'",
")",
"return",
"k",
",",
"idx",
",",
"proj"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/_interpolative_backend.py#L484-L512 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Image.GetOrFindMaskColour | (*args, **kwargs) | return _core_.Image_GetOrFindMaskColour(*args, **kwargs) | GetOrFindMaskColour() -> (r,g,b)
Get the current mask colour or find a suitable colour. | GetOrFindMaskColour() -> (r,g,b) | [
"GetOrFindMaskColour",
"()",
"-",
">",
"(",
"r",
"g",
"b",
")"
] | def GetOrFindMaskColour(*args, **kwargs):
"""
GetOrFindMaskColour() -> (r,g,b)
Get the current mask colour or find a suitable colour.
"""
return _core_.Image_GetOrFindMaskColour(*args, **kwargs) | [
"def",
"GetOrFindMaskColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_GetOrFindMaskColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L3442-L3448 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/special/_ellip_harm.py | python | ellip_harm | (h2, k2, n, p, s, signm=1, signn=1) | return _ellip_harm(h2, k2, n, p, s, signm, signn) | r"""
Ellipsoidal harmonic functions E^p_n(l)
These are also known as Lame functions of the first kind, and are
solutions to the Lame equation:
.. math:: (s^2 - h^2)(s^2 - k^2)E''(s) + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0
where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
returned) corresponding to the solutions.
Parameters
----------
h2 : float
``h**2``
k2 : float
``k**2``; should be larger than ``h**2``
n : int
Degree
s : float
Coordinate
p : int
Order, can range between [1,2n+1]
signm : {1, -1}, optional
Sign of prefactor of functions. Can be +/-1. See Notes.
signn : {1, -1}, optional
Sign of prefactor of functions. Can be +/-1. See Notes.
Returns
-------
E : float
the harmonic :math:`E^p_n(s)`
See Also
--------
ellip_harm_2, ellip_normal
Notes
-----
The geometric interpretation of the ellipsoidal functions is
explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the
sign of prefactors for functions according to their type::
K : +1
L : signm
M : signn
N : signm*signn
.. versionadded:: 0.15.0
References
----------
.. [1] Digital Library of Mathematical Functions 29.12
https://dlmf.nist.gov/29.12
.. [2] Bardhan and Knepley, "Computational science and
re-discovery: open-source implementations of
ellipsoidal harmonics for problems in potential theory",
Comput. Sci. Disc. 5, 014006 (2012)
:doi:`10.1088/1749-4699/5/1/014006`.
.. [3] David J.and Dechambre P, "Computation of Ellipsoidal
Gravity Field Harmonics for small solar system bodies"
pp. 30-36, 2000
.. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications"
pp. 418, 2012
Examples
--------
>>> from scipy.special import ellip_harm
>>> w = ellip_harm(5,8,1,1,2.5)
>>> w
2.5
Check that the functions indeed are solutions to the Lame equation:
>>> from scipy.interpolate import UnivariateSpline
>>> def eigenvalue(f, df, ddf):
... r = ((s**2 - h**2)*(s**2 - k**2)*ddf + s*(2*s**2 - h**2 - k**2)*df - n*(n+1)*s**2*f)/f
... return -r.mean(), r.std()
>>> s = np.linspace(0.1, 10, 200)
>>> k, h, n, p = 8.0, 2.2, 3, 2
>>> E = ellip_harm(h**2, k**2, n, p, s)
>>> E_spl = UnivariateSpline(s, E)
>>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2))
>>> a, a_err
(583.44366156701483, 6.4580890640310646e-11) | r"""
Ellipsoidal harmonic functions E^p_n(l) | [
"r",
"Ellipsoidal",
"harmonic",
"functions",
"E^p_n",
"(",
"l",
")"
] | def ellip_harm(h2, k2, n, p, s, signm=1, signn=1):
r"""
Ellipsoidal harmonic functions E^p_n(l)
These are also known as Lame functions of the first kind, and are
solutions to the Lame equation:
.. math:: (s^2 - h^2)(s^2 - k^2)E''(s) + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0
where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
returned) corresponding to the solutions.
Parameters
----------
h2 : float
``h**2``
k2 : float
``k**2``; should be larger than ``h**2``
n : int
Degree
s : float
Coordinate
p : int
Order, can range between [1,2n+1]
signm : {1, -1}, optional
Sign of prefactor of functions. Can be +/-1. See Notes.
signn : {1, -1}, optional
Sign of prefactor of functions. Can be +/-1. See Notes.
Returns
-------
E : float
the harmonic :math:`E^p_n(s)`
See Also
--------
ellip_harm_2, ellip_normal
Notes
-----
The geometric interpretation of the ellipsoidal functions is
explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the
sign of prefactors for functions according to their type::
K : +1
L : signm
M : signn
N : signm*signn
.. versionadded:: 0.15.0
References
----------
.. [1] Digital Library of Mathematical Functions 29.12
https://dlmf.nist.gov/29.12
.. [2] Bardhan and Knepley, "Computational science and
re-discovery: open-source implementations of
ellipsoidal harmonics for problems in potential theory",
Comput. Sci. Disc. 5, 014006 (2012)
:doi:`10.1088/1749-4699/5/1/014006`.
.. [3] David J.and Dechambre P, "Computation of Ellipsoidal
Gravity Field Harmonics for small solar system bodies"
pp. 30-36, 2000
.. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications"
pp. 418, 2012
Examples
--------
>>> from scipy.special import ellip_harm
>>> w = ellip_harm(5,8,1,1,2.5)
>>> w
2.5
Check that the functions indeed are solutions to the Lame equation:
>>> from scipy.interpolate import UnivariateSpline
>>> def eigenvalue(f, df, ddf):
... r = ((s**2 - h**2)*(s**2 - k**2)*ddf + s*(2*s**2 - h**2 - k**2)*df - n*(n+1)*s**2*f)/f
... return -r.mean(), r.std()
>>> s = np.linspace(0.1, 10, 200)
>>> k, h, n, p = 8.0, 2.2, 3, 2
>>> E = ellip_harm(h**2, k**2, n, p, s)
>>> E_spl = UnivariateSpline(s, E)
>>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2))
>>> a, a_err
(583.44366156701483, 6.4580890640310646e-11)
"""
return _ellip_harm(h2, k2, n, p, s, signm, signn) | [
"def",
"ellip_harm",
"(",
"h2",
",",
"k2",
",",
"n",
",",
"p",
",",
"s",
",",
"signm",
"=",
"1",
",",
"signn",
"=",
"1",
")",
":",
"return",
"_ellip_harm",
"(",
"h2",
",",
"k2",
",",
"n",
",",
"p",
",",
"s",
",",
"signm",
",",
"signn",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/special/_ellip_harm.py#L9-L97 | |
cksystemsgroup/scalloc | 049857919b5fa1d539c9e4206e353daca2e87394 | tools/cpplint.py | python | ParseArguments | (args) | return filenames | Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint. | Parses the command line arguments. | [
"Parses",
"the",
"command",
"line",
"arguments",
"."
] | def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
'linelength=',
'extensions='])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
filters = val
if not filters:
PrintCategories()
elif opt == '--counting':
if val not in ('total', 'toplevel', 'detailed'):
PrintUsage('Valid counting options are total, toplevel, and detailed')
counting_style = val
elif opt == '--root':
global _root
_root = val
elif opt == '--linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage('Line length must be digits.')
elif opt == '--extensions':
global _valid_extensions
try:
_valid_extensions = set(val.split(','))
except ValueError:
PrintUsage('Extensions must be comma seperated list.')
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames | [
"def",
"ParseArguments",
"(",
"args",
")",
":",
"try",
":",
"(",
"opts",
",",
"filenames",
")",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"''",
",",
"[",
"'help'",
",",
"'output='",
",",
"'verbose='",
",",
"'counting='",
",",
"'filter='",
",",
"'root='",
",",
"'linelength='",
",",
"'extensions='",
"]",
")",
"except",
"getopt",
".",
"GetoptError",
":",
"PrintUsage",
"(",
"'Invalid arguments.'",
")",
"verbosity",
"=",
"_VerboseLevel",
"(",
")",
"output_format",
"=",
"_OutputFormat",
"(",
")",
"filters",
"=",
"''",
"counting_style",
"=",
"''",
"for",
"(",
"opt",
",",
"val",
")",
"in",
"opts",
":",
"if",
"opt",
"==",
"'--help'",
":",
"PrintUsage",
"(",
"None",
")",
"elif",
"opt",
"==",
"'--output'",
":",
"if",
"val",
"not",
"in",
"(",
"'emacs'",
",",
"'vs7'",
",",
"'eclipse'",
")",
":",
"PrintUsage",
"(",
"'The only allowed output formats are emacs, vs7 and eclipse.'",
")",
"output_format",
"=",
"val",
"elif",
"opt",
"==",
"'--verbose'",
":",
"verbosity",
"=",
"int",
"(",
"val",
")",
"elif",
"opt",
"==",
"'--filter'",
":",
"filters",
"=",
"val",
"if",
"not",
"filters",
":",
"PrintCategories",
"(",
")",
"elif",
"opt",
"==",
"'--counting'",
":",
"if",
"val",
"not",
"in",
"(",
"'total'",
",",
"'toplevel'",
",",
"'detailed'",
")",
":",
"PrintUsage",
"(",
"'Valid counting options are total, toplevel, and detailed'",
")",
"counting_style",
"=",
"val",
"elif",
"opt",
"==",
"'--root'",
":",
"global",
"_root",
"_root",
"=",
"val",
"elif",
"opt",
"==",
"'--linelength'",
":",
"global",
"_line_length",
"try",
":",
"_line_length",
"=",
"int",
"(",
"val",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"'Line length must be digits.'",
")",
"elif",
"opt",
"==",
"'--extensions'",
":",
"global",
"_valid_extensions",
"try",
":",
"_valid_extensions",
"=",
"set",
"(",
"val",
".",
"split",
"(",
"','",
")",
")",
"except",
"ValueError",
":",
"PrintUsage",
"(",
"'Extensions must be comma seperated list.'",
")",
"if",
"not",
"filenames",
":",
"PrintUsage",
"(",
"'No files were specified.'",
")",
"_SetOutputFormat",
"(",
"output_format",
")",
"_SetVerboseLevel",
"(",
"verbosity",
")",
"_SetFilters",
"(",
"filters",
")",
"_SetCountingStyle",
"(",
"counting_style",
")",
"return",
"filenames"
] | https://github.com/cksystemsgroup/scalloc/blob/049857919b5fa1d539c9e4206e353daca2e87394/tools/cpplint.py#L4664-L4731 | |
asLody/whale | 6a661b27cc4cf83b7b5a3b02451597ee1ac7f264 | whale/cpplint.py | python | FindNextMultiLineCommentEnd | (lines, lineix) | return len(lines) | We are inside a comment, find the end marker. | We are inside a comment, find the end marker. | [
"We",
"are",
"inside",
"a",
"comment",
"find",
"the",
"end",
"marker",
"."
] | def FindNextMultiLineCommentEnd(lines, lineix):
"""We are inside a comment, find the end marker."""
while lineix < len(lines):
if lines[lineix].strip().endswith('*/'):
return lineix
lineix += 1
return len(lines) | [
"def",
"FindNextMultiLineCommentEnd",
"(",
"lines",
",",
"lineix",
")",
":",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"endswith",
"(",
"'*/'",
")",
":",
"return",
"lineix",
"lineix",
"+=",
"1",
"return",
"len",
"(",
"lines",
")"
] | https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L1375-L1381 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime_IsLeapYear | (*args, **kwargs) | return _misc_.DateTime_IsLeapYear(*args, **kwargs) | DateTime_IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool | DateTime_IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool | [
"DateTime_IsLeapYear",
"(",
"int",
"year",
"=",
"Inv_Year",
"int",
"cal",
"=",
"Gregorian",
")",
"-",
">",
"bool"
] | def DateTime_IsLeapYear(*args, **kwargs):
"""DateTime_IsLeapYear(int year=Inv_Year, int cal=Gregorian) -> bool"""
return _misc_.DateTime_IsLeapYear(*args, **kwargs) | [
"def",
"DateTime_IsLeapYear",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_IsLeapYear",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4249-L4251 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | FontDialog.GetFontData | (*args, **kwargs) | return _windows_.FontDialog_GetFontData(*args, **kwargs) | GetFontData(self) -> FontData
Returns a reference to the internal `wx.FontData` used by the
wx.FontDialog. | GetFontData(self) -> FontData | [
"GetFontData",
"(",
"self",
")",
"-",
">",
"FontData"
] | def GetFontData(*args, **kwargs):
"""
GetFontData(self) -> FontData
Returns a reference to the internal `wx.FontData` used by the
wx.FontDialog.
"""
return _windows_.FontDialog_GetFontData(*args, **kwargs) | [
"def",
"GetFontData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"FontDialog_GetFontData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L3600-L3607 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/arrays/datetimelike.py | python | maybe_infer_freq | (freq) | return freq, freq_infer | Comparing a DateOffset to the string "infer" raises, so we need to
be careful about comparisons. Make a dummy variable `freq_infer` to
signify the case where the given freq is "infer" and set freq to None
to avoid comparison trouble later on.
Parameters
----------
freq : {DateOffset, None, str}
Returns
-------
freq : {DateOffset, None}
freq_infer : bool | Comparing a DateOffset to the string "infer" raises, so we need to
be careful about comparisons. Make a dummy variable `freq_infer` to
signify the case where the given freq is "infer" and set freq to None
to avoid comparison trouble later on. | [
"Comparing",
"a",
"DateOffset",
"to",
"the",
"string",
"infer",
"raises",
"so",
"we",
"need",
"to",
"be",
"careful",
"about",
"comparisons",
".",
"Make",
"a",
"dummy",
"variable",
"freq_infer",
"to",
"signify",
"the",
"case",
"where",
"the",
"given",
"freq",
"is",
"infer",
"and",
"set",
"freq",
"to",
"None",
"to",
"avoid",
"comparison",
"trouble",
"later",
"on",
"."
] | def maybe_infer_freq(freq):
"""
Comparing a DateOffset to the string "infer" raises, so we need to
be careful about comparisons. Make a dummy variable `freq_infer` to
signify the case where the given freq is "infer" and set freq to None
to avoid comparison trouble later on.
Parameters
----------
freq : {DateOffset, None, str}
Returns
-------
freq : {DateOffset, None}
freq_infer : bool
"""
freq_infer = False
if not isinstance(freq, DateOffset):
# if a passed freq is None, don't infer automatically
if freq != 'infer':
freq = frequencies.to_offset(freq)
else:
freq_infer = True
freq = None
return freq, freq_infer | [
"def",
"maybe_infer_freq",
"(",
"freq",
")",
":",
"freq_infer",
"=",
"False",
"if",
"not",
"isinstance",
"(",
"freq",
",",
"DateOffset",
")",
":",
"# if a passed freq is None, don't infer automatically",
"if",
"freq",
"!=",
"'infer'",
":",
"freq",
"=",
"frequencies",
".",
"to_offset",
"(",
"freq",
")",
"else",
":",
"freq_infer",
"=",
"True",
"freq",
"=",
"None",
"return",
"freq",
",",
"freq_infer"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/datetimelike.py#L1537-L1561 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/specs/python/specs_ops.py | python | Var | (name, *args, **kw) | return specs_lib.Callable(var) | Implements an operator that generates a variable.
This function is still experimental. Use it only
for generating a single variable instance for
each name.
Args:
name: Name of the variable.
*args: Other arguments to get_variable.
**kw: Other keywords for get_variable.
Returns:
A specs object for generating a variable. | Implements an operator that generates a variable. | [
"Implements",
"an",
"operator",
"that",
"generates",
"a",
"variable",
"."
] | def Var(name, *args, **kw):
"""Implements an operator that generates a variable.
This function is still experimental. Use it only
for generating a single variable instance for
each name.
Args:
name: Name of the variable.
*args: Other arguments to get_variable.
**kw: Other keywords for get_variable.
Returns:
A specs object for generating a variable.
"""
def var(_):
return variable_scope.get_variable(name, *args, **kw)
return specs_lib.Callable(var) | [
"def",
"Var",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"def",
"var",
"(",
"_",
")",
":",
"return",
"variable_scope",
".",
"get_variable",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"specs_lib",
".",
"Callable",
"(",
"var",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/specs/python/specs_ops.py#L136-L155 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Tools/gnu_dirs.py | python | configure | (conf) | Reads the command-line options to set lots of variables in *conf.env*. The variables
BINDIR and LIBDIR will be overwritten. | Reads the command-line options to set lots of variables in *conf.env*. The variables
BINDIR and LIBDIR will be overwritten. | [
"Reads",
"the",
"command",
"-",
"line",
"options",
"to",
"set",
"lots",
"of",
"variables",
"in",
"*",
"conf",
".",
"env",
"*",
".",
"The",
"variables",
"BINDIR",
"and",
"LIBDIR",
"will",
"be",
"overwritten",
"."
] | def configure(conf):
"""
Reads the command-line options to set lots of variables in *conf.env*. The variables
BINDIR and LIBDIR will be overwritten.
"""
def get_param(varname, default):
return getattr(Options.options, varname, '') or default
env = conf.env
env.LIBDIR = env.BINDIR = []
env.EXEC_PREFIX = get_param('EXEC_PREFIX', env.PREFIX)
env.PACKAGE = getattr(Context.g_module, 'APPNAME', None) or env.PACKAGE
complete = False
iter = 0
while not complete and iter < len(_options) + 1:
iter += 1
complete = True
for name, help, default in _options:
name = name.upper()
if not env[name]:
try:
env[name] = Utils.subst_vars(get_param(name, default).replace('/', os.sep), env)
except TypeError:
complete = False
if not complete:
lst = [x for x, _, _ in _options if not env[x.upper()]]
raise conf.errors.WafError('Variable substitution failure %r' % lst) | [
"def",
"configure",
"(",
"conf",
")",
":",
"def",
"get_param",
"(",
"varname",
",",
"default",
")",
":",
"return",
"getattr",
"(",
"Options",
".",
"options",
",",
"varname",
",",
"''",
")",
"or",
"default",
"env",
"=",
"conf",
".",
"env",
"env",
".",
"LIBDIR",
"=",
"env",
".",
"BINDIR",
"=",
"[",
"]",
"env",
".",
"EXEC_PREFIX",
"=",
"get_param",
"(",
"'EXEC_PREFIX'",
",",
"env",
".",
"PREFIX",
")",
"env",
".",
"PACKAGE",
"=",
"getattr",
"(",
"Context",
".",
"g_module",
",",
"'APPNAME'",
",",
"None",
")",
"or",
"env",
".",
"PACKAGE",
"complete",
"=",
"False",
"iter",
"=",
"0",
"while",
"not",
"complete",
"and",
"iter",
"<",
"len",
"(",
"_options",
")",
"+",
"1",
":",
"iter",
"+=",
"1",
"complete",
"=",
"True",
"for",
"name",
",",
"help",
",",
"default",
"in",
"_options",
":",
"name",
"=",
"name",
".",
"upper",
"(",
")",
"if",
"not",
"env",
"[",
"name",
"]",
":",
"try",
":",
"env",
"[",
"name",
"]",
"=",
"Utils",
".",
"subst_vars",
"(",
"get_param",
"(",
"name",
",",
"default",
")",
".",
"replace",
"(",
"'/'",
",",
"os",
".",
"sep",
")",
",",
"env",
")",
"except",
"TypeError",
":",
"complete",
"=",
"False",
"if",
"not",
"complete",
":",
"lst",
"=",
"[",
"x",
"for",
"x",
",",
"_",
",",
"_",
"in",
"_options",
"if",
"not",
"env",
"[",
"x",
".",
"upper",
"(",
")",
"]",
"]",
"raise",
"conf",
".",
"errors",
".",
"WafError",
"(",
"'Variable substitution failure %r'",
"%",
"lst",
")"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/gnu_dirs.py#L72-L100 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillSample.py | python | DrillSample.getParameter | (self, name) | Get the parameter from its name or None if it does not exist.
Args:
name (str): name of the parameter
Returns:
DrillParameter: the sample parameter | Get the parameter from its name or None if it does not exist. | [
"Get",
"the",
"parameter",
"from",
"its",
"name",
"or",
"None",
"if",
"it",
"does",
"not",
"exist",
"."
] | def getParameter(self, name):
"""
Get the parameter from its name or None if it does not exist.
Args:
name (str): name of the parameter
Returns:
DrillParameter: the sample parameter
"""
if name in self._parameters:
return self._parameters[name]
else:
return None | [
"def",
"getParameter",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_parameters",
":",
"return",
"self",
".",
"_parameters",
"[",
"name",
"]",
"else",
":",
"return",
"None"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillSample.py#L216-L229 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/platform.py | python | _dist_try_harder | (distname,version,id) | return distname,version,id | Tries some special tricks to get the distribution
information in case the default method fails.
Currently supports older SuSE Linux, Caldera OpenLinux and
Slackware Linux distributions. | Tries some special tricks to get the distribution
information in case the default method fails. | [
"Tries",
"some",
"special",
"tricks",
"to",
"get",
"the",
"distribution",
"information",
"in",
"case",
"the",
"default",
"method",
"fails",
"."
] | def _dist_try_harder(distname,version,id):
""" Tries some special tricks to get the distribution
information in case the default method fails.
Currently supports older SuSE Linux, Caldera OpenLinux and
Slackware Linux distributions.
"""
if os.path.exists('/var/adm/inst-log/info'):
# SuSE Linux stores distribution information in that file
info = open('/var/adm/inst-log/info').readlines()
distname = 'SuSE'
for line in info:
tv = string.split(line)
if len(tv) == 2:
tag,value = tv
else:
continue
if tag == 'MIN_DIST_VERSION':
version = string.strip(value)
elif tag == 'DIST_IDENT':
values = string.split(value,'-')
id = values[2]
return distname,version,id
if os.path.exists('/etc/.installed'):
# Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
info = open('/etc/.installed').readlines()
for line in info:
pkg = string.split(line,'-')
if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
# XXX does Caldera support non Intel platforms ? If yes,
# where can we find the needed id ?
return 'OpenLinux',pkg[1],id
if os.path.isdir('/usr/lib/setup'):
# Check for slackware version tag file (thanks to Greg Andruk)
verfiles = os.listdir('/usr/lib/setup')
for n in range(len(verfiles)-1, -1, -1):
if verfiles[n][:14] != 'slack-version-':
del verfiles[n]
if verfiles:
verfiles.sort()
distname = 'slackware'
version = verfiles[-1][14:]
return distname,version,id
return distname,version,id | [
"def",
"_dist_try_harder",
"(",
"distname",
",",
"version",
",",
"id",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'/var/adm/inst-log/info'",
")",
":",
"# SuSE Linux stores distribution information in that file",
"info",
"=",
"open",
"(",
"'/var/adm/inst-log/info'",
")",
".",
"readlines",
"(",
")",
"distname",
"=",
"'SuSE'",
"for",
"line",
"in",
"info",
":",
"tv",
"=",
"string",
".",
"split",
"(",
"line",
")",
"if",
"len",
"(",
"tv",
")",
"==",
"2",
":",
"tag",
",",
"value",
"=",
"tv",
"else",
":",
"continue",
"if",
"tag",
"==",
"'MIN_DIST_VERSION'",
":",
"version",
"=",
"string",
".",
"strip",
"(",
"value",
")",
"elif",
"tag",
"==",
"'DIST_IDENT'",
":",
"values",
"=",
"string",
".",
"split",
"(",
"value",
",",
"'-'",
")",
"id",
"=",
"values",
"[",
"2",
"]",
"return",
"distname",
",",
"version",
",",
"id",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'/etc/.installed'",
")",
":",
"# Caldera OpenLinux has some infos in that file (thanks to Colin Kong)",
"info",
"=",
"open",
"(",
"'/etc/.installed'",
")",
".",
"readlines",
"(",
")",
"for",
"line",
"in",
"info",
":",
"pkg",
"=",
"string",
".",
"split",
"(",
"line",
",",
"'-'",
")",
"if",
"len",
"(",
"pkg",
")",
">=",
"2",
"and",
"pkg",
"[",
"0",
"]",
"==",
"'OpenLinux'",
":",
"# XXX does Caldera support non Intel platforms ? If yes,",
"# where can we find the needed id ?",
"return",
"'OpenLinux'",
",",
"pkg",
"[",
"1",
"]",
",",
"id",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"'/usr/lib/setup'",
")",
":",
"# Check for slackware version tag file (thanks to Greg Andruk)",
"verfiles",
"=",
"os",
".",
"listdir",
"(",
"'/usr/lib/setup'",
")",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"verfiles",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"verfiles",
"[",
"n",
"]",
"[",
":",
"14",
"]",
"!=",
"'slack-version-'",
":",
"del",
"verfiles",
"[",
"n",
"]",
"if",
"verfiles",
":",
"verfiles",
".",
"sort",
"(",
")",
"distname",
"=",
"'slackware'",
"version",
"=",
"verfiles",
"[",
"-",
"1",
"]",
"[",
"14",
":",
"]",
"return",
"distname",
",",
"version",
",",
"id",
"return",
"distname",
",",
"version",
",",
"id"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/platform.py#L228-L276 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_cdefns_cdefn | (p) | cdefns : cdefn | cdefns : cdefn | [
"cdefns",
":",
"cdefn"
] | def p_cdefns_cdefn(p):
'cdefns : cdefn'
p[0] = [p[1]] | [
"def",
"p_cdefns_cdefn",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L2434-L2436 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge2.py | python | ExodusModel.create_element_block | (self, element_block_id, info, connectivity=None) | Create a new element block.
The nodes for the elements in the block must have already been defined.
The info list should be comprised of the following information.
* '[element_type, element_count, nodes_per_element, 0]'
For example, the following would be valid.
* '["hex8", elements, 8, 0]'
The connectivity list should be a shallow list of element connectivity
and must be of length 'element_count * nodes_per_element'.
Element blocks are unnamed when created. To name them, use the
'rename_element_block' function.
Example:
>>> model.create_element_block(1, ['hex8', 0, 8, 0]) | Create a new element block. | [
"Create",
"a",
"new",
"element",
"block",
"."
] | def create_element_block(self, element_block_id, info, connectivity=None):
"""
Create a new element block.
The nodes for the elements in the block must have already been defined.
The info list should be comprised of the following information.
* '[element_type, element_count, nodes_per_element, 0]'
For example, the following would be valid.
* '["hex8", elements, 8, 0]'
The connectivity list should be a shallow list of element connectivity
and must be of length 'element_count * nodes_per_element'.
Element blocks are unnamed when created. To name them, use the
'rename_element_block' function.
Example:
>>> model.create_element_block(1, ['hex8', 0, 8, 0])
"""
# make sure it doesn't exist already
if self.element_block_exists(element_block_id):
self._exists_error(element_block_id, 'element block')
# set up an empty connectivity if none is given
if not connectivity:
connectivity = []
# create the actual block
self.element_blocks[element_block_id] = ['',
info,
connectivity,
{}] | [
"def",
"create_element_block",
"(",
"self",
",",
"element_block_id",
",",
"info",
",",
"connectivity",
"=",
"None",
")",
":",
"# make sure it doesn't exist already",
"if",
"self",
".",
"element_block_exists",
"(",
"element_block_id",
")",
":",
"self",
".",
"_exists_error",
"(",
"element_block_id",
",",
"'element block'",
")",
"# set up an empty connectivity if none is given",
"if",
"not",
"connectivity",
":",
"connectivity",
"=",
"[",
"]",
"# create the actual block",
"self",
".",
"element_blocks",
"[",
"element_block_id",
"]",
"=",
"[",
"''",
",",
"info",
",",
"connectivity",
",",
"{",
"}",
"]"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L6101-L6133 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Conv.py | python | Conv.filter_count | (self, new_filter_count) | Sets the number of filters. | Sets the number of filters. | [
"Sets",
"the",
"number",
"of",
"filters",
"."
] | def filter_count(self, new_filter_count):
"""Sets the number of filters.
"""
self._internal.set_filter_count(int(new_filter_count)) | [
"def",
"filter_count",
"(",
"self",
",",
"new_filter_count",
")",
":",
"self",
".",
"_internal",
".",
"set_filter_count",
"(",
"int",
"(",
"new_filter_count",
")",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Conv.py#L107-L110 | ||
POV-Ray/povray | 76a804d18a30a1dbb0afbc0070b62526715571eb | tools/meta-make/bluenoise/BlueNoise.py | python | GetVoidAndClusterBlueNoise | (OutputShape,StandardDeviation=1.5,InitialSeedFraction=0.1) | return DitherArray | Generates a blue noise dither array of the given shape using the method
proposed by Ulichney [1993] in "The void-and-cluster method for dither array
generation" published in Proc. SPIE 1913.
\param OutputShape The shape of the output array. This function works in
arbitrary dimension, i.e. OutputShape can have arbitrary length. Though
it is only tested for the 2D case where you should pass a tuple
(Height,Width).
\param StandardDeviation The standard deviation in pixels used for the
Gaussian filter defining largest voids and tightest clusters. Larger
values lead to more low-frequency content but better isotropy. Small
values lead to more ordered patterns with less low-frequency content.
Ulichney proposes to use a value of 1.5. If you want an anisotropic
Gaussian, you can pass a tuple of length len(OutputShape) with one
standard deviation per dimension.
\param InitialSeedFraction The only non-deterministic step in the algorithm
marks a small number of pixels in the grid randomly. This parameter
defines the fraction of such points. It has to be positive but less
than 0.5. Very small values lead to ordered patterns, beyond that there
is little change.
\return An integer array of shape OutputShape containing each integer from 0
to np.prod(OutputShape)-1 exactly once. | Generates a blue noise dither array of the given shape using the method
proposed by Ulichney [1993] in "The void-and-cluster method for dither array
generation" published in Proc. SPIE 1913.
\param OutputShape The shape of the output array. This function works in
arbitrary dimension, i.e. OutputShape can have arbitrary length. Though
it is only tested for the 2D case where you should pass a tuple
(Height,Width).
\param StandardDeviation The standard deviation in pixels used for the
Gaussian filter defining largest voids and tightest clusters. Larger
values lead to more low-frequency content but better isotropy. Small
values lead to more ordered patterns with less low-frequency content.
Ulichney proposes to use a value of 1.5. If you want an anisotropic
Gaussian, you can pass a tuple of length len(OutputShape) with one
standard deviation per dimension.
\param InitialSeedFraction The only non-deterministic step in the algorithm
marks a small number of pixels in the grid randomly. This parameter
defines the fraction of such points. It has to be positive but less
than 0.5. Very small values lead to ordered patterns, beyond that there
is little change.
\return An integer array of shape OutputShape containing each integer from 0
to np.prod(OutputShape)-1 exactly once. | [
"Generates",
"a",
"blue",
"noise",
"dither",
"array",
"of",
"the",
"given",
"shape",
"using",
"the",
"method",
"proposed",
"by",
"Ulichney",
"[",
"1993",
"]",
"in",
"The",
"void",
"-",
"and",
"-",
"cluster",
"method",
"for",
"dither",
"array",
"generation",
"published",
"in",
"Proc",
".",
"SPIE",
"1913",
".",
"\\",
"param",
"OutputShape",
"The",
"shape",
"of",
"the",
"output",
"array",
".",
"This",
"function",
"works",
"in",
"arbitrary",
"dimension",
"i",
".",
"e",
".",
"OutputShape",
"can",
"have",
"arbitrary",
"length",
".",
"Though",
"it",
"is",
"only",
"tested",
"for",
"the",
"2D",
"case",
"where",
"you",
"should",
"pass",
"a",
"tuple",
"(",
"Height",
"Width",
")",
".",
"\\",
"param",
"StandardDeviation",
"The",
"standard",
"deviation",
"in",
"pixels",
"used",
"for",
"the",
"Gaussian",
"filter",
"defining",
"largest",
"voids",
"and",
"tightest",
"clusters",
".",
"Larger",
"values",
"lead",
"to",
"more",
"low",
"-",
"frequency",
"content",
"but",
"better",
"isotropy",
".",
"Small",
"values",
"lead",
"to",
"more",
"ordered",
"patterns",
"with",
"less",
"low",
"-",
"frequency",
"content",
".",
"Ulichney",
"proposes",
"to",
"use",
"a",
"value",
"of",
"1",
".",
"5",
".",
"If",
"you",
"want",
"an",
"anisotropic",
"Gaussian",
"you",
"can",
"pass",
"a",
"tuple",
"of",
"length",
"len",
"(",
"OutputShape",
")",
"with",
"one",
"standard",
"deviation",
"per",
"dimension",
".",
"\\",
"param",
"InitialSeedFraction",
"The",
"only",
"non",
"-",
"deterministic",
"step",
"in",
"the",
"algorithm",
"marks",
"a",
"small",
"number",
"of",
"pixels",
"in",
"the",
"grid",
"randomly",
".",
"This",
"parameter",
"defines",
"the",
"fraction",
"of",
"such",
"points",
".",
"It",
"has",
"to",
"be",
"positive",
"but",
"less",
"than",
"0",
".",
"5",
".",
"Very",
"small",
"values",
"lead",
"to",
"ordered",
"patterns",
"beyond",
"that",
"there",
"is",
"little",
"change",
".",
"\\",
"return",
"An",
"integer",
"array",
"of",
"shape",
"OutputShape",
"containing",
"each",
"integer",
"from",
"0",
"to",
"np",
".",
"prod",
"(",
"OutputShape",
")",
"-",
"1",
"exactly",
"once",
"."
] | def GetVoidAndClusterBlueNoise(OutputShape,StandardDeviation=1.5,InitialSeedFraction=0.1):
"""Generates a blue noise dither array of the given shape using the method
proposed by Ulichney [1993] in "The void-and-cluster method for dither array
generation" published in Proc. SPIE 1913.
\param OutputShape The shape of the output array. This function works in
arbitrary dimension, i.e. OutputShape can have arbitrary length. Though
it is only tested for the 2D case where you should pass a tuple
(Height,Width).
\param StandardDeviation The standard deviation in pixels used for the
Gaussian filter defining largest voids and tightest clusters. Larger
values lead to more low-frequency content but better isotropy. Small
values lead to more ordered patterns with less low-frequency content.
Ulichney proposes to use a value of 1.5. If you want an anisotropic
Gaussian, you can pass a tuple of length len(OutputShape) with one
standard deviation per dimension.
\param InitialSeedFraction The only non-deterministic step in the algorithm
marks a small number of pixels in the grid randomly. This parameter
defines the fraction of such points. It has to be positive but less
than 0.5. Very small values lead to ordered patterns, beyond that there
is little change.
\return An integer array of shape OutputShape containing each integer from 0
to np.prod(OutputShape)-1 exactly once."""
nRank=np.prod(OutputShape);
# Generate the initial binary pattern with a prescribed number of ones
nInitialOne=max(1,min(int((nRank-1)/2),int(nRank*InitialSeedFraction)));
# Start from white noise (this is the only randomized step)
InitialBinaryPattern=np.zeros(OutputShape,dtype=np.bool);
InitialBinaryPattern.flat=np.random.permutation(np.arange(nRank))<nInitialOne;
# Swap ones from tightest clusters to largest voids iteratively until convergence
while(True):
iTightestCluster=FindTightestCluster(InitialBinaryPattern,StandardDeviation);
InitialBinaryPattern.flat[iTightestCluster]=False;
iLargestVoid=FindLargestVoid(InitialBinaryPattern,StandardDeviation);
if(iLargestVoid==iTightestCluster):
InitialBinaryPattern.flat[iTightestCluster]=True;
# Nothing has changed, so we have converged
break;
else:
InitialBinaryPattern.flat[iLargestVoid]=True;
# Rank all pixels
DitherArray=np.zeros(OutputShape,dtype=np.int);
# Phase 1: Rank minority pixels in the initial binary pattern
BinaryPattern=np.copy(InitialBinaryPattern);
for Rank in range(nInitialOne-1,-1,-1):
iTightestCluster=FindTightestCluster(BinaryPattern,StandardDeviation);
BinaryPattern.flat[iTightestCluster]=False;
DitherArray.flat[iTightestCluster]=Rank;
# Phase 2: Rank the remainder of the first half of all pixels
BinaryPattern=InitialBinaryPattern;
for Rank in range(nInitialOne,int((nRank+1)/2)):
iLargestVoid=FindLargestVoid(BinaryPattern,StandardDeviation);
BinaryPattern.flat[iLargestVoid]=True;
DitherArray.flat[iLargestVoid]=Rank;
# Phase 3: Rank the last half of pixels
for Rank in range(int((nRank+1)/2),nRank):
iTightestCluster=FindTightestCluster(BinaryPattern,StandardDeviation);
BinaryPattern.flat[iTightestCluster]=True;
DitherArray.flat[iTightestCluster]=Rank;
return DitherArray; | [
"def",
"GetVoidAndClusterBlueNoise",
"(",
"OutputShape",
",",
"StandardDeviation",
"=",
"1.5",
",",
"InitialSeedFraction",
"=",
"0.1",
")",
":",
"nRank",
"=",
"np",
".",
"prod",
"(",
"OutputShape",
")",
"# Generate the initial binary pattern with a prescribed number of ones",
"nInitialOne",
"=",
"max",
"(",
"1",
",",
"min",
"(",
"int",
"(",
"(",
"nRank",
"-",
"1",
")",
"/",
"2",
")",
",",
"int",
"(",
"nRank",
"*",
"InitialSeedFraction",
")",
")",
")",
"# Start from white noise (this is the only randomized step)",
"InitialBinaryPattern",
"=",
"np",
".",
"zeros",
"(",
"OutputShape",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"InitialBinaryPattern",
".",
"flat",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"np",
".",
"arange",
"(",
"nRank",
")",
")",
"<",
"nInitialOne",
"# Swap ones from tightest clusters to largest voids iteratively until convergence",
"while",
"(",
"True",
")",
":",
"iTightestCluster",
"=",
"FindTightestCluster",
"(",
"InitialBinaryPattern",
",",
"StandardDeviation",
")",
"InitialBinaryPattern",
".",
"flat",
"[",
"iTightestCluster",
"]",
"=",
"False",
"iLargestVoid",
"=",
"FindLargestVoid",
"(",
"InitialBinaryPattern",
",",
"StandardDeviation",
")",
"if",
"(",
"iLargestVoid",
"==",
"iTightestCluster",
")",
":",
"InitialBinaryPattern",
".",
"flat",
"[",
"iTightestCluster",
"]",
"=",
"True",
"# Nothing has changed, so we have converged",
"break",
"else",
":",
"InitialBinaryPattern",
".",
"flat",
"[",
"iLargestVoid",
"]",
"=",
"True",
"# Rank all pixels",
"DitherArray",
"=",
"np",
".",
"zeros",
"(",
"OutputShape",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"# Phase 1: Rank minority pixels in the initial binary pattern",
"BinaryPattern",
"=",
"np",
".",
"copy",
"(",
"InitialBinaryPattern",
")",
"for",
"Rank",
"in",
"range",
"(",
"nInitialOne",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"iTightestCluster",
"=",
"FindTightestCluster",
"(",
"BinaryPattern",
",",
"StandardDeviation",
")",
"BinaryPattern",
".",
"flat",
"[",
"iTightestCluster",
"]",
"=",
"False",
"DitherArray",
".",
"flat",
"[",
"iTightestCluster",
"]",
"=",
"Rank",
"# Phase 2: Rank the remainder of the first half of all pixels",
"BinaryPattern",
"=",
"InitialBinaryPattern",
"for",
"Rank",
"in",
"range",
"(",
"nInitialOne",
",",
"int",
"(",
"(",
"nRank",
"+",
"1",
")",
"/",
"2",
")",
")",
":",
"iLargestVoid",
"=",
"FindLargestVoid",
"(",
"BinaryPattern",
",",
"StandardDeviation",
")",
"BinaryPattern",
".",
"flat",
"[",
"iLargestVoid",
"]",
"=",
"True",
"DitherArray",
".",
"flat",
"[",
"iLargestVoid",
"]",
"=",
"Rank",
"# Phase 3: Rank the last half of pixels",
"for",
"Rank",
"in",
"range",
"(",
"int",
"(",
"(",
"nRank",
"+",
"1",
")",
"/",
"2",
")",
",",
"nRank",
")",
":",
"iTightestCluster",
"=",
"FindTightestCluster",
"(",
"BinaryPattern",
",",
"StandardDeviation",
")",
"BinaryPattern",
".",
"flat",
"[",
"iTightestCluster",
"]",
"=",
"True",
"DitherArray",
".",
"flat",
"[",
"iTightestCluster",
"]",
"=",
"Rank",
"return",
"DitherArray"
] | https://github.com/POV-Ray/povray/blob/76a804d18a30a1dbb0afbc0070b62526715571eb/tools/meta-make/bluenoise/BlueNoise.py#L66-L124 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.UpdateWindowUI | (*args, **kwargs) | return _core_.Window_UpdateWindowUI(*args, **kwargs) | UpdateWindowUI(self, long flags=UPDATE_UI_NONE)
This function sends EVT_UPDATE_UI events to the window. The particular
implementation depends on the window; for example a wx.ToolBar will
send an update UI event for each toolbar button, and a wx.Frame will
send an update UI event for each menubar menu item. You can call this
function from your application to ensure that your UI is up-to-date at
a particular point in time (as far as your EVT_UPDATE_UI handlers are
concerned). This may be necessary if you have called
`wx.UpdateUIEvent.SetMode` or `wx.UpdateUIEvent.SetUpdateInterval` to
limit the overhead that wxWindows incurs by sending update UI events
in idle time. | UpdateWindowUI(self, long flags=UPDATE_UI_NONE) | [
"UpdateWindowUI",
"(",
"self",
"long",
"flags",
"=",
"UPDATE_UI_NONE",
")"
] | def UpdateWindowUI(*args, **kwargs):
"""
UpdateWindowUI(self, long flags=UPDATE_UI_NONE)
This function sends EVT_UPDATE_UI events to the window. The particular
implementation depends on the window; for example a wx.ToolBar will
send an update UI event for each toolbar button, and a wx.Frame will
send an update UI event for each menubar menu item. You can call this
function from your application to ensure that your UI is up-to-date at
a particular point in time (as far as your EVT_UPDATE_UI handlers are
concerned). This may be necessary if you have called
`wx.UpdateUIEvent.SetMode` or `wx.UpdateUIEvent.SetUpdateInterval` to
limit the overhead that wxWindows incurs by sending update UI events
in idle time.
"""
return _core_.Window_UpdateWindowUI(*args, **kwargs) | [
"def",
"UpdateWindowUI",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_UpdateWindowUI",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L11105-L11120 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/io/matlab/mio4.py | python | arr_to_2d | (arr, oned_as='row') | return arr.reshape(dims) | Make ``arr`` exactly two dimensional
If `arr` has more than 2 dimensions, raise a ValueError
Parameters
----------
arr : array
oned_as : {'row', 'column'}, optional
Whether to reshape 1D vectors as row vectors or column vectors.
See documentation for ``matdims`` for more detail
Returns
-------
arr2d : array
2D version of the array | Make ``arr`` exactly two dimensional | [
"Make",
"arr",
"exactly",
"two",
"dimensional"
] | def arr_to_2d(arr, oned_as='row'):
''' Make ``arr`` exactly two dimensional
If `arr` has more than 2 dimensions, raise a ValueError
Parameters
----------
arr : array
oned_as : {'row', 'column'}, optional
Whether to reshape 1D vectors as row vectors or column vectors.
See documentation for ``matdims`` for more detail
Returns
-------
arr2d : array
2D version of the array
'''
dims = matdims(arr, oned_as)
if len(dims) > 2:
raise ValueError('Matlab 4 files cannot save arrays with more than '
'2 dimensions')
return arr.reshape(dims) | [
"def",
"arr_to_2d",
"(",
"arr",
",",
"oned_as",
"=",
"'row'",
")",
":",
"dims",
"=",
"matdims",
"(",
"arr",
",",
"oned_as",
")",
"if",
"len",
"(",
"dims",
")",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Matlab 4 files cannot save arrays with more than '",
"'2 dimensions'",
")",
"return",
"arr",
".",
"reshape",
"(",
"dims",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/matlab/mio4.py#L424-L445 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/contrib/onnx/onnx2mx/_op_translations.py | python | reduce_max | (attrs, inputs, proto_obj) | return 'max', new_attrs, inputs | Reduce the array along a given axis by maximum value | Reduce the array along a given axis by maximum value | [
"Reduce",
"the",
"array",
"along",
"a",
"given",
"axis",
"by",
"maximum",
"value"
] | def reduce_max(attrs, inputs, proto_obj):
"""Reduce the array along a given axis by maximum value"""
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'max', new_attrs, inputs | [
"def",
"reduce_max",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"new_attrs",
"=",
"translation_utils",
".",
"_fix_attribute_names",
"(",
"attrs",
",",
"{",
"'axes'",
":",
"'axis'",
"}",
")",
"return",
"'max'",
",",
"new_attrs",
",",
"inputs"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L615-L618 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge2.py | python | ExodusModel._format_node_set_id_list | (self, id_list, *args, **kwargs) | return self._format_id_list(id_list,
sorted(object.keys()),
entity=entity,
*args,
translator=dict(tuples),
**kwargs) | Return a validated list of node set IDs. | Return a validated list of node set IDs. | [
"Return",
"a",
"validated",
"list",
"of",
"node",
"set",
"IDs",
"."
] | def _format_node_set_id_list(self, id_list, *args, **kwargs):
"""Return a validated list of node set IDs."""
object = self.node_sets
entity = 'node set'
# get element block translations
tuples = [(value[0], key)
for key, value in object.items()
if value[0]]
# ensure element block names are unique
if len(set(x[0] for x in tuples)) != len(tuples):
self._warning('Duplicate %s names' % entity,
'At least two %s have the same name. '
'This may cause problems.' % self._plural(entity))
return self._format_id_list(id_list,
sorted(object.keys()),
entity=entity,
*args,
translator=dict(tuples),
**kwargs) | [
"def",
"_format_node_set_id_list",
"(",
"self",
",",
"id_list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"object",
"=",
"self",
".",
"node_sets",
"entity",
"=",
"'node set'",
"# get element block translations",
"tuples",
"=",
"[",
"(",
"value",
"[",
"0",
"]",
",",
"key",
")",
"for",
"key",
",",
"value",
"in",
"object",
".",
"items",
"(",
")",
"if",
"value",
"[",
"0",
"]",
"]",
"# ensure element block names are unique",
"if",
"len",
"(",
"set",
"(",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"tuples",
")",
")",
"!=",
"len",
"(",
"tuples",
")",
":",
"self",
".",
"_warning",
"(",
"'Duplicate %s names'",
"%",
"entity",
",",
"'At least two %s have the same name. '",
"'This may cause problems.'",
"%",
"self",
".",
"_plural",
"(",
"entity",
")",
")",
"return",
"self",
".",
"_format_id_list",
"(",
"id_list",
",",
"sorted",
"(",
"object",
".",
"keys",
"(",
")",
")",
",",
"entity",
"=",
"entity",
",",
"*",
"args",
",",
"translator",
"=",
"dict",
"(",
"tuples",
")",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L1124-L1142 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/MSVSSettings.py | python | _ConvertedToAdditionalOption | (tool, msvs_name, flag) | Defines a setting that's handled via a command line option in MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
msvs_name: the name of the MSVS setting that if 'true' becomes a flag
flag: the flag to insert at the end of the AdditionalOptions | Defines a setting that's handled via a command line option in MSBuild. | [
"Defines",
"a",
"setting",
"that",
"s",
"handled",
"via",
"a",
"command",
"line",
"option",
"in",
"MSBuild",
"."
] | def _ConvertedToAdditionalOption(tool, msvs_name, flag):
"""Defines a setting that's handled via a command line option in MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
msvs_name: the name of the MSVS setting that if 'true' becomes a flag
flag: the flag to insert at the end of the AdditionalOptions
"""
def _Translate(value, msbuild_settings):
if value == 'true':
tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool)
if 'AdditionalOptions' in tool_settings:
new_flags = '%s %s' % (tool_settings['AdditionalOptions'], flag)
else:
new_flags = flag
tool_settings['AdditionalOptions'] = new_flags
_msvs_validators[tool.msvs_name][msvs_name] = _boolean.ValidateMSVS
_msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate | [
"def",
"_ConvertedToAdditionalOption",
"(",
"tool",
",",
"msvs_name",
",",
"flag",
")",
":",
"def",
"_Translate",
"(",
"value",
",",
"msbuild_settings",
")",
":",
"if",
"value",
"==",
"'true'",
":",
"tool_settings",
"=",
"_GetMSBuildToolSettings",
"(",
"msbuild_settings",
",",
"tool",
")",
"if",
"'AdditionalOptions'",
"in",
"tool_settings",
":",
"new_flags",
"=",
"'%s %s'",
"%",
"(",
"tool_settings",
"[",
"'AdditionalOptions'",
"]",
",",
"flag",
")",
"else",
":",
"new_flags",
"=",
"flag",
"tool_settings",
"[",
"'AdditionalOptions'",
"]",
"=",
"new_flags",
"_msvs_validators",
"[",
"tool",
".",
"msvs_name",
"]",
"[",
"msvs_name",
"]",
"=",
"_boolean",
".",
"ValidateMSVS",
"_msvs_to_msbuild_converters",
"[",
"tool",
".",
"msvs_name",
"]",
"[",
"msvs_name",
"]",
"=",
"_Translate"
] | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/MSVSSettings.py#L327-L345 | ||
apache/trafodion | 8455c839ad6b6d7b6e04edda5715053095b78046 | install/python-installer/scripts/common.py | python | Remote.execute | (self, user_cmd, verbose=False, shell=False, chkerr=True) | @params: user_cmd should be a string | [] | def execute(self, user_cmd, verbose=False, shell=False, chkerr=True):
""" @params: user_cmd should be a string """
cmd = self._commands('ssh')
cmd += ['-tt'] # force tty allocation
if self.user:
cmd += ['%s@%s' % (self.user, self.host)]
else:
cmd += [self.host]
# if shell=True, cmd should be a string not list
if shell:
cmd = ' '.join(cmd) + ' '
cmd += user_cmd
else:
cmd += user_cmd.split()
self._execute(cmd, verbose=verbose, shell=shell)
if chkerr and self.rc != 0:
err_m('Failed to execute command on remote host [%s]: "%s"' % (self.host, user_cmd)) | [
"def",
"execute",
"(",
"self",
",",
"user_cmd",
",",
"verbose",
"=",
"False",
",",
"shell",
"=",
"False",
",",
"chkerr",
"=",
"True",
")",
":",
"cmd",
"=",
"self",
".",
"_commands",
"(",
"'ssh'",
")",
"cmd",
"+=",
"[",
"'-tt'",
"]",
"# force tty allocation",
"if",
"self",
".",
"user",
":",
"cmd",
"+=",
"[",
"'%s@%s'",
"%",
"(",
"self",
".",
"user",
",",
"self",
".",
"host",
")",
"]",
"else",
":",
"cmd",
"+=",
"[",
"self",
".",
"host",
"]",
"# if shell=True, cmd should be a string not list",
"if",
"shell",
":",
"cmd",
"=",
"' '",
".",
"join",
"(",
"cmd",
")",
"+",
"' '",
"cmd",
"+=",
"user_cmd",
"else",
":",
"cmd",
"+=",
"user_cmd",
".",
"split",
"(",
")",
"self",
".",
"_execute",
"(",
"cmd",
",",
"verbose",
"=",
"verbose",
",",
"shell",
"=",
"shell",
")",
"if",
"chkerr",
"and",
"self",
".",
"rc",
"!=",
"0",
":",
"err_m",
"(",
"'Failed to execute command on remote host [%s]: \"%s\"'",
"%",
"(",
"self",
".",
"host",
",",
"user_cmd",
")",
")"
] | https://github.com/apache/trafodion/blob/8455c839ad6b6d7b6e04edda5715053095b78046/install/python-installer/scripts/common.py#L382-L401 | |||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Text.dlineinfo | (self, index) | return self._getints(self.tk.call(self._w, 'dlineinfo', index)) | Return tuple (x,y,width,height,baseline) giving the bounding box
and baseline position of the visible part of the line containing
the character at INDEX. | Return tuple (x,y,width,height,baseline) giving the bounding box
and baseline position of the visible part of the line containing
the character at INDEX. | [
"Return",
"tuple",
"(",
"x",
"y",
"width",
"height",
"baseline",
")",
"giving",
"the",
"bounding",
"box",
"and",
"baseline",
"position",
"of",
"the",
"visible",
"part",
"of",
"the",
"line",
"containing",
"the",
"character",
"at",
"INDEX",
"."
] | def dlineinfo(self, index):
"""Return tuple (x,y,width,height,baseline) giving the bounding box
and baseline position of the visible part of the line containing
the character at INDEX."""
return self._getints(self.tk.call(self._w, 'dlineinfo', index)) | [
"def",
"dlineinfo",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'dlineinfo'",
",",
"index",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2916-L2920 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Entry.icursor | (self, index) | Insert cursor at INDEX. | Insert cursor at INDEX. | [
"Insert",
"cursor",
"at",
"INDEX",
"."
] | def icursor(self, index):
"""Insert cursor at INDEX."""
self.tk.call(self._w, 'icursor', index) | [
"def",
"icursor",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'icursor'",
",",
"index",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2454-L2456 | ||
blackberry/Boost | fc90c3fde129c62565c023f091eddc4a7ed9902b | tools/build/v2/build/targets.py | python | TargetRegistry.create_typed_target | (self, type, project, name, sources, requirements, default_build, usage_requirements) | return self.main_target_alternative (TypedTarget (name, project, type,
self.main_target_sources (sources, name),
self.main_target_requirements (requirements, project),
self.main_target_default_build (default_build, project),
self.main_target_usage_requirements (usage_requirements, project))) | Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'. | Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'. | [
"Creates",
"a",
"TypedTarget",
"with",
"the",
"specified",
"properties",
".",
"The",
"name",
"sources",
"requirements",
"default_build",
"and",
"usage_requirements",
"are",
"assumed",
"to",
"be",
"in",
"the",
"form",
"specified",
"by",
"the",
"user",
"in",
"Jamfile",
"corresponding",
"to",
"project",
"."
] | def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements):
""" Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'.
"""
return self.main_target_alternative (TypedTarget (name, project, type,
self.main_target_sources (sources, name),
self.main_target_requirements (requirements, project),
self.main_target_default_build (default_build, project),
self.main_target_usage_requirements (usage_requirements, project))) | [
"def",
"create_typed_target",
"(",
"self",
",",
"type",
",",
"project",
",",
"name",
",",
"sources",
",",
"requirements",
",",
"default_build",
",",
"usage_requirements",
")",
":",
"return",
"self",
".",
"main_target_alternative",
"(",
"TypedTarget",
"(",
"name",
",",
"project",
",",
"type",
",",
"self",
".",
"main_target_sources",
"(",
"sources",
",",
"name",
")",
",",
"self",
".",
"main_target_requirements",
"(",
"requirements",
",",
"project",
")",
",",
"self",
".",
"main_target_default_build",
"(",
"default_build",
",",
"project",
")",
",",
"self",
".",
"main_target_usage_requirements",
"(",
"usage_requirements",
",",
"project",
")",
")",
")"
] | https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/targets.py#L208-L218 | |
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | vtr_flow/scripts/upgrade_arch.py | python | add_site_directs | (arch) | return True | This function adds the direct pin mappings between a physical
tile and a corresponding logical block.
Note: the example below is only for explanatory reasons, the signal names are invented
BEFORE:
<tiles>
<tile name="BRAM_TILE" area="2" height="4" width="1" capacity="1">
<inputs ... />
<outputs ... />
<fc ... />
<pinlocations ... />
<switchblock_locations ... />
<equivalent_sites>
<site pb_type="BRAM_SITE"/>
</equivalent_sites>
</tile>
</tiles>
AFTER:
<tiles>
<tile name="BRAM_TILE" area="2" height="4" width="1" capacity="1">
<inputs ... />
<outputs ... />
<fc ... />
<pinlocations ... />
<switchblock_locations ... />
<equivalent_sites>
<site pb_type="BRAM" pin_mapping="direct">
</equivalent_sites>
</tile>
</tiles> | This function adds the direct pin mappings between a physical
tile and a corresponding logical block. | [
"This",
"function",
"adds",
"the",
"direct",
"pin",
"mappings",
"between",
"a",
"physical",
"tile",
"and",
"a",
"corresponding",
"logical",
"block",
"."
] | def add_site_directs(arch):
"""
This function adds the direct pin mappings between a physical
tile and a corresponding logical block.
Note: the example below is only for explanatory reasons, the signal names are invented
BEFORE:
<tiles>
<tile name="BRAM_TILE" area="2" height="4" width="1" capacity="1">
<inputs ... />
<outputs ... />
<fc ... />
<pinlocations ... />
<switchblock_locations ... />
<equivalent_sites>
<site pb_type="BRAM_SITE"/>
</equivalent_sites>
</tile>
</tiles>
AFTER:
<tiles>
<tile name="BRAM_TILE" area="2" height="4" width="1" capacity="1">
<inputs ... />
<outputs ... />
<fc ... />
<pinlocations ... />
<switchblock_locations ... />
<equivalent_sites>
<site pb_type="BRAM" pin_mapping="direct">
</equivalent_sites>
</tile>
</tiles>
"""
top_pb_types = []
for pb_type in arch.iter("pb_type"):
if pb_type.getparent().tag == "complexblocklist":
top_pb_types.append(pb_type)
sites = []
for pb_type in arch.iter("site"):
sites.append(pb_type)
for pb_type in top_pb_types:
for site in sites:
if "pin_mapping" not in site.attrib:
site.attrib["pin_mapping"] = "direct"
return True | [
"def",
"add_site_directs",
"(",
"arch",
")",
":",
"top_pb_types",
"=",
"[",
"]",
"for",
"pb_type",
"in",
"arch",
".",
"iter",
"(",
"\"pb_type\"",
")",
":",
"if",
"pb_type",
".",
"getparent",
"(",
")",
".",
"tag",
"==",
"\"complexblocklist\"",
":",
"top_pb_types",
".",
"append",
"(",
"pb_type",
")",
"sites",
"=",
"[",
"]",
"for",
"pb_type",
"in",
"arch",
".",
"iter",
"(",
"\"site\"",
")",
":",
"sites",
".",
"append",
"(",
"pb_type",
")",
"for",
"pb_type",
"in",
"top_pb_types",
":",
"for",
"site",
"in",
"sites",
":",
"if",
"\"pin_mapping\"",
"not",
"in",
"site",
".",
"attrib",
":",
"site",
".",
"attrib",
"[",
"\"pin_mapping\"",
"]",
"=",
"\"direct\"",
"return",
"True"
] | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/upgrade_arch.py#L1067-L1117 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/impl/api.py | python | do_not_convert | (func=None) | return wrapper | Decorator that suppresses the conversion of a function.
Args:
func: function to decorate.
Returns:
If `func` is not None, returns a `Callable` which is equivalent to
`func`, but is not converted by AutoGraph.
If `func` is None, returns a decorator that, when invoked with a
single `func` argument, returns a `Callable` equivalent to the
above case. | Decorator that suppresses the conversion of a function. | [
"Decorator",
"that",
"suppresses",
"the",
"conversion",
"of",
"a",
"function",
"."
] | def do_not_convert(func=None):
"""Decorator that suppresses the conversion of a function.
Args:
func: function to decorate.
Returns:
If `func` is not None, returns a `Callable` which is equivalent to
`func`, but is not converted by AutoGraph.
If `func` is None, returns a decorator that, when invoked with a
single `func` argument, returns a `Callable` equivalent to the
above case.
"""
if func is None:
return do_not_convert
def wrapper(*args, **kwargs):
with ag_ctx.ControlStatusCtx(status=ag_ctx.Status.DISABLED):
return func(*args, **kwargs)
if inspect.isfunction(func) or inspect.ismethod(func):
wrapper = functools.update_wrapper(wrapper, func)
setattr(wrapper, '__ag_compiled', True)
return wrapper | [
"def",
"do_not_convert",
"(",
"func",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"do_not_convert",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"ag_ctx",
".",
"ControlStatusCtx",
"(",
"status",
"=",
"ag_ctx",
".",
"Status",
".",
"DISABLED",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"inspect",
".",
"isfunction",
"(",
"func",
")",
"or",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"wrapper",
"=",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"func",
")",
"setattr",
"(",
"wrapper",
",",
"'__ag_compiled'",
",",
"True",
")",
"return",
"wrapper"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/impl/api.py#L274-L298 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/intelc.py | python | get_version_from_list | (v, vlist) | See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way. | See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way. | [
"See",
"if",
"we",
"can",
"match",
"v",
"(",
"string",
")",
"in",
"vlist",
"(",
"list",
"of",
"strings",
")",
"Linux",
"has",
"to",
"match",
"in",
"a",
"fuzzy",
"way",
"."
] | def get_version_from_list(v, vlist):
"""See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way."""
if is_windows:
# Simple case, just find it in the list
if v in vlist: return v
else: return None
else:
# Fuzzy match: normalize version number first, but still return
# original non-normalized form.
fuzz = 0.001
for vi in vlist:
if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz:
return vi
# Not found
return None | [
"def",
"get_version_from_list",
"(",
"v",
",",
"vlist",
")",
":",
"if",
"is_windows",
":",
"# Simple case, just find it in the list",
"if",
"v",
"in",
"vlist",
":",
"return",
"v",
"else",
":",
"return",
"None",
"else",
":",
"# Fuzzy match: normalize version number first, but still return",
"# original non-normalized form.",
"fuzz",
"=",
"0.001",
"for",
"vi",
"in",
"vlist",
":",
"if",
"math",
".",
"fabs",
"(",
"linux_ver_normalize",
"(",
"vi",
")",
"-",
"linux_ver_normalize",
"(",
"v",
")",
")",
"<",
"fuzz",
":",
"return",
"vi",
"# Not found",
"return",
"None"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/intelc.py#L121-L136 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/iam/connection.py | python | IAMConnection.delete_instance_profile | (self, instance_profile_name) | return self.get_response(
'DeleteInstanceProfile',
{'InstanceProfileName': instance_profile_name}) | Deletes the specified instance profile. The instance profile must not
have an associated role.
:type instance_profile_name: string
:param instance_profile_name: Name of the instance profile to delete. | Deletes the specified instance profile. The instance profile must not
have an associated role. | [
"Deletes",
"the",
"specified",
"instance",
"profile",
".",
"The",
"instance",
"profile",
"must",
"not",
"have",
"an",
"associated",
"role",
"."
] | def delete_instance_profile(self, instance_profile_name):
"""
Deletes the specified instance profile. The instance profile must not
have an associated role.
:type instance_profile_name: string
:param instance_profile_name: Name of the instance profile to delete.
"""
return self.get_response(
'DeleteInstanceProfile',
{'InstanceProfileName': instance_profile_name}) | [
"def",
"delete_instance_profile",
"(",
"self",
",",
"instance_profile_name",
")",
":",
"return",
"self",
".",
"get_response",
"(",
"'DeleteInstanceProfile'",
",",
"{",
"'InstanceProfileName'",
":",
"instance_profile_name",
"}",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/iam/connection.py#L1157-L1167 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListMainWindow.MoveToFocus | (self) | Brings tyhe current item into view. | Brings tyhe current item into view. | [
"Brings",
"tyhe",
"current",
"item",
"into",
"view",
"."
] | def MoveToFocus(self):
""" Brings tyhe current item into view. """
self.MoveToItem(self._current) | [
"def",
"MoveToFocus",
"(",
"self",
")",
":",
"self",
".",
"MoveToItem",
"(",
"self",
".",
"_current",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L6312-L6315 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParserElement.__rand__ | (self, other ) | return other & self | Implementation of & operator when left operand is not a C{L{ParserElement}} | Implementation of & operator when left operand is not a C{L{ParserElement}} | [
"Implementation",
"of",
"&",
"operator",
"when",
"left",
"operand",
"is",
"not",
"a",
"C",
"{",
"L",
"{",
"ParserElement",
"}}"
] | def __rand__(self, other ):
"""
Implementation of & operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other & self | [
"def",
"__rand__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"&",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/_vendor/pyparsing.py#L2008-L2018 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBDebugger.Initialize | () | return _lldb.SBDebugger_Initialize() | Initialize() | Initialize() | [
"Initialize",
"()"
] | def Initialize():
"""Initialize()"""
return _lldb.SBDebugger_Initialize() | [
"def",
"Initialize",
"(",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_Initialize",
"(",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3163-L3165 | |
CoolProp/CoolProp | 381c8535e5dec3eec27ad430ebbfff8bc9dfc008 | wrappers/Python/CoolProp/Plots/ConsistencyPlots.py | python | ConsistencyFigure.calc_saturation_curves | (self) | Calculate all the saturation curves in one shot using the state class to save computational time | Calculate all the saturation curves in one shot using the state class to save computational time | [
"Calculate",
"all",
"the",
"saturation",
"curves",
"in",
"one",
"shot",
"using",
"the",
"state",
"class",
"to",
"save",
"computational",
"time"
] | def calc_saturation_curves(self):
"""
Calculate all the saturation curves in one shot using the state class to save computational time
"""
HEOS = CP.AbstractState(self.backend, self.fluid)
self.dictL, self.dictV = {}, {}
for Q, dic in zip([0, 1], [self.dictL, self.dictV]):
rhomolar, smolar, hmolar, T, p, umolar = [], [], [], [], [], []
for _T in np.logspace(np.log10(HEOS.keyed_output(CP.iT_triple)), np.log10(HEOS.keyed_output(CP.iT_critical)), 500):
try:
HEOS.update(CP.QT_INPUTS, Q, _T)
if (HEOS.p() < 0): raise ValueError('P is negative:' + str(HEOS.p()))
HEOS.T(), HEOS.p(), HEOS.rhomolar(), HEOS.hmolar(), HEOS.smolar()
HEOS.umolar()
T.append(HEOS.T())
p.append(HEOS.p())
rhomolar.append(HEOS.rhomolar())
hmolar.append(HEOS.hmolar())
smolar.append(HEOS.smolar())
umolar.append(HEOS.umolar())
except ValueError as VE:
myprint(1, 'satT error:', VE, '; T:', '{T:0.16g}'.format(T=_T), 'T/Tc:', _T / HEOS.keyed_output(CP.iT_critical))
dic.update(dict(T=np.array(T),
P=np.array(p),
Dmolar=np.array(rhomolar),
Hmolar=np.array(hmolar),
Smolar=np.array(smolar),
Umolar=np.array(umolar))) | [
"def",
"calc_saturation_curves",
"(",
"self",
")",
":",
"HEOS",
"=",
"CP",
".",
"AbstractState",
"(",
"self",
".",
"backend",
",",
"self",
".",
"fluid",
")",
"self",
".",
"dictL",
",",
"self",
".",
"dictV",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"Q",
",",
"dic",
"in",
"zip",
"(",
"[",
"0",
",",
"1",
"]",
",",
"[",
"self",
".",
"dictL",
",",
"self",
".",
"dictV",
"]",
")",
":",
"rhomolar",
",",
"smolar",
",",
"hmolar",
",",
"T",
",",
"p",
",",
"umolar",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"_T",
"in",
"np",
".",
"logspace",
"(",
"np",
".",
"log10",
"(",
"HEOS",
".",
"keyed_output",
"(",
"CP",
".",
"iT_triple",
")",
")",
",",
"np",
".",
"log10",
"(",
"HEOS",
".",
"keyed_output",
"(",
"CP",
".",
"iT_critical",
")",
")",
",",
"500",
")",
":",
"try",
":",
"HEOS",
".",
"update",
"(",
"CP",
".",
"QT_INPUTS",
",",
"Q",
",",
"_T",
")",
"if",
"(",
"HEOS",
".",
"p",
"(",
")",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'P is negative:'",
"+",
"str",
"(",
"HEOS",
".",
"p",
"(",
")",
")",
")",
"HEOS",
".",
"T",
"(",
")",
",",
"HEOS",
".",
"p",
"(",
")",
",",
"HEOS",
".",
"rhomolar",
"(",
")",
",",
"HEOS",
".",
"hmolar",
"(",
")",
",",
"HEOS",
".",
"smolar",
"(",
")",
"HEOS",
".",
"umolar",
"(",
")",
"T",
".",
"append",
"(",
"HEOS",
".",
"T",
"(",
")",
")",
"p",
".",
"append",
"(",
"HEOS",
".",
"p",
"(",
")",
")",
"rhomolar",
".",
"append",
"(",
"HEOS",
".",
"rhomolar",
"(",
")",
")",
"hmolar",
".",
"append",
"(",
"HEOS",
".",
"hmolar",
"(",
")",
")",
"smolar",
".",
"append",
"(",
"HEOS",
".",
"smolar",
"(",
")",
")",
"umolar",
".",
"append",
"(",
"HEOS",
".",
"umolar",
"(",
")",
")",
"except",
"ValueError",
"as",
"VE",
":",
"myprint",
"(",
"1",
",",
"'satT error:'",
",",
"VE",
",",
"'; T:'",
",",
"'{T:0.16g}'",
".",
"format",
"(",
"T",
"=",
"_T",
")",
",",
"'T/Tc:'",
",",
"_T",
"/",
"HEOS",
".",
"keyed_output",
"(",
"CP",
".",
"iT_critical",
")",
")",
"dic",
".",
"update",
"(",
"dict",
"(",
"T",
"=",
"np",
".",
"array",
"(",
"T",
")",
",",
"P",
"=",
"np",
".",
"array",
"(",
"p",
")",
",",
"Dmolar",
"=",
"np",
".",
"array",
"(",
"rhomolar",
")",
",",
"Hmolar",
"=",
"np",
".",
"array",
"(",
"hmolar",
")",
",",
"Smolar",
"=",
"np",
".",
"array",
"(",
"smolar",
")",
",",
"Umolar",
"=",
"np",
".",
"array",
"(",
"umolar",
")",
")",
")"
] | https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/wrappers/Python/CoolProp/Plots/ConsistencyPlots.py#L128-L157 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/common/position.py | python | Position.IsAtBeginning | (self) | return self.start == 0 and self.length == 0 | Returns whether this position is at the beginning of any string.
Returns:
Whether this position is at the beginning of any string. | Returns whether this position is at the beginning of any string. | [
"Returns",
"whether",
"this",
"position",
"is",
"at",
"the",
"beginning",
"of",
"any",
"string",
"."
] | def IsAtBeginning(self):
"""Returns whether this position is at the beginning of any string.
Returns:
Whether this position is at the beginning of any string.
"""
return self.start == 0 and self.length == 0 | [
"def",
"IsAtBeginning",
"(",
"self",
")",
":",
"return",
"self",
".",
"start",
"==",
"0",
"and",
"self",
".",
"length",
"==",
"0"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/common/position.py#L96-L102 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/framework/python/ops/variables.py | python | get_local_variables | (scope=None, suffix=None) | return get_variables(scope, suffix, ops.GraphKeys.LOCAL_VARIABLES) | Gets the list of local variables, filtered by scope and/or suffix.
Args:
scope: an optional scope for filtering the variables to return.
suffix: an optional suffix for filtering the variables to return.
Returns:
a list of variables in collection with scope and suffix. | Gets the list of local variables, filtered by scope and/or suffix. | [
"Gets",
"the",
"list",
"of",
"local",
"variables",
"filtered",
"by",
"scope",
"and",
"/",
"or",
"suffix",
"."
] | def get_local_variables(scope=None, suffix=None):
"""Gets the list of local variables, filtered by scope and/or suffix.
Args:
scope: an optional scope for filtering the variables to return.
suffix: an optional suffix for filtering the variables to return.
Returns:
a list of variables in collection with scope and suffix.
"""
return get_variables(scope, suffix, ops.GraphKeys.LOCAL_VARIABLES) | [
"def",
"get_local_variables",
"(",
"scope",
"=",
"None",
",",
"suffix",
"=",
"None",
")",
":",
"return",
"get_variables",
"(",
"scope",
",",
"suffix",
",",
"ops",
".",
"GraphKeys",
".",
"LOCAL_VARIABLES",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/framework/python/ops/variables.py#L312-L322 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings._ConfigAttrib | (self, path, config,
default=None, prefix='', append=None, map=None) | return self._GetAndMunge(
self.msvs_configuration_attributes[config],
path, default, prefix, append, map) | _GetAndMunge for msvs_configuration_attributes. | _GetAndMunge for msvs_configuration_attributes. | [
"_GetAndMunge",
"for",
"msvs_configuration_attributes",
"."
] | def _ConfigAttrib(self, path, config,
default=None, prefix='', append=None, map=None):
"""_GetAndMunge for msvs_configuration_attributes."""
return self._GetAndMunge(
self.msvs_configuration_attributes[config],
path, default, prefix, append, map) | [
"def",
"_ConfigAttrib",
"(",
"self",
",",
"path",
",",
"config",
",",
"default",
"=",
"None",
",",
"prefix",
"=",
"''",
",",
"append",
"=",
"None",
",",
"map",
"=",
"None",
")",
":",
"return",
"self",
".",
"_GetAndMunge",
"(",
"self",
".",
"msvs_configuration_attributes",
"[",
"config",
"]",
",",
"path",
",",
"default",
",",
"prefix",
",",
"append",
",",
"map",
")"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/msvs_emulation.py#L325-L330 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/kmeans.py | python | KMeansClustering.clusters | (self) | return checkpoints.load_variable(self.model_dir, self.CLUSTERS) | Returns cluster centers. | Returns cluster centers. | [
"Returns",
"cluster",
"centers",
"."
] | def clusters(self):
"""Returns cluster centers."""
return checkpoints.load_variable(self.model_dir, self.CLUSTERS) | [
"def",
"clusters",
"(",
"self",
")",
":",
"return",
"checkpoints",
".",
"load_variable",
"(",
"self",
".",
"model_dir",
",",
"self",
".",
"CLUSTERS",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/kmeans.py#L218-L220 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/EditorWindow.py | python | EditorWindow.reset_help_menu_entries | (self) | Update the additional help entries on the Help menu | Update the additional help entries on the Help menu | [
"Update",
"the",
"additional",
"help",
"entries",
"on",
"the",
"Help",
"menu"
] | def reset_help_menu_entries(self):
"Update the additional help entries on the Help menu"
help_list = idleConf.GetAllExtraHelpSourcesList()
helpmenu = self.menudict['help']
# first delete the extra help entries, if any
helpmenu_length = helpmenu.index(END)
if helpmenu_length > self.base_helpmenu_length:
helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length)
# then rebuild them
if help_list:
helpmenu.add_separator()
for entry in help_list:
cmd = self.__extra_help_callback(entry[1])
helpmenu.add_command(label=entry[0], command=cmd)
# and update the menu dictionary
self.menudict['help'] = helpmenu | [
"def",
"reset_help_menu_entries",
"(",
"self",
")",
":",
"help_list",
"=",
"idleConf",
".",
"GetAllExtraHelpSourcesList",
"(",
")",
"helpmenu",
"=",
"self",
".",
"menudict",
"[",
"'help'",
"]",
"# first delete the extra help entries, if any",
"helpmenu_length",
"=",
"helpmenu",
".",
"index",
"(",
"END",
")",
"if",
"helpmenu_length",
">",
"self",
".",
"base_helpmenu_length",
":",
"helpmenu",
".",
"delete",
"(",
"(",
"self",
".",
"base_helpmenu_length",
"+",
"1",
")",
",",
"helpmenu_length",
")",
"# then rebuild them",
"if",
"help_list",
":",
"helpmenu",
".",
"add_separator",
"(",
")",
"for",
"entry",
"in",
"help_list",
":",
"cmd",
"=",
"self",
".",
"__extra_help_callback",
"(",
"entry",
"[",
"1",
"]",
")",
"helpmenu",
".",
"add_command",
"(",
"label",
"=",
"entry",
"[",
"0",
"]",
",",
"command",
"=",
"cmd",
")",
"# and update the menu dictionary",
"self",
".",
"menudict",
"[",
"'help'",
"]",
"=",
"helpmenu"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/EditorWindow.py#L836-L851 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/s3transfer/futures.py | python | TransferCoordinator.add_done_callback | (self, function, *args, **kwargs) | Add a done callback to be invoked when transfer is done | Add a done callback to be invoked when transfer is done | [
"Add",
"a",
"done",
"callback",
"to",
"be",
"invoked",
"when",
"transfer",
"is",
"done"
] | def add_done_callback(self, function, *args, **kwargs):
"""Add a done callback to be invoked when transfer is done"""
with self._done_callbacks_lock:
self._done_callbacks.append(
FunctionContainer(function, *args, **kwargs)
) | [
"def",
"add_done_callback",
"(",
"self",
",",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_done_callbacks_lock",
":",
"self",
".",
"_done_callbacks",
".",
"append",
"(",
"FunctionContainer",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/s3transfer/futures.py#L314-L319 | ||
libfive/libfive | ab5e354cf6fd992f80aaa9432c52683219515c8a | libfive/bind/python/libfive/stdlib/transforms.py | python | attract_z | (shape, locus, radius, exaggerate=1) | return Shape(stdlib.attract_z(
args[0].ptr,
tvec3(*[a.ptr for a in args[1]]),
args[2].ptr,
args[3].ptr)) | Attracts the shape away from a XY plane based upon a radius r,
with optional exaggeration | Attracts the shape away from a XY plane based upon a radius r,
with optional exaggeration | [
"Attracts",
"the",
"shape",
"away",
"from",
"a",
"XY",
"plane",
"based",
"upon",
"a",
"radius",
"r",
"with",
"optional",
"exaggeration"
] | def attract_z(shape, locus, radius, exaggerate=1):
""" Attracts the shape away from a XY plane based upon a radius r,
with optional exaggeration
"""
args = [Shape.wrap(shape), list([Shape.wrap(i) for i in locus]), Shape.wrap(radius), Shape.wrap(exaggerate)]
return Shape(stdlib.attract_z(
args[0].ptr,
tvec3(*[a.ptr for a in args[1]]),
args[2].ptr,
args[3].ptr)) | [
"def",
"attract_z",
"(",
"shape",
",",
"locus",
",",
"radius",
",",
"exaggerate",
"=",
"1",
")",
":",
"args",
"=",
"[",
"Shape",
".",
"wrap",
"(",
"shape",
")",
",",
"list",
"(",
"[",
"Shape",
".",
"wrap",
"(",
"i",
")",
"for",
"i",
"in",
"locus",
"]",
")",
",",
"Shape",
".",
"wrap",
"(",
"radius",
")",
",",
"Shape",
".",
"wrap",
"(",
"exaggerate",
")",
"]",
"return",
"Shape",
"(",
"stdlib",
".",
"attract_z",
"(",
"args",
"[",
"0",
"]",
".",
"ptr",
",",
"tvec3",
"(",
"*",
"[",
"a",
".",
"ptr",
"for",
"a",
"in",
"args",
"[",
"1",
"]",
"]",
")",
",",
"args",
"[",
"2",
"]",
".",
"ptr",
",",
"args",
"[",
"3",
"]",
".",
"ptr",
")",
")"
] | https://github.com/libfive/libfive/blob/ab5e354cf6fd992f80aaa9432c52683219515c8a/libfive/bind/python/libfive/stdlib/transforms.py#L371-L380 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/json_schema_compiler/ppapi_generator.py | python | _PpapiGeneratorBase.NeedsOptional | (self, type_) | return self._NameComponents(type_) in self._optional_types | Returns True if an optional |type_| is required. | Returns True if an optional |type_| is required. | [
"Returns",
"True",
"if",
"an",
"optional",
"|type_|",
"is",
"required",
"."
] | def NeedsOptional(self, type_):
"""Returns True if an optional |type_| is required."""
return self._NameComponents(type_) in self._optional_types | [
"def",
"NeedsOptional",
"(",
"self",
",",
"type_",
")",
":",
"return",
"self",
".",
"_NameComponents",
"(",
"type_",
")",
"in",
"self",
".",
"_optional_types"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/json_schema_compiler/ppapi_generator.py#L222-L224 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/timeit.py | python | main | (args=None, *, _wrap_timer=None) | return None | Main program, used when run as a script.
The optional 'args' argument specifies the command line to be parsed,
defaulting to sys.argv[1:].
The return value is an exit code to be passed to sys.exit(); it
may be None to indicate success.
When an exception happens during timing, a traceback is printed to
stderr and the return value is 1. Exceptions at other times
(including the template compilation) are not caught.
'_wrap_timer' is an internal interface used for unit testing. If it
is not None, it must be a callable that accepts a timer function
and returns another timer function (used for unit testing). | Main program, used when run as a script. | [
"Main",
"program",
"used",
"when",
"run",
"as",
"a",
"script",
"."
] | def main(args=None, *, _wrap_timer=None):
"""Main program, used when run as a script.
The optional 'args' argument specifies the command line to be parsed,
defaulting to sys.argv[1:].
The return value is an exit code to be passed to sys.exit(); it
may be None to indicate success.
When an exception happens during timing, a traceback is printed to
stderr and the return value is 1. Exceptions at other times
(including the template compilation) are not caught.
'_wrap_timer' is an internal interface used for unit testing. If it
is not None, it must be a callable that accepts a timer function
and returns another timer function (used for unit testing).
"""
if args is None:
args = sys.argv[1:]
import getopt
try:
opts, args = getopt.getopt(args, "n:u:s:r:tcpvh",
["number=", "setup=", "repeat=",
"time", "clock", "process",
"verbose", "unit=", "help"])
except getopt.error as err:
print(err)
print("use -h/--help for command line help")
return 2
timer = default_timer
stmt = "\n".join(args) or "pass"
number = 0 # auto-determine
setup = []
repeat = default_repeat
verbose = 0
time_unit = None
units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0}
precision = 3
for o, a in opts:
if o in ("-n", "--number"):
number = int(a)
if o in ("-s", "--setup"):
setup.append(a)
if o in ("-u", "--unit"):
if a in units:
time_unit = a
else:
print("Unrecognized unit. Please select nsec, usec, msec, or sec.",
file=sys.stderr)
return 2
if o in ("-r", "--repeat"):
repeat = int(a)
if repeat <= 0:
repeat = 1
if o in ("-p", "--process"):
timer = time.process_time
if o in ("-v", "--verbose"):
if verbose:
precision += 1
verbose += 1
if o in ("-h", "--help"):
print(__doc__, end=' ')
return 0
setup = "\n".join(setup) or "pass"
# Include the current directory, so that local imports work (sys.path
# contains the directory of this script, rather than the current
# directory)
import os
sys.path.insert(0, os.curdir)
if _wrap_timer is not None:
timer = _wrap_timer(timer)
t = Timer(stmt, setup, timer)
if number == 0:
# determine number so that 0.2 <= total time < 2.0
callback = None
if verbose:
def callback(number, time_taken):
msg = "{num} loop{s} -> {secs:.{prec}g} secs"
plural = (number != 1)
print(msg.format(num=number, s='s' if plural else '',
secs=time_taken, prec=precision))
try:
number, _ = t.autorange(callback)
except:
t.print_exc()
return 1
if verbose:
print()
try:
raw_timings = t.repeat(repeat, number)
except:
t.print_exc()
return 1
def format_time(dt):
unit = time_unit
if unit is not None:
scale = units[unit]
else:
scales = [(scale, unit) for unit, scale in units.items()]
scales.sort(reverse=True)
for scale, unit in scales:
if dt >= scale:
break
return "%.*g %s" % (precision, dt / scale, unit)
if verbose:
print("raw times: %s" % ", ".join(map(format_time, raw_timings)))
print()
timings = [dt / number for dt in raw_timings]
best = min(timings)
print("%d loop%s, best of %d: %s per loop"
% (number, 's' if number != 1 else '',
repeat, format_time(best)))
best = min(timings)
worst = max(timings)
if worst >= best * 4:
import warnings
warnings.warn_explicit("The test results are likely unreliable. "
"The worst time (%s) was more than four times "
"slower than the best time (%s)."
% (format_time(worst), format_time(best)),
UserWarning, '', 0)
return None | [
"def",
"main",
"(",
"args",
"=",
"None",
",",
"*",
",",
"_wrap_timer",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"import",
"getopt",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"args",
",",
"\"n:u:s:r:tcpvh\"",
",",
"[",
"\"number=\"",
",",
"\"setup=\"",
",",
"\"repeat=\"",
",",
"\"time\"",
",",
"\"clock\"",
",",
"\"process\"",
",",
"\"verbose\"",
",",
"\"unit=\"",
",",
"\"help\"",
"]",
")",
"except",
"getopt",
".",
"error",
"as",
"err",
":",
"print",
"(",
"err",
")",
"print",
"(",
"\"use -h/--help for command line help\"",
")",
"return",
"2",
"timer",
"=",
"default_timer",
"stmt",
"=",
"\"\\n\"",
".",
"join",
"(",
"args",
")",
"or",
"\"pass\"",
"number",
"=",
"0",
"# auto-determine",
"setup",
"=",
"[",
"]",
"repeat",
"=",
"default_repeat",
"verbose",
"=",
"0",
"time_unit",
"=",
"None",
"units",
"=",
"{",
"\"nsec\"",
":",
"1e-9",
",",
"\"usec\"",
":",
"1e-6",
",",
"\"msec\"",
":",
"1e-3",
",",
"\"sec\"",
":",
"1.0",
"}",
"precision",
"=",
"3",
"for",
"o",
",",
"a",
"in",
"opts",
":",
"if",
"o",
"in",
"(",
"\"-n\"",
",",
"\"--number\"",
")",
":",
"number",
"=",
"int",
"(",
"a",
")",
"if",
"o",
"in",
"(",
"\"-s\"",
",",
"\"--setup\"",
")",
":",
"setup",
".",
"append",
"(",
"a",
")",
"if",
"o",
"in",
"(",
"\"-u\"",
",",
"\"--unit\"",
")",
":",
"if",
"a",
"in",
"units",
":",
"time_unit",
"=",
"a",
"else",
":",
"print",
"(",
"\"Unrecognized unit. Please select nsec, usec, msec, or sec.\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
"2",
"if",
"o",
"in",
"(",
"\"-r\"",
",",
"\"--repeat\"",
")",
":",
"repeat",
"=",
"int",
"(",
"a",
")",
"if",
"repeat",
"<=",
"0",
":",
"repeat",
"=",
"1",
"if",
"o",
"in",
"(",
"\"-p\"",
",",
"\"--process\"",
")",
":",
"timer",
"=",
"time",
".",
"process_time",
"if",
"o",
"in",
"(",
"\"-v\"",
",",
"\"--verbose\"",
")",
":",
"if",
"verbose",
":",
"precision",
"+=",
"1",
"verbose",
"+=",
"1",
"if",
"o",
"in",
"(",
"\"-h\"",
",",
"\"--help\"",
")",
":",
"print",
"(",
"__doc__",
",",
"end",
"=",
"' '",
")",
"return",
"0",
"setup",
"=",
"\"\\n\"",
".",
"join",
"(",
"setup",
")",
"or",
"\"pass\"",
"# Include the current directory, so that local imports work (sys.path",
"# contains the directory of this script, rather than the current",
"# directory)",
"import",
"os",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"curdir",
")",
"if",
"_wrap_timer",
"is",
"not",
"None",
":",
"timer",
"=",
"_wrap_timer",
"(",
"timer",
")",
"t",
"=",
"Timer",
"(",
"stmt",
",",
"setup",
",",
"timer",
")",
"if",
"number",
"==",
"0",
":",
"# determine number so that 0.2 <= total time < 2.0",
"callback",
"=",
"None",
"if",
"verbose",
":",
"def",
"callback",
"(",
"number",
",",
"time_taken",
")",
":",
"msg",
"=",
"\"{num} loop{s} -> {secs:.{prec}g} secs\"",
"plural",
"=",
"(",
"number",
"!=",
"1",
")",
"print",
"(",
"msg",
".",
"format",
"(",
"num",
"=",
"number",
",",
"s",
"=",
"'s'",
"if",
"plural",
"else",
"''",
",",
"secs",
"=",
"time_taken",
",",
"prec",
"=",
"precision",
")",
")",
"try",
":",
"number",
",",
"_",
"=",
"t",
".",
"autorange",
"(",
"callback",
")",
"except",
":",
"t",
".",
"print_exc",
"(",
")",
"return",
"1",
"if",
"verbose",
":",
"print",
"(",
")",
"try",
":",
"raw_timings",
"=",
"t",
".",
"repeat",
"(",
"repeat",
",",
"number",
")",
"except",
":",
"t",
".",
"print_exc",
"(",
")",
"return",
"1",
"def",
"format_time",
"(",
"dt",
")",
":",
"unit",
"=",
"time_unit",
"if",
"unit",
"is",
"not",
"None",
":",
"scale",
"=",
"units",
"[",
"unit",
"]",
"else",
":",
"scales",
"=",
"[",
"(",
"scale",
",",
"unit",
")",
"for",
"unit",
",",
"scale",
"in",
"units",
".",
"items",
"(",
")",
"]",
"scales",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"for",
"scale",
",",
"unit",
"in",
"scales",
":",
"if",
"dt",
">=",
"scale",
":",
"break",
"return",
"\"%.*g %s\"",
"%",
"(",
"precision",
",",
"dt",
"/",
"scale",
",",
"unit",
")",
"if",
"verbose",
":",
"print",
"(",
"\"raw times: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"map",
"(",
"format_time",
",",
"raw_timings",
")",
")",
")",
"print",
"(",
")",
"timings",
"=",
"[",
"dt",
"/",
"number",
"for",
"dt",
"in",
"raw_timings",
"]",
"best",
"=",
"min",
"(",
"timings",
")",
"print",
"(",
"\"%d loop%s, best of %d: %s per loop\"",
"%",
"(",
"number",
",",
"'s'",
"if",
"number",
"!=",
"1",
"else",
"''",
",",
"repeat",
",",
"format_time",
"(",
"best",
")",
")",
")",
"best",
"=",
"min",
"(",
"timings",
")",
"worst",
"=",
"max",
"(",
"timings",
")",
"if",
"worst",
">=",
"best",
"*",
"4",
":",
"import",
"warnings",
"warnings",
".",
"warn_explicit",
"(",
"\"The test results are likely unreliable. \"",
"\"The worst time (%s) was more than four times \"",
"\"slower than the best time (%s).\"",
"%",
"(",
"format_time",
"(",
"worst",
")",
",",
"format_time",
"(",
"best",
")",
")",
",",
"UserWarning",
",",
"''",
",",
"0",
")",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/timeit.py#L240-L372 | |
Z3Prover/z3 | d745d03afdfdf638d66093e2bfbacaf87187f35b | src/api/python/z3/z3.py | python | Lambda | (vs, body) | return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx) | Create a Z3 lambda expression.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> mem0 = Array('mem0', IntSort(), IntSort())
>>> lo, hi, e, i = Ints('lo hi e i')
>>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
>>> mem1
Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i])) | Create a Z3 lambda expression. | [
"Create",
"a",
"Z3",
"lambda",
"expression",
"."
] | def Lambda(vs, body):
"""Create a Z3 lambda expression.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> mem0 = Array('mem0', IntSort(), IntSort())
>>> lo, hi, e, i = Ints('lo hi e i')
>>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
>>> mem1
Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
"""
ctx = body.ctx
if is_app(vs):
vs = [vs]
num_vars = len(vs)
_vs = (Ast * num_vars)()
for i in range(num_vars):
# TODO: Check if is constant
_vs[i] = vs[i].as_ast()
return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx) | [
"def",
"Lambda",
"(",
"vs",
",",
"body",
")",
":",
"ctx",
"=",
"body",
".",
"ctx",
"if",
"is_app",
"(",
"vs",
")",
":",
"vs",
"=",
"[",
"vs",
"]",
"num_vars",
"=",
"len",
"(",
"vs",
")",
"_vs",
"=",
"(",
"Ast",
"*",
"num_vars",
")",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"num_vars",
")",
":",
"# TODO: Check if is constant",
"_vs",
"[",
"i",
"]",
"=",
"vs",
"[",
"i",
"]",
".",
"as_ast",
"(",
")",
"return",
"QuantifierRef",
"(",
"Z3_mk_lambda_const",
"(",
"ctx",
".",
"ref",
"(",
")",
",",
"num_vars",
",",
"_vs",
",",
"body",
".",
"as_ast",
"(",
")",
")",
",",
"ctx",
")"
] | https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L2229-L2247 | |
devpack/android-python27 | d42dd67565e104cf7b0b50eb473f615db3e69901 | python-build-with-qt/PyQt-x11-gpl-4.8/examples/mainwindows/separations.py | python | Viewer.__init__ | (self) | Constructor initializes a default value for the brightness, creates
the main menu entries, and constructs a central widget that contains
enough space for images to be displayed. | Constructor initializes a default value for the brightness, creates
the main menu entries, and constructs a central widget that contains
enough space for images to be displayed. | [
"Constructor",
"initializes",
"a",
"default",
"value",
"for",
"the",
"brightness",
"creates",
"the",
"main",
"menu",
"entries",
"and",
"constructs",
"a",
"central",
"widget",
"that",
"contains",
"enough",
"space",
"for",
"images",
"to",
"be",
"displayed",
"."
] | def __init__(self):
""" Constructor initializes a default value for the brightness, creates
the main menu entries, and constructs a central widget that contains
enough space for images to be displayed.
"""
super(Viewer, self).__init__()
self.scaledImage = QtGui.QImage()
self.menuMap = {}
self.path = ''
self.brightness = 255
self.setWindowTitle("QImage Color Separations")
self.createMenus()
self.setCentralWidget(self.createCentralWidget()) | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"Viewer",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"scaledImage",
"=",
"QtGui",
".",
"QImage",
"(",
")",
"self",
".",
"menuMap",
"=",
"{",
"}",
"self",
".",
"path",
"=",
"''",
"self",
".",
"brightness",
"=",
"255",
"self",
".",
"setWindowTitle",
"(",
"\"QImage Color Separations\"",
")",
"self",
".",
"createMenus",
"(",
")",
"self",
".",
"setCentralWidget",
"(",
"self",
".",
"createCentralWidget",
"(",
")",
")"
] | https://github.com/devpack/android-python27/blob/d42dd67565e104cf7b0b50eb473f615db3e69901/python-build-with-qt/PyQt-x11-gpl-4.8/examples/mainwindows/separations.py#L254-L269 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py | python | MacTool._CopyStringsFile | (self, source, dest, convert_to_binary) | Copies a .strings file using iconv to reconvert the input into UTF-16. | Copies a .strings file using iconv to reconvert the input into UTF-16. | [
"Copies",
"a",
".",
"strings",
"file",
"using",
"iconv",
"to",
"reconvert",
"the",
"input",
"into",
"UTF",
"-",
"16",
"."
] | def _CopyStringsFile(self, source, dest, convert_to_binary):
"""Copies a .strings file using iconv to reconvert the input into UTF-16."""
input_code = self._DetectInputEncoding(source) or "UTF-8"
# Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call
# CFPropertyListCreateFromXMLData() behind the scenes; at least it prints
# CFPropertyListCreateFromXMLData(): Old-style plist parser: missing
# semicolon in dictionary.
# on invalid files. Do the same kind of validation.
import CoreFoundation
s = open(source, 'rb').read()
d = CoreFoundation.CFDataCreate(None, s, len(s))
_, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
if error:
return
fp = open(dest, 'wb')
fp.write(s.decode(input_code).encode('UTF-16'))
fp.close()
if convert_to_binary == 'True':
self._ConvertToBinary(dest) | [
"def",
"_CopyStringsFile",
"(",
"self",
",",
"source",
",",
"dest",
",",
"convert_to_binary",
")",
":",
"input_code",
"=",
"self",
".",
"_DetectInputEncoding",
"(",
"source",
")",
"or",
"\"UTF-8\"",
"# Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call",
"# CFPropertyListCreateFromXMLData() behind the scenes; at least it prints",
"# CFPropertyListCreateFromXMLData(): Old-style plist parser: missing",
"# semicolon in dictionary.",
"# on invalid files. Do the same kind of validation.",
"import",
"CoreFoundation",
"s",
"=",
"open",
"(",
"source",
",",
"'rb'",
")",
".",
"read",
"(",
")",
"d",
"=",
"CoreFoundation",
".",
"CFDataCreate",
"(",
"None",
",",
"s",
",",
"len",
"(",
"s",
")",
")",
"_",
",",
"error",
"=",
"CoreFoundation",
".",
"CFPropertyListCreateFromXMLData",
"(",
"None",
",",
"d",
",",
"0",
",",
"None",
")",
"if",
"error",
":",
"return",
"fp",
"=",
"open",
"(",
"dest",
",",
"'wb'",
")",
"fp",
".",
"write",
"(",
"s",
".",
"decode",
"(",
"input_code",
")",
".",
"encode",
"(",
"'UTF-16'",
")",
")",
"fp",
".",
"close",
"(",
")",
"if",
"convert_to_binary",
"==",
"'True'",
":",
"self",
".",
"_ConvertToBinary",
"(",
"dest",
")"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py#L99-L120 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/interpolate/_fitpack_impl.py | python | bisplrep | (x, y, z, w=None, xb=None, xe=None, yb=None, ye=None,
kx=3, ky=3, task=0, s=None, eps=1e-16, tx=None, ty=None,
full_output=0, nxest=None, nyest=None, quiet=1) | Find a bivariate B-spline representation of a surface.
Given a set of data points (x[i], y[i], z[i]) representing a surface
z=f(x,y), compute a B-spline representation of the surface. Based on
the routine SURFIT from FITPACK.
Parameters
----------
x, y, z : ndarray
Rank-1 arrays of data points.
w : ndarray, optional
Rank-1 array of weights. By default ``w=np.ones(len(x))``.
xb, xe : float, optional
End points of approximation interval in `x`.
By default ``xb = x.min(), xe=x.max()``.
yb, ye : float, optional
End points of approximation interval in `y`.
By default ``yb=y.min(), ye = y.max()``.
kx, ky : int, optional
The degrees of the spline (1 <= kx, ky <= 5).
Third order (kx=ky=3) is recommended.
task : int, optional
If task=0, find knots in x and y and coefficients for a given
smoothing factor, s.
If task=1, find knots and coefficients for another value of the
smoothing factor, s. bisplrep must have been previously called
with task=0 or task=1.
If task=-1, find coefficients for a given set of knots tx, ty.
s : float, optional
A non-negative smoothing factor. If weights correspond
to the inverse of the standard-deviation of the errors in z,
then a good s-value should be found in the range
``(m-sqrt(2*m),m+sqrt(2*m))`` where m=len(x).
eps : float, optional
A threshold for determining the effective rank of an
over-determined linear system of equations (0 < eps < 1).
`eps` is not likely to need changing.
tx, ty : ndarray, optional
Rank-1 arrays of the knots of the spline for task=-1
full_output : int, optional
Non-zero to return optional outputs.
nxest, nyest : int, optional
Over-estimates of the total number of knots. If None then
``nxest = max(kx+sqrt(m/2),2*kx+3)``,
``nyest = max(ky+sqrt(m/2),2*ky+3)``.
quiet : int, optional
Non-zero to suppress printing of messages.
This parameter is deprecated; use standard Python warning filters
instead.
Returns
-------
tck : array_like
A list [tx, ty, c, kx, ky] containing the knots (tx, ty) and
coefficients (c) of the bivariate B-spline representation of the
surface along with the degree of the spline.
fp : ndarray
The weighted sum of squared residuals of the spline approximation.
ier : int
An integer flag about splrep success. Success is indicated if
ier<=0. If ier in [1,2,3] an error occurred but was not raised.
Otherwise an error is raised.
msg : str
A message corresponding to the integer flag, ier.
See Also
--------
splprep, splrep, splint, sproot, splev
UnivariateSpline, BivariateSpline
Notes
-----
See `bisplev` to evaluate the value of the B-spline given its tck
representation.
References
----------
.. [1] Dierckx P.:An algorithm for surface fitting with spline functions
Ima J. Numer. Anal. 1 (1981) 267-283.
.. [2] Dierckx P.:An algorithm for surface fitting with spline functions
report tw50, Dept. Computer Science,K.U.Leuven, 1980.
.. [3] Dierckx P.:Curve and surface fitting with splines, Monographs on
Numerical Analysis, Oxford University Press, 1993. | Find a bivariate B-spline representation of a surface. | [
"Find",
"a",
"bivariate",
"B",
"-",
"spline",
"representation",
"of",
"a",
"surface",
"."
] | def bisplrep(x, y, z, w=None, xb=None, xe=None, yb=None, ye=None,
kx=3, ky=3, task=0, s=None, eps=1e-16, tx=None, ty=None,
full_output=0, nxest=None, nyest=None, quiet=1):
"""
Find a bivariate B-spline representation of a surface.
Given a set of data points (x[i], y[i], z[i]) representing a surface
z=f(x,y), compute a B-spline representation of the surface. Based on
the routine SURFIT from FITPACK.
Parameters
----------
x, y, z : ndarray
Rank-1 arrays of data points.
w : ndarray, optional
Rank-1 array of weights. By default ``w=np.ones(len(x))``.
xb, xe : float, optional
End points of approximation interval in `x`.
By default ``xb = x.min(), xe=x.max()``.
yb, ye : float, optional
End points of approximation interval in `y`.
By default ``yb=y.min(), ye = y.max()``.
kx, ky : int, optional
The degrees of the spline (1 <= kx, ky <= 5).
Third order (kx=ky=3) is recommended.
task : int, optional
If task=0, find knots in x and y and coefficients for a given
smoothing factor, s.
If task=1, find knots and coefficients for another value of the
smoothing factor, s. bisplrep must have been previously called
with task=0 or task=1.
If task=-1, find coefficients for a given set of knots tx, ty.
s : float, optional
A non-negative smoothing factor. If weights correspond
to the inverse of the standard-deviation of the errors in z,
then a good s-value should be found in the range
``(m-sqrt(2*m),m+sqrt(2*m))`` where m=len(x).
eps : float, optional
A threshold for determining the effective rank of an
over-determined linear system of equations (0 < eps < 1).
`eps` is not likely to need changing.
tx, ty : ndarray, optional
Rank-1 arrays of the knots of the spline for task=-1
full_output : int, optional
Non-zero to return optional outputs.
nxest, nyest : int, optional
Over-estimates of the total number of knots. If None then
``nxest = max(kx+sqrt(m/2),2*kx+3)``,
``nyest = max(ky+sqrt(m/2),2*ky+3)``.
quiet : int, optional
Non-zero to suppress printing of messages.
This parameter is deprecated; use standard Python warning filters
instead.
Returns
-------
tck : array_like
A list [tx, ty, c, kx, ky] containing the knots (tx, ty) and
coefficients (c) of the bivariate B-spline representation of the
surface along with the degree of the spline.
fp : ndarray
The weighted sum of squared residuals of the spline approximation.
ier : int
An integer flag about splrep success. Success is indicated if
ier<=0. If ier in [1,2,3] an error occurred but was not raised.
Otherwise an error is raised.
msg : str
A message corresponding to the integer flag, ier.
See Also
--------
splprep, splrep, splint, sproot, splev
UnivariateSpline, BivariateSpline
Notes
-----
See `bisplev` to evaluate the value of the B-spline given its tck
representation.
References
----------
.. [1] Dierckx P.:An algorithm for surface fitting with spline functions
Ima J. Numer. Anal. 1 (1981) 267-283.
.. [2] Dierckx P.:An algorithm for surface fitting with spline functions
report tw50, Dept. Computer Science,K.U.Leuven, 1980.
.. [3] Dierckx P.:Curve and surface fitting with splines, Monographs on
Numerical Analysis, Oxford University Press, 1993.
"""
x, y, z = map(ravel, [x, y, z]) # ensure 1-d arrays.
m = len(x)
if not (m == len(y) == len(z)):
raise TypeError('len(x)==len(y)==len(z) must hold.')
if w is None:
w = ones(m, float)
else:
w = atleast_1d(w)
if not len(w) == m:
raise TypeError('len(w)=%d is not equal to m=%d' % (len(w), m))
if xb is None:
xb = x.min()
if xe is None:
xe = x.max()
if yb is None:
yb = y.min()
if ye is None:
ye = y.max()
if not (-1 <= task <= 1):
raise TypeError('task must be -1, 0 or 1')
if s is None:
s = m - sqrt(2*m)
if tx is None and task == -1:
raise TypeError('Knots_x must be given for task=-1')
if tx is not None:
_surfit_cache['tx'] = atleast_1d(tx)
nx = len(_surfit_cache['tx'])
if ty is None and task == -1:
raise TypeError('Knots_y must be given for task=-1')
if ty is not None:
_surfit_cache['ty'] = atleast_1d(ty)
ny = len(_surfit_cache['ty'])
if task == -1 and nx < 2*kx+2:
raise TypeError('There must be at least 2*kx+2 knots_x for task=-1')
if task == -1 and ny < 2*ky+2:
raise TypeError('There must be at least 2*ky+2 knots_x for task=-1')
if not ((1 <= kx <= 5) and (1 <= ky <= 5)):
raise TypeError('Given degree of the spline (kx,ky=%d,%d) is not '
'supported. (1<=k<=5)' % (kx, ky))
if m < (kx + 1)*(ky + 1):
raise TypeError('m >= (kx+1)(ky+1) must hold')
if nxest is None:
nxest = int(kx + sqrt(m/2))
if nyest is None:
nyest = int(ky + sqrt(m/2))
nxest, nyest = max(nxest, 2*kx + 3), max(nyest, 2*ky + 3)
if task >= 0 and s == 0:
nxest = int(kx + sqrt(3*m))
nyest = int(ky + sqrt(3*m))
if task == -1:
_surfit_cache['tx'] = atleast_1d(tx)
_surfit_cache['ty'] = atleast_1d(ty)
tx, ty = _surfit_cache['tx'], _surfit_cache['ty']
wrk = _surfit_cache['wrk']
u = nxest - kx - 1
v = nyest - ky - 1
km = max(kx, ky) + 1
ne = max(nxest, nyest)
bx, by = kx*v + ky + 1, ky*u + kx + 1
b1, b2 = bx, bx + v - ky
if bx > by:
b1, b2 = by, by + u - kx
msg = "Too many data points to interpolate"
lwrk1 = _intc_overflow(u*v*(2 + b1 + b2) +
2*(u + v + km*(m + ne) + ne - kx - ky) + b2 + 1,
msg=msg)
lwrk2 = _intc_overflow(u*v*(b2 + 1) + b2, msg=msg)
tx, ty, c, o = _fitpack._surfit(x, y, z, w, xb, xe, yb, ye, kx, ky,
task, s, eps, tx, ty, nxest, nyest,
wrk, lwrk1, lwrk2)
_curfit_cache['tx'] = tx
_curfit_cache['ty'] = ty
_curfit_cache['wrk'] = o['wrk']
ier, fp = o['ier'], o['fp']
tck = [tx, ty, c, kx, ky]
ierm = min(11, max(-3, ier))
if ierm <= 0 and not quiet:
_mess = (_iermess2[ierm][0] +
"\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" %
(kx, ky, len(tx), len(ty), m, fp, s))
warnings.warn(RuntimeWarning(_mess))
if ierm > 0 and not full_output:
if ier in [1, 2, 3, 4, 5]:
_mess = ("\n\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" %
(kx, ky, len(tx), len(ty), m, fp, s))
warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess))
else:
try:
raise _iermess2[ierm][1](_iermess2[ierm][0])
except KeyError:
raise _iermess2['unknown'][1](_iermess2['unknown'][0])
if full_output:
try:
return tck, fp, ier, _iermess2[ierm][0]
except KeyError:
return tck, fp, ier, _iermess2['unknown'][0]
else:
return tck | [
"def",
"bisplrep",
"(",
"x",
",",
"y",
",",
"z",
",",
"w",
"=",
"None",
",",
"xb",
"=",
"None",
",",
"xe",
"=",
"None",
",",
"yb",
"=",
"None",
",",
"ye",
"=",
"None",
",",
"kx",
"=",
"3",
",",
"ky",
"=",
"3",
",",
"task",
"=",
"0",
",",
"s",
"=",
"None",
",",
"eps",
"=",
"1e-16",
",",
"tx",
"=",
"None",
",",
"ty",
"=",
"None",
",",
"full_output",
"=",
"0",
",",
"nxest",
"=",
"None",
",",
"nyest",
"=",
"None",
",",
"quiet",
"=",
"1",
")",
":",
"x",
",",
"y",
",",
"z",
"=",
"map",
"(",
"ravel",
",",
"[",
"x",
",",
"y",
",",
"z",
"]",
")",
"# ensure 1-d arrays.",
"m",
"=",
"len",
"(",
"x",
")",
"if",
"not",
"(",
"m",
"==",
"len",
"(",
"y",
")",
"==",
"len",
"(",
"z",
")",
")",
":",
"raise",
"TypeError",
"(",
"'len(x)==len(y)==len(z) must hold.'",
")",
"if",
"w",
"is",
"None",
":",
"w",
"=",
"ones",
"(",
"m",
",",
"float",
")",
"else",
":",
"w",
"=",
"atleast_1d",
"(",
"w",
")",
"if",
"not",
"len",
"(",
"w",
")",
"==",
"m",
":",
"raise",
"TypeError",
"(",
"'len(w)=%d is not equal to m=%d'",
"%",
"(",
"len",
"(",
"w",
")",
",",
"m",
")",
")",
"if",
"xb",
"is",
"None",
":",
"xb",
"=",
"x",
".",
"min",
"(",
")",
"if",
"xe",
"is",
"None",
":",
"xe",
"=",
"x",
".",
"max",
"(",
")",
"if",
"yb",
"is",
"None",
":",
"yb",
"=",
"y",
".",
"min",
"(",
")",
"if",
"ye",
"is",
"None",
":",
"ye",
"=",
"y",
".",
"max",
"(",
")",
"if",
"not",
"(",
"-",
"1",
"<=",
"task",
"<=",
"1",
")",
":",
"raise",
"TypeError",
"(",
"'task must be -1, 0 or 1'",
")",
"if",
"s",
"is",
"None",
":",
"s",
"=",
"m",
"-",
"sqrt",
"(",
"2",
"*",
"m",
")",
"if",
"tx",
"is",
"None",
"and",
"task",
"==",
"-",
"1",
":",
"raise",
"TypeError",
"(",
"'Knots_x must be given for task=-1'",
")",
"if",
"tx",
"is",
"not",
"None",
":",
"_surfit_cache",
"[",
"'tx'",
"]",
"=",
"atleast_1d",
"(",
"tx",
")",
"nx",
"=",
"len",
"(",
"_surfit_cache",
"[",
"'tx'",
"]",
")",
"if",
"ty",
"is",
"None",
"and",
"task",
"==",
"-",
"1",
":",
"raise",
"TypeError",
"(",
"'Knots_y must be given for task=-1'",
")",
"if",
"ty",
"is",
"not",
"None",
":",
"_surfit_cache",
"[",
"'ty'",
"]",
"=",
"atleast_1d",
"(",
"ty",
")",
"ny",
"=",
"len",
"(",
"_surfit_cache",
"[",
"'ty'",
"]",
")",
"if",
"task",
"==",
"-",
"1",
"and",
"nx",
"<",
"2",
"*",
"kx",
"+",
"2",
":",
"raise",
"TypeError",
"(",
"'There must be at least 2*kx+2 knots_x for task=-1'",
")",
"if",
"task",
"==",
"-",
"1",
"and",
"ny",
"<",
"2",
"*",
"ky",
"+",
"2",
":",
"raise",
"TypeError",
"(",
"'There must be at least 2*ky+2 knots_x for task=-1'",
")",
"if",
"not",
"(",
"(",
"1",
"<=",
"kx",
"<=",
"5",
")",
"and",
"(",
"1",
"<=",
"ky",
"<=",
"5",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Given degree of the spline (kx,ky=%d,%d) is not '",
"'supported. (1<=k<=5)'",
"%",
"(",
"kx",
",",
"ky",
")",
")",
"if",
"m",
"<",
"(",
"kx",
"+",
"1",
")",
"*",
"(",
"ky",
"+",
"1",
")",
":",
"raise",
"TypeError",
"(",
"'m >= (kx+1)(ky+1) must hold'",
")",
"if",
"nxest",
"is",
"None",
":",
"nxest",
"=",
"int",
"(",
"kx",
"+",
"sqrt",
"(",
"m",
"/",
"2",
")",
")",
"if",
"nyest",
"is",
"None",
":",
"nyest",
"=",
"int",
"(",
"ky",
"+",
"sqrt",
"(",
"m",
"/",
"2",
")",
")",
"nxest",
",",
"nyest",
"=",
"max",
"(",
"nxest",
",",
"2",
"*",
"kx",
"+",
"3",
")",
",",
"max",
"(",
"nyest",
",",
"2",
"*",
"ky",
"+",
"3",
")",
"if",
"task",
">=",
"0",
"and",
"s",
"==",
"0",
":",
"nxest",
"=",
"int",
"(",
"kx",
"+",
"sqrt",
"(",
"3",
"*",
"m",
")",
")",
"nyest",
"=",
"int",
"(",
"ky",
"+",
"sqrt",
"(",
"3",
"*",
"m",
")",
")",
"if",
"task",
"==",
"-",
"1",
":",
"_surfit_cache",
"[",
"'tx'",
"]",
"=",
"atleast_1d",
"(",
"tx",
")",
"_surfit_cache",
"[",
"'ty'",
"]",
"=",
"atleast_1d",
"(",
"ty",
")",
"tx",
",",
"ty",
"=",
"_surfit_cache",
"[",
"'tx'",
"]",
",",
"_surfit_cache",
"[",
"'ty'",
"]",
"wrk",
"=",
"_surfit_cache",
"[",
"'wrk'",
"]",
"u",
"=",
"nxest",
"-",
"kx",
"-",
"1",
"v",
"=",
"nyest",
"-",
"ky",
"-",
"1",
"km",
"=",
"max",
"(",
"kx",
",",
"ky",
")",
"+",
"1",
"ne",
"=",
"max",
"(",
"nxest",
",",
"nyest",
")",
"bx",
",",
"by",
"=",
"kx",
"*",
"v",
"+",
"ky",
"+",
"1",
",",
"ky",
"*",
"u",
"+",
"kx",
"+",
"1",
"b1",
",",
"b2",
"=",
"bx",
",",
"bx",
"+",
"v",
"-",
"ky",
"if",
"bx",
">",
"by",
":",
"b1",
",",
"b2",
"=",
"by",
",",
"by",
"+",
"u",
"-",
"kx",
"msg",
"=",
"\"Too many data points to interpolate\"",
"lwrk1",
"=",
"_intc_overflow",
"(",
"u",
"*",
"v",
"*",
"(",
"2",
"+",
"b1",
"+",
"b2",
")",
"+",
"2",
"*",
"(",
"u",
"+",
"v",
"+",
"km",
"*",
"(",
"m",
"+",
"ne",
")",
"+",
"ne",
"-",
"kx",
"-",
"ky",
")",
"+",
"b2",
"+",
"1",
",",
"msg",
"=",
"msg",
")",
"lwrk2",
"=",
"_intc_overflow",
"(",
"u",
"*",
"v",
"*",
"(",
"b2",
"+",
"1",
")",
"+",
"b2",
",",
"msg",
"=",
"msg",
")",
"tx",
",",
"ty",
",",
"c",
",",
"o",
"=",
"_fitpack",
".",
"_surfit",
"(",
"x",
",",
"y",
",",
"z",
",",
"w",
",",
"xb",
",",
"xe",
",",
"yb",
",",
"ye",
",",
"kx",
",",
"ky",
",",
"task",
",",
"s",
",",
"eps",
",",
"tx",
",",
"ty",
",",
"nxest",
",",
"nyest",
",",
"wrk",
",",
"lwrk1",
",",
"lwrk2",
")",
"_curfit_cache",
"[",
"'tx'",
"]",
"=",
"tx",
"_curfit_cache",
"[",
"'ty'",
"]",
"=",
"ty",
"_curfit_cache",
"[",
"'wrk'",
"]",
"=",
"o",
"[",
"'wrk'",
"]",
"ier",
",",
"fp",
"=",
"o",
"[",
"'ier'",
"]",
",",
"o",
"[",
"'fp'",
"]",
"tck",
"=",
"[",
"tx",
",",
"ty",
",",
"c",
",",
"kx",
",",
"ky",
"]",
"ierm",
"=",
"min",
"(",
"11",
",",
"max",
"(",
"-",
"3",
",",
"ier",
")",
")",
"if",
"ierm",
"<=",
"0",
"and",
"not",
"quiet",
":",
"_mess",
"=",
"(",
"_iermess2",
"[",
"ierm",
"]",
"[",
"0",
"]",
"+",
"\"\\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f\"",
"%",
"(",
"kx",
",",
"ky",
",",
"len",
"(",
"tx",
")",
",",
"len",
"(",
"ty",
")",
",",
"m",
",",
"fp",
",",
"s",
")",
")",
"warnings",
".",
"warn",
"(",
"RuntimeWarning",
"(",
"_mess",
")",
")",
"if",
"ierm",
">",
"0",
"and",
"not",
"full_output",
":",
"if",
"ier",
"in",
"[",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
"]",
":",
"_mess",
"=",
"(",
"\"\\n\\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f\"",
"%",
"(",
"kx",
",",
"ky",
",",
"len",
"(",
"tx",
")",
",",
"len",
"(",
"ty",
")",
",",
"m",
",",
"fp",
",",
"s",
")",
")",
"warnings",
".",
"warn",
"(",
"RuntimeWarning",
"(",
"_iermess2",
"[",
"ierm",
"]",
"[",
"0",
"]",
"+",
"_mess",
")",
")",
"else",
":",
"try",
":",
"raise",
"_iermess2",
"[",
"ierm",
"]",
"[",
"1",
"]",
"(",
"_iermess2",
"[",
"ierm",
"]",
"[",
"0",
"]",
")",
"except",
"KeyError",
":",
"raise",
"_iermess2",
"[",
"'unknown'",
"]",
"[",
"1",
"]",
"(",
"_iermess2",
"[",
"'unknown'",
"]",
"[",
"0",
"]",
")",
"if",
"full_output",
":",
"try",
":",
"return",
"tck",
",",
"fp",
",",
"ier",
",",
"_iermess2",
"[",
"ierm",
"]",
"[",
"0",
"]",
"except",
"KeyError",
":",
"return",
"tck",
",",
"fp",
",",
"ier",
",",
"_iermess2",
"[",
"'unknown'",
"]",
"[",
"0",
"]",
"else",
":",
"return",
"tck"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/_fitpack_impl.py#L801-L988 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.InsertTextUTF8 | (self, pos, text) | Insert UTF8 encoded text at a position. Works 'natively' in a
unicode build of wxPython, and will also work in an ansi build if
the UTF8 text is compatible with the current encoding. | Insert UTF8 encoded text at a position. Works 'natively' in a
unicode build of wxPython, and will also work in an ansi build if
the UTF8 text is compatible with the current encoding. | [
"Insert",
"UTF8",
"encoded",
"text",
"at",
"a",
"position",
".",
"Works",
"natively",
"in",
"a",
"unicode",
"build",
"of",
"wxPython",
"and",
"will",
"also",
"work",
"in",
"an",
"ansi",
"build",
"if",
"the",
"UTF8",
"text",
"is",
"compatible",
"with",
"the",
"current",
"encoding",
"."
] | def InsertTextUTF8(self, pos, text):
"""
Insert UTF8 encoded text at a position. Works 'natively' in a
unicode build of wxPython, and will also work in an ansi build if
the UTF8 text is compatible with the current encoding.
"""
if not wx.USE_UNICODE:
u = text.decode('utf-8')
text = u.encode(wx.GetDefaultPyEncoding())
self.InsertTextRaw(pos, text) | [
"def",
"InsertTextUTF8",
"(",
"self",
",",
"pos",
",",
"text",
")",
":",
"if",
"not",
"wx",
".",
"USE_UNICODE",
":",
"u",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"text",
"=",
"u",
".",
"encode",
"(",
"wx",
".",
"GetDefaultPyEncoding",
"(",
")",
")",
"self",
".",
"InsertTextRaw",
"(",
"pos",
",",
"text",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L6791-L6800 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/training_v1.py | python | Model._check_call_args | (self, method_name) | Check that `call` has only one positional arg. | Check that `call` has only one positional arg. | [
"Check",
"that",
"call",
"has",
"only",
"one",
"positional",
"arg",
"."
] | def _check_call_args(self, method_name):
"""Check that `call` has only one positional arg."""
# Always allow first arg, regardless of arg name.
fullargspec = self._call_full_argspec
if fullargspec.defaults:
positional_args = fullargspec.args[:-len(fullargspec.defaults)]
else:
positional_args = fullargspec.args
if 'training' in positional_args:
positional_args.remove('training')
# self and first arg can be positional.
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
'Models passed to `' + method_name + '` can only have `training` '
'and the first argument in `call` as positional arguments, '
'found: ' + str(extra_args) + '.') | [
"def",
"_check_call_args",
"(",
"self",
",",
"method_name",
")",
":",
"# Always allow first arg, regardless of arg name.",
"fullargspec",
"=",
"self",
".",
"_call_full_argspec",
"if",
"fullargspec",
".",
"defaults",
":",
"positional_args",
"=",
"fullargspec",
".",
"args",
"[",
":",
"-",
"len",
"(",
"fullargspec",
".",
"defaults",
")",
"]",
"else",
":",
"positional_args",
"=",
"fullargspec",
".",
"args",
"if",
"'training'",
"in",
"positional_args",
":",
"positional_args",
".",
"remove",
"(",
"'training'",
")",
"# self and first arg can be positional.",
"if",
"len",
"(",
"positional_args",
")",
">",
"2",
":",
"extra_args",
"=",
"positional_args",
"[",
"2",
":",
"]",
"raise",
"ValueError",
"(",
"'Models passed to `'",
"+",
"method_name",
"+",
"'` can only have `training` '",
"'and the first argument in `call` as positional arguments, '",
"'found: '",
"+",
"str",
"(",
"extra_args",
")",
"+",
"'.'",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/training_v1.py#L1315-L1332 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nccl_ops.py | python | reduce_sum | (tensors) | return _apply_reduce('sum', tensors) | Returns a tensor with the reduce sum across `tensors`.
The computation is done with a reduce operation, so only one tensor is
returned.
Args:
tensors: The input tensors across which to sum; must be assigned
to GPU devices.
Returns:
A tensor containing the sum of the input tensors.
Raises:
LookupError: If context is not currently using a GPU device. | Returns a tensor with the reduce sum across `tensors`. | [
"Returns",
"a",
"tensor",
"with",
"the",
"reduce",
"sum",
"across",
"tensors",
"."
] | def reduce_sum(tensors):
"""Returns a tensor with the reduce sum across `tensors`.
The computation is done with a reduce operation, so only one tensor is
returned.
Args:
tensors: The input tensors across which to sum; must be assigned
to GPU devices.
Returns:
A tensor containing the sum of the input tensors.
Raises:
LookupError: If context is not currently using a GPU device.
"""
return _apply_reduce('sum', tensors) | [
"def",
"reduce_sum",
"(",
"tensors",
")",
":",
"return",
"_apply_reduce",
"(",
"'sum'",
",",
"tensors",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nccl_ops.py#L130-L146 | |
ivansafrin/Polycode | 37a40fefe194ec7f6e9d1257f3bb3517b0a168bc | Bindings/Scripts/create_lua_library/CppHeaderParser.py | python | CppHeader.evaluate_enum_stack | (self) | Create an Enum out of the name stack | Create an Enum out of the name stack | [
"Create",
"an",
"Enum",
"out",
"of",
"the",
"name",
"stack"
] | def evaluate_enum_stack(self):
"""Create an Enum out of the name stack"""
debug_print( "evaluating enum" )
newEnum = CppEnum(self.nameStack)
if len(newEnum.keys()):
if len(self.curClass):
newEnum["namespace"] = self.cur_namespace(False)
klass = self.classes[self.curClass]
klass["enums"][self.curAccessSpecifier].append(newEnum)
if self.curAccessSpecifier == 'public' and 'name' in newEnum: klass._public_enums[ newEnum['name'] ] = newEnum
else:
newEnum["namespace"] = self.cur_namespace(True)
self.enums.append(newEnum)
if 'name' in newEnum and newEnum['name']: self.global_enums[ newEnum['name'] ] = newEnum
#This enum has instances, turn them into properties
if newEnum.has_key("instances"):
instanceType = "enum"
if newEnum.has_key("name"):
instanceType = newEnum["name"]
for instance in newEnum["instances"]:
self.nameStack = [instanceType, instance]
self.evaluate_property_stack()
del newEnum["instances"] | [
"def",
"evaluate_enum_stack",
"(",
"self",
")",
":",
"debug_print",
"(",
"\"evaluating enum\"",
")",
"newEnum",
"=",
"CppEnum",
"(",
"self",
".",
"nameStack",
")",
"if",
"len",
"(",
"newEnum",
".",
"keys",
"(",
")",
")",
":",
"if",
"len",
"(",
"self",
".",
"curClass",
")",
":",
"newEnum",
"[",
"\"namespace\"",
"]",
"=",
"self",
".",
"cur_namespace",
"(",
"False",
")",
"klass",
"=",
"self",
".",
"classes",
"[",
"self",
".",
"curClass",
"]",
"klass",
"[",
"\"enums\"",
"]",
"[",
"self",
".",
"curAccessSpecifier",
"]",
".",
"append",
"(",
"newEnum",
")",
"if",
"self",
".",
"curAccessSpecifier",
"==",
"'public'",
"and",
"'name'",
"in",
"newEnum",
":",
"klass",
".",
"_public_enums",
"[",
"newEnum",
"[",
"'name'",
"]",
"]",
"=",
"newEnum",
"else",
":",
"newEnum",
"[",
"\"namespace\"",
"]",
"=",
"self",
".",
"cur_namespace",
"(",
"True",
")",
"self",
".",
"enums",
".",
"append",
"(",
"newEnum",
")",
"if",
"'name'",
"in",
"newEnum",
"and",
"newEnum",
"[",
"'name'",
"]",
":",
"self",
".",
"global_enums",
"[",
"newEnum",
"[",
"'name'",
"]",
"]",
"=",
"newEnum",
"#This enum has instances, turn them into properties",
"if",
"newEnum",
".",
"has_key",
"(",
"\"instances\"",
")",
":",
"instanceType",
"=",
"\"enum\"",
"if",
"newEnum",
".",
"has_key",
"(",
"\"name\"",
")",
":",
"instanceType",
"=",
"newEnum",
"[",
"\"name\"",
"]",
"for",
"instance",
"in",
"newEnum",
"[",
"\"instances\"",
"]",
":",
"self",
".",
"nameStack",
"=",
"[",
"instanceType",
",",
"instance",
"]",
"self",
".",
"evaluate_property_stack",
"(",
")",
"del",
"newEnum",
"[",
"\"instances\"",
"]"
] | https://github.com/ivansafrin/Polycode/blob/37a40fefe194ec7f6e9d1257f3bb3517b0a168bc/Bindings/Scripts/create_lua_library/CppHeaderParser.py#L2247-L2270 | ||
spring/spring | 553a21526b144568b608a0507674b076ec80d9f9 | buildbot/stacktrace_translator/stacktrace_translator.py | python | test_version | (string) | return re.search(RE_VERSION, string, re.MULTILINE).groups() | >>> test_version('Spring 91.0 (OMP)')
('91.0', None)
>>> test_version('spring 93.2.1-82-g863e91e release (Debug OMP)')
('93.2.1-82-g863e91e', 'release') | >>> test_version('Spring 91.0 (OMP)')
('91.0', None) | [
">>>",
"test_version",
"(",
"Spring",
"91",
".",
"0",
"(",
"OMP",
")",
")",
"(",
"91",
".",
"0",
"None",
")"
] | def test_version(string):
'''
>>> test_version('Spring 91.0 (OMP)')
('91.0', None)
>>> test_version('spring 93.2.1-82-g863e91e release (Debug OMP)')
('93.2.1-82-g863e91e', 'release')
'''
log.debug('test_version():'+string)
return re.search(RE_VERSION, string, re.MULTILINE).groups() | [
"def",
"test_version",
"(",
"string",
")",
":",
"log",
".",
"debug",
"(",
"'test_version():'",
"+",
"string",
")",
"return",
"re",
".",
"search",
"(",
"RE_VERSION",
",",
"string",
",",
"re",
".",
"MULTILINE",
")",
".",
"groups",
"(",
")"
] | https://github.com/spring/spring/blob/553a21526b144568b608a0507674b076ec80d9f9/buildbot/stacktrace_translator/stacktrace_translator.py#L91-L100 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/environment.py | python | Template.render | (self, *args, **kwargs) | return self.environment.handle_exception(exc_info, True) | This method accepts the same arguments as the `dict` constructor:
A dict, a dict subclass or some keyword arguments. If no arguments
are given the context will be empty. These two calls do the same::
template.render(knights='that say nih')
template.render({'knights': 'that say nih'})
This will return the rendered template as unicode string. | This method accepts the same arguments as the `dict` constructor:
A dict, a dict subclass or some keyword arguments. If no arguments
are given the context will be empty. These two calls do the same:: | [
"This",
"method",
"accepts",
"the",
"same",
"arguments",
"as",
"the",
"dict",
"constructor",
":",
"A",
"dict",
"a",
"dict",
"subclass",
"or",
"some",
"keyword",
"arguments",
".",
"If",
"no",
"arguments",
"are",
"given",
"the",
"context",
"will",
"be",
"empty",
".",
"These",
"two",
"calls",
"do",
"the",
"same",
"::"
] | def render(self, *args, **kwargs):
"""This method accepts the same arguments as the `dict` constructor:
A dict, a dict subclass or some keyword arguments. If no arguments
are given the context will be empty. These two calls do the same::
template.render(knights='that say nih')
template.render({'knights': 'that say nih'})
This will return the rendered template as unicode string.
"""
vars = dict(*args, **kwargs)
try:
return concat(self.root_render_func(self.new_context(vars)))
except Exception:
exc_info = sys.exc_info()
return self.environment.handle_exception(exc_info, True) | [
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"vars",
"=",
"dict",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"return",
"concat",
"(",
"self",
".",
"root_render_func",
"(",
"self",
".",
"new_context",
"(",
"vars",
")",
")",
")",
"except",
"Exception",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"return",
"self",
".",
"environment",
".",
"handle_exception",
"(",
"exc_info",
",",
"True",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/environment.py#L993-L1008 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | parse_requirements | (strs) | Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof. | Yield ``Requirement`` objects for each specification in `strs` | [
"Yield",
"Requirement",
"objects",
"for",
"each",
"specification",
"in",
"strs"
] | def parse_requirements(strs):
"""Yield ``Requirement`` objects for each specification in `strs`
`strs` must be a string, or a (possibly-nested) iterable thereof.
"""
# create a steppable iterator, so we can handle \-continuations
lines = iter(yield_lines(strs))
for line in lines:
# Drop comments -- a hash without a space may be in a URL.
if ' #' in line:
line = line[:line.find(' #')]
# If there is a line continuation, drop it, and append the next line.
if line.endswith('\\'):
line = line[:-2].strip()
try:
line += next(lines)
except StopIteration:
return
yield Requirement(line) | [
"def",
"parse_requirements",
"(",
"strs",
")",
":",
"# create a steppable iterator, so we can handle \\-continuations",
"lines",
"=",
"iter",
"(",
"yield_lines",
"(",
"strs",
")",
")",
"for",
"line",
"in",
"lines",
":",
"# Drop comments -- a hash without a space may be in a URL.",
"if",
"' #'",
"in",
"line",
":",
"line",
"=",
"line",
"[",
":",
"line",
".",
"find",
"(",
"' #'",
")",
"]",
"# If there is a line continuation, drop it, and append the next line.",
"if",
"line",
".",
"endswith",
"(",
"'\\\\'",
")",
":",
"line",
"=",
"line",
"[",
":",
"-",
"2",
"]",
".",
"strip",
"(",
")",
"try",
":",
"line",
"+=",
"next",
"(",
"lines",
")",
"except",
"StopIteration",
":",
"return",
"yield",
"Requirement",
"(",
"line",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L3075-L3094 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/png/png.py | python | Test.testPtrns | (self) | Test colour type 3 and tRNS chunk (and 4-bit palette). | Test colour type 3 and tRNS chunk (and 4-bit palette). | [
"Test",
"colour",
"type",
"3",
"and",
"tRNS",
"chunk",
"(",
"and",
"4",
"-",
"bit",
"palette",
")",
"."
] | def testPtrns(self):
"Test colour type 3 and tRNS chunk (and 4-bit palette)."
a = (50,99,50,50)
b = (200,120,120,80)
c = (255,255,255)
d = (200,120,120)
e = (50,99,50)
w = Writer(3, 3, bitdepth=4, palette=[a,b,c,d,e])
f = BytesIO()
w.write_array(f, array('B', (4, 3, 2, 3, 2, 0, 2, 0, 1)))
r = Reader(bytes=f.getvalue())
x,y,pixels,meta = r.asRGBA8()
self.assertEqual(x, 3)
self.assertEqual(y, 3)
c = c+(255,)
d = d+(255,)
e = e+(255,)
boxed = [(e,d,c),(d,c,a),(c,a,b)]
flat = map(lambda row: itertools.chain(*row), boxed)
self.assertEqual(map(list, pixels), map(list, flat)) | [
"def",
"testPtrns",
"(",
"self",
")",
":",
"a",
"=",
"(",
"50",
",",
"99",
",",
"50",
",",
"50",
")",
"b",
"=",
"(",
"200",
",",
"120",
",",
"120",
",",
"80",
")",
"c",
"=",
"(",
"255",
",",
"255",
",",
"255",
")",
"d",
"=",
"(",
"200",
",",
"120",
",",
"120",
")",
"e",
"=",
"(",
"50",
",",
"99",
",",
"50",
")",
"w",
"=",
"Writer",
"(",
"3",
",",
"3",
",",
"bitdepth",
"=",
"4",
",",
"palette",
"=",
"[",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"e",
"]",
")",
"f",
"=",
"BytesIO",
"(",
")",
"w",
".",
"write_array",
"(",
"f",
",",
"array",
"(",
"'B'",
",",
"(",
"4",
",",
"3",
",",
"2",
",",
"3",
",",
"2",
",",
"0",
",",
"2",
",",
"0",
",",
"1",
")",
")",
")",
"r",
"=",
"Reader",
"(",
"bytes",
"=",
"f",
".",
"getvalue",
"(",
")",
")",
"x",
",",
"y",
",",
"pixels",
",",
"meta",
"=",
"r",
".",
"asRGBA8",
"(",
")",
"self",
".",
"assertEqual",
"(",
"x",
",",
"3",
")",
"self",
".",
"assertEqual",
"(",
"y",
",",
"3",
")",
"c",
"=",
"c",
"+",
"(",
"255",
",",
")",
"d",
"=",
"d",
"+",
"(",
"255",
",",
")",
"e",
"=",
"e",
"+",
"(",
"255",
",",
")",
"boxed",
"=",
"[",
"(",
"e",
",",
"d",
",",
"c",
")",
",",
"(",
"d",
",",
"c",
",",
"a",
")",
",",
"(",
"c",
",",
"a",
",",
"b",
")",
"]",
"flat",
"=",
"map",
"(",
"lambda",
"row",
":",
"itertools",
".",
"chain",
"(",
"*",
"row",
")",
",",
"boxed",
")",
"self",
".",
"assertEqual",
"(",
"map",
"(",
"list",
",",
"pixels",
")",
",",
"map",
"(",
"list",
",",
"flat",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/png/png.py#L2554-L2573 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/check_ops.py | python | _assert_rank_condition | (x, rank, static_condition, dynamic_condition, data,
summarize, name) | return logging_ops.Assert(condition, data, summarize=summarize) | Assert `x` has a rank that satisfies a given condition.
Args:
x: Numeric `Tensor`.
rank: Scalar `Tensor`.
static_condition: A python function that takes `[actual_rank, given_rank]`
and returns `True` if the condition is satisfied, `False` otherwise.
dynamic_condition: An `op` that takes [actual_rank, given_rank]
and return `True` if the condition is satisfied, `False` otherwise.
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.
name: A name for this operation (optional).
Defaults to "assert_rank_at_least".
Returns:
Op raising `InvalidArgumentError` if `x` fails dynamic_condition.
Raises:
ValueError: If static checks determine `x` fails static_condition. | Assert `x` has a rank that satisfies a given condition. | [
"Assert",
"x",
"has",
"a",
"rank",
"that",
"satisfies",
"a",
"given",
"condition",
"."
] | def _assert_rank_condition(x, rank, static_condition, dynamic_condition, data,
summarize, name):
"""Assert `x` has a rank that satisfies a given condition.
Args:
x: Numeric `Tensor`.
rank: Scalar `Tensor`.
static_condition: A python function that takes `[actual_rank, given_rank]`
and returns `True` if the condition is satisfied, `False` otherwise.
dynamic_condition: An `op` that takes [actual_rank, given_rank]
and return `True` if the condition is satisfied, `False` otherwise.
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.
name: A name for this operation (optional).
Defaults to "assert_rank_at_least".
Returns:
Op raising `InvalidArgumentError` if `x` fails dynamic_condition.
Raises:
ValueError: If static checks determine `x` fails static_condition.
"""
with ops.op_scope([x], name, 'assert_rank'):
x = ops.convert_to_tensor(x, name='x')
rank = ops.convert_to_tensor(rank, name='rank')
# Attempt to statically defined rank.
x_rank_static = x.get_shape().ndims
rank_static = tensor_util.constant_value(rank)
assert_type(rank, dtypes.int32)
if rank_static is not None:
if rank_static.ndim != 0:
raise ValueError('Rank must be a scalar')
if x_rank_static is not None:
if not static_condition(x_rank_static, rank_static):
raise ValueError(
'Static rank condition failed', x_rank_static, rank_static)
return control_flow_ops.no_op(name='static_checks_determined_all_ok')
condition = dynamic_condition(array_ops.rank(x), rank)
# Add the condition that `rank` must have rank zero. Prevents the bug where
# someone does assert_rank(x, [n]), rather than assert_rank(x, n).
if rank_static is None:
this_data = ['Rank must be a scalar. Received rank: ', rank]
rank_check = assert_rank(rank, 0, data=this_data)
condition = control_flow_ops.with_dependencies([rank_check], condition)
return logging_ops.Assert(condition, data, summarize=summarize) | [
"def",
"_assert_rank_condition",
"(",
"x",
",",
"rank",
",",
"static_condition",
",",
"dynamic_condition",
",",
"data",
",",
"summarize",
",",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"x",
"]",
",",
"name",
",",
"'assert_rank'",
")",
":",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
",",
"name",
"=",
"'x'",
")",
"rank",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"rank",
",",
"name",
"=",
"'rank'",
")",
"# Attempt to statically defined rank.",
"x_rank_static",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"ndims",
"rank_static",
"=",
"tensor_util",
".",
"constant_value",
"(",
"rank",
")",
"assert_type",
"(",
"rank",
",",
"dtypes",
".",
"int32",
")",
"if",
"rank_static",
"is",
"not",
"None",
":",
"if",
"rank_static",
".",
"ndim",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'Rank must be a scalar'",
")",
"if",
"x_rank_static",
"is",
"not",
"None",
":",
"if",
"not",
"static_condition",
"(",
"x_rank_static",
",",
"rank_static",
")",
":",
"raise",
"ValueError",
"(",
"'Static rank condition failed'",
",",
"x_rank_static",
",",
"rank_static",
")",
"return",
"control_flow_ops",
".",
"no_op",
"(",
"name",
"=",
"'static_checks_determined_all_ok'",
")",
"condition",
"=",
"dynamic_condition",
"(",
"array_ops",
".",
"rank",
"(",
"x",
")",
",",
"rank",
")",
"# Add the condition that `rank` must have rank zero. Prevents the bug where",
"# someone does assert_rank(x, [n]), rather than assert_rank(x, n).",
"if",
"rank_static",
"is",
"None",
":",
"this_data",
"=",
"[",
"'Rank must be a scalar. Received rank: '",
",",
"rank",
"]",
"rank_check",
"=",
"assert_rank",
"(",
"rank",
",",
"0",
",",
"data",
"=",
"this_data",
")",
"condition",
"=",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"rank_check",
"]",
",",
"condition",
")",
"return",
"logging_ops",
".",
"Assert",
"(",
"condition",
",",
"data",
",",
"summarize",
"=",
"summarize",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/check_ops.py#L403-L455 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/lib2to3/fixer_util.py | python | in_special_context | (node) | return False | Returns true if node is in an environment where all that is required
of it is being itterable (ie, it doesn't matter if it returns a list
or an itterator).
See test_map_nochange in test_fixers.py for some examples and tests. | Returns true if node is in an environment where all that is required
of it is being itterable (ie, it doesn't matter if it returns a list
or an itterator).
See test_map_nochange in test_fixers.py for some examples and tests. | [
"Returns",
"true",
"if",
"node",
"is",
"in",
"an",
"environment",
"where",
"all",
"that",
"is",
"required",
"of",
"it",
"is",
"being",
"itterable",
"(",
"ie",
"it",
"doesn",
"t",
"matter",
"if",
"it",
"returns",
"a",
"list",
"or",
"an",
"itterator",
")",
".",
"See",
"test_map_nochange",
"in",
"test_fixers",
".",
"py",
"for",
"some",
"examples",
"and",
"tests",
"."
] | def in_special_context(node):
""" Returns true if node is in an environment where all that is required
of it is being itterable (ie, it doesn't matter if it returns a list
or an itterator).
See test_map_nochange in test_fixers.py for some examples and tests.
"""
global p0, p1, p2, pats_built
if not pats_built:
p1 = patcomp.compile_pattern(p1)
p0 = patcomp.compile_pattern(p0)
p2 = patcomp.compile_pattern(p2)
pats_built = True
patterns = [p0, p1, p2]
for pattern, parent in zip(patterns, attr_chain(node, "parent")):
results = {}
if pattern.match(parent, results) and results["node"] is node:
return True
return False | [
"def",
"in_special_context",
"(",
"node",
")",
":",
"global",
"p0",
",",
"p1",
",",
"p2",
",",
"pats_built",
"if",
"not",
"pats_built",
":",
"p1",
"=",
"patcomp",
".",
"compile_pattern",
"(",
"p1",
")",
"p0",
"=",
"patcomp",
".",
"compile_pattern",
"(",
"p0",
")",
"p2",
"=",
"patcomp",
".",
"compile_pattern",
"(",
"p2",
")",
"pats_built",
"=",
"True",
"patterns",
"=",
"[",
"p0",
",",
"p1",
",",
"p2",
"]",
"for",
"pattern",
",",
"parent",
"in",
"zip",
"(",
"patterns",
",",
"attr_chain",
"(",
"node",
",",
"\"parent\"",
")",
")",
":",
"results",
"=",
"{",
"}",
"if",
"pattern",
".",
"match",
"(",
"parent",
",",
"results",
")",
"and",
"results",
"[",
"\"node\"",
"]",
"is",
"node",
":",
"return",
"True",
"return",
"False"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/fixer_util.py#L206-L223 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/bindings/python/clang/cindex.py | python | TranslationUnit.cursor | (self) | return conf.lib.clang_getTranslationUnitCursor(self) | Retrieve the cursor that represents the given translation unit. | Retrieve the cursor that represents the given translation unit. | [
"Retrieve",
"the",
"cursor",
"that",
"represents",
"the",
"given",
"translation",
"unit",
"."
] | def cursor(self):
"""Retrieve the cursor that represents the given translation unit."""
return conf.lib.clang_getTranslationUnitCursor(self) | [
"def",
"cursor",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTranslationUnitCursor",
"(",
"self",
")"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/bindings/python/clang/cindex.py#L2877-L2879 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/all_reduce/python/all_reduce.py | python | _reshape_tensors | (tensors, shape) | return reshaped | Reshape tensors flattened by _flatten_tensors.
Args:
tensors: list of T @{tf.Tensor} of identical length 1D tensors.
shape: list of integers describing the desired shape. Product of
the elements must equal the length of each tensor.
Returns:
list of T @{tf.Tensor} which are the reshaped inputs. | Reshape tensors flattened by _flatten_tensors. | [
"Reshape",
"tensors",
"flattened",
"by",
"_flatten_tensors",
"."
] | def _reshape_tensors(tensors, shape):
"""Reshape tensors flattened by _flatten_tensors.
Args:
tensors: list of T @{tf.Tensor} of identical length 1D tensors.
shape: list of integers describing the desired shape. Product of
the elements must equal the length of each tensor.
Returns:
list of T @{tf.Tensor} which are the reshaped inputs.
"""
reshaped = []
for t in tensors:
with ops.colocate_with(t):
reshaped.append(array_ops.reshape(t, shape))
return reshaped | [
"def",
"_reshape_tensors",
"(",
"tensors",
",",
"shape",
")",
":",
"reshaped",
"=",
"[",
"]",
"for",
"t",
"in",
"tensors",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"t",
")",
":",
"reshaped",
".",
"append",
"(",
"array_ops",
".",
"reshape",
"(",
"t",
",",
"shape",
")",
")",
"return",
"reshaped"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/all_reduce/python/all_reduce.py#L60-L75 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/bijector/power_transform.py | python | PowerTransform.extend_repr | (self) | return str_info | Display instance object as string. | Display instance object as string. | [
"Display",
"instance",
"object",
"as",
"string",
"."
] | def extend_repr(self):
"""Display instance object as string."""
if self.is_scalar_batch:
str_info = 'power = {}'.format(self.power)
else:
str_info = 'batch_shape = {}'.format(self.batch_shape)
return str_info | [
"def",
"extend_repr",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_scalar_batch",
":",
"str_info",
"=",
"'power = {}'",
".",
"format",
"(",
"self",
".",
"power",
")",
"else",
":",
"str_info",
"=",
"'batch_shape = {}'",
".",
"format",
"(",
"self",
".",
"batch_shape",
")",
"return",
"str_info"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/bijector/power_transform.py#L116-L122 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py | python | _NNTPBase._getresp | (self) | return resp | Internal: get a response from the server.
Raise various errors if the response indicates an error.
Returns a unicode string. | Internal: get a response from the server.
Raise various errors if the response indicates an error.
Returns a unicode string. | [
"Internal",
":",
"get",
"a",
"response",
"from",
"the",
"server",
".",
"Raise",
"various",
"errors",
"if",
"the",
"response",
"indicates",
"an",
"error",
".",
"Returns",
"a",
"unicode",
"string",
"."
] | def _getresp(self):
"""Internal: get a response from the server.
Raise various errors if the response indicates an error.
Returns a unicode string."""
resp = self._getline()
if self.debugging: print('*resp*', repr(resp))
resp = resp.decode(self.encoding, self.errors)
c = resp[:1]
if c == '4':
raise NNTPTemporaryError(resp)
if c == '5':
raise NNTPPermanentError(resp)
if c not in '123':
raise NNTPProtocolError(resp)
return resp | [
"def",
"_getresp",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_getline",
"(",
")",
"if",
"self",
".",
"debugging",
":",
"print",
"(",
"'*resp*'",
",",
"repr",
"(",
"resp",
")",
")",
"resp",
"=",
"resp",
".",
"decode",
"(",
"self",
".",
"encoding",
",",
"self",
".",
"errors",
")",
"c",
"=",
"resp",
"[",
":",
"1",
"]",
"if",
"c",
"==",
"'4'",
":",
"raise",
"NNTPTemporaryError",
"(",
"resp",
")",
"if",
"c",
"==",
"'5'",
":",
"raise",
"NNTPPermanentError",
"(",
"resp",
")",
"if",
"c",
"not",
"in",
"'123'",
":",
"raise",
"NNTPProtocolError",
"(",
"resp",
")",
"return",
"resp"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py#L445-L459 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/clang/scripts/run_tool.py | python | _GetFilesFromGit | (paths = None) | return output.splitlines() | Gets the list of files in the git repository.
Args:
paths: Prefix filter for the returned paths. May contain multiple entries. | Gets the list of files in the git repository. | [
"Gets",
"the",
"list",
"of",
"files",
"in",
"the",
"git",
"repository",
"."
] | def _GetFilesFromGit(paths = None):
"""Gets the list of files in the git repository.
Args:
paths: Prefix filter for the returned paths. May contain multiple entries.
"""
args = ['git', 'ls-files']
if paths:
args.extend(paths)
command = subprocess.Popen(args, stdout=subprocess.PIPE)
output, _ = command.communicate()
return output.splitlines() | [
"def",
"_GetFilesFromGit",
"(",
"paths",
"=",
"None",
")",
":",
"args",
"=",
"[",
"'git'",
",",
"'ls-files'",
"]",
"if",
"paths",
":",
"args",
".",
"extend",
"(",
"paths",
")",
"command",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"output",
",",
"_",
"=",
"command",
".",
"communicate",
"(",
")",
"return",
"output",
".",
"splitlines",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/clang/scripts/run_tool.py#L50-L61 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/misc.py | python | redact_password_from_url | (url) | return _transform_url(url, redact_netloc) | Replace the password in a given url with ****. | Replace the password in a given url with ****. | [
"Replace",
"the",
"password",
"in",
"a",
"given",
"url",
"with",
"****",
"."
] | def redact_password_from_url(url):
# type: (str) -> str
"""Replace the password in a given url with ****."""
return _transform_url(url, redact_netloc) | [
"def",
"redact_password_from_url",
"(",
"url",
")",
":",
"# type: (str) -> str",
"return",
"_transform_url",
"(",
"url",
",",
"redact_netloc",
")"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/misc.py#L1008-L1011 | |
toggl-open-source/toggldesktop | 91865205885531cc8fd9e8d613dad49d625d56e7 | third_party/cpplint/cpplint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/toggl-open-source/toggldesktop/blob/91865205885531cc8fd9e8d613dad49d625d56e7/third_party/cpplint/cpplint.py#L1313-L1315 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Sizer.AddSizer | (self, *args, **kw) | return self.Add(*args, **kw) | Compatibility alias for `Add`. | Compatibility alias for `Add`. | [
"Compatibility",
"alias",
"for",
"Add",
"."
] | def AddSizer(self, *args, **kw):
"""Compatibility alias for `Add`."""
return self.Add(*args, **kw) | [
"def",
"AddSizer",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"Add",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L14720-L14722 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/google/protobuf/text_format.py | python | _Parser.MergeFromString | (self, text, message) | return self._MergeLines(text.split('\n'), message) | Merges an text representation of a protocol message into a message. | Merges an text representation of a protocol message into a message. | [
"Merges",
"an",
"text",
"representation",
"of",
"a",
"protocol",
"message",
"into",
"a",
"message",
"."
] | def MergeFromString(self, text, message):
"""Merges an text representation of a protocol message into a message."""
return self._MergeLines(text.split('\n'), message) | [
"def",
"MergeFromString",
"(",
"self",
",",
"text",
",",
"message",
")",
":",
"return",
"self",
".",
"_MergeLines",
"(",
"text",
".",
"split",
"(",
"'\\n'",
")",
",",
"message",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/text_format.py#L433-L435 | |
openMSX/openMSX | c9cfbc0a2a2baaf2c4513c87543fe29bfe8cf806 | build/version.py | python | getVersionTripleString | () | return '%s.%d' % (packageVersionNumber, extractRevisionNumber()) | Version in "x.y.z" format. | Version in "x.y.z" format. | [
"Version",
"in",
"x",
".",
"y",
".",
"z",
"format",
"."
] | def getVersionTripleString():
"""Version in "x.y.z" format."""
return '%s.%d' % (packageVersionNumber, extractRevisionNumber()) | [
"def",
"getVersionTripleString",
"(",
")",
":",
"return",
"'%s.%d'",
"%",
"(",
"packageVersionNumber",
",",
"extractRevisionNumber",
"(",
")",
")"
] | https://github.com/openMSX/openMSX/blob/c9cfbc0a2a2baaf2c4513c87543fe29bfe8cf806/build/version.py#L83-L85 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/__init__.py | python | Distribution._get_metadata_path_for_display | (self, name) | return path | Return the path to the given metadata file, if available. | Return the path to the given metadata file, if available. | [
"Return",
"the",
"path",
"to",
"the",
"given",
"metadata",
"file",
"if",
"available",
"."
] | def _get_metadata_path_for_display(self, name):
"""
Return the path to the given metadata file, if available.
"""
try:
# We need to access _get_metadata_path() on the provider object
# directly rather than through this class's __getattr__()
# since _get_metadata_path() is marked private.
path = self._provider._get_metadata_path(name)
# Handle exceptions e.g. in case the distribution's metadata
# provider doesn't support _get_metadata_path().
except Exception:
return '[could not detect]'
return path | [
"def",
"_get_metadata_path_for_display",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"# We need to access _get_metadata_path() on the provider object",
"# directly rather than through this class's __getattr__()",
"# since _get_metadata_path() is marked private.",
"path",
"=",
"self",
".",
"_provider",
".",
"_get_metadata_path",
"(",
"name",
")",
"# Handle exceptions e.g. in case the distribution's metadata",
"# provider doesn't support _get_metadata_path().",
"except",
"Exception",
":",
"return",
"'[could not detect]'",
"return",
"path"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/__init__.py#L2761-L2776 | |
yuxng/DA-RNN | 77fbb50b4272514588a10a9f90b7d5f8d46974fb | lib/fcn/config.py | python | _merge_a_into_b | (a, b) | Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a. | Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a. | [
"Merge",
"config",
"dictionary",
"a",
"into",
"config",
"dictionary",
"b",
"clobbering",
"the",
"options",
"in",
"b",
"whenever",
"they",
"are",
"also",
"specified",
"in",
"a",
"."
] | def _merge_a_into_b(a, b):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
if type(a) is not edict:
return
for k, v in a.iteritems():
# a must specify keys that are in b
if not b.has_key(k):
raise KeyError('{} is not a valid config key'.format(k))
# the types must match, too
if type(b[k]) is not type(v):
raise ValueError(('Type mismatch ({} vs. {}) '
'for config key: {}').format(type(b[k]),
type(v), k))
# recursively merge dicts
if type(v) is edict:
try:
_merge_a_into_b(a[k], b[k])
except:
print('Error under config key: {}'.format(k))
raise
else:
b[k] = v | [
"def",
"_merge_a_into_b",
"(",
"a",
",",
"b",
")",
":",
"if",
"type",
"(",
"a",
")",
"is",
"not",
"edict",
":",
"return",
"for",
"k",
",",
"v",
"in",
"a",
".",
"iteritems",
"(",
")",
":",
"# a must specify keys that are in b",
"if",
"not",
"b",
".",
"has_key",
"(",
"k",
")",
":",
"raise",
"KeyError",
"(",
"'{} is not a valid config key'",
".",
"format",
"(",
"k",
")",
")",
"# the types must match, too",
"if",
"type",
"(",
"b",
"[",
"k",
"]",
")",
"is",
"not",
"type",
"(",
"v",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Type mismatch ({} vs. {}) '",
"'for config key: {}'",
")",
".",
"format",
"(",
"type",
"(",
"b",
"[",
"k",
"]",
")",
",",
"type",
"(",
"v",
")",
",",
"k",
")",
")",
"# recursively merge dicts",
"if",
"type",
"(",
"v",
")",
"is",
"edict",
":",
"try",
":",
"_merge_a_into_b",
"(",
"a",
"[",
"k",
"]",
",",
"b",
"[",
"k",
"]",
")",
"except",
":",
"print",
"(",
"'Error under config key: {}'",
".",
"format",
"(",
"k",
")",
")",
"raise",
"else",
":",
"b",
"[",
"k",
"]",
"=",
"v"
] | https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/fcn/config.py#L130-L156 | ||
isl-org/Open3D | 79aec3ddde6a571ce2f28e4096477e52ec465244 | python/open3d/ml/torch/python/layers/neighbor_search.py | python | FixedRadiusSearch.forward | (self,
points,
queries,
radius,
points_row_splits=None,
queries_row_splits=None,
hash_table_size_factor=1 / 64,
hash_table=None) | return result | This function computes the neighbors within a fixed radius for each query point.
Arguments:
points: The 3D positions of the input points. It can be a RaggedTensor.
queries: The 3D positions of the query points. It can be a RaggedTensor.
radius: A scalar with the neighborhood radius
points_row_splits: Optional 1D vector with the row splits information
if points is batched. This vector is [0, num_points] if there is
only 1 batch item.
queries_row_splits: Optional 1D vector with the row splits information
if queries is batched. This vector is [0, num_queries] if there is
only 1 batch item.
hash_table_size_factor: Scalar. The size of the hash table as fraction
of points.
hash_table: A precomputed hash table generated with build_spatial_hash_table().
This input can be used to explicitly force the reuse of a hash table in special
cases and is usually not needed.
Note that the hash table must have been generated with the same 'points' array.
Returns:
3 Tensors in the following order
neighbors_index
The compact list of indices of the neighbors. The corresponding query point
can be inferred from the 'neighbor_count_row_splits' vector.
neighbors_row_splits
The exclusive prefix sum of the neighbor count for the query points including
the total neighbor count as the last element. The size of this array is the
number of queries + 1.
neighbors_distance
Stores the distance to each neighbor if 'return_distances' is True.
Note that the distances are squared if metric is L2.
This is a zero length Tensor if 'return_distances' is False. | This function computes the neighbors within a fixed radius for each query point. | [
"This",
"function",
"computes",
"the",
"neighbors",
"within",
"a",
"fixed",
"radius",
"for",
"each",
"query",
"point",
"."
] | def forward(self,
points,
queries,
radius,
points_row_splits=None,
queries_row_splits=None,
hash_table_size_factor=1 / 64,
hash_table=None):
"""This function computes the neighbors within a fixed radius for each query point.
Arguments:
points: The 3D positions of the input points. It can be a RaggedTensor.
queries: The 3D positions of the query points. It can be a RaggedTensor.
radius: A scalar with the neighborhood radius
points_row_splits: Optional 1D vector with the row splits information
if points is batched. This vector is [0, num_points] if there is
only 1 batch item.
queries_row_splits: Optional 1D vector with the row splits information
if queries is batched. This vector is [0, num_queries] if there is
only 1 batch item.
hash_table_size_factor: Scalar. The size of the hash table as fraction
of points.
hash_table: A precomputed hash table generated with build_spatial_hash_table().
This input can be used to explicitly force the reuse of a hash table in special
cases and is usually not needed.
Note that the hash table must have been generated with the same 'points' array.
Returns:
3 Tensors in the following order
neighbors_index
The compact list of indices of the neighbors. The corresponding query point
can be inferred from the 'neighbor_count_row_splits' vector.
neighbors_row_splits
The exclusive prefix sum of the neighbor count for the query points including
the total neighbor count as the last element. The size of this array is the
number of queries + 1.
neighbors_distance
Stores the distance to each neighbor if 'return_distances' is True.
Note that the distances are squared if metric is L2.
This is a zero length Tensor if 'return_distances' is False.
"""
if isinstance(points, classes.RaggedTensor):
points_row_splits = points.row_splits
points = points.values
if isinstance(queries, classes.RaggedTensor):
queries_row_splits = queries.row_splits
queries = queries.values
if points_row_splits is None:
points_row_splits = torch.LongTensor([0, points.shape[0]])
if queries_row_splits is None:
queries_row_splits = torch.LongTensor([0, queries.shape[0]])
if hash_table is None:
table = ops.build_spatial_hash_table(
max_hash_table_size=self.max_hash_table_size,
points=points,
radius=radius,
points_row_splits=points_row_splits,
hash_table_size_factor=hash_table_size_factor)
else:
table = hash_table
result = ops.fixed_radius_search(
ignore_query_point=self.ignore_query_point,
return_distances=self.return_distances,
metric=self.metric,
points=points,
queries=queries,
radius=radius,
points_row_splits=points_row_splits,
queries_row_splits=queries_row_splits,
hash_table_splits=table.hash_table_splits,
hash_table_index=table.hash_table_index,
hash_table_cell_splits=table.hash_table_cell_splits)
return result | [
"def",
"forward",
"(",
"self",
",",
"points",
",",
"queries",
",",
"radius",
",",
"points_row_splits",
"=",
"None",
",",
"queries_row_splits",
"=",
"None",
",",
"hash_table_size_factor",
"=",
"1",
"/",
"64",
",",
"hash_table",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"points",
",",
"classes",
".",
"RaggedTensor",
")",
":",
"points_row_splits",
"=",
"points",
".",
"row_splits",
"points",
"=",
"points",
".",
"values",
"if",
"isinstance",
"(",
"queries",
",",
"classes",
".",
"RaggedTensor",
")",
":",
"queries_row_splits",
"=",
"queries",
".",
"row_splits",
"queries",
"=",
"queries",
".",
"values",
"if",
"points_row_splits",
"is",
"None",
":",
"points_row_splits",
"=",
"torch",
".",
"LongTensor",
"(",
"[",
"0",
",",
"points",
".",
"shape",
"[",
"0",
"]",
"]",
")",
"if",
"queries_row_splits",
"is",
"None",
":",
"queries_row_splits",
"=",
"torch",
".",
"LongTensor",
"(",
"[",
"0",
",",
"queries",
".",
"shape",
"[",
"0",
"]",
"]",
")",
"if",
"hash_table",
"is",
"None",
":",
"table",
"=",
"ops",
".",
"build_spatial_hash_table",
"(",
"max_hash_table_size",
"=",
"self",
".",
"max_hash_table_size",
",",
"points",
"=",
"points",
",",
"radius",
"=",
"radius",
",",
"points_row_splits",
"=",
"points_row_splits",
",",
"hash_table_size_factor",
"=",
"hash_table_size_factor",
")",
"else",
":",
"table",
"=",
"hash_table",
"result",
"=",
"ops",
".",
"fixed_radius_search",
"(",
"ignore_query_point",
"=",
"self",
".",
"ignore_query_point",
",",
"return_distances",
"=",
"self",
".",
"return_distances",
",",
"metric",
"=",
"self",
".",
"metric",
",",
"points",
"=",
"points",
",",
"queries",
"=",
"queries",
",",
"radius",
"=",
"radius",
",",
"points_row_splits",
"=",
"points_row_splits",
",",
"queries_row_splits",
"=",
"queries_row_splits",
",",
"hash_table_splits",
"=",
"table",
".",
"hash_table_splits",
",",
"hash_table_index",
"=",
"table",
".",
"hash_table_index",
",",
"hash_table_cell_splits",
"=",
"table",
".",
"hash_table_cell_splits",
")",
"return",
"result"
] | https://github.com/isl-org/Open3D/blob/79aec3ddde6a571ce2f28e4096477e52ec465244/python/open3d/ml/torch/python/layers/neighbor_search.py#L78-L163 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py | python | NDFrame.tail | (self: FrameOrSeries, n: int = 5) | return self.iloc[-n:] | Return the last `n` rows.
This function returns last `n` rows from the object based on
position. It is useful for quickly verifying data, for example,
after sorting or appending rows.
For negative values of `n`, this function returns all rows except
the first `n` rows, equivalent to ``df[n:]``.
Parameters
----------
n : int, default 5
Number of rows to select.
Returns
-------
type of caller
The last `n` rows of the caller object.
See Also
--------
DataFrame.head : The first `n` rows of the caller object.
Examples
--------
>>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion',
... 'monkey', 'parrot', 'shark', 'whale', 'zebra']})
>>> df
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
5 parrot
6 shark
7 whale
8 zebra
Viewing the last 5 lines
>>> df.tail()
animal
4 monkey
5 parrot
6 shark
7 whale
8 zebra
Viewing the last `n` lines (three in this case)
>>> df.tail(3)
animal
6 shark
7 whale
8 zebra
For negative values of `n`
>>> df.tail(-3)
animal
3 lion
4 monkey
5 parrot
6 shark
7 whale
8 zebra | Return the last `n` rows. | [
"Return",
"the",
"last",
"n",
"rows",
"."
] | def tail(self: FrameOrSeries, n: int = 5) -> FrameOrSeries:
"""
Return the last `n` rows.
This function returns last `n` rows from the object based on
position. It is useful for quickly verifying data, for example,
after sorting or appending rows.
For negative values of `n`, this function returns all rows except
the first `n` rows, equivalent to ``df[n:]``.
Parameters
----------
n : int, default 5
Number of rows to select.
Returns
-------
type of caller
The last `n` rows of the caller object.
See Also
--------
DataFrame.head : The first `n` rows of the caller object.
Examples
--------
>>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion',
... 'monkey', 'parrot', 'shark', 'whale', 'zebra']})
>>> df
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
5 parrot
6 shark
7 whale
8 zebra
Viewing the last 5 lines
>>> df.tail()
animal
4 monkey
5 parrot
6 shark
7 whale
8 zebra
Viewing the last `n` lines (three in this case)
>>> df.tail(3)
animal
6 shark
7 whale
8 zebra
For negative values of `n`
>>> df.tail(-3)
animal
3 lion
4 monkey
5 parrot
6 shark
7 whale
8 zebra
"""
if n == 0:
return self.iloc[0:0]
return self.iloc[-n:] | [
"def",
"tail",
"(",
"self",
":",
"FrameOrSeries",
",",
"n",
":",
"int",
"=",
"5",
")",
"->",
"FrameOrSeries",
":",
"if",
"n",
"==",
"0",
":",
"return",
"self",
".",
"iloc",
"[",
"0",
":",
"0",
"]",
"return",
"self",
".",
"iloc",
"[",
"-",
"n",
":",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L4791-L4864 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | Context.to_integral_value | (self, a) | return a.to_integral_value(context=self) | Rounds to an integer.
When the operand has a negative exponent, the result is the same
as using the quantize() operation using the given operand as the
left-hand-operand, 1E+0 as the right-hand-operand, and the precision
of the operand as the precision setting, except that no flags will
be set. The rounding mode is taken from the context.
>>> ExtendedContext.to_integral_value(Decimal('2.1'))
Decimal('2')
>>> ExtendedContext.to_integral_value(Decimal('100'))
Decimal('100')
>>> ExtendedContext.to_integral_value(Decimal('100.0'))
Decimal('100')
>>> ExtendedContext.to_integral_value(Decimal('101.5'))
Decimal('102')
>>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Decimal('-102')
>>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Decimal('1.0E+6')
>>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Decimal('7.89E+77')
>>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Decimal('-Infinity') | Rounds to an integer. | [
"Rounds",
"to",
"an",
"integer",
"."
] | def to_integral_value(self, a):
"""Rounds to an integer.
When the operand has a negative exponent, the result is the same
as using the quantize() operation using the given operand as the
left-hand-operand, 1E+0 as the right-hand-operand, and the precision
of the operand as the precision setting, except that no flags will
be set. The rounding mode is taken from the context.
>>> ExtendedContext.to_integral_value(Decimal('2.1'))
Decimal('2')
>>> ExtendedContext.to_integral_value(Decimal('100'))
Decimal('100')
>>> ExtendedContext.to_integral_value(Decimal('100.0'))
Decimal('100')
>>> ExtendedContext.to_integral_value(Decimal('101.5'))
Decimal('102')
>>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Decimal('-102')
>>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Decimal('1.0E+6')
>>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Decimal('7.89E+77')
>>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Decimal('-Infinity')
"""
a = _convert_other(a, raiseit=True)
return a.to_integral_value(context=self) | [
"def",
"to_integral_value",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"to_integral_value",
"(",
"context",
"=",
"self",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L5386-L5413 | |
p4lang/behavioral-model | 81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9 | tools/cpplint.py | python | _CppLintState.SetOutputFormat | (self, output_format) | Sets the output format for errors. | Sets the output format for errors. | [
"Sets",
"the",
"output",
"format",
"for",
"errors",
"."
] | def SetOutputFormat(self, output_format):
"""Sets the output format for errors."""
self.output_format = output_format | [
"def",
"SetOutputFormat",
"(",
"self",
",",
"output_format",
")",
":",
"self",
".",
"output_format",
"=",
"output_format"
] | https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/cpplint.py#L1273-L1275 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/compile_resources.py | python | _RenameLocaleResourceDirs | (resource_dirs, path_info) | Rename locale resource directories into standard names when necessary.
This is necessary to deal with the fact that older Android releases only
support ISO 639-1 two-letter codes, and sometimes even obsolete versions
of them.
In practice it means:
* 3-letter ISO 639-2 qualifiers are renamed under a corresponding
2-letter one. E.g. for Filipino, strings under values-fil/ will be moved
to a new corresponding values-tl/ sub-directory.
* Modern ISO 639-1 codes will be renamed to their obsolete variant
for Indonesian, Hebrew and Yiddish (e.g. 'values-in/ -> values-id/).
* Norwegian macrolanguage strings will be renamed to Bokmal (main
Norway language). See http://crbug.com/920960. In practice this
means that 'values-no/ -> values-nb/' unless 'values-nb/' already
exists.
* BCP 47 langauge tags will be renamed to an equivalent ISO 639-1
locale qualifier if possible (e.g. 'values-b+en+US/ -> values-en-rUS').
Args:
resource_dirs: list of top-level resource directories. | Rename locale resource directories into standard names when necessary. | [
"Rename",
"locale",
"resource",
"directories",
"into",
"standard",
"names",
"when",
"necessary",
"."
] | def _RenameLocaleResourceDirs(resource_dirs, path_info):
"""Rename locale resource directories into standard names when necessary.
This is necessary to deal with the fact that older Android releases only
support ISO 639-1 two-letter codes, and sometimes even obsolete versions
of them.
In practice it means:
* 3-letter ISO 639-2 qualifiers are renamed under a corresponding
2-letter one. E.g. for Filipino, strings under values-fil/ will be moved
to a new corresponding values-tl/ sub-directory.
* Modern ISO 639-1 codes will be renamed to their obsolete variant
for Indonesian, Hebrew and Yiddish (e.g. 'values-in/ -> values-id/).
* Norwegian macrolanguage strings will be renamed to Bokmal (main
Norway language). See http://crbug.com/920960. In practice this
means that 'values-no/ -> values-nb/' unless 'values-nb/' already
exists.
* BCP 47 langauge tags will be renamed to an equivalent ISO 639-1
locale qualifier if possible (e.g. 'values-b+en+US/ -> values-en-rUS').
Args:
resource_dirs: list of top-level resource directories.
"""
for resource_dir in resource_dirs:
ignore_dirs = {}
for path in _IterFiles(resource_dir):
locale = resource_utils.FindLocaleInStringResourceFilePath(path)
if not locale:
continue
cr_locale = resource_utils.ToChromiumLocaleName(locale)
if not cr_locale:
continue # Unsupported Android locale qualifier!?
locale2 = resource_utils.ToAndroidLocaleName(cr_locale)
if locale != locale2:
path2 = path.replace('/values-%s/' % locale, '/values-%s/' % locale2)
if path == path2:
raise Exception('Could not substitute locale %s for %s in %s' %
(locale, locale2, path))
# Ignore rather than rename when the destination resources config
# already exists.
# e.g. some libraries provide both values-nb/ and values-no/.
# e.g. material design provides:
# * res/values-rUS/values-rUS.xml
# * res/values-b+es+419/values-b+es+419.xml
config_dir = os.path.dirname(path2)
already_has_renamed_config = ignore_dirs.get(config_dir)
if already_has_renamed_config is None:
# Cache the result of the first time the directory is encountered
# since subsequent encounters will find the directory already exists
# (due to the rename).
already_has_renamed_config = os.path.exists(config_dir)
ignore_dirs[config_dir] = already_has_renamed_config
if already_has_renamed_config:
continue
build_utils.MakeDirectory(os.path.dirname(path2))
shutil.move(path, path2)
path_info.RegisterRename(
os.path.relpath(path, resource_dir),
os.path.relpath(path2, resource_dir)) | [
"def",
"_RenameLocaleResourceDirs",
"(",
"resource_dirs",
",",
"path_info",
")",
":",
"for",
"resource_dir",
"in",
"resource_dirs",
":",
"ignore_dirs",
"=",
"{",
"}",
"for",
"path",
"in",
"_IterFiles",
"(",
"resource_dir",
")",
":",
"locale",
"=",
"resource_utils",
".",
"FindLocaleInStringResourceFilePath",
"(",
"path",
")",
"if",
"not",
"locale",
":",
"continue",
"cr_locale",
"=",
"resource_utils",
".",
"ToChromiumLocaleName",
"(",
"locale",
")",
"if",
"not",
"cr_locale",
":",
"continue",
"# Unsupported Android locale qualifier!?",
"locale2",
"=",
"resource_utils",
".",
"ToAndroidLocaleName",
"(",
"cr_locale",
")",
"if",
"locale",
"!=",
"locale2",
":",
"path2",
"=",
"path",
".",
"replace",
"(",
"'/values-%s/'",
"%",
"locale",
",",
"'/values-%s/'",
"%",
"locale2",
")",
"if",
"path",
"==",
"path2",
":",
"raise",
"Exception",
"(",
"'Could not substitute locale %s for %s in %s'",
"%",
"(",
"locale",
",",
"locale2",
",",
"path",
")",
")",
"# Ignore rather than rename when the destination resources config",
"# already exists.",
"# e.g. some libraries provide both values-nb/ and values-no/.",
"# e.g. material design provides:",
"# * res/values-rUS/values-rUS.xml",
"# * res/values-b+es+419/values-b+es+419.xml",
"config_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path2",
")",
"already_has_renamed_config",
"=",
"ignore_dirs",
".",
"get",
"(",
"config_dir",
")",
"if",
"already_has_renamed_config",
"is",
"None",
":",
"# Cache the result of the first time the directory is encountered",
"# since subsequent encounters will find the directory already exists",
"# (due to the rename).",
"already_has_renamed_config",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"config_dir",
")",
"ignore_dirs",
"[",
"config_dir",
"]",
"=",
"already_has_renamed_config",
"if",
"already_has_renamed_config",
":",
"continue",
"build_utils",
".",
"MakeDirectory",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path2",
")",
")",
"shutil",
".",
"move",
"(",
"path",
",",
"path2",
")",
"path_info",
".",
"RegisterRename",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"resource_dir",
")",
",",
"os",
".",
"path",
".",
"relpath",
"(",
"path2",
",",
"resource_dir",
")",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/compile_resources.py#L252-L315 | ||
qt/qt | 0a2f2382541424726168804be2c90b91381608c6 | src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/input.py | python | DependencyGraphNode.LinkDependencies | (self, targets, dependencies=None, initial=True) | return dependencies | Returns a list of dependency targets that are linked into this target.
This function has a split personality, depending on the setting of
|initial|. Outside callers should always leave |initial| at its default
setting.
When adding a target to the list of dependencies, this function will
recurse into itself with |initial| set to False, to collect depenedencies
that are linked into the linkable target for which the list is being built. | Returns a list of dependency targets that are linked into this target. | [
"Returns",
"a",
"list",
"of",
"dependency",
"targets",
"that",
"are",
"linked",
"into",
"this",
"target",
"."
] | def LinkDependencies(self, targets, dependencies=None, initial=True):
"""Returns a list of dependency targets that are linked into this target.
This function has a split personality, depending on the setting of
|initial|. Outside callers should always leave |initial| at its default
setting.
When adding a target to the list of dependencies, this function will
recurse into itself with |initial| set to False, to collect depenedencies
that are linked into the linkable target for which the list is being built.
"""
if dependencies == None:
dependencies = []
# Check for None, corresponding to the root node.
if self.ref == None:
return dependencies
# It's kind of sucky that |targets| has to be passed into this function,
# but that's presently the easiest way to access the target dicts so that
# this function can find target types.
if not 'target_name' in targets[self.ref]:
raise Exception("Missing 'target_name' field in target.")
try:
target_type = targets[self.ref]['type']
except KeyError, e:
raise Exception("Missing 'type' field in target %s" %
targets[self.ref]['target_name'])
is_linkable = target_type in linkable_types
if initial and not is_linkable:
# If this is the first target being examined and it's not linkable,
# return an empty list of link dependencies, because the link
# dependencies are intended to apply to the target itself (initial is
# True) and this target won't be linked.
return dependencies
# Executables and loadable modules are already fully and finally linked.
# Nothing else can be a link dependency of them, there can only be
# dependencies in the sense that a dependent target might run an
# executable or load the loadable_module.
if not initial and target_type in ('executable', 'loadable_module'):
return dependencies
# The target is linkable, add it to the list of link dependencies.
if self.ref not in dependencies:
if target_type != 'none':
# Special case: "none" type targets don't produce any linkable products
# and shouldn't be exposed as link dependencies, although dependencies
# of "none" type targets may still be link dependencies.
dependencies.append(self.ref)
if initial or not is_linkable:
# If this is a subsequent target and it's linkable, don't look any
# further for linkable dependencies, as they'll already be linked into
# this target linkable. Always look at dependencies of the initial
# target, and always look at dependencies of non-linkables.
for dependency in self.dependencies:
dependency.LinkDependencies(targets, dependencies, False)
return dependencies | [
"def",
"LinkDependencies",
"(",
"self",
",",
"targets",
",",
"dependencies",
"=",
"None",
",",
"initial",
"=",
"True",
")",
":",
"if",
"dependencies",
"==",
"None",
":",
"dependencies",
"=",
"[",
"]",
"# Check for None, corresponding to the root node.",
"if",
"self",
".",
"ref",
"==",
"None",
":",
"return",
"dependencies",
"# It's kind of sucky that |targets| has to be passed into this function,",
"# but that's presently the easiest way to access the target dicts so that",
"# this function can find target types.",
"if",
"not",
"'target_name'",
"in",
"targets",
"[",
"self",
".",
"ref",
"]",
":",
"raise",
"Exception",
"(",
"\"Missing 'target_name' field in target.\"",
")",
"try",
":",
"target_type",
"=",
"targets",
"[",
"self",
".",
"ref",
"]",
"[",
"'type'",
"]",
"except",
"KeyError",
",",
"e",
":",
"raise",
"Exception",
"(",
"\"Missing 'type' field in target %s\"",
"%",
"targets",
"[",
"self",
".",
"ref",
"]",
"[",
"'target_name'",
"]",
")",
"is_linkable",
"=",
"target_type",
"in",
"linkable_types",
"if",
"initial",
"and",
"not",
"is_linkable",
":",
"# If this is the first target being examined and it's not linkable,",
"# return an empty list of link dependencies, because the link",
"# dependencies are intended to apply to the target itself (initial is",
"# True) and this target won't be linked.",
"return",
"dependencies",
"# Executables and loadable modules are already fully and finally linked.",
"# Nothing else can be a link dependency of them, there can only be",
"# dependencies in the sense that a dependent target might run an",
"# executable or load the loadable_module.",
"if",
"not",
"initial",
"and",
"target_type",
"in",
"(",
"'executable'",
",",
"'loadable_module'",
")",
":",
"return",
"dependencies",
"# The target is linkable, add it to the list of link dependencies.",
"if",
"self",
".",
"ref",
"not",
"in",
"dependencies",
":",
"if",
"target_type",
"!=",
"'none'",
":",
"# Special case: \"none\" type targets don't produce any linkable products",
"# and shouldn't be exposed as link dependencies, although dependencies",
"# of \"none\" type targets may still be link dependencies.",
"dependencies",
".",
"append",
"(",
"self",
".",
"ref",
")",
"if",
"initial",
"or",
"not",
"is_linkable",
":",
"# If this is a subsequent target and it's linkable, don't look any",
"# further for linkable dependencies, as they'll already be linked into",
"# this target linkable. Always look at dependencies of the initial",
"# target, and always look at dependencies of non-linkables.",
"for",
"dependency",
"in",
"self",
".",
"dependencies",
":",
"dependency",
".",
"LinkDependencies",
"(",
"targets",
",",
"dependencies",
",",
"False",
")",
"return",
"dependencies"
] | https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/input.py#L1273-L1335 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/generator/msvs.py | python | _GenerateMSVSProject | (project, options, version, generator_flags) | return missing_sources | Generates a .vcproj file. It may create .rules and .user files too.
Arguments:
project: The project object we will generate the file for.
options: Global options passed to the generator.
version: The VisualStudioVersion object.
generator_flags: dict of generator-specific flags. | Generates a .vcproj file. It may create .rules and .user files too. | [
"Generates",
"a",
".",
"vcproj",
"file",
".",
"It",
"may",
"create",
".",
"rules",
"and",
".",
"user",
"files",
"too",
"."
] | def _GenerateMSVSProject(project, options, version, generator_flags):
"""Generates a .vcproj file. It may create .rules and .user files too.
Arguments:
project: The project object we will generate the file for.
options: Global options passed to the generator.
version: The VisualStudioVersion object.
generator_flags: dict of generator-specific flags.
"""
spec = project.spec
gyp.common.EnsureDirExists(project.path)
platforms = _GetUniquePlatforms(spec)
p = MSVSProject.Writer(project.path, version, spec['target_name'],
project.guid, platforms)
# Get directory project file is in.
project_dir = os.path.split(project.path)[0]
gyp_path = _NormalizedSource(project.build_file)
relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)
config_type = _GetMSVSConfigurationType(spec, project.build_file)
for config_name, config in spec['configurations'].items():
_AddConfigurationToMSVSProject(p, spec, config_type, config_name, config)
# MSVC08 and prior version cannot handle duplicate basenames in the same
# target.
# TODO: Take excluded sources into consideration if possible.
_ValidateSourcesForMSVSProject(spec, version)
# Prepare list of sources and excluded sources.
gyp_file = os.path.split(project.build_file)[1]
sources, excluded_sources = _PrepareListOfSources(spec, generator_flags,
gyp_file)
# Add rules.
actions_to_add = {}
_GenerateRulesForMSVS(p, project_dir, options, spec,
sources, excluded_sources,
actions_to_add)
list_excluded = generator_flags.get('msvs_list_excluded_files', True)
sources, excluded_sources, excluded_idl = (
_AdjustSourcesAndConvertToFilterHierarchy(spec, options, project_dir,
sources, excluded_sources,
list_excluded, version))
# Add in files.
missing_sources = _VerifySourcesExist(sources, project_dir)
p.AddFiles(sources)
_AddToolFilesToMSVS(p, spec)
_HandlePreCompiledHeaders(p, sources, spec)
_AddActions(actions_to_add, spec, relative_path_of_gyp_file)
_AddCopies(actions_to_add, spec)
_WriteMSVSUserFile(project.path, version, spec)
# NOTE: this stanza must appear after all actions have been decided.
# Don't excluded sources with actions attached, or they won't run.
excluded_sources = _FilterActionsFromExcluded(
excluded_sources, actions_to_add)
_ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl,
list_excluded)
_AddAccumulatedActionsToMSVS(p, spec, actions_to_add)
# Write it out.
p.WriteIfChanged()
return missing_sources | [
"def",
"_GenerateMSVSProject",
"(",
"project",
",",
"options",
",",
"version",
",",
"generator_flags",
")",
":",
"spec",
"=",
"project",
".",
"spec",
"gyp",
".",
"common",
".",
"EnsureDirExists",
"(",
"project",
".",
"path",
")",
"platforms",
"=",
"_GetUniquePlatforms",
"(",
"spec",
")",
"p",
"=",
"MSVSProject",
".",
"Writer",
"(",
"project",
".",
"path",
",",
"version",
",",
"spec",
"[",
"'target_name'",
"]",
",",
"project",
".",
"guid",
",",
"platforms",
")",
"# Get directory project file is in.",
"project_dir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"project",
".",
"path",
")",
"[",
"0",
"]",
"gyp_path",
"=",
"_NormalizedSource",
"(",
"project",
".",
"build_file",
")",
"relative_path_of_gyp_file",
"=",
"gyp",
".",
"common",
".",
"RelativePath",
"(",
"gyp_path",
",",
"project_dir",
")",
"config_type",
"=",
"_GetMSVSConfigurationType",
"(",
"spec",
",",
"project",
".",
"build_file",
")",
"for",
"config_name",
",",
"config",
"in",
"spec",
"[",
"'configurations'",
"]",
".",
"items",
"(",
")",
":",
"_AddConfigurationToMSVSProject",
"(",
"p",
",",
"spec",
",",
"config_type",
",",
"config_name",
",",
"config",
")",
"# MSVC08 and prior version cannot handle duplicate basenames in the same",
"# target.",
"# TODO: Take excluded sources into consideration if possible.",
"_ValidateSourcesForMSVSProject",
"(",
"spec",
",",
"version",
")",
"# Prepare list of sources and excluded sources.",
"gyp_file",
"=",
"os",
".",
"path",
".",
"split",
"(",
"project",
".",
"build_file",
")",
"[",
"1",
"]",
"sources",
",",
"excluded_sources",
"=",
"_PrepareListOfSources",
"(",
"spec",
",",
"generator_flags",
",",
"gyp_file",
")",
"# Add rules.",
"actions_to_add",
"=",
"{",
"}",
"_GenerateRulesForMSVS",
"(",
"p",
",",
"project_dir",
",",
"options",
",",
"spec",
",",
"sources",
",",
"excluded_sources",
",",
"actions_to_add",
")",
"list_excluded",
"=",
"generator_flags",
".",
"get",
"(",
"'msvs_list_excluded_files'",
",",
"True",
")",
"sources",
",",
"excluded_sources",
",",
"excluded_idl",
"=",
"(",
"_AdjustSourcesAndConvertToFilterHierarchy",
"(",
"spec",
",",
"options",
",",
"project_dir",
",",
"sources",
",",
"excluded_sources",
",",
"list_excluded",
",",
"version",
")",
")",
"# Add in files.",
"missing_sources",
"=",
"_VerifySourcesExist",
"(",
"sources",
",",
"project_dir",
")",
"p",
".",
"AddFiles",
"(",
"sources",
")",
"_AddToolFilesToMSVS",
"(",
"p",
",",
"spec",
")",
"_HandlePreCompiledHeaders",
"(",
"p",
",",
"sources",
",",
"spec",
")",
"_AddActions",
"(",
"actions_to_add",
",",
"spec",
",",
"relative_path_of_gyp_file",
")",
"_AddCopies",
"(",
"actions_to_add",
",",
"spec",
")",
"_WriteMSVSUserFile",
"(",
"project",
".",
"path",
",",
"version",
",",
"spec",
")",
"# NOTE: this stanza must appear after all actions have been decided.",
"# Don't excluded sources with actions attached, or they won't run.",
"excluded_sources",
"=",
"_FilterActionsFromExcluded",
"(",
"excluded_sources",
",",
"actions_to_add",
")",
"_ExcludeFilesFromBeingBuilt",
"(",
"p",
",",
"spec",
",",
"excluded_sources",
",",
"excluded_idl",
",",
"list_excluded",
")",
"_AddAccumulatedActionsToMSVS",
"(",
"p",
",",
"spec",
",",
"actions_to_add",
")",
"# Write it out.",
"p",
".",
"WriteIfChanged",
"(",
")",
"return",
"missing_sources"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/msvs.py#L1013-L1080 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/difflib.py | python | get_close_matches | (word, possibilities, n=3, cutoff=0.6) | return [x for score, x in result] | Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of strings).
Optional arg n (default 3) is the maximum number of close matches to
return. n must be > 0.
Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
that don't score at least that similar to word are ignored.
The best (no more than n) matches among the possibilities are returned
in a list, sorted by similarity score, most similar first.
>>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
['apple', 'ape']
>>> import keyword as _keyword
>>> get_close_matches("wheel", _keyword.kwlist)
['while']
>>> get_close_matches("apple", _keyword.kwlist)
[]
>>> get_close_matches("accept", _keyword.kwlist)
['except'] | Use SequenceMatcher to return list of the best "good enough" matches. | [
"Use",
"SequenceMatcher",
"to",
"return",
"list",
"of",
"the",
"best",
"good",
"enough",
"matches",
"."
] | def get_close_matches(word, possibilities, n=3, cutoff=0.6):
"""Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of strings).
Optional arg n (default 3) is the maximum number of close matches to
return. n must be > 0.
Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
that don't score at least that similar to word are ignored.
The best (no more than n) matches among the possibilities are returned
in a list, sorted by similarity score, most similar first.
>>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
['apple', 'ape']
>>> import keyword as _keyword
>>> get_close_matches("wheel", _keyword.kwlist)
['while']
>>> get_close_matches("apple", _keyword.kwlist)
[]
>>> get_close_matches("accept", _keyword.kwlist)
['except']
"""
if not n > 0:
raise ValueError("n must be > 0: %r" % (n,))
if not 0.0 <= cutoff <= 1.0:
raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
result = []
s = SequenceMatcher()
s.set_seq2(word)
for x in possibilities:
s.set_seq1(x)
if s.real_quick_ratio() >= cutoff and \
s.quick_ratio() >= cutoff and \
s.ratio() >= cutoff:
result.append((s.ratio(), x))
# Move the best scorers to head of list
result = heapq.nlargest(n, result)
# Strip scores for the best n matches
return [x for score, x in result] | [
"def",
"get_close_matches",
"(",
"word",
",",
"possibilities",
",",
"n",
"=",
"3",
",",
"cutoff",
"=",
"0.6",
")",
":",
"if",
"not",
"n",
">",
"0",
":",
"raise",
"ValueError",
"(",
"\"n must be > 0: %r\"",
"%",
"(",
"n",
",",
")",
")",
"if",
"not",
"0.0",
"<=",
"cutoff",
"<=",
"1.0",
":",
"raise",
"ValueError",
"(",
"\"cutoff must be in [0.0, 1.0]: %r\"",
"%",
"(",
"cutoff",
",",
")",
")",
"result",
"=",
"[",
"]",
"s",
"=",
"SequenceMatcher",
"(",
")",
"s",
".",
"set_seq2",
"(",
"word",
")",
"for",
"x",
"in",
"possibilities",
":",
"s",
".",
"set_seq1",
"(",
"x",
")",
"if",
"s",
".",
"real_quick_ratio",
"(",
")",
">=",
"cutoff",
"and",
"s",
".",
"quick_ratio",
"(",
")",
">=",
"cutoff",
"and",
"s",
".",
"ratio",
"(",
")",
">=",
"cutoff",
":",
"result",
".",
"append",
"(",
"(",
"s",
".",
"ratio",
"(",
")",
",",
"x",
")",
")",
"# Move the best scorers to head of list",
"result",
"=",
"heapq",
".",
"nlargest",
"(",
"n",
",",
"result",
")",
"# Strip scores for the best n matches",
"return",
"[",
"x",
"for",
"score",
",",
"x",
"in",
"result",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/difflib.py#L703-L749 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.