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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | Pen.GetWidth | (*args, **kwargs) | return _gdi_.Pen_GetWidth(*args, **kwargs) | GetWidth(self) -> int | GetWidth(self) -> int | [
"GetWidth",
"(",
"self",
")",
"-",
">",
"int"
] | def GetWidth(*args, **kwargs):
"""GetWidth(self) -> int"""
return _gdi_.Pen_GetWidth(*args, **kwargs) | [
"def",
"GetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Pen_GetWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L416-L418 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/PreprocessWindow.py | python | ScanPreProcessWindow.update_merge_value | (self, scan_number, message) | update merged signal
:param scan_number:
:param message:
:return: | update merged signal
:param scan_number:
:param message:
:return: | [
"update",
"merged",
"signal",
":",
"param",
"scan_number",
":",
":",
"param",
"message",
":",
":",
"return",
":"
] | def update_merge_value(self, scan_number, message):
"""update merged signal
:param scan_number:
:param message:
:return:
"""
row_number = self._rowScanDict[scan_number]
self.ui.tableView_scanProcessState.set_status(row_number, message)
self.ui.tableView_scanProcessState.resizeColumnsToContents() | [
"def",
"update_merge_value",
"(",
"self",
",",
"scan_number",
",",
"message",
")",
":",
"row_number",
"=",
"self",
".",
"_rowScanDict",
"[",
"scan_number",
"]",
"self",
".",
"ui",
".",
"tableView_scanProcessState",
".",
"set_status",
"(",
"row_number",
",",
"message",
")",
"self",
".",
"ui",
".",
"tableView_scanProcessState",
".",
"resizeColumnsToContents",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/PreprocessWindow.py#L406-L414 | ||
alexozer/jankdrone | c4b403eb254b41b832ab2bdfade12ba59c99e5dc | shm/lib/pyratemp/pyratemp.py | python | LoaderFile.__init__ | (self, allowed_path=None, encoding='utf-8') | Init the loader.
:Parameters:
- `allowed_path`: path of the template-files
- `encoding`: encoding of the template-files
:Exceptions:
- `ValueError`: if `allowed_path` is not a directory | Init the loader. | [
"Init",
"the",
"loader",
"."
] | def __init__(self, allowed_path=None, encoding='utf-8'):
"""Init the loader.
:Parameters:
- `allowed_path`: path of the template-files
- `encoding`: encoding of the template-files
:Exceptions:
- `ValueError`: if `allowed_path` is not a directory
"""
if allowed_path and not os.path.isdir(allowed_path):
raise ValueError("'allowed_path' has to be a directory.")
self.path = allowed_path
self.encoding = encoding | [
"def",
"__init__",
"(",
"self",
",",
"allowed_path",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"allowed_path",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"allowed_path",
")",
":",
"raise",
"ValueError",
"(",
"\"'allowed_path' has to be a directory.\"",
")",
"self",
".",
"path",
"=",
"allowed_path",
"self",
".",
"encoding",
"=",
"encoding"
] | https://github.com/alexozer/jankdrone/blob/c4b403eb254b41b832ab2bdfade12ba59c99e5dc/shm/lib/pyratemp/pyratemp.py#L393-L405 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/cut.py | python | cut | (
x,
bins,
right: bool = True,
labels=None,
retbins: bool = False,
precision: int = 3,
include_lowest: bool = False,
duplicates: str = "raise",
ordered: bool = True,
) | Bin values into discrete intervals.
Use cut when you need to segment and sort data values into bins. This
function is also useful for going from a continuous variable to a
categorical variable.
Parameters
----------
x : array-like
The input array to be binned. Must be 1-dimensional.
bins : int, sequence of scalars, or IntervalIndex
The criteria to bin by.
* int : Defines the number of equal-width bins in the
range of x. The range of x is extended by .1% on each
side to include the minimum and maximum values of x.
right : bool, default True
Indicates whether bins includes the rightmost edge or not.
labels : array or False, default None
Specifies the labels for the returned bins. Must be the same
length as the resulting bins. If False, returns only integer
indicators of thebins. If True,raises an error. When ordered=False,
labels must be provided.
retbins : bool, default False
Whether to return the bins or not.
precision : int, default 3
The precision at which to store and display the bins labels.
include_lowest : bool, default False
Whether the first interval should be left-inclusive or not.
duplicates : {default 'raise', 'drop'}, optional
If bin edges are not unique, raise ValueError or drop non-uniques.
ordered : bool, default True
Whether the labels are ordered or not. Applies to returned types
Categorical and Series (with Categorical dtype). If True,
the resulting categorical will be ordered. If False, the resulting
categorical will be unordered (labels must be provided).
Returns
-------
out : CategoricalIndex
An array-like object representing the respective bin for each value
of x. The type depends on the value of labels.
bins : numpy.ndarray or IntervalIndex.
The computed or specified bins. Only returned when retbins=True.
For scalar or sequence bins, this is an ndarray with the computed
bins. If set duplicates=drop, bins will drop non-unique bin. For
an IntervalIndex bins, this is equal to bins.
Examples
--------
Discretize into three equal-sized bins.
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3)
CategoricalIndex([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0],
... (5.0, 7.0],(0.994, 3.0]], categories=[(0.994, 3.0],
... (3.0, 5.0], (5.0, 7.0]], ordered=True, dtype='category')
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)
(CategoricalIndex([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0],
... (5.0, 7.0],(0.994, 3.0]],categories=[(0.994, 3.0],
... (3.0, 5.0], (5.0, 7.0]],ordered=True, dtype='category'),
array([0.994, 3. , 5. , 7. ]))
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]),
... 3, labels=["bad", "medium", "good"])
CategoricalIndex(['bad', 'good', 'medium', 'medium', 'good', 'bad'],
... categories=['bad', 'medium', 'good'],ordered=True,
... dtype='category')
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3,
... labels=["B", "A", "B"], ordered=False)
CategoricalIndex(['B', 'B', 'A', 'A', 'B', 'B'], categories=['A', 'B'],
... ordered=False, dtype='category')
>>> cudf.cut([0, 1, 1, 2], bins=4, labels=False)
array([0, 1, 1, 3], dtype=int32)
Passing a Series as an input returns a Series with categorical dtype:
>>> s = cudf.Series(np.array([2, 4, 6, 8, 10]),
... index=['a', 'b', 'c', 'd', 'e'])
>>> cudf.cut(s, 3) | Bin values into discrete intervals.
Use cut when you need to segment and sort data values into bins. This
function is also useful for going from a continuous variable to a
categorical variable.
Parameters
----------
x : array-like
The input array to be binned. Must be 1-dimensional.
bins : int, sequence of scalars, or IntervalIndex
The criteria to bin by.
* int : Defines the number of equal-width bins in the
range of x. The range of x is extended by .1% on each
side to include the minimum and maximum values of x.
right : bool, default True
Indicates whether bins includes the rightmost edge or not.
labels : array or False, default None
Specifies the labels for the returned bins. Must be the same
length as the resulting bins. If False, returns only integer
indicators of thebins. If True,raises an error. When ordered=False,
labels must be provided.
retbins : bool, default False
Whether to return the bins or not.
precision : int, default 3
The precision at which to store and display the bins labels.
include_lowest : bool, default False
Whether the first interval should be left-inclusive or not.
duplicates : {default 'raise', 'drop'}, optional
If bin edges are not unique, raise ValueError or drop non-uniques.
ordered : bool, default True
Whether the labels are ordered or not. Applies to returned types
Categorical and Series (with Categorical dtype). If True,
the resulting categorical will be ordered. If False, the resulting
categorical will be unordered (labels must be provided).
Returns
-------
out : CategoricalIndex
An array-like object representing the respective bin for each value
of x. The type depends on the value of labels.
bins : numpy.ndarray or IntervalIndex.
The computed or specified bins. Only returned when retbins=True.
For scalar or sequence bins, this is an ndarray with the computed
bins. If set duplicates=drop, bins will drop non-unique bin. For
an IntervalIndex bins, this is equal to bins.
Examples
--------
Discretize into three equal-sized bins.
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3)
CategoricalIndex([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0],
... (5.0, 7.0],(0.994, 3.0]], categories=[(0.994, 3.0],
... (3.0, 5.0], (5.0, 7.0]], ordered=True, dtype='category')
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)
(CategoricalIndex([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0],
... (5.0, 7.0],(0.994, 3.0]],categories=[(0.994, 3.0],
... (3.0, 5.0], (5.0, 7.0]],ordered=True, dtype='category'),
array([0.994, 3. , 5. , 7. ]))
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]),
... 3, labels=["bad", "medium", "good"])
CategoricalIndex(['bad', 'good', 'medium', 'medium', 'good', 'bad'],
... categories=['bad', 'medium', 'good'],ordered=True,
... dtype='category')
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3,
... labels=["B", "A", "B"], ordered=False)
CategoricalIndex(['B', 'B', 'A', 'A', 'B', 'B'], categories=['A', 'B'],
... ordered=False, dtype='category')
>>> cudf.cut([0, 1, 1, 2], bins=4, labels=False)
array([0, 1, 1, 3], dtype=int32)
Passing a Series as an input returns a Series with categorical dtype:
>>> s = cudf.Series(np.array([2, 4, 6, 8, 10]),
... index=['a', 'b', 'c', 'd', 'e'])
>>> cudf.cut(s, 3) | [
"Bin",
"values",
"into",
"discrete",
"intervals",
".",
"Use",
"cut",
"when",
"you",
"need",
"to",
"segment",
"and",
"sort",
"data",
"values",
"into",
"bins",
".",
"This",
"function",
"is",
"also",
"useful",
"for",
"going",
"from",
"a",
"continuous",
"variable",
"to",
"a",
"categorical",
"variable",
".",
"Parameters",
"----------",
"x",
":",
"array",
"-",
"like",
"The",
"input",
"array",
"to",
"be",
"binned",
".",
"Must",
"be",
"1",
"-",
"dimensional",
".",
"bins",
":",
"int",
"sequence",
"of",
"scalars",
"or",
"IntervalIndex",
"The",
"criteria",
"to",
"bin",
"by",
".",
"*",
"int",
":",
"Defines",
"the",
"number",
"of",
"equal",
"-",
"width",
"bins",
"in",
"the",
"range",
"of",
"x",
".",
"The",
"range",
"of",
"x",
"is",
"extended",
"by",
".",
"1%",
"on",
"each",
"side",
"to",
"include",
"the",
"minimum",
"and",
"maximum",
"values",
"of",
"x",
".",
"right",
":",
"bool",
"default",
"True",
"Indicates",
"whether",
"bins",
"includes",
"the",
"rightmost",
"edge",
"or",
"not",
".",
"labels",
":",
"array",
"or",
"False",
"default",
"None",
"Specifies",
"the",
"labels",
"for",
"the",
"returned",
"bins",
".",
"Must",
"be",
"the",
"same",
"length",
"as",
"the",
"resulting",
"bins",
".",
"If",
"False",
"returns",
"only",
"integer",
"indicators",
"of",
"thebins",
".",
"If",
"True",
"raises",
"an",
"error",
".",
"When",
"ordered",
"=",
"False",
"labels",
"must",
"be",
"provided",
".",
"retbins",
":",
"bool",
"default",
"False",
"Whether",
"to",
"return",
"the",
"bins",
"or",
"not",
".",
"precision",
":",
"int",
"default",
"3",
"The",
"precision",
"at",
"which",
"to",
"store",
"and",
"display",
"the",
"bins",
"labels",
".",
"include_lowest",
":",
"bool",
"default",
"False",
"Whether",
"the",
"first",
"interval",
"should",
"be",
"left",
"-",
"inclusive",
"or",
"not",
".",
"duplicates",
":",
"{",
"default",
"raise",
"drop",
"}",
"optional",
"If",
"bin",
"edges",
"are",
"not",
"unique",
"raise",
"ValueError",
"or",
"drop",
"non",
"-",
"uniques",
".",
"ordered",
":",
"bool",
"default",
"True",
"Whether",
"the",
"labels",
"are",
"ordered",
"or",
"not",
".",
"Applies",
"to",
"returned",
"types",
"Categorical",
"and",
"Series",
"(",
"with",
"Categorical",
"dtype",
")",
".",
"If",
"True",
"the",
"resulting",
"categorical",
"will",
"be",
"ordered",
".",
"If",
"False",
"the",
"resulting",
"categorical",
"will",
"be",
"unordered",
"(",
"labels",
"must",
"be",
"provided",
")",
".",
"Returns",
"-------",
"out",
":",
"CategoricalIndex",
"An",
"array",
"-",
"like",
"object",
"representing",
"the",
"respective",
"bin",
"for",
"each",
"value",
"of",
"x",
".",
"The",
"type",
"depends",
"on",
"the",
"value",
"of",
"labels",
".",
"bins",
":",
"numpy",
".",
"ndarray",
"or",
"IntervalIndex",
".",
"The",
"computed",
"or",
"specified",
"bins",
".",
"Only",
"returned",
"when",
"retbins",
"=",
"True",
".",
"For",
"scalar",
"or",
"sequence",
"bins",
"this",
"is",
"an",
"ndarray",
"with",
"the",
"computed",
"bins",
".",
"If",
"set",
"duplicates",
"=",
"drop",
"bins",
"will",
"drop",
"non",
"-",
"unique",
"bin",
".",
"For",
"an",
"IntervalIndex",
"bins",
"this",
"is",
"equal",
"to",
"bins",
".",
"Examples",
"--------",
"Discretize",
"into",
"three",
"equal",
"-",
"sized",
"bins",
".",
">>>",
"cudf",
".",
"cut",
"(",
"np",
".",
"array",
"(",
"[",
"1",
"7",
"5",
"4",
"6",
"3",
"]",
")",
"3",
")",
"CategoricalIndex",
"(",
"[",
"(",
"0",
".",
"994",
"3",
".",
"0",
"]",
"(",
"5",
".",
"0",
"7",
".",
"0",
"]",
"(",
"3",
".",
"0",
"5",
".",
"0",
"]",
"(",
"3",
".",
"0",
"5",
".",
"0",
"]",
"...",
"(",
"5",
".",
"0",
"7",
".",
"0",
"]",
"(",
"0",
".",
"994",
"3",
".",
"0",
"]]",
"categories",
"=",
"[",
"(",
"0",
".",
"994",
"3",
".",
"0",
"]",
"...",
"(",
"3",
".",
"0",
"5",
".",
"0",
"]",
"(",
"5",
".",
"0",
"7",
".",
"0",
"]]",
"ordered",
"=",
"True",
"dtype",
"=",
"category",
")",
">>>",
"cudf",
".",
"cut",
"(",
"np",
".",
"array",
"(",
"[",
"1",
"7",
"5",
"4",
"6",
"3",
"]",
")",
"3",
"retbins",
"=",
"True",
")",
"(",
"CategoricalIndex",
"(",
"[",
"(",
"0",
".",
"994",
"3",
".",
"0",
"]",
"(",
"5",
".",
"0",
"7",
".",
"0",
"]",
"(",
"3",
".",
"0",
"5",
".",
"0",
"]",
"(",
"3",
".",
"0",
"5",
".",
"0",
"]",
"...",
"(",
"5",
".",
"0",
"7",
".",
"0",
"]",
"(",
"0",
".",
"994",
"3",
".",
"0",
"]]",
"categories",
"=",
"[",
"(",
"0",
".",
"994",
"3",
".",
"0",
"]",
"...",
"(",
"3",
".",
"0",
"5",
".",
"0",
"]",
"(",
"5",
".",
"0",
"7",
".",
"0",
"]]",
"ordered",
"=",
"True",
"dtype",
"=",
"category",
")",
"array",
"(",
"[",
"0",
".",
"994",
"3",
".",
"5",
".",
"7",
".",
"]",
"))",
">>>",
"cudf",
".",
"cut",
"(",
"np",
".",
"array",
"(",
"[",
"1",
"7",
"5",
"4",
"6",
"3",
"]",
")",
"...",
"3",
"labels",
"=",
"[",
"bad",
"medium",
"good",
"]",
")",
"CategoricalIndex",
"(",
"[",
"bad",
"good",
"medium",
"medium",
"good",
"bad",
"]",
"...",
"categories",
"=",
"[",
"bad",
"medium",
"good",
"]",
"ordered",
"=",
"True",
"...",
"dtype",
"=",
"category",
")",
">>>",
"cudf",
".",
"cut",
"(",
"np",
".",
"array",
"(",
"[",
"1",
"7",
"5",
"4",
"6",
"3",
"]",
")",
"3",
"...",
"labels",
"=",
"[",
"B",
"A",
"B",
"]",
"ordered",
"=",
"False",
")",
"CategoricalIndex",
"(",
"[",
"B",
"B",
"A",
"A",
"B",
"B",
"]",
"categories",
"=",
"[",
"A",
"B",
"]",
"...",
"ordered",
"=",
"False",
"dtype",
"=",
"category",
")",
">>>",
"cudf",
".",
"cut",
"(",
"[",
"0",
"1",
"1",
"2",
"]",
"bins",
"=",
"4",
"labels",
"=",
"False",
")",
"array",
"(",
"[",
"0",
"1",
"1",
"3",
"]",
"dtype",
"=",
"int32",
")",
"Passing",
"a",
"Series",
"as",
"an",
"input",
"returns",
"a",
"Series",
"with",
"categorical",
"dtype",
":",
">>>",
"s",
"=",
"cudf",
".",
"Series",
"(",
"np",
".",
"array",
"(",
"[",
"2",
"4",
"6",
"8",
"10",
"]",
")",
"...",
"index",
"=",
"[",
"a",
"b",
"c",
"d",
"e",
"]",
")",
">>>",
"cudf",
".",
"cut",
"(",
"s",
"3",
")"
] | def cut(
x,
bins,
right: bool = True,
labels=None,
retbins: bool = False,
precision: int = 3,
include_lowest: bool = False,
duplicates: str = "raise",
ordered: bool = True,
):
"""
Bin values into discrete intervals.
Use cut when you need to segment and sort data values into bins. This
function is also useful for going from a continuous variable to a
categorical variable.
Parameters
----------
x : array-like
The input array to be binned. Must be 1-dimensional.
bins : int, sequence of scalars, or IntervalIndex
The criteria to bin by.
* int : Defines the number of equal-width bins in the
range of x. The range of x is extended by .1% on each
side to include the minimum and maximum values of x.
right : bool, default True
Indicates whether bins includes the rightmost edge or not.
labels : array or False, default None
Specifies the labels for the returned bins. Must be the same
length as the resulting bins. If False, returns only integer
indicators of thebins. If True,raises an error. When ordered=False,
labels must be provided.
retbins : bool, default False
Whether to return the bins or not.
precision : int, default 3
The precision at which to store and display the bins labels.
include_lowest : bool, default False
Whether the first interval should be left-inclusive or not.
duplicates : {default 'raise', 'drop'}, optional
If bin edges are not unique, raise ValueError or drop non-uniques.
ordered : bool, default True
Whether the labels are ordered or not. Applies to returned types
Categorical and Series (with Categorical dtype). If True,
the resulting categorical will be ordered. If False, the resulting
categorical will be unordered (labels must be provided).
Returns
-------
out : CategoricalIndex
An array-like object representing the respective bin for each value
of x. The type depends on the value of labels.
bins : numpy.ndarray or IntervalIndex.
The computed or specified bins. Only returned when retbins=True.
For scalar or sequence bins, this is an ndarray with the computed
bins. If set duplicates=drop, bins will drop non-unique bin. For
an IntervalIndex bins, this is equal to bins.
Examples
--------
Discretize into three equal-sized bins.
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3)
CategoricalIndex([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0],
... (5.0, 7.0],(0.994, 3.0]], categories=[(0.994, 3.0],
... (3.0, 5.0], (5.0, 7.0]], ordered=True, dtype='category')
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)
(CategoricalIndex([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0],
... (5.0, 7.0],(0.994, 3.0]],categories=[(0.994, 3.0],
... (3.0, 5.0], (5.0, 7.0]],ordered=True, dtype='category'),
array([0.994, 3. , 5. , 7. ]))
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]),
... 3, labels=["bad", "medium", "good"])
CategoricalIndex(['bad', 'good', 'medium', 'medium', 'good', 'bad'],
... categories=['bad', 'medium', 'good'],ordered=True,
... dtype='category')
>>> cudf.cut(np.array([1, 7, 5, 4, 6, 3]), 3,
... labels=["B", "A", "B"], ordered=False)
CategoricalIndex(['B', 'B', 'A', 'A', 'B', 'B'], categories=['A', 'B'],
... ordered=False, dtype='category')
>>> cudf.cut([0, 1, 1, 2], bins=4, labels=False)
array([0, 1, 1, 3], dtype=int32)
Passing a Series as an input returns a Series with categorical dtype:
>>> s = cudf.Series(np.array([2, 4, 6, 8, 10]),
... index=['a', 'b', 'c', 'd', 'e'])
>>> cudf.cut(s, 3)
"""
left_inclusive = False
right_inclusive = True
# saving the original input x for use in case its a series
orig_x = x
old_bins = bins
if not ordered and labels is None:
raise ValueError("'labels' must be provided if 'ordered = False'")
if duplicates not in ["raise", "drop"]:
raise ValueError(
"invalid value for 'duplicates' parameter, valid options are: "
"raise, drop"
)
if labels is not False:
if not (labels is None or is_list_like(labels)):
raise ValueError(
"Bin labels must either be False, None or passed in as a "
"list-like argument"
)
if ordered and labels is not None:
if len(set(labels)) != len(labels):
raise ValueError(
"labels must be unique if ordered=True;"
"pass ordered=False for duplicate labels"
)
# bins can either be an int, sequence of scalars or an intervalIndex
if isinstance(bins, Sequence):
if len(set(bins)) is not len(bins):
if duplicates == "raise":
raise ValueError(
f"Bin edges must be unique: {repr(bins)}.\n"
f"You can drop duplicate edges by setting the 'duplicates'"
"kwarg"
)
elif duplicates == "drop":
# get unique values but maintain list dtype
bins = list(dict.fromkeys(bins))
# if bins is an intervalIndex we ignore the value of right
elif isinstance(bins, (pd.IntervalIndex, cudf.IntervalIndex)):
right = bins.closed == "right"
# create bins if given an int or single scalar
if not isinstance(bins, pd.IntervalIndex):
if not isinstance(bins, (Sequence)):
if isinstance(
x, (pd.Series, cudf.Series, np.ndarray, cupy.ndarray)
):
mn = x.min()
mx = x.max()
else:
mn = min(x)
mx = max(x)
bins = np.linspace(mn, mx, bins + 1, endpoint=True)
adj = (mx - mn) * 0.001
if right:
bins[0] -= adj
else:
bins[-1] += adj
# if right and include lowest we adjust the first
# bin edge to make sure it is included
if right and include_lowest:
bins[0] = bins[0] - 10 ** (-precision)
# if right is false the last bin edge is not included
if not right:
right_edge = bins[-1]
x = cupy.asarray(x)
x[x == right_edge] = right_edge + 1
# adjust bin edges decimal precision
int_label_bins = np.around(bins, precision)
# the inputs is a column of the values in the array x
input_arr = as_column(x)
# checking for the correct inclusivity values
if right:
closed = "right"
else:
closed = "left"
left_inclusive = True
if isinstance(bins, pd.IntervalIndex):
interval_labels = bins
elif labels is None:
if duplicates == "drop" and len(bins) == 1 and len(old_bins) != 1:
if right and include_lowest:
old_bins[0] = old_bins[0] - 10 ** (-precision)
interval_labels = interval_range(
old_bins[0], old_bins[1], periods=1, closed=closed
)
else:
interval_labels = IntervalIndex.from_breaks(
old_bins, closed=closed
)
else:
# get labels for categories
interval_labels = IntervalIndex.from_breaks(
int_label_bins, closed=closed
)
elif labels is not False:
if not (is_list_like(labels)):
raise ValueError(
"Bin labels must either be False, None or passed in as a "
"list-like argument"
)
if ordered and len(set(labels)) != len(labels):
raise ValueError(
"labels must be unique if ordered=True; "
"pass ordered=False for"
"duplicate labels"
)
if len(labels) != len(bins) - 1:
raise ValueError(
"Bin labels must be one fewer than the number of bin edges"
)
if not ordered and len(set(labels)) != len(labels):
interval_labels = cudf.CategoricalIndex(
labels, categories=None, ordered=False
)
else:
interval_labels = (
labels if len(set(labels)) == len(labels) else None
)
if isinstance(bins, pd.IntervalIndex):
# get the left and right edges of the bins as columns
# we cannot typecast an IntervalIndex, so we need to
# make the edges the same type as the input array
left_edges = as_column(bins.left).astype(input_arr.dtype)
right_edges = as_column(bins.right).astype(input_arr.dtype)
else:
# get the left and right edges of the bins as columns
left_edges = as_column(bins[:-1:], dtype="float64")
right_edges = as_column(bins[+1::], dtype="float64")
# the input arr must be changed to the same type as the edges
input_arr = input_arr.astype(left_edges.dtype)
# get the indexes for the appropriate number
index_labels = cudf._lib.labeling.label_bins(
input_arr, left_edges, left_inclusive, right_edges, right_inclusive
)
if labels is False:
# if labels is false we return the index labels, we return them
# as a series if we have a series input
if isinstance(orig_x, (pd.Series, cudf.Series)):
# need to run more tests but looks like in this case pandas
# always returns a float64 dtype
indx_arr_series = cudf.Series(index_labels, dtype="float64")
# if retbins we return the bins as well
if retbins:
return indx_arr_series, bins
else:
return indx_arr_series
elif retbins:
return index_labels.values, bins
else:
return index_labels.values
if labels is not None:
if labels is not ordered and len(set(labels)) != len(labels):
# when we have duplicate labels and ordered is False, we
# should allow duplicate categories. The categories are
# returned in order
new_data = [interval_labels[i][0] for i in index_labels.values]
return cudf.CategoricalIndex(
new_data, categories=sorted(set(labels)), ordered=False
)
col = build_categorical_column(
categories=interval_labels,
codes=index_labels,
mask=index_labels.base_mask,
offset=index_labels.offset,
size=index_labels.size,
ordered=ordered,
)
# we return a categorical index, as we don't have a Categorical method
categorical_index = cudf.core.index.as_index(col)
if isinstance(orig_x, (pd.Series, cudf.Series)):
# if we have a series input we return a series output
res_series = cudf.Series(categorical_index, index=orig_x.index)
if retbins:
return res_series, bins
else:
return res_series
elif retbins:
# if retbins is true we return the bins as well
return categorical_index, bins
else:
return categorical_index | [
"def",
"cut",
"(",
"x",
",",
"bins",
",",
"right",
":",
"bool",
"=",
"True",
",",
"labels",
"=",
"None",
",",
"retbins",
":",
"bool",
"=",
"False",
",",
"precision",
":",
"int",
"=",
"3",
",",
"include_lowest",
":",
"bool",
"=",
"False",
",",
"duplicates",
":",
"str",
"=",
"\"raise\"",
",",
"ordered",
":",
"bool",
"=",
"True",
",",
")",
":",
"left_inclusive",
"=",
"False",
"right_inclusive",
"=",
"True",
"# saving the original input x for use in case its a series",
"orig_x",
"=",
"x",
"old_bins",
"=",
"bins",
"if",
"not",
"ordered",
"and",
"labels",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"'labels' must be provided if 'ordered = False'\"",
")",
"if",
"duplicates",
"not",
"in",
"[",
"\"raise\"",
",",
"\"drop\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"invalid value for 'duplicates' parameter, valid options are: \"",
"\"raise, drop\"",
")",
"if",
"labels",
"is",
"not",
"False",
":",
"if",
"not",
"(",
"labels",
"is",
"None",
"or",
"is_list_like",
"(",
"labels",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Bin labels must either be False, None or passed in as a \"",
"\"list-like argument\"",
")",
"if",
"ordered",
"and",
"labels",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"set",
"(",
"labels",
")",
")",
"!=",
"len",
"(",
"labels",
")",
":",
"raise",
"ValueError",
"(",
"\"labels must be unique if ordered=True;\"",
"\"pass ordered=False for duplicate labels\"",
")",
"# bins can either be an int, sequence of scalars or an intervalIndex",
"if",
"isinstance",
"(",
"bins",
",",
"Sequence",
")",
":",
"if",
"len",
"(",
"set",
"(",
"bins",
")",
")",
"is",
"not",
"len",
"(",
"bins",
")",
":",
"if",
"duplicates",
"==",
"\"raise\"",
":",
"raise",
"ValueError",
"(",
"f\"Bin edges must be unique: {repr(bins)}.\\n\"",
"f\"You can drop duplicate edges by setting the 'duplicates'\"",
"\"kwarg\"",
")",
"elif",
"duplicates",
"==",
"\"drop\"",
":",
"# get unique values but maintain list dtype",
"bins",
"=",
"list",
"(",
"dict",
".",
"fromkeys",
"(",
"bins",
")",
")",
"# if bins is an intervalIndex we ignore the value of right",
"elif",
"isinstance",
"(",
"bins",
",",
"(",
"pd",
".",
"IntervalIndex",
",",
"cudf",
".",
"IntervalIndex",
")",
")",
":",
"right",
"=",
"bins",
".",
"closed",
"==",
"\"right\"",
"# create bins if given an int or single scalar",
"if",
"not",
"isinstance",
"(",
"bins",
",",
"pd",
".",
"IntervalIndex",
")",
":",
"if",
"not",
"isinstance",
"(",
"bins",
",",
"(",
"Sequence",
")",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"(",
"pd",
".",
"Series",
",",
"cudf",
".",
"Series",
",",
"np",
".",
"ndarray",
",",
"cupy",
".",
"ndarray",
")",
")",
":",
"mn",
"=",
"x",
".",
"min",
"(",
")",
"mx",
"=",
"x",
".",
"max",
"(",
")",
"else",
":",
"mn",
"=",
"min",
"(",
"x",
")",
"mx",
"=",
"max",
"(",
"x",
")",
"bins",
"=",
"np",
".",
"linspace",
"(",
"mn",
",",
"mx",
",",
"bins",
"+",
"1",
",",
"endpoint",
"=",
"True",
")",
"adj",
"=",
"(",
"mx",
"-",
"mn",
")",
"*",
"0.001",
"if",
"right",
":",
"bins",
"[",
"0",
"]",
"-=",
"adj",
"else",
":",
"bins",
"[",
"-",
"1",
"]",
"+=",
"adj",
"# if right and include lowest we adjust the first",
"# bin edge to make sure it is included",
"if",
"right",
"and",
"include_lowest",
":",
"bins",
"[",
"0",
"]",
"=",
"bins",
"[",
"0",
"]",
"-",
"10",
"**",
"(",
"-",
"precision",
")",
"# if right is false the last bin edge is not included",
"if",
"not",
"right",
":",
"right_edge",
"=",
"bins",
"[",
"-",
"1",
"]",
"x",
"=",
"cupy",
".",
"asarray",
"(",
"x",
")",
"x",
"[",
"x",
"==",
"right_edge",
"]",
"=",
"right_edge",
"+",
"1",
"# adjust bin edges decimal precision",
"int_label_bins",
"=",
"np",
".",
"around",
"(",
"bins",
",",
"precision",
")",
"# the inputs is a column of the values in the array x",
"input_arr",
"=",
"as_column",
"(",
"x",
")",
"# checking for the correct inclusivity values",
"if",
"right",
":",
"closed",
"=",
"\"right\"",
"else",
":",
"closed",
"=",
"\"left\"",
"left_inclusive",
"=",
"True",
"if",
"isinstance",
"(",
"bins",
",",
"pd",
".",
"IntervalIndex",
")",
":",
"interval_labels",
"=",
"bins",
"elif",
"labels",
"is",
"None",
":",
"if",
"duplicates",
"==",
"\"drop\"",
"and",
"len",
"(",
"bins",
")",
"==",
"1",
"and",
"len",
"(",
"old_bins",
")",
"!=",
"1",
":",
"if",
"right",
"and",
"include_lowest",
":",
"old_bins",
"[",
"0",
"]",
"=",
"old_bins",
"[",
"0",
"]",
"-",
"10",
"**",
"(",
"-",
"precision",
")",
"interval_labels",
"=",
"interval_range",
"(",
"old_bins",
"[",
"0",
"]",
",",
"old_bins",
"[",
"1",
"]",
",",
"periods",
"=",
"1",
",",
"closed",
"=",
"closed",
")",
"else",
":",
"interval_labels",
"=",
"IntervalIndex",
".",
"from_breaks",
"(",
"old_bins",
",",
"closed",
"=",
"closed",
")",
"else",
":",
"# get labels for categories",
"interval_labels",
"=",
"IntervalIndex",
".",
"from_breaks",
"(",
"int_label_bins",
",",
"closed",
"=",
"closed",
")",
"elif",
"labels",
"is",
"not",
"False",
":",
"if",
"not",
"(",
"is_list_like",
"(",
"labels",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Bin labels must either be False, None or passed in as a \"",
"\"list-like argument\"",
")",
"if",
"ordered",
"and",
"len",
"(",
"set",
"(",
"labels",
")",
")",
"!=",
"len",
"(",
"labels",
")",
":",
"raise",
"ValueError",
"(",
"\"labels must be unique if ordered=True; \"",
"\"pass ordered=False for\"",
"\"duplicate labels\"",
")",
"if",
"len",
"(",
"labels",
")",
"!=",
"len",
"(",
"bins",
")",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"Bin labels must be one fewer than the number of bin edges\"",
")",
"if",
"not",
"ordered",
"and",
"len",
"(",
"set",
"(",
"labels",
")",
")",
"!=",
"len",
"(",
"labels",
")",
":",
"interval_labels",
"=",
"cudf",
".",
"CategoricalIndex",
"(",
"labels",
",",
"categories",
"=",
"None",
",",
"ordered",
"=",
"False",
")",
"else",
":",
"interval_labels",
"=",
"(",
"labels",
"if",
"len",
"(",
"set",
"(",
"labels",
")",
")",
"==",
"len",
"(",
"labels",
")",
"else",
"None",
")",
"if",
"isinstance",
"(",
"bins",
",",
"pd",
".",
"IntervalIndex",
")",
":",
"# get the left and right edges of the bins as columns",
"# we cannot typecast an IntervalIndex, so we need to",
"# make the edges the same type as the input array",
"left_edges",
"=",
"as_column",
"(",
"bins",
".",
"left",
")",
".",
"astype",
"(",
"input_arr",
".",
"dtype",
")",
"right_edges",
"=",
"as_column",
"(",
"bins",
".",
"right",
")",
".",
"astype",
"(",
"input_arr",
".",
"dtype",
")",
"else",
":",
"# get the left and right edges of the bins as columns",
"left_edges",
"=",
"as_column",
"(",
"bins",
"[",
":",
"-",
"1",
":",
"]",
",",
"dtype",
"=",
"\"float64\"",
")",
"right_edges",
"=",
"as_column",
"(",
"bins",
"[",
"+",
"1",
":",
":",
"]",
",",
"dtype",
"=",
"\"float64\"",
")",
"# the input arr must be changed to the same type as the edges",
"input_arr",
"=",
"input_arr",
".",
"astype",
"(",
"left_edges",
".",
"dtype",
")",
"# get the indexes for the appropriate number",
"index_labels",
"=",
"cudf",
".",
"_lib",
".",
"labeling",
".",
"label_bins",
"(",
"input_arr",
",",
"left_edges",
",",
"left_inclusive",
",",
"right_edges",
",",
"right_inclusive",
")",
"if",
"labels",
"is",
"False",
":",
"# if labels is false we return the index labels, we return them",
"# as a series if we have a series input",
"if",
"isinstance",
"(",
"orig_x",
",",
"(",
"pd",
".",
"Series",
",",
"cudf",
".",
"Series",
")",
")",
":",
"# need to run more tests but looks like in this case pandas",
"# always returns a float64 dtype",
"indx_arr_series",
"=",
"cudf",
".",
"Series",
"(",
"index_labels",
",",
"dtype",
"=",
"\"float64\"",
")",
"# if retbins we return the bins as well",
"if",
"retbins",
":",
"return",
"indx_arr_series",
",",
"bins",
"else",
":",
"return",
"indx_arr_series",
"elif",
"retbins",
":",
"return",
"index_labels",
".",
"values",
",",
"bins",
"else",
":",
"return",
"index_labels",
".",
"values",
"if",
"labels",
"is",
"not",
"None",
":",
"if",
"labels",
"is",
"not",
"ordered",
"and",
"len",
"(",
"set",
"(",
"labels",
")",
")",
"!=",
"len",
"(",
"labels",
")",
":",
"# when we have duplicate labels and ordered is False, we",
"# should allow duplicate categories. The categories are",
"# returned in order",
"new_data",
"=",
"[",
"interval_labels",
"[",
"i",
"]",
"[",
"0",
"]",
"for",
"i",
"in",
"index_labels",
".",
"values",
"]",
"return",
"cudf",
".",
"CategoricalIndex",
"(",
"new_data",
",",
"categories",
"=",
"sorted",
"(",
"set",
"(",
"labels",
")",
")",
",",
"ordered",
"=",
"False",
")",
"col",
"=",
"build_categorical_column",
"(",
"categories",
"=",
"interval_labels",
",",
"codes",
"=",
"index_labels",
",",
"mask",
"=",
"index_labels",
".",
"base_mask",
",",
"offset",
"=",
"index_labels",
".",
"offset",
",",
"size",
"=",
"index_labels",
".",
"size",
",",
"ordered",
"=",
"ordered",
",",
")",
"# we return a categorical index, as we don't have a Categorical method",
"categorical_index",
"=",
"cudf",
".",
"core",
".",
"index",
".",
"as_index",
"(",
"col",
")",
"if",
"isinstance",
"(",
"orig_x",
",",
"(",
"pd",
".",
"Series",
",",
"cudf",
".",
"Series",
")",
")",
":",
"# if we have a series input we return a series output",
"res_series",
"=",
"cudf",
".",
"Series",
"(",
"categorical_index",
",",
"index",
"=",
"orig_x",
".",
"index",
")",
"if",
"retbins",
":",
"return",
"res_series",
",",
"bins",
"else",
":",
"return",
"res_series",
"elif",
"retbins",
":",
"# if retbins is true we return the bins as well",
"return",
"categorical_index",
",",
"bins",
"else",
":",
"return",
"categorical_index"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/cut.py#L13-L295 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/util/_decorators.py | python | deprecate_kwarg | (old_arg_name, new_arg_name, mapping=None, stacklevel=2) | return _deprecate_kwarg | Decorator to deprecate a keyword argument of a function.
Parameters
----------
old_arg_name : str
Name of argument in function to deprecate
new_arg_name : str or None
Name of preferred argument in function. Use None to raise warning that
``old_arg_name`` keyword is deprecated.
mapping : dict or callable
If mapping is present, use it to translate old arguments to
new arguments. A callable must do its own value checking;
values not found in a dict will be forwarded unchanged.
Examples
--------
The following deprecates 'cols', using 'columns' instead
>>> @deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
... def f(columns=''):
... print(columns)
...
>>> f(columns='should work ok')
should work ok
>>> f(cols='should raise warning')
FutureWarning: cols is deprecated, use columns instead
warnings.warn(msg, FutureWarning)
should raise warning
>>> f(cols='should error', columns="can\'t pass do both")
TypeError: Can only specify 'cols' or 'columns', not both
>>> @deprecate_kwarg('old', 'new', {'yes': True, 'no': False})
... def f(new=False):
... print('yes!' if new else 'no!')
...
>>> f(old='yes')
FutureWarning: old='yes' is deprecated, use new=True instead
warnings.warn(msg, FutureWarning)
yes!
To raise a warning that a keyword will be removed entirely in the future
>>> @deprecate_kwarg(old_arg_name='cols', new_arg_name=None)
... def f(cols='', another_param=''):
... print(cols)
...
>>> f(cols='should raise warning')
FutureWarning: the 'cols' keyword is deprecated and will be removed in a
future version please takes steps to stop use of 'cols'
should raise warning
>>> f(another_param='should not raise warning')
should not raise warning
>>> f(cols='should raise warning', another_param='')
FutureWarning: the 'cols' keyword is deprecated and will be removed in a
future version please takes steps to stop use of 'cols'
should raise warning | Decorator to deprecate a keyword argument of a function. | [
"Decorator",
"to",
"deprecate",
"a",
"keyword",
"argument",
"of",
"a",
"function",
"."
] | def deprecate_kwarg(old_arg_name, new_arg_name, mapping=None, stacklevel=2):
"""
Decorator to deprecate a keyword argument of a function.
Parameters
----------
old_arg_name : str
Name of argument in function to deprecate
new_arg_name : str or None
Name of preferred argument in function. Use None to raise warning that
``old_arg_name`` keyword is deprecated.
mapping : dict or callable
If mapping is present, use it to translate old arguments to
new arguments. A callable must do its own value checking;
values not found in a dict will be forwarded unchanged.
Examples
--------
The following deprecates 'cols', using 'columns' instead
>>> @deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
... def f(columns=''):
... print(columns)
...
>>> f(columns='should work ok')
should work ok
>>> f(cols='should raise warning')
FutureWarning: cols is deprecated, use columns instead
warnings.warn(msg, FutureWarning)
should raise warning
>>> f(cols='should error', columns="can\'t pass do both")
TypeError: Can only specify 'cols' or 'columns', not both
>>> @deprecate_kwarg('old', 'new', {'yes': True, 'no': False})
... def f(new=False):
... print('yes!' if new else 'no!')
...
>>> f(old='yes')
FutureWarning: old='yes' is deprecated, use new=True instead
warnings.warn(msg, FutureWarning)
yes!
To raise a warning that a keyword will be removed entirely in the future
>>> @deprecate_kwarg(old_arg_name='cols', new_arg_name=None)
... def f(cols='', another_param=''):
... print(cols)
...
>>> f(cols='should raise warning')
FutureWarning: the 'cols' keyword is deprecated and will be removed in a
future version please takes steps to stop use of 'cols'
should raise warning
>>> f(another_param='should not raise warning')
should not raise warning
>>> f(cols='should raise warning', another_param='')
FutureWarning: the 'cols' keyword is deprecated and will be removed in a
future version please takes steps to stop use of 'cols'
should raise warning
"""
if mapping is not None and not hasattr(mapping, 'get') and \
not callable(mapping):
raise TypeError("mapping from old to new argument values "
"must be dict or callable!")
def _deprecate_kwarg(func):
@wraps(func)
def wrapper(*args, **kwargs):
old_arg_value = kwargs.pop(old_arg_name, None)
if new_arg_name is None and old_arg_value is not None:
msg = (
"the '{old_name}' keyword is deprecated and will be "
"removed in a future version. "
"Please take steps to stop the use of '{old_name}'"
).format(old_name=old_arg_name)
warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
kwargs[old_arg_name] = old_arg_value
return func(*args, **kwargs)
if old_arg_value is not None:
if mapping is not None:
if hasattr(mapping, 'get'):
new_arg_value = mapping.get(old_arg_value,
old_arg_value)
else:
new_arg_value = mapping(old_arg_value)
msg = ("the {old_name}={old_val!r} keyword is deprecated, "
"use {new_name}={new_val!r} instead"
).format(old_name=old_arg_name,
old_val=old_arg_value,
new_name=new_arg_name,
new_val=new_arg_value)
else:
new_arg_value = old_arg_value
msg = ("the '{old_name}' keyword is deprecated, "
"use '{new_name}' instead"
).format(old_name=old_arg_name,
new_name=new_arg_name)
warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
if kwargs.get(new_arg_name, None) is not None:
msg = ("Can only specify '{old_name}' or '{new_name}', "
"not both").format(old_name=old_arg_name,
new_name=new_arg_name)
raise TypeError(msg)
else:
kwargs[new_arg_name] = new_arg_value
return func(*args, **kwargs)
return wrapper
return _deprecate_kwarg | [
"def",
"deprecate_kwarg",
"(",
"old_arg_name",
",",
"new_arg_name",
",",
"mapping",
"=",
"None",
",",
"stacklevel",
"=",
"2",
")",
":",
"if",
"mapping",
"is",
"not",
"None",
"and",
"not",
"hasattr",
"(",
"mapping",
",",
"'get'",
")",
"and",
"not",
"callable",
"(",
"mapping",
")",
":",
"raise",
"TypeError",
"(",
"\"mapping from old to new argument values \"",
"\"must be dict or callable!\"",
")",
"def",
"_deprecate_kwarg",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"old_arg_value",
"=",
"kwargs",
".",
"pop",
"(",
"old_arg_name",
",",
"None",
")",
"if",
"new_arg_name",
"is",
"None",
"and",
"old_arg_value",
"is",
"not",
"None",
":",
"msg",
"=",
"(",
"\"the '{old_name}' keyword is deprecated and will be \"",
"\"removed in a future version. \"",
"\"Please take steps to stop the use of '{old_name}'\"",
")",
".",
"format",
"(",
"old_name",
"=",
"old_arg_name",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"stacklevel",
")",
"kwargs",
"[",
"old_arg_name",
"]",
"=",
"old_arg_value",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"old_arg_value",
"is",
"not",
"None",
":",
"if",
"mapping",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"mapping",
",",
"'get'",
")",
":",
"new_arg_value",
"=",
"mapping",
".",
"get",
"(",
"old_arg_value",
",",
"old_arg_value",
")",
"else",
":",
"new_arg_value",
"=",
"mapping",
"(",
"old_arg_value",
")",
"msg",
"=",
"(",
"\"the {old_name}={old_val!r} keyword is deprecated, \"",
"\"use {new_name}={new_val!r} instead\"",
")",
".",
"format",
"(",
"old_name",
"=",
"old_arg_name",
",",
"old_val",
"=",
"old_arg_value",
",",
"new_name",
"=",
"new_arg_name",
",",
"new_val",
"=",
"new_arg_value",
")",
"else",
":",
"new_arg_value",
"=",
"old_arg_value",
"msg",
"=",
"(",
"\"the '{old_name}' keyword is deprecated, \"",
"\"use '{new_name}' instead\"",
")",
".",
"format",
"(",
"old_name",
"=",
"old_arg_name",
",",
"new_name",
"=",
"new_arg_name",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"stacklevel",
")",
"if",
"kwargs",
".",
"get",
"(",
"new_arg_name",
",",
"None",
")",
"is",
"not",
"None",
":",
"msg",
"=",
"(",
"\"Can only specify '{old_name}' or '{new_name}', \"",
"\"not both\"",
")",
".",
"format",
"(",
"old_name",
"=",
"old_arg_name",
",",
"new_name",
"=",
"new_arg_name",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"else",
":",
"kwargs",
"[",
"new_arg_name",
"]",
"=",
"new_arg_value",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"return",
"_deprecate_kwarg"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/util/_decorators.py#L77-L190 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ebmlib/_trash.py | python | _unixTrash | (paths) | Move paths to FreeDesktop Trash can
See <http://www.ramendik.ru/docs/trashspec.html> | Move paths to FreeDesktop Trash can
See <http://www.ramendik.ru/docs/trashspec.html> | [
"Move",
"paths",
"to",
"FreeDesktop",
"Trash",
"can",
"See",
"<http",
":",
"//",
"www",
".",
"ramendik",
".",
"ru",
"/",
"docs",
"/",
"trashspec",
".",
"html",
">"
] | def _unixTrash(paths):
"""
Move paths to FreeDesktop Trash can
See <http://www.ramendik.ru/docs/trashspec.html>
"""
trashdir = os.path.join(os.environ.get('XDG_DATA_HOME',
os.path.join(os.path.expanduser('~'),'.local','share')), 'Trash')
# Create trash directories as needed
try:
os.makedirs(os.path.join(trashdir, 'files'))
except (IOError, OSError):
pass
try:
os.makedirs(os.path.join(trashdir, 'info'))
except (IOError, OSError):
pass
# Make sure that directories got created
if not os.path.isdir(os.path.join(trashdir, 'files')):
raise TrashDirectoryError, ('Could not locate trash directory', trashdir)
if not os.path.isdir(os.path.join(trashdir, 'info')):
raise TrashDirectoryError, ('Could not locate trash directory', trashdir)
for path in paths:
# See if we can even do this
_ensurePermissions(path)
# Create unique filename
origpath = newpath = os.path.join(trashdir, 'files',
os.path.basename(path))
while os.path.exists(newpath):
newpath = origpath
base, ext = os.path.splitext(newpath)
newpath = '%s %s%s' % (base, time.strftime('%H-%M-%S'), ext)
# Write info file
try:
root, base = os.path.split(newpath)
infopath = os.path.join(os.path.dirname(root),
'info', base + '.trashinfo')
info = open(infopath,'w')
info.write('[Trash Info]\n')
info.write('Path=%s\n' % path)
info.write(time.strftime('DeletionDate=%Y%m%dT%H:%M:%S\n'))
info.close()
except (OSError, IOError), msg:
try:
os.remove(infopath)
except:
pass
raise TrashMoveError, ('Could not move path', path, msg)
# Move file
try:
shutil.move(path, newpath)
except (OSError, IOError), msg:
raise TrashMoveError, ('Could not move path', path, msg) | [
"def",
"_unixTrash",
"(",
"paths",
")",
":",
"trashdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_DATA_HOME'",
",",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.local'",
",",
"'share'",
")",
")",
",",
"'Trash'",
")",
"# Create trash directories as needed",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"trashdir",
",",
"'files'",
")",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"pass",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"trashdir",
",",
"'info'",
")",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"pass",
"# Make sure that directories got created",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"trashdir",
",",
"'files'",
")",
")",
":",
"raise",
"TrashDirectoryError",
",",
"(",
"'Could not locate trash directory'",
",",
"trashdir",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"trashdir",
",",
"'info'",
")",
")",
":",
"raise",
"TrashDirectoryError",
",",
"(",
"'Could not locate trash directory'",
",",
"trashdir",
")",
"for",
"path",
"in",
"paths",
":",
"# See if we can even do this",
"_ensurePermissions",
"(",
"path",
")",
"# Create unique filename",
"origpath",
"=",
"newpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"trashdir",
",",
"'files'",
",",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"while",
"os",
".",
"path",
".",
"exists",
"(",
"newpath",
")",
":",
"newpath",
"=",
"origpath",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"newpath",
")",
"newpath",
"=",
"'%s %s%s'",
"%",
"(",
"base",
",",
"time",
".",
"strftime",
"(",
"'%H-%M-%S'",
")",
",",
"ext",
")",
"# Write info file",
"try",
":",
"root",
",",
"base",
"=",
"os",
".",
"path",
".",
"split",
"(",
"newpath",
")",
"infopath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"root",
")",
",",
"'info'",
",",
"base",
"+",
"'.trashinfo'",
")",
"info",
"=",
"open",
"(",
"infopath",
",",
"'w'",
")",
"info",
".",
"write",
"(",
"'[Trash Info]\\n'",
")",
"info",
".",
"write",
"(",
"'Path=%s\\n'",
"%",
"path",
")",
"info",
".",
"write",
"(",
"time",
".",
"strftime",
"(",
"'DeletionDate=%Y%m%dT%H:%M:%S\\n'",
")",
")",
"info",
".",
"close",
"(",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
",",
"msg",
":",
"try",
":",
"os",
".",
"remove",
"(",
"infopath",
")",
"except",
":",
"pass",
"raise",
"TrashMoveError",
",",
"(",
"'Could not move path'",
",",
"path",
",",
"msg",
")",
"# Move file",
"try",
":",
"shutil",
".",
"move",
"(",
"path",
",",
"newpath",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
",",
"msg",
":",
"raise",
"TrashMoveError",
",",
"(",
"'Could not move path'",
",",
"path",
",",
"msg",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/_trash.py#L137-L197 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/lexer.py | python | compile_rules | (environment) | return [x[1:] for x in sorted(rules, reverse=True)] | Compiles all the rules from the environment into a list of rules. | Compiles all the rules from the environment into a list of rules. | [
"Compiles",
"all",
"the",
"rules",
"from",
"the",
"environment",
"into",
"a",
"list",
"of",
"rules",
"."
] | def compile_rules(environment):
"""Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(len(environment.comment_start_string), 'comment',
e(environment.comment_start_string)),
(len(environment.block_start_string), 'block',
e(environment.block_start_string)),
(len(environment.variable_start_string), 'variable',
e(environment.variable_start_string))
]
if environment.line_statement_prefix is not None:
rules.append((len(environment.line_statement_prefix), 'linestatement',
r'^[ \t\v]*' + e(environment.line_statement_prefix)))
if environment.line_comment_prefix is not None:
rules.append((len(environment.line_comment_prefix), 'linecomment',
r'(?:^|(?<=\S))[^\S\r\n]*' +
e(environment.line_comment_prefix)))
return [x[1:] for x in sorted(rules, reverse=True)] | [
"def",
"compile_rules",
"(",
"environment",
")",
":",
"e",
"=",
"re",
".",
"escape",
"rules",
"=",
"[",
"(",
"len",
"(",
"environment",
".",
"comment_start_string",
")",
",",
"'comment'",
",",
"e",
"(",
"environment",
".",
"comment_start_string",
")",
")",
",",
"(",
"len",
"(",
"environment",
".",
"block_start_string",
")",
",",
"'block'",
",",
"e",
"(",
"environment",
".",
"block_start_string",
")",
")",
",",
"(",
"len",
"(",
"environment",
".",
"variable_start_string",
")",
",",
"'variable'",
",",
"e",
"(",
"environment",
".",
"variable_start_string",
")",
")",
"]",
"if",
"environment",
".",
"line_statement_prefix",
"is",
"not",
"None",
":",
"rules",
".",
"append",
"(",
"(",
"len",
"(",
"environment",
".",
"line_statement_prefix",
")",
",",
"'linestatement'",
",",
"r'^[ \\t\\v]*'",
"+",
"e",
"(",
"environment",
".",
"line_statement_prefix",
")",
")",
")",
"if",
"environment",
".",
"line_comment_prefix",
"is",
"not",
"None",
":",
"rules",
".",
"append",
"(",
"(",
"len",
"(",
"environment",
".",
"line_comment_prefix",
")",
",",
"'linecomment'",
",",
"r'(?:^|(?<=\\S))[^\\S\\r\\n]*'",
"+",
"e",
"(",
"environment",
".",
"line_comment_prefix",
")",
")",
")",
"return",
"[",
"x",
"[",
"1",
":",
"]",
"for",
"x",
"in",
"sorted",
"(",
"rules",
",",
"reverse",
"=",
"True",
")",
"]"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/lexer.py#L196-L216 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/json_schema_compiler/js_interface_generator.py | python | _Generator._AppendInterfaceObject | (self, c) | Appends the code creating the interface object.
For example:
/** @interface */
function SettingsPrivate() {} | Appends the code creating the interface object.
For example:
/** | [
"Appends",
"the",
"code",
"creating",
"the",
"interface",
"object",
".",
"For",
"example",
":",
"/",
"**"
] | def _AppendInterfaceObject(self, c):
"""Appends the code creating the interface object.
For example:
/** @interface */
function SettingsPrivate() {}
"""
(c.Append('/** @interface */')
.Append('function %s() {}' % self._interface)) | [
"def",
"_AppendInterfaceObject",
"(",
"self",
",",
"c",
")",
":",
"(",
"c",
".",
"Append",
"(",
"'/** @interface */'",
")",
".",
"Append",
"(",
"'function %s() {}'",
"%",
"self",
".",
"_interface",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/js_interface_generator.py#L69-L76 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/gdal-utils/osgeo_utils/gdal_merge.py | python | names_to_fileinfos | (names) | return file_infos | Translate a list of GDAL filenames, into file_info objects.
names -- list of valid GDAL dataset names.
Returns a list of file_info objects. There may be less file_info objects
than names if some of the names could not be opened as GDAL files. | Translate a list of GDAL filenames, into file_info objects. | [
"Translate",
"a",
"list",
"of",
"GDAL",
"filenames",
"into",
"file_info",
"objects",
"."
] | def names_to_fileinfos(names):
"""
Translate a list of GDAL filenames, into file_info objects.
names -- list of valid GDAL dataset names.
Returns a list of file_info objects. There may be less file_info objects
than names if some of the names could not be opened as GDAL files.
"""
file_infos = []
for name in names:
fi = file_info()
if fi.init_from_name(name) == 1:
file_infos.append(fi)
return file_infos | [
"def",
"names_to_fileinfos",
"(",
"names",
")",
":",
"file_infos",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"fi",
"=",
"file_info",
"(",
")",
"if",
"fi",
".",
"init_from_name",
"(",
"name",
")",
"==",
"1",
":",
"file_infos",
".",
"append",
"(",
"fi",
")",
"return",
"file_infos"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/gdal-utils/osgeo_utils/gdal_merge.py#L138-L154 | |
alibaba/weex_js_engine | 2bdf4b6f020c1fc99c63f649718f6faf7e27fdde | jni/v8core/v8/build/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings._GetStandaloneBinaryPath | (self) | return target_prefix + target + target_ext | Returns the name of the non-bundle binary represented by this target.
E.g. hello_world. Only valid for non-bundles. | Returns the name of the non-bundle binary represented by this target.
E.g. hello_world. Only valid for non-bundles. | [
"Returns",
"the",
"name",
"of",
"the",
"non",
"-",
"bundle",
"binary",
"represented",
"by",
"this",
"target",
".",
"E",
".",
"g",
".",
"hello_world",
".",
"Only",
"valid",
"for",
"non",
"-",
"bundles",
"."
] | def _GetStandaloneBinaryPath(self):
"""Returns the name of the non-bundle binary represented by this target.
E.g. hello_world. Only valid for non-bundles."""
assert not self._IsBundle()
assert self.spec['type'] in (
'executable', 'shared_library', 'static_library', 'loadable_module'), (
'Unexpected type %s' % self.spec['type'])
target = self.spec['target_name']
if self.spec['type'] == 'static_library':
if target[:3] == 'lib':
target = target[3:]
elif self.spec['type'] in ('loadable_module', 'shared_library'):
if target[:3] == 'lib':
target = target[3:]
target_prefix = self._GetStandaloneExecutablePrefix()
target = self.spec.get('product_name', target)
target_ext = self._GetStandaloneExecutableSuffix()
return target_prefix + target + target_ext | [
"def",
"_GetStandaloneBinaryPath",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_IsBundle",
"(",
")",
"assert",
"self",
".",
"spec",
"[",
"'type'",
"]",
"in",
"(",
"'executable'",
",",
"'shared_library'",
",",
"'static_library'",
",",
"'loadable_module'",
")",
",",
"(",
"'Unexpected type %s'",
"%",
"self",
".",
"spec",
"[",
"'type'",
"]",
")",
"target",
"=",
"self",
".",
"spec",
"[",
"'target_name'",
"]",
"if",
"self",
".",
"spec",
"[",
"'type'",
"]",
"==",
"'static_library'",
":",
"if",
"target",
"[",
":",
"3",
"]",
"==",
"'lib'",
":",
"target",
"=",
"target",
"[",
"3",
":",
"]",
"elif",
"self",
".",
"spec",
"[",
"'type'",
"]",
"in",
"(",
"'loadable_module'",
",",
"'shared_library'",
")",
":",
"if",
"target",
"[",
":",
"3",
"]",
"==",
"'lib'",
":",
"target",
"=",
"target",
"[",
"3",
":",
"]",
"target_prefix",
"=",
"self",
".",
"_GetStandaloneExecutablePrefix",
"(",
")",
"target",
"=",
"self",
".",
"spec",
".",
"get",
"(",
"'product_name'",
",",
"target",
")",
"target_ext",
"=",
"self",
".",
"_GetStandaloneExecutableSuffix",
"(",
")",
"return",
"target_prefix",
"+",
"target",
"+",
"target_ext"
] | https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/xcode_emulation.py#L186-L204 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Task.py | python | Task.compute_sig_implicit_deps | (self) | return self.m.digest() | Used by :py:meth:`waflib.Task.Task.sig_implicit_deps` for computing the actual hash of the
:py:class:`waflib.Node.Node` returned by the scanner.
:return: a hash value for the implicit dependencies
:rtype: string or bytes | Used by :py:meth:`waflib.Task.Task.sig_implicit_deps` for computing the actual hash of the
:py:class:`waflib.Node.Node` returned by the scanner. | [
"Used",
"by",
":",
"py",
":",
"meth",
":",
"waflib",
".",
"Task",
".",
"Task",
".",
"sig_implicit_deps",
"for",
"computing",
"the",
"actual",
"hash",
"of",
"the",
":",
"py",
":",
"class",
":",
"waflib",
".",
"Node",
".",
"Node",
"returned",
"by",
"the",
"scanner",
"."
] | def compute_sig_implicit_deps(self):
"""
Used by :py:meth:`waflib.Task.Task.sig_implicit_deps` for computing the actual hash of the
:py:class:`waflib.Node.Node` returned by the scanner.
:return: a hash value for the implicit dependencies
:rtype: string or bytes
"""
upd = self.m.update
self.are_implicit_nodes_ready()
# scanner returns a node that does not have a signature
# just *ignore* the error and let them figure out from the compiler output
# waf -k behaviour
for k in self.generator.bld.node_deps.get(self.uid(), []):
upd(k.get_bld_sig())
return self.m.digest() | [
"def",
"compute_sig_implicit_deps",
"(",
"self",
")",
":",
"upd",
"=",
"self",
".",
"m",
".",
"update",
"self",
".",
"are_implicit_nodes_ready",
"(",
")",
"# scanner returns a node that does not have a signature",
"# just *ignore* the error and let them figure out from the compiler output",
"# waf -k behaviour",
"for",
"k",
"in",
"self",
".",
"generator",
".",
"bld",
".",
"node_deps",
".",
"get",
"(",
"self",
".",
"uid",
"(",
")",
",",
"[",
"]",
")",
":",
"upd",
"(",
"k",
".",
"get_bld_sig",
"(",
")",
")",
"return",
"self",
".",
"m",
".",
"digest",
"(",
")"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Task.py#L856-L872 | |
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/gemmlowp/meta/generators/meta_arm_32.py | python | Main | () | Generate the single threaded meta gemm library. | Generate the single threaded meta gemm library. | [
"Generate",
"the",
"single",
"threaded",
"meta",
"gemm",
"library",
"."
] | def Main():
"""Generate the single threaded meta gemm library."""
cc = cc_emitter.CCEmitter()
meta_arm_common.GenerateHeader(cc, 'gemmlowp_meta_single_thread_gemm_arm32',
'GEMMLOWP_NEON_32')
cc.EmitNamespaceBegin('gemmlowp')
cc.EmitNamespaceBegin('meta')
cc.EmitNamespaceBegin('internal')
cc.EmitNewline()
meta_arm_common.GenerateInternalFunctions(cc, neon_emitter.NeonEmitter())
cc.EmitNamespaceEnd()
cc.EmitNamespaceEnd()
cc.EmitNamespaceEnd()
cc.EmitNewline()
meta_arm_common.GenerateFooter(
cc, 'Meta gemm for arm32 requires: GEMMLOWP_NEON_32!') | [
"def",
"Main",
"(",
")",
":",
"cc",
"=",
"cc_emitter",
".",
"CCEmitter",
"(",
")",
"meta_arm_common",
".",
"GenerateHeader",
"(",
"cc",
",",
"'gemmlowp_meta_single_thread_gemm_arm32'",
",",
"'GEMMLOWP_NEON_32'",
")",
"cc",
".",
"EmitNamespaceBegin",
"(",
"'gemmlowp'",
")",
"cc",
".",
"EmitNamespaceBegin",
"(",
"'meta'",
")",
"cc",
".",
"EmitNamespaceBegin",
"(",
"'internal'",
")",
"cc",
".",
"EmitNewline",
"(",
")",
"meta_arm_common",
".",
"GenerateInternalFunctions",
"(",
"cc",
",",
"neon_emitter",
".",
"NeonEmitter",
"(",
")",
")",
"cc",
".",
"EmitNamespaceEnd",
"(",
")",
"cc",
".",
"EmitNamespaceEnd",
"(",
")",
"cc",
".",
"EmitNamespaceEnd",
"(",
")",
"cc",
".",
"EmitNewline",
"(",
")",
"meta_arm_common",
".",
"GenerateFooter",
"(",
"cc",
",",
"'Meta gemm for arm32 requires: GEMMLOWP_NEON_32!'",
")"
] | https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/gemmlowp/meta/generators/meta_arm_32.py#L8-L27 | ||
google/ion | ef47f3b824050499ce5c6f774b366f6c4dbce0af | ion/build.py | python | BuildState._ParseCommandLineArgs | (self, argv) | return parser.parse_args(argv[1:]) | Parses command line arguments and shows help/usage if necessary.
This function wraps some advanced usage of argparse.parser. We use a two-
pass parsing strategy: the first pass populates all of the options and
arguments that aren't dependent on any other options (which is most of
them). The second pass uses the information gained from the first pass to
determine what other options (such as configuration names and build flags,
which depend on what gypfile is being built) should be available, and parses
those as well.
Args:
argv: The full command line, including the name of the script in argv[0].
Returns:
A 2-tuple consisting of a dictionary of command-line options and their
values, followed by a list of positional arguments. (This is the same
tuple returned by argparse.ArgumentParser.parse_args.) | Parses command line arguments and shows help/usage if necessary. | [
"Parses",
"command",
"line",
"arguments",
"and",
"shows",
"help",
"/",
"usage",
"if",
"necessary",
"."
] | def _ParseCommandLineArgs(self, argv):
"""Parses command line arguments and shows help/usage if necessary.
This function wraps some advanced usage of argparse.parser. We use a two-
pass parsing strategy: the first pass populates all of the options and
arguments that aren't dependent on any other options (which is most of
them). The second pass uses the information gained from the first pass to
determine what other options (such as configuration names and build flags,
which depend on what gypfile is being built) should be available, and parses
those as well.
Args:
argv: The full command line, including the name of the script in argv[0].
Returns:
A 2-tuple consisting of a dictionary of command-line options and their
values, followed by a list of positional arguments. (This is the same
tuple returned by argparse.ArgumentParser.parse_args.)
"""
# Load the registry of builders that have been annotated with
# @RegisterBuilder and determine what OSes and configurations we know how to
# build. This information is displayed if the --help option is found.
available_builds = []
unavailable_builds = []
this_os = GetHostOS()
self.all_configs_ = self._FindAllConfigurations()
for key, builder in BUILDER_REGISTRY.items():
target_os, generator = key
can_build = this_os in builder.POSSIBLE_HOST_OS
if can_build:
style = colorama.Style.RESET_ALL
else:
style = colorama.Style.DIM
if generator:
os_and_configs = '{2}{0} ({1}): '.format(target_os, generator, style)
else:
os_and_configs = '{1}{0}: '.format(target_os, style)
os_and_configs += ', '.join(
self.all_configs_[builder.TARGET_OS, builder.TARGET_FLAVOR,
builder.GYP_GENERATOR])
if can_build:
available_builds.append(os_and_configs)
else:
unavailable_builds.append(os_and_configs)
all_builds = available_builds + unavailable_builds
# First pass: add options whose presence or default value doesn't depend on
# any other arguments. We create the parser without a --help option,
# because if we added one and the user passed the option, ArgumentParser
# would print usage and exit before performing the second pass.
parser = argparse.ArgumentParser(
epilog=('\nPossible OS and configuration values:\n ' +
'\n '.join(all_builds)) + '\n',
formatter_class=argparse.RawDescriptionHelpFormatter,
add_help=False)
parser.add_argument(
'-o', '--os',
default=self.default_target_os_,
help='The target OS to build for.')
parser.add_argument(
'-j', '--threads', default=None,
help='How many threads to use for the build process.')
parser.add_argument(
'--ninja', action='store_true',
default=False,
help='Whether to use ninja instead of the native build tool. If '
'passed, this is equivalent to -g ninja.')
parser.add_argument(
'-k', '--keep-going', action='store_true',
default=False,
help='Continue building after errors.')
parser.add_argument(
'--nogyp', action='store_true',
default=False,
help='If true, will not generate project files, only build. Use '
'this to save a couple of seconds if you know your gyp files have '
'not been modified.')
parser.add_argument(
'--nobuild', action='store_true',
default=False,
help='If true, will not build binaries, only the project files.')
parser.add_argument(
'--clean', action='store_true',
default=False,
help='If true, clean the build directory and generator files ('
'gyp-out/$os and gyp-projects).')
parser.add_argument(
'--gypd', action='store_true',
default=False,
help='Whether to output a .gypd debug file, and exit. '
'(Implies --nobuild).')
parser.add_argument(
'--deps', action='store_true',
default=False,
help='Whether to output the dependency graph in JSON format to '
'dump.json, and exit. (Implies --nobuild).')
parser.add_argument(
'-w', '--verbose', action='store_true',
default=False,
help='Whether to invoke the build in verbose mode.')
parser.add_argument(
'-t', '--test', action='store_true',
default=False,
help='Run all tests.')
parser.add_argument(
'-D', action='append',
default=[],
help='Additional values to pass to gyp. Use as: -D=my_var=my_value')
parser.add_argument(
'--test_arg', action='append',
default=None,
help='Specifies a flag to pass to the test. For example, to pass a '
'filter to gunit use --test_arg=--gunit_filter=Example.TestCase. '
'To pass multiple flags use --test_arg multiple times.')
parser.add_argument(
'-T', '--test_until_failure', action='store_true',
dest='test_until_failure',
default=False,
help='Run all tests, until the first failing test.')
parser.add_argument(
'-c', '--configuration',
default=None,
help='What configuration to build. See below for available '
'configurations.')
parser.add_argument(
'-g', '--generator',
default=None,
help='What gyp generator to use. If not specified, uses the default '
'generator for the target OS.')
parser.add_argument(
'-G', action='append',
default=[],
help='Generator flags to pass to gyp.')
parser.add_argument(
'path',
nargs='?',
default=None,
help='The gypfile or package path you wish to build.')
# Parse only known args, since project-specific build flags will be
# determined later.
args = parser.parse_known_args(argv[1:])
# Second pass: calculate the path to the gyp file the user wants to build,
# and parse it looking for project-specific build flags we should add
# options for.
if args and args[0].path:
self.filename_ = self._MakeGypFilePath(args[0].path)
elif os.path.isfile(os.path.join(ROOT_DIR,
self._MakeGypFilePath(os.getcwd()))):
self.filename_ = self._MakeGypFilePath(os.getcwd())
else:
self.filename_ = None
self.possible_build_flags_ = {}
if self.filename_:
self.possible_build_flags_ = self._FindBuildFlags(self.filename_)
if self.possible_build_flags_:
# We'll add the build flags to this group as options in a moment.
build_flags = parser.add_argument_group('build flags')
elif not self.filename_:
# The user didn't give us a gyp file, so we can only show generic help.
build_flags = parser.add_argument_group(
'build flags', 'To see project-specific flags, specify a gyp file.')
else:
# The gyp file was valid, but contained no build flags.
build_flags = parser.add_argument_group(
'build flags', 'No project-specific build flags are defined.')
# Add a new command-line option for each build flag we found.
for variable, default_value in self.GetPossibleBuildFlags().items():
# Default values that can be converted to integers are treated as such
# and other values (strings) are left as strings. Initially, all values
# were converted to integers but this would cause an exception if a
# non-int string was used as a default.
try:
default_converted = int(default_value)
except ValueError:
default_converted = default_value
build_flags.add_argument(
'--' + variable,
default=default_converted,
help='(default: %(default)s)')
# Add the help option now that our option list is complete.
parser.add_argument('-h', '--help', action='help')
# Now parse all args, since if the user passed something we don't recognize
# by this point, it's not a valid option.
return parser.parse_args(argv[1:]) | [
"def",
"_ParseCommandLineArgs",
"(",
"self",
",",
"argv",
")",
":",
"# Load the registry of builders that have been annotated with",
"# @RegisterBuilder and determine what OSes and configurations we know how to",
"# build. This information is displayed if the --help option is found.",
"available_builds",
"=",
"[",
"]",
"unavailable_builds",
"=",
"[",
"]",
"this_os",
"=",
"GetHostOS",
"(",
")",
"self",
".",
"all_configs_",
"=",
"self",
".",
"_FindAllConfigurations",
"(",
")",
"for",
"key",
",",
"builder",
"in",
"BUILDER_REGISTRY",
".",
"items",
"(",
")",
":",
"target_os",
",",
"generator",
"=",
"key",
"can_build",
"=",
"this_os",
"in",
"builder",
".",
"POSSIBLE_HOST_OS",
"if",
"can_build",
":",
"style",
"=",
"colorama",
".",
"Style",
".",
"RESET_ALL",
"else",
":",
"style",
"=",
"colorama",
".",
"Style",
".",
"DIM",
"if",
"generator",
":",
"os_and_configs",
"=",
"'{2}{0} ({1}): '",
".",
"format",
"(",
"target_os",
",",
"generator",
",",
"style",
")",
"else",
":",
"os_and_configs",
"=",
"'{1}{0}: '",
".",
"format",
"(",
"target_os",
",",
"style",
")",
"os_and_configs",
"+=",
"', '",
".",
"join",
"(",
"self",
".",
"all_configs_",
"[",
"builder",
".",
"TARGET_OS",
",",
"builder",
".",
"TARGET_FLAVOR",
",",
"builder",
".",
"GYP_GENERATOR",
"]",
")",
"if",
"can_build",
":",
"available_builds",
".",
"append",
"(",
"os_and_configs",
")",
"else",
":",
"unavailable_builds",
".",
"append",
"(",
"os_and_configs",
")",
"all_builds",
"=",
"available_builds",
"+",
"unavailable_builds",
"# First pass: add options whose presence or default value doesn't depend on",
"# any other arguments. We create the parser without a --help option,",
"# because if we added one and the user passed the option, ArgumentParser",
"# would print usage and exit before performing the second pass.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"epilog",
"=",
"(",
"'\\nPossible OS and configuration values:\\n '",
"+",
"'\\n '",
".",
"join",
"(",
"all_builds",
")",
")",
"+",
"'\\n'",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
",",
"add_help",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'-o'",
",",
"'--os'",
",",
"default",
"=",
"self",
".",
"default_target_os_",
",",
"help",
"=",
"'The target OS to build for.'",
")",
"parser",
".",
"add_argument",
"(",
"'-j'",
",",
"'--threads'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'How many threads to use for the build process.'",
")",
"parser",
".",
"add_argument",
"(",
"'--ninja'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Whether to use ninja instead of the native build tool. If '",
"'passed, this is equivalent to -g ninja.'",
")",
"parser",
".",
"add_argument",
"(",
"'-k'",
",",
"'--keep-going'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Continue building after errors.'",
")",
"parser",
".",
"add_argument",
"(",
"'--nogyp'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'If true, will not generate project files, only build. Use '",
"'this to save a couple of seconds if you know your gyp files have '",
"'not been modified.'",
")",
"parser",
".",
"add_argument",
"(",
"'--nobuild'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'If true, will not build binaries, only the project files.'",
")",
"parser",
".",
"add_argument",
"(",
"'--clean'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'If true, clean the build directory and generator files ('",
"'gyp-out/$os and gyp-projects).'",
")",
"parser",
".",
"add_argument",
"(",
"'--gypd'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Whether to output a .gypd debug file, and exit. '",
"'(Implies --nobuild).'",
")",
"parser",
".",
"add_argument",
"(",
"'--deps'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Whether to output the dependency graph in JSON format to '",
"'dump.json, and exit. (Implies --nobuild).'",
")",
"parser",
".",
"add_argument",
"(",
"'-w'",
",",
"'--verbose'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Whether to invoke the build in verbose mode.'",
")",
"parser",
".",
"add_argument",
"(",
"'-t'",
",",
"'--test'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Run all tests.'",
")",
"parser",
".",
"add_argument",
"(",
"'-D'",
",",
"action",
"=",
"'append'",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"'Additional values to pass to gyp. Use as: -D=my_var=my_value'",
")",
"parser",
".",
"add_argument",
"(",
"'--test_arg'",
",",
"action",
"=",
"'append'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Specifies a flag to pass to the test. For example, to pass a '",
"'filter to gunit use --test_arg=--gunit_filter=Example.TestCase. '",
"'To pass multiple flags use --test_arg multiple times.'",
")",
"parser",
".",
"add_argument",
"(",
"'-T'",
",",
"'--test_until_failure'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'test_until_failure'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Run all tests, until the first failing test.'",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--configuration'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'What configuration to build. See below for available '",
"'configurations.'",
")",
"parser",
".",
"add_argument",
"(",
"'-g'",
",",
"'--generator'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'What gyp generator to use. If not specified, uses the default '",
"'generator for the target OS.'",
")",
"parser",
".",
"add_argument",
"(",
"'-G'",
",",
"action",
"=",
"'append'",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"'Generator flags to pass to gyp.'",
")",
"parser",
".",
"add_argument",
"(",
"'path'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'The gypfile or package path you wish to build.'",
")",
"# Parse only known args, since project-specific build flags will be",
"# determined later.",
"args",
"=",
"parser",
".",
"parse_known_args",
"(",
"argv",
"[",
"1",
":",
"]",
")",
"# Second pass: calculate the path to the gyp file the user wants to build,",
"# and parse it looking for project-specific build flags we should add",
"# options for.",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
".",
"path",
":",
"self",
".",
"filename_",
"=",
"self",
".",
"_MakeGypFilePath",
"(",
"args",
"[",
"0",
"]",
".",
"path",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"ROOT_DIR",
",",
"self",
".",
"_MakeGypFilePath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
")",
")",
":",
"self",
".",
"filename_",
"=",
"self",
".",
"_MakeGypFilePath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"else",
":",
"self",
".",
"filename_",
"=",
"None",
"self",
".",
"possible_build_flags_",
"=",
"{",
"}",
"if",
"self",
".",
"filename_",
":",
"self",
".",
"possible_build_flags_",
"=",
"self",
".",
"_FindBuildFlags",
"(",
"self",
".",
"filename_",
")",
"if",
"self",
".",
"possible_build_flags_",
":",
"# We'll add the build flags to this group as options in a moment.",
"build_flags",
"=",
"parser",
".",
"add_argument_group",
"(",
"'build flags'",
")",
"elif",
"not",
"self",
".",
"filename_",
":",
"# The user didn't give us a gyp file, so we can only show generic help.",
"build_flags",
"=",
"parser",
".",
"add_argument_group",
"(",
"'build flags'",
",",
"'To see project-specific flags, specify a gyp file.'",
")",
"else",
":",
"# The gyp file was valid, but contained no build flags.",
"build_flags",
"=",
"parser",
".",
"add_argument_group",
"(",
"'build flags'",
",",
"'No project-specific build flags are defined.'",
")",
"# Add a new command-line option for each build flag we found.",
"for",
"variable",
",",
"default_value",
"in",
"self",
".",
"GetPossibleBuildFlags",
"(",
")",
".",
"items",
"(",
")",
":",
"# Default values that can be converted to integers are treated as such",
"# and other values (strings) are left as strings. Initially, all values",
"# were converted to integers but this would cause an exception if a",
"# non-int string was used as a default.",
"try",
":",
"default_converted",
"=",
"int",
"(",
"default_value",
")",
"except",
"ValueError",
":",
"default_converted",
"=",
"default_value",
"build_flags",
".",
"add_argument",
"(",
"'--'",
"+",
"variable",
",",
"default",
"=",
"default_converted",
",",
"help",
"=",
"'(default: %(default)s)'",
")",
"# Add the help option now that our option list is complete.",
"parser",
".",
"add_argument",
"(",
"'-h'",
",",
"'--help'",
",",
"action",
"=",
"'help'",
")",
"# Now parse all args, since if the user passed something we don't recognize",
"# by this point, it's not a valid option.",
"return",
"parser",
".",
"parse_args",
"(",
"argv",
"[",
"1",
":",
"]",
")"
] | https://github.com/google/ion/blob/ef47f3b824050499ce5c6f774b366f6c4dbce0af/ion/build.py#L1869-L2063 | |
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/python_message.py | python | _DefaultValueConstructorForField | (field) | return MakeScalarDefault | Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in turn returns a default value for this field. The default
value may refer back to |message| via a weak reference. | Returns a function which returns a default value for a field. | [
"Returns",
"a",
"function",
"which",
"returns",
"a",
"default",
"value",
"for",
"a",
"field",
"."
] | def _DefaultValueConstructorForField(field):
"""Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in turn returns a default value for this field. The default
value may refer back to |message| via a weak reference.
"""
if field.label == _FieldDescriptor.LABEL_REPEATED:
if field.has_default_value and field.default_value != []:
raise ValueError('Repeated field default value not empty list: %s' % (
field.default_value))
if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
# We can't look at _concrete_class yet since it might not have
# been set. (Depends on order in which we initialize the classes).
message_type = field.message_type
def MakeRepeatedMessageDefault(message):
return containers.RepeatedCompositeFieldContainer(
message._listener_for_children, field.message_type)
return MakeRepeatedMessageDefault
else:
type_checker = type_checkers.GetTypeChecker(field.cpp_type, field.type)
def MakeRepeatedScalarDefault(message):
return containers.RepeatedScalarFieldContainer(
message._listener_for_children, type_checker)
return MakeRepeatedScalarDefault
if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
# _concrete_class may not yet be initialized.
message_type = field.message_type
def MakeSubMessageDefault(message):
result = message_type._concrete_class()
result._SetListener(message._listener_for_children)
return result
return MakeSubMessageDefault
def MakeScalarDefault(message):
# TODO(protobuf-team): This may be broken since there may not be
# default_value. Combine with has_default_value somehow.
return field.default_value
return MakeScalarDefault | [
"def",
"_DefaultValueConstructorForField",
"(",
"field",
")",
":",
"if",
"field",
".",
"label",
"==",
"_FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"if",
"field",
".",
"has_default_value",
"and",
"field",
".",
"default_value",
"!=",
"[",
"]",
":",
"raise",
"ValueError",
"(",
"'Repeated field default value not empty list: %s'",
"%",
"(",
"field",
".",
"default_value",
")",
")",
"if",
"field",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"# We can't look at _concrete_class yet since it might not have",
"# been set. (Depends on order in which we initialize the classes).",
"message_type",
"=",
"field",
".",
"message_type",
"def",
"MakeRepeatedMessageDefault",
"(",
"message",
")",
":",
"return",
"containers",
".",
"RepeatedCompositeFieldContainer",
"(",
"message",
".",
"_listener_for_children",
",",
"field",
".",
"message_type",
")",
"return",
"MakeRepeatedMessageDefault",
"else",
":",
"type_checker",
"=",
"type_checkers",
".",
"GetTypeChecker",
"(",
"field",
".",
"cpp_type",
",",
"field",
".",
"type",
")",
"def",
"MakeRepeatedScalarDefault",
"(",
"message",
")",
":",
"return",
"containers",
".",
"RepeatedScalarFieldContainer",
"(",
"message",
".",
"_listener_for_children",
",",
"type_checker",
")",
"return",
"MakeRepeatedScalarDefault",
"if",
"field",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"# _concrete_class may not yet be initialized.",
"message_type",
"=",
"field",
".",
"message_type",
"def",
"MakeSubMessageDefault",
"(",
"message",
")",
":",
"result",
"=",
"message_type",
".",
"_concrete_class",
"(",
")",
"result",
".",
"_SetListener",
"(",
"message",
".",
"_listener_for_children",
")",
"return",
"result",
"return",
"MakeSubMessageDefault",
"def",
"MakeScalarDefault",
"(",
"message",
")",
":",
"# TODO(protobuf-team): This may be broken since there may not be",
"# default_value. Combine with has_default_value somehow.",
"return",
"field",
".",
"default_value",
"return",
"MakeScalarDefault"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L248-L294 | |
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/BASIC/basparse.py | python | p_expr_group | (p) | expr : LPAREN expr RPAREN | expr : LPAREN expr RPAREN | [
"expr",
":",
"LPAREN",
"expr",
"RPAREN"
] | def p_expr_group(p):
'''expr : LPAREN expr RPAREN'''
p[0] = ('GROUP',p[2]) | [
"def",
"p_expr_group",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"'GROUP'",
",",
"p",
"[",
"2",
"]",
")"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/BASIC/basparse.py#L300-L302 | ||
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/gmock/scripts/generator/cpp/ast.py | python | Node.IsDefinition | (self) | return False | Returns bool if this node is a definition. | Returns bool if this node is a definition. | [
"Returns",
"bool",
"if",
"this",
"node",
"is",
"a",
"definition",
"."
] | def IsDefinition(self):
"""Returns bool if this node is a definition."""
return False | [
"def",
"IsDefinition",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/gmock/scripts/generator/cpp/ast.py#L119-L121 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py | python | ParserElement.__ror__ | (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 __ror__(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",
"__ror__",
"(",
"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/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L1960-L1970 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/compiler.py | python | CodeGenerator.macro_def | (self, node, frame) | Dump the macro definition for the def created by macro_body. | Dump the macro definition for the def created by macro_body. | [
"Dump",
"the",
"macro",
"definition",
"for",
"the",
"def",
"created",
"by",
"macro_body",
"."
] | def macro_def(self, node, frame):
"""Dump the macro definition for the def created by macro_body."""
arg_tuple = ', '.join(repr(x.name) for x in node.args)
name = getattr(node, 'name', None)
if len(node.args) == 1:
arg_tuple += ','
self.write('Macro(environment, macro, %r, (%s), (' %
(name, arg_tuple))
for arg in node.defaults:
self.visit(arg, frame)
self.write(', ')
self.write('), %r, %r, %r)' % (
bool(frame.accesses_kwargs),
bool(frame.accesses_varargs),
bool(frame.accesses_caller)
)) | [
"def",
"macro_def",
"(",
"self",
",",
"node",
",",
"frame",
")",
":",
"arg_tuple",
"=",
"', '",
".",
"join",
"(",
"repr",
"(",
"x",
".",
"name",
")",
"for",
"x",
"in",
"node",
".",
"args",
")",
"name",
"=",
"getattr",
"(",
"node",
",",
"'name'",
",",
"None",
")",
"if",
"len",
"(",
"node",
".",
"args",
")",
"==",
"1",
":",
"arg_tuple",
"+=",
"','",
"self",
".",
"write",
"(",
"'Macro(environment, macro, %r, (%s), ('",
"%",
"(",
"name",
",",
"arg_tuple",
")",
")",
"for",
"arg",
"in",
"node",
".",
"defaults",
":",
"self",
".",
"visit",
"(",
"arg",
",",
"frame",
")",
"self",
".",
"write",
"(",
"', '",
")",
"self",
".",
"write",
"(",
"'), %r, %r, %r)'",
"%",
"(",
"bool",
"(",
"frame",
".",
"accesses_kwargs",
")",
",",
"bool",
"(",
"frame",
".",
"accesses_varargs",
")",
",",
"bool",
"(",
"frame",
".",
"accesses_caller",
")",
")",
")"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/compiler.py#L735-L750 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TNEANet.GetRndEI | (self, *args) | return _snap.TNEANet_GetRndEI(self, *args) | GetRndEI(TNEANet self, TRnd Rnd=Rnd) -> TNEANet::TEdgeI
Parameters:
Rnd: TRnd &
GetRndEI(TNEANet self) -> TNEANet::TEdgeI
Parameters:
self: TNEANet * | GetRndEI(TNEANet self, TRnd Rnd=Rnd) -> TNEANet::TEdgeI | [
"GetRndEI",
"(",
"TNEANet",
"self",
"TRnd",
"Rnd",
"=",
"Rnd",
")",
"-",
">",
"TNEANet",
"::",
"TEdgeI"
] | def GetRndEI(self, *args):
"""
GetRndEI(TNEANet self, TRnd Rnd=Rnd) -> TNEANet::TEdgeI
Parameters:
Rnd: TRnd &
GetRndEI(TNEANet self) -> TNEANet::TEdgeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndEI(self, *args) | [
"def",
"GetRndEI",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TNEANet_GetRndEI",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L21929-L21942 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/pstatbar.py | python | ProgressStatusBar.IsBusy | (self) | return self.timer.IsRunning() | Is the progress indicator busy or not
@return: bool | Is the progress indicator busy or not
@return: bool | [
"Is",
"the",
"progress",
"indicator",
"busy",
"or",
"not",
"@return",
":",
"bool"
] | def IsBusy(self):
"""Is the progress indicator busy or not
@return: bool
"""
return self.timer.IsRunning() | [
"def",
"IsBusy",
"(",
"self",
")",
":",
"return",
"self",
".",
"timer",
".",
"IsRunning",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/pstatbar.py#L157-L162 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_osx_support.py | python | _remove_unsupported_archs | (_config_vars) | return _config_vars | Remove any unsupported archs from config vars | Remove any unsupported archs from config vars | [
"Remove",
"any",
"unsupported",
"archs",
"from",
"config",
"vars"
] | def _remove_unsupported_archs(_config_vars):
"""Remove any unsupported archs from config vars"""
# Different Xcode releases support different sets for '-arch'
# flags. In particular, Xcode 4.x no longer supports the
# PPC architectures.
#
# This code automatically removes '-arch ppc' and '-arch ppc64'
# when these are not supported. That makes it possible to
# build extensions on OSX 10.7 and later with the prebuilt
# 32-bit installer on the python.org website.
# skip checks if the compiler was overridden with a CC env variable
if 'CC' in os.environ:
return _config_vars
if re.search(r'-arch\s+ppc', _config_vars['CFLAGS']) is not None:
# NOTE: Cannot use subprocess here because of bootstrap
# issues when building Python itself
status = os.system(
"""echo 'int main{};' | """
"""'%s' -c -arch ppc -x c -o /dev/null /dev/null 2>/dev/null"""
%(_config_vars['CC'].replace("'", "'\"'\"'"),))
if status:
# The compile failed for some reason. Because of differences
# across Xcode and compiler versions, there is no reliable way
# to be sure why it failed. Assume here it was due to lack of
# PPC support and remove the related '-arch' flags from each
# config variables not explicitly overridden by an environment
# variable. If the error was for some other reason, we hope the
# failure will show up again when trying to compile an extension
# module.
for cv in _UNIVERSAL_CONFIG_VARS:
if cv in _config_vars and cv not in os.environ:
flags = _config_vars[cv]
flags = re.sub(r'-arch\s+ppc\w*\s', ' ', flags)
_save_modified_value(_config_vars, cv, flags)
return _config_vars | [
"def",
"_remove_unsupported_archs",
"(",
"_config_vars",
")",
":",
"# Different Xcode releases support different sets for '-arch'",
"# flags. In particular, Xcode 4.x no longer supports the",
"# PPC architectures.",
"#",
"# This code automatically removes '-arch ppc' and '-arch ppc64'",
"# when these are not supported. That makes it possible to",
"# build extensions on OSX 10.7 and later with the prebuilt",
"# 32-bit installer on the python.org website.",
"# skip checks if the compiler was overridden with a CC env variable",
"if",
"'CC'",
"in",
"os",
".",
"environ",
":",
"return",
"_config_vars",
"if",
"re",
".",
"search",
"(",
"r'-arch\\s+ppc'",
",",
"_config_vars",
"[",
"'CFLAGS'",
"]",
")",
"is",
"not",
"None",
":",
"# NOTE: Cannot use subprocess here because of bootstrap",
"# issues when building Python itself",
"status",
"=",
"os",
".",
"system",
"(",
"\"\"\"echo 'int main{};' | \"\"\"",
"\"\"\"'%s' -c -arch ppc -x c -o /dev/null /dev/null 2>/dev/null\"\"\"",
"%",
"(",
"_config_vars",
"[",
"'CC'",
"]",
".",
"replace",
"(",
"\"'\"",
",",
"\"'\\\"'\\\"'\"",
")",
",",
")",
")",
"if",
"status",
":",
"# The compile failed for some reason. Because of differences",
"# across Xcode and compiler versions, there is no reliable way",
"# to be sure why it failed. Assume here it was due to lack of",
"# PPC support and remove the related '-arch' flags from each",
"# config variables not explicitly overridden by an environment",
"# variable. If the error was for some other reason, we hope the",
"# failure will show up again when trying to compile an extension",
"# module.",
"for",
"cv",
"in",
"_UNIVERSAL_CONFIG_VARS",
":",
"if",
"cv",
"in",
"_config_vars",
"and",
"cv",
"not",
"in",
"os",
".",
"environ",
":",
"flags",
"=",
"_config_vars",
"[",
"cv",
"]",
"flags",
"=",
"re",
".",
"sub",
"(",
"r'-arch\\s+ppc\\w*\\s'",
",",
"' '",
",",
"flags",
")",
"_save_modified_value",
"(",
"_config_vars",
",",
"cv",
",",
"flags",
")",
"return",
"_config_vars"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_osx_support.py#L220-L257 | |
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | build/fbcode_builder/getdeps/fetcher.py | python | copy_if_different | (src_name, dest_name) | return True | Copy src_name -> dest_name, but only touch dest_name
if src_name is different from dest_name, making this a
more build system friendly way to copy. | Copy src_name -> dest_name, but only touch dest_name
if src_name is different from dest_name, making this a
more build system friendly way to copy. | [
"Copy",
"src_name",
"-",
">",
"dest_name",
"but",
"only",
"touch",
"dest_name",
"if",
"src_name",
"is",
"different",
"from",
"dest_name",
"making",
"this",
"a",
"more",
"build",
"system",
"friendly",
"way",
"to",
"copy",
"."
] | def copy_if_different(src_name, dest_name):
"""Copy src_name -> dest_name, but only touch dest_name
if src_name is different from dest_name, making this a
more build system friendly way to copy."""
src_st = os.lstat(src_name)
if not does_file_need_update(src_name, src_st, dest_name):
return False
dest_parent = os.path.dirname(dest_name)
if not os.path.exists(dest_parent):
os.makedirs(dest_parent)
if stat.S_ISLNK(src_st.st_mode):
try:
os.unlink(dest_name)
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
target = os.readlink(src_name)
print("Symlinking %s -> %s" % (dest_name, target))
os.symlink(target, dest_name)
else:
print("Copying %s -> %s" % (src_name, dest_name))
shutil.copy2(src_name, dest_name)
return True | [
"def",
"copy_if_different",
"(",
"src_name",
",",
"dest_name",
")",
":",
"src_st",
"=",
"os",
".",
"lstat",
"(",
"src_name",
")",
"if",
"not",
"does_file_need_update",
"(",
"src_name",
",",
"src_st",
",",
"dest_name",
")",
":",
"return",
"False",
"dest_parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dest_name",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest_parent",
")",
":",
"os",
".",
"makedirs",
"(",
"dest_parent",
")",
"if",
"stat",
".",
"S_ISLNK",
"(",
"src_st",
".",
"st_mode",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"dest_name",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"target",
"=",
"os",
".",
"readlink",
"(",
"src_name",
")",
"print",
"(",
"\"Symlinking %s -> %s\"",
"%",
"(",
"dest_name",
",",
"target",
")",
")",
"os",
".",
"symlink",
"(",
"target",
",",
"dest_name",
")",
"else",
":",
"print",
"(",
"\"Copying %s -> %s\"",
"%",
"(",
"src_name",
",",
"dest_name",
")",
")",
"shutil",
".",
"copy2",
"(",
"src_name",
",",
"dest_name",
")",
"return",
"True"
] | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/build/fbcode_builder/getdeps/fetcher.py#L359-L383 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py | python | AddOdDialog.refresh_browser | (self) | Deletes previous conents
Builds panel for obj
Updates path window and history | Deletes previous conents
Builds panel for obj
Updates path window and history | [
"Deletes",
"previous",
"conents",
"Builds",
"panel",
"for",
"obj",
"Updates",
"path",
"window",
"and",
"history"
] | def refresh_browser(self):
"""
Deletes previous conents
Builds panel for obj
Updates path window and history
"""
# print 'Wizzard.refresh_panel with',obj.ident
# remove previous obj panel
sizer = self.GetSizer()
sizer.Remove(0)
self.browser.Destroy()
#del self.browser
self.browser = self.make_browser()
sizer.Add(self.browser, 1, wx.GROW)
self.Refresh()
# sizer.Fit(self)
sizer.Layout() | [
"def",
"refresh_browser",
"(",
"self",
")",
":",
"# print 'Wizzard.refresh_panel with',obj.ident",
"# remove previous obj panel",
"sizer",
"=",
"self",
".",
"GetSizer",
"(",
")",
"sizer",
".",
"Remove",
"(",
"0",
")",
"self",
".",
"browser",
".",
"Destroy",
"(",
")",
"#del self.browser",
"self",
".",
"browser",
"=",
"self",
".",
"make_browser",
"(",
")",
"sizer",
".",
"Add",
"(",
"self",
".",
"browser",
",",
"1",
",",
"wx",
".",
"GROW",
")",
"self",
".",
"Refresh",
"(",
")",
"# sizer.Fit(self)",
"sizer",
".",
"Layout",
"(",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py#L848-L866 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py#L767-L769 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/collections.py | python | Counter.__add__ | (self, other) | return result | Add counts from two counters.
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1}) | Add counts from two counters. | [
"Add",
"counts",
"from",
"two",
"counters",
"."
] | def __add__(self, other):
'''Add counts from two counters.
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count + other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Counter",
")",
":",
"return",
"NotImplemented",
"result",
"=",
"Counter",
"(",
")",
"for",
"elem",
",",
"count",
"in",
"self",
".",
"items",
"(",
")",
":",
"newcount",
"=",
"count",
"+",
"other",
"[",
"elem",
"]",
"if",
"newcount",
">",
"0",
":",
"result",
"[",
"elem",
"]",
"=",
"newcount",
"for",
"elem",
",",
"count",
"in",
"other",
".",
"items",
"(",
")",
":",
"if",
"elem",
"not",
"in",
"self",
"and",
"count",
">",
"0",
":",
"result",
"[",
"elem",
"]",
"=",
"count",
"return",
"result"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/collections.py#L584-L601 | |
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/input.py | python | DependencyGraphNode.DirectDependencies | (self, dependencies=None) | return dependencies | Returns a list of just direct dependencies. | Returns a list of just direct dependencies. | [
"Returns",
"a",
"list",
"of",
"just",
"direct",
"dependencies",
"."
] | def DirectDependencies(self, dependencies=None):
"""Returns a list of just direct dependencies."""
if dependencies == None:
dependencies = []
for dependency in self.dependencies:
# Check for None, corresponding to the root node.
if dependency.ref != None and dependency.ref not in dependencies:
dependencies.append(dependency.ref)
return dependencies | [
"def",
"DirectDependencies",
"(",
"self",
",",
"dependencies",
"=",
"None",
")",
":",
"if",
"dependencies",
"==",
"None",
":",
"dependencies",
"=",
"[",
"]",
"for",
"dependency",
"in",
"self",
".",
"dependencies",
":",
"# Check for None, corresponding to the root node.",
"if",
"dependency",
".",
"ref",
"!=",
"None",
"and",
"dependency",
".",
"ref",
"not",
"in",
"dependencies",
":",
"dependencies",
".",
"append",
"(",
"dependency",
".",
"ref",
")",
"return",
"dependencies"
] | 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/input.py#L1600-L1610 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/clang/cindex.py | python | SourceLocation.file | (self) | return self._get_instantiation()[0] | Get the file represented by this source location. | Get the file represented by this source location. | [
"Get",
"the",
"file",
"represented",
"by",
"this",
"source",
"location",
"."
] | def file(self):
"""Get the file represented by this source location."""
return self._get_instantiation()[0] | [
"def",
"file",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_instantiation",
"(",
")",
"[",
"0",
"]"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/clang/cindex.py#L119-L121 | |
RobotLocomotion/drake | 0e18a34604c45ed65bc9018a54f7610f91cdad5b | tools/workspace/pybind11/mkdoc.py | python | print_symbols | (f, name, node, level=0, *, tree_parser_doc,
tree_parser_xpath, ignore_dirs_for_coverage) | Prints C++ code for relevant documentation. | Prints C++ code for relevant documentation. | [
"Prints",
"C",
"++",
"code",
"for",
"relevant",
"documentation",
"."
] | def print_symbols(f, name, node, level=0, *, tree_parser_doc,
tree_parser_xpath, ignore_dirs_for_coverage):
"""
Prints C++ code for relevant documentation.
"""
indent = ' ' * level
def iprint(s):
f.write((indent + s).rstrip() + "\n")
name_var = name
if not node.first_symbol:
assert level == 0, name_var
full_name = name
else:
name_chain = node.first_symbol.name_chain
assert name == name_chain[-1]
full_name = "::".join(name_chain)
# Override variable.
if node.first_symbol.cursor.kind == CursorKind.CONSTRUCTOR:
name_var = "ctor"
name_var = sanitize_name(name_var)
# We may get empty symbols if `libclang` produces warnings.
assert len(name_var) > 0, node.first_symbol.sorting_key()
iprint('// Symbol: {}'.format(full_name))
modifier = ""
if level == 0:
modifier = "constexpr "
iprint('{}struct /* {} */ {{'.format(modifier, name_var))
root = tree_parser_xpath[-1]
kind = node.first_symbol.cursor.kind if node.first_symbol else None
tree_parser_doc.append(name_var)
new_ele = None
# Print documentation items.
symbol_iter = sorted(node.doc_symbols, key=Symbol.sorting_key)
doc_vars = choose_doc_var_names(symbol_iter)
# New element in the XML tree.
new_ele = None
for symbol, doc_var in zip(symbol_iter, doc_vars):
if doc_var is None:
continue
assert name_chain == symbol.name_chain
comment = re.sub(
r'@pydrake_mkdoc[a-z_]*\{.*\}', '',
symbol.comment)
delim = "\n"
if "\n" not in comment and len(comment) < 40:
delim = " "
iprint(' // Source: {}:{}'.format(symbol.include, symbol.line))
iprint(' const char* {} ={}R"""({})""";'.format(
doc_var, delim, comment.strip()))
tree_doc_var = ".".join(tree_parser_doc + [doc_var])
ignore_xpath = False
if ignore_dirs_for_coverage:
ignore_xpath = symbol.include.startswith(ignore_dirs_for_coverage)
new_ele = ET.SubElement(root, "Node", {
"kind": str(kind),
"name": name_var,
"full_name": full_name,
"ignore": str(int(ignore_xpath)),
"doc_var": tree_doc_var,
"file_name": symbol.include,
})
# If the node has no doc_var's
if new_ele is None:
new_ele = ET.SubElement(root, "Node", {
"kind": str(kind),
"name": name_var,
"full_name": full_name,
"ignore": "",
"doc_var": "",
"file_name": "",
})
tree_parser_xpath.append(new_ele)
# Recurse into child elements.
keys = sorted(node.children_map.keys())
for key in keys:
child = node.children_map[key]
tree_parser_args = {
"tree_parser_doc": tree_parser_doc,
"tree_parser_xpath": tree_parser_xpath,
"ignore_dirs_for_coverage": ignore_dirs_for_coverage
}
print_symbols(f, key, child, level=level + 1, **tree_parser_args)
iprint('}} {};'.format(name_var))
tree_parser_doc.pop()
tree_parser_xpath.pop() | [
"def",
"print_symbols",
"(",
"f",
",",
"name",
",",
"node",
",",
"level",
"=",
"0",
",",
"*",
",",
"tree_parser_doc",
",",
"tree_parser_xpath",
",",
"ignore_dirs_for_coverage",
")",
":",
"indent",
"=",
"' '",
"*",
"level",
"def",
"iprint",
"(",
"s",
")",
":",
"f",
".",
"write",
"(",
"(",
"indent",
"+",
"s",
")",
".",
"rstrip",
"(",
")",
"+",
"\"\\n\"",
")",
"name_var",
"=",
"name",
"if",
"not",
"node",
".",
"first_symbol",
":",
"assert",
"level",
"==",
"0",
",",
"name_var",
"full_name",
"=",
"name",
"else",
":",
"name_chain",
"=",
"node",
".",
"first_symbol",
".",
"name_chain",
"assert",
"name",
"==",
"name_chain",
"[",
"-",
"1",
"]",
"full_name",
"=",
"\"::\"",
".",
"join",
"(",
"name_chain",
")",
"# Override variable.",
"if",
"node",
".",
"first_symbol",
".",
"cursor",
".",
"kind",
"==",
"CursorKind",
".",
"CONSTRUCTOR",
":",
"name_var",
"=",
"\"ctor\"",
"name_var",
"=",
"sanitize_name",
"(",
"name_var",
")",
"# We may get empty symbols if `libclang` produces warnings.",
"assert",
"len",
"(",
"name_var",
")",
">",
"0",
",",
"node",
".",
"first_symbol",
".",
"sorting_key",
"(",
")",
"iprint",
"(",
"'// Symbol: {}'",
".",
"format",
"(",
"full_name",
")",
")",
"modifier",
"=",
"\"\"",
"if",
"level",
"==",
"0",
":",
"modifier",
"=",
"\"constexpr \"",
"iprint",
"(",
"'{}struct /* {} */ {{'",
".",
"format",
"(",
"modifier",
",",
"name_var",
")",
")",
"root",
"=",
"tree_parser_xpath",
"[",
"-",
"1",
"]",
"kind",
"=",
"node",
".",
"first_symbol",
".",
"cursor",
".",
"kind",
"if",
"node",
".",
"first_symbol",
"else",
"None",
"tree_parser_doc",
".",
"append",
"(",
"name_var",
")",
"new_ele",
"=",
"None",
"# Print documentation items.",
"symbol_iter",
"=",
"sorted",
"(",
"node",
".",
"doc_symbols",
",",
"key",
"=",
"Symbol",
".",
"sorting_key",
")",
"doc_vars",
"=",
"choose_doc_var_names",
"(",
"symbol_iter",
")",
"# New element in the XML tree.",
"new_ele",
"=",
"None",
"for",
"symbol",
",",
"doc_var",
"in",
"zip",
"(",
"symbol_iter",
",",
"doc_vars",
")",
":",
"if",
"doc_var",
"is",
"None",
":",
"continue",
"assert",
"name_chain",
"==",
"symbol",
".",
"name_chain",
"comment",
"=",
"re",
".",
"sub",
"(",
"r'@pydrake_mkdoc[a-z_]*\\{.*\\}'",
",",
"''",
",",
"symbol",
".",
"comment",
")",
"delim",
"=",
"\"\\n\"",
"if",
"\"\\n\"",
"not",
"in",
"comment",
"and",
"len",
"(",
"comment",
")",
"<",
"40",
":",
"delim",
"=",
"\" \"",
"iprint",
"(",
"' // Source: {}:{}'",
".",
"format",
"(",
"symbol",
".",
"include",
",",
"symbol",
".",
"line",
")",
")",
"iprint",
"(",
"' const char* {} ={}R\"\"\"({})\"\"\";'",
".",
"format",
"(",
"doc_var",
",",
"delim",
",",
"comment",
".",
"strip",
"(",
")",
")",
")",
"tree_doc_var",
"=",
"\".\"",
".",
"join",
"(",
"tree_parser_doc",
"+",
"[",
"doc_var",
"]",
")",
"ignore_xpath",
"=",
"False",
"if",
"ignore_dirs_for_coverage",
":",
"ignore_xpath",
"=",
"symbol",
".",
"include",
".",
"startswith",
"(",
"ignore_dirs_for_coverage",
")",
"new_ele",
"=",
"ET",
".",
"SubElement",
"(",
"root",
",",
"\"Node\"",
",",
"{",
"\"kind\"",
":",
"str",
"(",
"kind",
")",
",",
"\"name\"",
":",
"name_var",
",",
"\"full_name\"",
":",
"full_name",
",",
"\"ignore\"",
":",
"str",
"(",
"int",
"(",
"ignore_xpath",
")",
")",
",",
"\"doc_var\"",
":",
"tree_doc_var",
",",
"\"file_name\"",
":",
"symbol",
".",
"include",
",",
"}",
")",
"# If the node has no doc_var's",
"if",
"new_ele",
"is",
"None",
":",
"new_ele",
"=",
"ET",
".",
"SubElement",
"(",
"root",
",",
"\"Node\"",
",",
"{",
"\"kind\"",
":",
"str",
"(",
"kind",
")",
",",
"\"name\"",
":",
"name_var",
",",
"\"full_name\"",
":",
"full_name",
",",
"\"ignore\"",
":",
"\"\"",
",",
"\"doc_var\"",
":",
"\"\"",
",",
"\"file_name\"",
":",
"\"\"",
",",
"}",
")",
"tree_parser_xpath",
".",
"append",
"(",
"new_ele",
")",
"# Recurse into child elements.",
"keys",
"=",
"sorted",
"(",
"node",
".",
"children_map",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"keys",
":",
"child",
"=",
"node",
".",
"children_map",
"[",
"key",
"]",
"tree_parser_args",
"=",
"{",
"\"tree_parser_doc\"",
":",
"tree_parser_doc",
",",
"\"tree_parser_xpath\"",
":",
"tree_parser_xpath",
",",
"\"ignore_dirs_for_coverage\"",
":",
"ignore_dirs_for_coverage",
"}",
"print_symbols",
"(",
"f",
",",
"key",
",",
"child",
",",
"level",
"=",
"level",
"+",
"1",
",",
"*",
"*",
"tree_parser_args",
")",
"iprint",
"(",
"'}} {};'",
".",
"format",
"(",
"name_var",
")",
")",
"tree_parser_doc",
".",
"pop",
"(",
")",
"tree_parser_xpath",
".",
"pop",
"(",
")"
] | https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/tools/workspace/pybind11/mkdoc.py#L541-L637 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py | python | _ShardedMutableHashTable.values_reduce_sum | (self, name=None) | return math_ops.add_n(sums) | Computes reduce_sum reducing dimension 0 across all values in all shards.
Args:
name: A name for the operation (optional).
Returns:
A tensor with the sum across all values in the same shape as the table's
value shape. | Computes reduce_sum reducing dimension 0 across all values in all shards. | [
"Computes",
"reduce_sum",
"reducing",
"dimension",
"0",
"across",
"all",
"values",
"in",
"all",
"shards",
"."
] | def values_reduce_sum(self, name=None):
"""Computes reduce_sum reducing dimension 0 across all values in all shards.
Args:
name: A name for the operation (optional).
Returns:
A tensor with the sum across all values in the same shape as the table's
value shape.
"""
# TODO(andreasst): consider replacing with something like export_sharded
# and doing the sum in SdcaModel.
sums = []
for table_shard in self._table_shards:
_, exported_values = table_shard.export(name=name)
sums.append(math_ops.reduce_sum(exported_values, 0))
return math_ops.add_n(sums) | [
"def",
"values_reduce_sum",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"# TODO(andreasst): consider replacing with something like export_sharded",
"# and doing the sum in SdcaModel.",
"sums",
"=",
"[",
"]",
"for",
"table_shard",
"in",
"self",
".",
"_table_shards",
":",
"_",
",",
"exported_values",
"=",
"table_shard",
".",
"export",
"(",
"name",
"=",
"name",
")",
"sums",
".",
"append",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"exported_values",
",",
"0",
")",
")",
"return",
"math_ops",
".",
"add_n",
"(",
"sums",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py#L154-L170 | |
mgbellemare/Arcade-Learning-Environment | 0af0ff4a49a981d113c67b866fa152dbc7a1c0a7 | src/gym/envs/atari/environment.py | python | AtariEnv.__init__ | (
self,
game: str = "pong",
mode: Optional[int] = None,
difficulty: Optional[int] = None,
obs_type: str = "rgb",
frameskip: Union[Tuple[int, int], int] = 5,
repeat_action_probability: float = 0.25,
full_action_space: bool = True,
render_mode: str = None,
) | Initialize the ALE for Gym.
Default parameters are taken from Machado et al., 2018.
Args:
game: str => Game to initialize env with.
mode: Optional[int] => Game mode, see Machado et al., 2018
difficulty: Optional[int] => Game difficulty,see Machado et al., 2018
obs_type: str => Observation type in { 'rgb', 'grayscale', 'ram' }
frameskip: Union[Tuple[int, int], int] =>
Stochastic frameskip as tuple or fixed.
repeat_action_probability: int =>
Probability to repeat actions, see Machado et al., 2018
full_action_space: bool => Use full action space?
render_mode: str => One of { 'human', 'rgb_array' }.
If `human` we'll interactively display the screen and enable
game sounds. This will lock emulation to the ROMs specified FPS
If `rgb_array` we'll return the `rgb` key in step metadata with
the current environment RGB frame.
Note:
- The game must be installed, see ale-import-roms, or ale-py-roms.
- Frameskip values of (low, high) will enable stochastic frame skip
which will sample a random frameskip uniformly each action.
- It is recommended to enable full action space.
See Machado et al., 2018 for more details.
References:
`Revisiting the Arcade Learning Environment: Evaluation Protocols
and Open Problems for General Agents`, Machado et al., 2018, JAIR
URL: https://jair.org/index.php/jair/article/view/11182 | Initialize the ALE for Gym.
Default parameters are taken from Machado et al., 2018. | [
"Initialize",
"the",
"ALE",
"for",
"Gym",
".",
"Default",
"parameters",
"are",
"taken",
"from",
"Machado",
"et",
"al",
".",
"2018",
"."
] | def __init__(
self,
game: str = "pong",
mode: Optional[int] = None,
difficulty: Optional[int] = None,
obs_type: str = "rgb",
frameskip: Union[Tuple[int, int], int] = 5,
repeat_action_probability: float = 0.25,
full_action_space: bool = True,
render_mode: str = None,
) -> None:
"""
Initialize the ALE for Gym.
Default parameters are taken from Machado et al., 2018.
Args:
game: str => Game to initialize env with.
mode: Optional[int] => Game mode, see Machado et al., 2018
difficulty: Optional[int] => Game difficulty,see Machado et al., 2018
obs_type: str => Observation type in { 'rgb', 'grayscale', 'ram' }
frameskip: Union[Tuple[int, int], int] =>
Stochastic frameskip as tuple or fixed.
repeat_action_probability: int =>
Probability to repeat actions, see Machado et al., 2018
full_action_space: bool => Use full action space?
render_mode: str => One of { 'human', 'rgb_array' }.
If `human` we'll interactively display the screen and enable
game sounds. This will lock emulation to the ROMs specified FPS
If `rgb_array` we'll return the `rgb` key in step metadata with
the current environment RGB frame.
Note:
- The game must be installed, see ale-import-roms, or ale-py-roms.
- Frameskip values of (low, high) will enable stochastic frame skip
which will sample a random frameskip uniformly each action.
- It is recommended to enable full action space.
See Machado et al., 2018 for more details.
References:
`Revisiting the Arcade Learning Environment: Evaluation Protocols
and Open Problems for General Agents`, Machado et al., 2018, JAIR
URL: https://jair.org/index.php/jair/article/view/11182
"""
if obs_type == "image":
logger.warn(
'obs_type "image" should be replaced with the image type, one of: rgb, grayscale'
)
obs_type = "rgb"
if obs_type not in {"rgb", "grayscale", "ram"}:
raise error.Error(
f"Invalid observation type: {obs_type}. Expecting: rgb, grayscale, ram."
)
if not (
isinstance(frameskip, int)
or (isinstance(frameskip, tuple) and len(frameskip) == 2)
):
raise error.Error(f"Invalid frameskip type: {frameskip}")
if render_mode is not None and render_mode not in {"rgb_array", "human"}:
raise error.Error(
f"Render mode {render_mode} not supported (rgb_array, human)."
)
utils.EzPickle.__init__(
self,
game,
mode,
difficulty,
obs_type,
frameskip,
repeat_action_probability,
full_action_space,
render_mode,
)
# Initialize ALE
self.ale = ALEInterface()
self.viewer = None
self._game = rom_id_to_name(game)
self._game_mode = mode
self._game_difficulty = difficulty
self._frameskip = frameskip
self._obs_type = obs_type
self._render_mode = render_mode
# Set logger mode to error only
self.ale.setLoggerMode(LoggerMode.Error)
# Config sticky action prob.
self.ale.setFloat("repeat_action_probability", repeat_action_probability)
# If render mode is human we can display screen and sound
if render_mode == "human":
self.ale.setBool("display_screen", True)
self.ale.setBool("sound", True)
# Seed + Load
self.seed()
self._action_set = (
self.ale.getLegalActionSet()
if full_action_space
else self.ale.getMinimalActionSet()
)
self._action_space = spaces.Discrete(len(self._action_set))
# Initialize observation type
if self._obs_type == "ram":
self._obs_space = spaces.Box(
low=0, high=255, dtype=np.uint8, shape=(self.ale.getRAMSize(),)
)
elif self._obs_type == "rgb" or self._obs_type == "grayscale":
(screen_height, screen_width) = self.ale.getScreenDims()
image_shape = (
screen_height,
screen_width,
)
if self._obs_type == "rgb":
image_shape += (3,)
self._obs_space = spaces.Box(
low=0, high=255, dtype=np.uint8, shape=image_shape
)
else:
raise error.Error(f"Unrecognized observation type: {self._obs_type}") | [
"def",
"__init__",
"(",
"self",
",",
"game",
":",
"str",
"=",
"\"pong\"",
",",
"mode",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"difficulty",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"obs_type",
":",
"str",
"=",
"\"rgb\"",
",",
"frameskip",
":",
"Union",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
",",
"int",
"]",
"=",
"5",
",",
"repeat_action_probability",
":",
"float",
"=",
"0.25",
",",
"full_action_space",
":",
"bool",
"=",
"True",
",",
"render_mode",
":",
"str",
"=",
"None",
",",
")",
"->",
"None",
":",
"if",
"obs_type",
"==",
"\"image\"",
":",
"logger",
".",
"warn",
"(",
"'obs_type \"image\" should be replaced with the image type, one of: rgb, grayscale'",
")",
"obs_type",
"=",
"\"rgb\"",
"if",
"obs_type",
"not",
"in",
"{",
"\"rgb\"",
",",
"\"grayscale\"",
",",
"\"ram\"",
"}",
":",
"raise",
"error",
".",
"Error",
"(",
"f\"Invalid observation type: {obs_type}. Expecting: rgb, grayscale, ram.\"",
")",
"if",
"not",
"(",
"isinstance",
"(",
"frameskip",
",",
"int",
")",
"or",
"(",
"isinstance",
"(",
"frameskip",
",",
"tuple",
")",
"and",
"len",
"(",
"frameskip",
")",
"==",
"2",
")",
")",
":",
"raise",
"error",
".",
"Error",
"(",
"f\"Invalid frameskip type: {frameskip}\"",
")",
"if",
"render_mode",
"is",
"not",
"None",
"and",
"render_mode",
"not",
"in",
"{",
"\"rgb_array\"",
",",
"\"human\"",
"}",
":",
"raise",
"error",
".",
"Error",
"(",
"f\"Render mode {render_mode} not supported (rgb_array, human).\"",
")",
"utils",
".",
"EzPickle",
".",
"__init__",
"(",
"self",
",",
"game",
",",
"mode",
",",
"difficulty",
",",
"obs_type",
",",
"frameskip",
",",
"repeat_action_probability",
",",
"full_action_space",
",",
"render_mode",
",",
")",
"# Initialize ALE",
"self",
".",
"ale",
"=",
"ALEInterface",
"(",
")",
"self",
".",
"viewer",
"=",
"None",
"self",
".",
"_game",
"=",
"rom_id_to_name",
"(",
"game",
")",
"self",
".",
"_game_mode",
"=",
"mode",
"self",
".",
"_game_difficulty",
"=",
"difficulty",
"self",
".",
"_frameskip",
"=",
"frameskip",
"self",
".",
"_obs_type",
"=",
"obs_type",
"self",
".",
"_render_mode",
"=",
"render_mode",
"# Set logger mode to error only",
"self",
".",
"ale",
".",
"setLoggerMode",
"(",
"LoggerMode",
".",
"Error",
")",
"# Config sticky action prob.",
"self",
".",
"ale",
".",
"setFloat",
"(",
"\"repeat_action_probability\"",
",",
"repeat_action_probability",
")",
"# If render mode is human we can display screen and sound",
"if",
"render_mode",
"==",
"\"human\"",
":",
"self",
".",
"ale",
".",
"setBool",
"(",
"\"display_screen\"",
",",
"True",
")",
"self",
".",
"ale",
".",
"setBool",
"(",
"\"sound\"",
",",
"True",
")",
"# Seed + Load",
"self",
".",
"seed",
"(",
")",
"self",
".",
"_action_set",
"=",
"(",
"self",
".",
"ale",
".",
"getLegalActionSet",
"(",
")",
"if",
"full_action_space",
"else",
"self",
".",
"ale",
".",
"getMinimalActionSet",
"(",
")",
")",
"self",
".",
"_action_space",
"=",
"spaces",
".",
"Discrete",
"(",
"len",
"(",
"self",
".",
"_action_set",
")",
")",
"# Initialize observation type",
"if",
"self",
".",
"_obs_type",
"==",
"\"ram\"",
":",
"self",
".",
"_obs_space",
"=",
"spaces",
".",
"Box",
"(",
"low",
"=",
"0",
",",
"high",
"=",
"255",
",",
"dtype",
"=",
"np",
".",
"uint8",
",",
"shape",
"=",
"(",
"self",
".",
"ale",
".",
"getRAMSize",
"(",
")",
",",
")",
")",
"elif",
"self",
".",
"_obs_type",
"==",
"\"rgb\"",
"or",
"self",
".",
"_obs_type",
"==",
"\"grayscale\"",
":",
"(",
"screen_height",
",",
"screen_width",
")",
"=",
"self",
".",
"ale",
".",
"getScreenDims",
"(",
")",
"image_shape",
"=",
"(",
"screen_height",
",",
"screen_width",
",",
")",
"if",
"self",
".",
"_obs_type",
"==",
"\"rgb\"",
":",
"image_shape",
"+=",
"(",
"3",
",",
")",
"self",
".",
"_obs_space",
"=",
"spaces",
".",
"Box",
"(",
"low",
"=",
"0",
",",
"high",
"=",
"255",
",",
"dtype",
"=",
"np",
".",
"uint8",
",",
"shape",
"=",
"image_shape",
")",
"else",
":",
"raise",
"error",
".",
"Error",
"(",
"f\"Unrecognized observation type: {self._obs_type}\"",
")"
] | https://github.com/mgbellemare/Arcade-Learning-Environment/blob/0af0ff4a49a981d113c67b866fa152dbc7a1c0a7/src/gym/envs/atari/environment.py#L25-L149 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/suncxx.py | python | sxx_common_flags | (conf) | Flags required for executing the sun C++ compiler | Flags required for executing the sun C++ compiler | [
"Flags",
"required",
"for",
"executing",
"the",
"sun",
"C",
"++",
"compiler"
] | def sxx_common_flags(conf):
"""
Flags required for executing the sun C++ compiler
"""
v = conf.env
v['CXX_SRC_F'] = []
v['CXX_TGT_F'] = ['-c', '-o']
# linker
if not v['LINK_CXX']: v['LINK_CXX'] = v['CXX']
v['CXXLNK_SRC_F'] = []
v['CXXLNK_TGT_F'] = ['-o']
v['CPPPATH_ST'] = '-I%s'
v['DEFINES_ST'] = '-D%s'
v['LIB_ST'] = '-l%s' # template for adding libs
v['LIBPATH_ST'] = '-L%s' # template for adding libpaths
v['STLIB_ST'] = '-l%s'
v['STLIBPATH_ST'] = '-L%s'
v['SONAME_ST'] = '-Wl,-h,%s'
v['SHLIB_MARKER'] = '-Bdynamic'
v['STLIB_MARKER'] = '-Bstatic'
# program
v['cxxprogram_PATTERN'] = '%s'
# shared library
v['CXXFLAGS_cxxshlib'] = ['-Kpic', '-DPIC']
v['LINKFLAGS_cxxshlib'] = ['-G']
v['cxxshlib_PATTERN'] = 'lib%s.so'
# static lib
v['LINKFLAGS_cxxstlib'] = ['-Bstatic']
v['cxxstlib_PATTERN'] = 'lib%s.a' | [
"def",
"sxx_common_flags",
"(",
"conf",
")",
":",
"v",
"=",
"conf",
".",
"env",
"v",
"[",
"'CXX_SRC_F'",
"]",
"=",
"[",
"]",
"v",
"[",
"'CXX_TGT_F'",
"]",
"=",
"[",
"'-c'",
",",
"'-o'",
"]",
"# linker",
"if",
"not",
"v",
"[",
"'LINK_CXX'",
"]",
":",
"v",
"[",
"'LINK_CXX'",
"]",
"=",
"v",
"[",
"'CXX'",
"]",
"v",
"[",
"'CXXLNK_SRC_F'",
"]",
"=",
"[",
"]",
"v",
"[",
"'CXXLNK_TGT_F'",
"]",
"=",
"[",
"'-o'",
"]",
"v",
"[",
"'CPPPATH_ST'",
"]",
"=",
"'-I%s'",
"v",
"[",
"'DEFINES_ST'",
"]",
"=",
"'-D%s'",
"v",
"[",
"'LIB_ST'",
"]",
"=",
"'-l%s'",
"# template for adding libs",
"v",
"[",
"'LIBPATH_ST'",
"]",
"=",
"'-L%s'",
"# template for adding libpaths",
"v",
"[",
"'STLIB_ST'",
"]",
"=",
"'-l%s'",
"v",
"[",
"'STLIBPATH_ST'",
"]",
"=",
"'-L%s'",
"v",
"[",
"'SONAME_ST'",
"]",
"=",
"'-Wl,-h,%s'",
"v",
"[",
"'SHLIB_MARKER'",
"]",
"=",
"'-Bdynamic'",
"v",
"[",
"'STLIB_MARKER'",
"]",
"=",
"'-Bstatic'",
"# program",
"v",
"[",
"'cxxprogram_PATTERN'",
"]",
"=",
"'%s'",
"# shared library",
"v",
"[",
"'CXXFLAGS_cxxshlib'",
"]",
"=",
"[",
"'-Kpic'",
",",
"'-DPIC'",
"]",
"v",
"[",
"'LINKFLAGS_cxxshlib'",
"]",
"=",
"[",
"'-G'",
"]",
"v",
"[",
"'cxxshlib_PATTERN'",
"]",
"=",
"'lib%s.so'",
"# static lib",
"v",
"[",
"'LINKFLAGS_cxxstlib'",
"]",
"=",
"[",
"'-Bstatic'",
"]",
"v",
"[",
"'cxxstlib_PATTERN'",
"]",
"=",
"'lib%s.a'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/suncxx.py#L36-L71 | ||
google/angle | d5df233189cad620b8e0de653fe5e6cb778e209d | third_party/logdog/logdog/stream.py | python | StreamClient.project | (self) | return self._project | Returns (str or None): The stream project, or None if not configured. | Returns (str or None): The stream project, or None if not configured. | [
"Returns",
"(",
"str",
"or",
"None",
")",
":",
"The",
"stream",
"project",
"or",
"None",
"if",
"not",
"configured",
"."
] | def project(self):
"""Returns (str or None): The stream project, or None if not configured."""
return self._project | [
"def",
"project",
"(",
"self",
")",
":",
"return",
"self",
".",
"_project"
] | https://github.com/google/angle/blob/d5df233189cad620b8e0de653fe5e6cb778e209d/third_party/logdog/logdog/stream.py#L253-L255 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | RadioBox.IsItemShown | (*args, **kwargs) | return _controls_.RadioBox_IsItemShown(*args, **kwargs) | IsItemShown(self, unsigned int n) -> bool | IsItemShown(self, unsigned int n) -> bool | [
"IsItemShown",
"(",
"self",
"unsigned",
"int",
"n",
")",
"-",
">",
"bool"
] | def IsItemShown(*args, **kwargs):
"""IsItemShown(self, unsigned int n) -> bool"""
return _controls_.RadioBox_IsItemShown(*args, **kwargs) | [
"def",
"IsItemShown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"RadioBox_IsItemShown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L2641-L2643 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/uuid.py | python | getnode | () | Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122. | Get the hardware address as a 48-bit positive integer. | [
"Get",
"the",
"hardware",
"address",
"as",
"a",
"48",
"-",
"bit",
"positive",
"integer",
"."
] | def getnode():
"""Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122.
"""
global _node
if _node is not None:
return _node
import sys
if sys.platform == 'win32':
getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode]
else:
getters = [_unixdll_getnode, _ifconfig_getnode]
for getter in getters + [_random_getnode]:
try:
_node = getter()
except:
continue
if _node is not None:
return _node | [
"def",
"getnode",
"(",
")",
":",
"global",
"_node",
"if",
"_node",
"is",
"not",
"None",
":",
"return",
"_node",
"import",
"sys",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"getters",
"=",
"[",
"_windll_getnode",
",",
"_netbios_getnode",
",",
"_ipconfig_getnode",
"]",
"else",
":",
"getters",
"=",
"[",
"_unixdll_getnode",
",",
"_ifconfig_getnode",
"]",
"for",
"getter",
"in",
"getters",
"+",
"[",
"_random_getnode",
"]",
":",
"try",
":",
"_node",
"=",
"getter",
"(",
")",
"except",
":",
"continue",
"if",
"_node",
"is",
"not",
"None",
":",
"return",
"_node"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/uuid.py#L461-L486 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/copy.py | python | copy | (x) | return _reconstruct(x, rv, 0) | Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info. | Shallow copy operation on arbitrary Python objects. | [
"Shallow",
"copy",
"operation",
"on",
"arbitrary",
"Python",
"objects",
"."
] | def copy(x):
"""Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
cls = type(x)
copier = _copy_dispatch.get(cls)
if copier:
return copier(x)
copier = getattr(cls, "__copy__", None)
if copier:
return copier(x)
reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor:
rv = reductor(2)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
raise Error("un(shallow)copyable object of type %s" % cls)
return _reconstruct(x, rv, 0) | [
"def",
"copy",
"(",
"x",
")",
":",
"cls",
"=",
"type",
"(",
"x",
")",
"copier",
"=",
"_copy_dispatch",
".",
"get",
"(",
"cls",
")",
"if",
"copier",
":",
"return",
"copier",
"(",
"x",
")",
"copier",
"=",
"getattr",
"(",
"cls",
",",
"\"__copy__\"",
",",
"None",
")",
"if",
"copier",
":",
"return",
"copier",
"(",
"x",
")",
"reductor",
"=",
"dispatch_table",
".",
"get",
"(",
"cls",
")",
"if",
"reductor",
":",
"rv",
"=",
"reductor",
"(",
"x",
")",
"else",
":",
"reductor",
"=",
"getattr",
"(",
"x",
",",
"\"__reduce_ex__\"",
",",
"None",
")",
"if",
"reductor",
":",
"rv",
"=",
"reductor",
"(",
"2",
")",
"else",
":",
"reductor",
"=",
"getattr",
"(",
"x",
",",
"\"__reduce__\"",
",",
"None",
")",
"if",
"reductor",
":",
"rv",
"=",
"reductor",
"(",
")",
"else",
":",
"raise",
"Error",
"(",
"\"un(shallow)copyable object of type %s\"",
"%",
"cls",
")",
"return",
"_reconstruct",
"(",
"x",
",",
"rv",
",",
"0",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/copy.py#L66-L96 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/utils/generic_utils.py | python | _shared_object_loading_scope | () | return getattr(SHARED_OBJECT_LOADING, 'scope', NoopLoadingScope()) | Get the current shared object saving scope in a threadsafe manner. | Get the current shared object saving scope in a threadsafe manner. | [
"Get",
"the",
"current",
"shared",
"object",
"saving",
"scope",
"in",
"a",
"threadsafe",
"manner",
"."
] | def _shared_object_loading_scope():
"""Get the current shared object saving scope in a threadsafe manner."""
return getattr(SHARED_OBJECT_LOADING, 'scope', NoopLoadingScope()) | [
"def",
"_shared_object_loading_scope",
"(",
")",
":",
"return",
"getattr",
"(",
"SHARED_OBJECT_LOADING",
",",
"'scope'",
",",
"NoopLoadingScope",
"(",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/generic_utils.py#L135-L137 | |
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/tomviz/executor.py | python | JsonProgress.write_to_file | (self, data) | Write data to write and return path. Implemented by subclass. | Write data to write and return path. Implemented by subclass. | [
"Write",
"data",
"to",
"write",
"and",
"return",
"path",
".",
"Implemented",
"by",
"subclass",
"."
] | def write_to_file(self, data):
"""
Write data to write and return path. Implemented by subclass.
""" | [
"def",
"write_to_file",
"(",
"self",
",",
"data",
")",
":"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/executor.py#L131-L134 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/roslaunch/src/roslaunch/server.py | python | ROSLaunchChildNode.start | (self) | Initialize child. Must be called before run | Initialize child. Must be called before run | [
"Initialize",
"child",
".",
"Must",
"be",
"called",
"before",
"run"
] | def start(self):
"""
Initialize child. Must be called before run
"""
self.logger.info("starting roslaunch child process [%s], server URI is [%s]", self.name, self.server_uri)
super(ROSLaunchChildNode, self).start()
self._register_with_server() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"starting roslaunch child process [%s], server URI is [%s]\"",
",",
"self",
".",
"name",
",",
"self",
".",
"server_uri",
")",
"super",
"(",
"ROSLaunchChildNode",
",",
"self",
")",
".",
"start",
"(",
")",
"self",
".",
"_register_with_server",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/server.py#L527-L533 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/idl_parser/idl_parser.py | python | IDLParser.p_ReadonlyMemberRest | (self, p) | ReadonlyMemberRest : AttributeRest
| MaplikeRest
| SetlikeRest | ReadonlyMemberRest : AttributeRest
| MaplikeRest
| SetlikeRest | [
"ReadonlyMemberRest",
":",
"AttributeRest",
"|",
"MaplikeRest",
"|",
"SetlikeRest"
] | def p_ReadonlyMemberRest(self, p):
"""ReadonlyMemberRest : AttributeRest
| MaplikeRest
| SetlikeRest"""
p[0] = p[1] | [
"def",
"p_ReadonlyMemberRest",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_parser.py#L588-L592 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/runtime/nrt.py | python | _Runtime.library | (self) | return self._library | Return the Library object containing the various NRT functions. | Return the Library object containing the various NRT functions. | [
"Return",
"the",
"Library",
"object",
"containing",
"the",
"various",
"NRT",
"functions",
"."
] | def library(self):
"""
Return the Library object containing the various NRT functions.
"""
self._init_guard()
return self._library | [
"def",
"library",
"(",
"self",
")",
":",
"self",
".",
"_init_guard",
"(",
")",
"return",
"self",
".",
"_library"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/runtime/nrt.py#L65-L70 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/compiler/pycodegen.py | python | CodeGenerator.set_lineno | (self, node, force=False) | return False | Emit SET_LINENO if necessary.
The instruction is considered necessary if the node has a
lineno attribute and it is different than the last lineno
emitted.
Returns true if SET_LINENO was emitted.
There are no rules for when an AST node should have a lineno
attribute. The transformer and AST code need to be reviewed
and a consistent policy implemented and documented. Until
then, this method works around missing line numbers. | Emit SET_LINENO if necessary. | [
"Emit",
"SET_LINENO",
"if",
"necessary",
"."
] | def set_lineno(self, node, force=False):
"""Emit SET_LINENO if necessary.
The instruction is considered necessary if the node has a
lineno attribute and it is different than the last lineno
emitted.
Returns true if SET_LINENO was emitted.
There are no rules for when an AST node should have a lineno
attribute. The transformer and AST code need to be reviewed
and a consistent policy implemented and documented. Until
then, this method works around missing line numbers.
"""
lineno = getattr(node, 'lineno', None)
if lineno is not None and (lineno != self.last_lineno
or force):
self.emit('SET_LINENO', lineno)
self.last_lineno = lineno
return True
return False | [
"def",
"set_lineno",
"(",
"self",
",",
"node",
",",
"force",
"=",
"False",
")",
":",
"lineno",
"=",
"getattr",
"(",
"node",
",",
"'lineno'",
",",
"None",
")",
"if",
"lineno",
"is",
"not",
"None",
"and",
"(",
"lineno",
"!=",
"self",
".",
"last_lineno",
"or",
"force",
")",
":",
"self",
".",
"emit",
"(",
"'SET_LINENO'",
",",
"lineno",
")",
"self",
".",
"last_lineno",
"=",
"lineno",
"return",
"True",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/compiler/pycodegen.py#L316-L336 | |
sfzhang15/FaceBoxes | b52cc92f9362d3adc08d54666aeb9ebb62fdb7da | scripts/cpp_lint.py | python | CloseExpression | (clean_lines, linenum, pos) | return (line, clean_lines.NumLines(), -1) | If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum. | If input points to ( or { or [ or <, finds the position that closes it. | [
"If",
"input",
"points",
"to",
"(",
"or",
"{",
"or",
"[",
"or",
"<",
"finds",
"the",
"position",
"that",
"closes",
"it",
"."
] | def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
startchar = line[pos]
if startchar not in '({[<':
return (line, clean_lines.NumLines(), -1)
if startchar == '(': endchar = ')'
if startchar == '[': endchar = ']'
if startchar == '{': endchar = '}'
if startchar == '<': endchar = '>'
# Check first line
(end_pos, num_open) = FindEndOfExpressionInLine(
line, pos, 0, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, num_open) = FindEndOfExpressionInLine(
line, 0, num_open, startchar, endchar)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find endchar before end of file, give up
return (line, clean_lines.NumLines(), -1) | [
"def",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"startchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"startchar",
"not",
"in",
"'({[<'",
":",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")",
"if",
"startchar",
"==",
"'('",
":",
"endchar",
"=",
"')'",
"if",
"startchar",
"==",
"'['",
":",
"endchar",
"=",
"']'",
"if",
"startchar",
"==",
"'{'",
":",
"endchar",
"=",
"'}'",
"if",
"startchar",
"==",
"'<'",
":",
"endchar",
"=",
"'>'",
"# Check first line",
"(",
"end_pos",
",",
"num_open",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"pos",
",",
"0",
",",
"startchar",
",",
"endchar",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Continue scanning forward",
"while",
"linenum",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
"-",
"1",
":",
"linenum",
"+=",
"1",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"(",
"end_pos",
",",
"num_open",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"0",
",",
"num_open",
",",
"startchar",
",",
"endchar",
")",
"if",
"end_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"end_pos",
")",
"# Did not find endchar before end of file, give up",
"return",
"(",
"line",
",",
"clean_lines",
".",
"NumLines",
"(",
")",
",",
"-",
"1",
")"
] | https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/scripts/cpp_lint.py#L1254-L1297 | |
cksystemsgroup/scal | fa2208a97a77d65f4e90f85fef3404c27c1f2ac2 | tools/cpplint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
nesting_state, error) | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"r",
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style. Also look for
# non-single-argument constructors which are also technically valid, but
# strongly suggest something is wrong.
explicit_constructor_match = Match(
r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*'
r'\(((?:[^()]|\([^()]*\))*)\)'
% re.escape(base_classname),
line)
if explicit_constructor_match:
is_marked_explicit = explicit_constructor_match.group(1)
if not explicit_constructor_match.group(2):
constructor_args = []
else:
constructor_args = explicit_constructor_match.group(2).split(',')
# collapse arguments so that commas in template parameter lists and function
# argument parameter lists don't split arguments in two
i = 0
while i < len(constructor_args):
constructor_arg = constructor_args[i]
while (constructor_arg.count('<') > constructor_arg.count('>') or
constructor_arg.count('(') > constructor_arg.count(')')):
constructor_arg += ',' + constructor_args[i + 1]
del constructor_args[i + 1]
constructor_args[i] = constructor_arg
i += 1
defaulted_args = [arg for arg in constructor_args if '=' in arg]
noarg_constructor = (not constructor_args or # empty arg list
# 'void' arg specifier
(len(constructor_args) == 1 and
constructor_args[0].strip() == 'void'))
onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
not noarg_constructor) or
# all but at most one arg defaulted
(len(constructor_args) >= 1 and
not noarg_constructor and
len(defaulted_args) >= len(constructor_args) - 1))
initializer_list_constructor = bool(
onearg_constructor and
Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
copy_constructor = bool(
onearg_constructor and
Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), constructor_args[0].strip()))
if (not is_marked_explicit and
onearg_constructor and
not initializer_list_constructor and
not copy_constructor):
if defaulted_args:
error(filename, linenum, 'runtime/explicit', 5,
'Constructors callable with one argument '
'should be marked explicit.')
else:
error(filename, linenum, 'runtime/explicit', 5,
'Single-parameter constructors should be marked explicit.')
elif is_marked_explicit and not onearg_constructor:
if noarg_constructor:
error(filename, linenum, 'runtime/explicit', 5,
'Zero-parameter constructors should not be marked explicit.')
else:
error(filename, linenum, 'runtime/explicit', 0,
'Constructors that require multiple arguments '
'should not be marked explicit.') | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"3",
",",
"'%q in format strings is deprecated. Use %ll instead.'",
")",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%\\d+\\$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"2",
",",
"'%N$ formats are unconventional. Try rewriting to avoid them.'",
")",
"# Remove escaped backslashes before looking for undefined escapes.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"Search",
"(",
"r'(\"|\\').*\\\\(%|\\[|\\(|{)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/printf_format'",
",",
"3",
",",
"'%, [, (, and { are undefined character escapes. Unescape them.'",
")",
"# For the rest, work with both comments and strings removed.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\b(const|volatile|void|char|short|int|long'",
"r'|float|double|signed|unsigned'",
"r'|schar|u?int8|u?int16|u?int32|u?int64)'",
"r'\\s+(register|static|extern|typedef)\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/storage_class'",
",",
"5",
",",
"'Storage class (static, extern, typedef, etc) should be first.'",
")",
"if",
"Match",
"(",
"r'\\s*#\\s*endif\\s*[^/\\s]+'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/endif_comment'",
",",
"5",
",",
"'Uncommented text after #endif is non-standard. Use a comment.'",
")",
"if",
"Match",
"(",
"r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/forward_decl'",
",",
"5",
",",
"'Inner-style forward declarations are invalid. Remove this line.'",
")",
"if",
"Search",
"(",
"r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/deprecated'",
",",
"3",
",",
"'>? and <? (max and min) operators are non-standard and deprecated.'",
")",
"if",
"Search",
"(",
"r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'",
",",
"line",
")",
":",
"# TODO(unknown): Could it be expanded safely to arbitrary references,",
"# without triggering too many false positives? The first",
"# attempt triggered 5 warnings for mostly benign code in the regtest, hence",
"# the restriction.",
"# Here's the original regexp, for the reference:",
"# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'",
"# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/member_string_references'",
",",
"2",
",",
"'const string& members are dangerous. It is much better to use '",
"'alternatives, such as pointers or simple constants.'",
")",
"# Everything else in this function operates on class declarations.",
"# Return early if the top of the nesting stack is not a class, or if",
"# the class head is not completed yet.",
"classinfo",
"=",
"nesting_state",
".",
"InnermostClass",
"(",
")",
"if",
"not",
"classinfo",
"or",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"return",
"# The class may have been declared with namespace or classname qualifiers.",
"# The constructor and destructor will not have those qualifiers.",
"base_classname",
"=",
"classinfo",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
"# Look for single-argument constructors that aren't marked explicit.",
"# Technically a valid construct, but against style. Also look for",
"# non-single-argument constructors which are also technically valid, but",
"# strongly suggest something is wrong.",
"explicit_constructor_match",
"=",
"Match",
"(",
"r'\\s+(?:inline\\s+)?(explicit\\s+)?(?:inline\\s+)?%s\\s*'",
"r'\\(((?:[^()]|\\([^()]*\\))*)\\)'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"line",
")",
"if",
"explicit_constructor_match",
":",
"is_marked_explicit",
"=",
"explicit_constructor_match",
".",
"group",
"(",
"1",
")",
"if",
"not",
"explicit_constructor_match",
".",
"group",
"(",
"2",
")",
":",
"constructor_args",
"=",
"[",
"]",
"else",
":",
"constructor_args",
"=",
"explicit_constructor_match",
".",
"group",
"(",
"2",
")",
".",
"split",
"(",
"','",
")",
"# collapse arguments so that commas in template parameter lists and function",
"# argument parameter lists don't split arguments in two",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"constructor_args",
")",
":",
"constructor_arg",
"=",
"constructor_args",
"[",
"i",
"]",
"while",
"(",
"constructor_arg",
".",
"count",
"(",
"'<'",
")",
">",
"constructor_arg",
".",
"count",
"(",
"'>'",
")",
"or",
"constructor_arg",
".",
"count",
"(",
"'('",
")",
">",
"constructor_arg",
".",
"count",
"(",
"')'",
")",
")",
":",
"constructor_arg",
"+=",
"','",
"+",
"constructor_args",
"[",
"i",
"+",
"1",
"]",
"del",
"constructor_args",
"[",
"i",
"+",
"1",
"]",
"constructor_args",
"[",
"i",
"]",
"=",
"constructor_arg",
"i",
"+=",
"1",
"defaulted_args",
"=",
"[",
"arg",
"for",
"arg",
"in",
"constructor_args",
"if",
"'='",
"in",
"arg",
"]",
"noarg_constructor",
"=",
"(",
"not",
"constructor_args",
"or",
"# empty arg list",
"# 'void' arg specifier",
"(",
"len",
"(",
"constructor_args",
")",
"==",
"1",
"and",
"constructor_args",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"==",
"'void'",
")",
")",
"onearg_constructor",
"=",
"(",
"(",
"len",
"(",
"constructor_args",
")",
"==",
"1",
"and",
"# exactly one arg",
"not",
"noarg_constructor",
")",
"or",
"# all but at most one arg defaulted",
"(",
"len",
"(",
"constructor_args",
")",
">=",
"1",
"and",
"not",
"noarg_constructor",
"and",
"len",
"(",
"defaulted_args",
")",
">=",
"len",
"(",
"constructor_args",
")",
"-",
"1",
")",
")",
"initializer_list_constructor",
"=",
"bool",
"(",
"onearg_constructor",
"and",
"Search",
"(",
"r'\\bstd\\s*::\\s*initializer_list\\b'",
",",
"constructor_args",
"[",
"0",
"]",
")",
")",
"copy_constructor",
"=",
"bool",
"(",
"onearg_constructor",
"and",
"Match",
"(",
"r'(const\\s+)?%s(\\s*<[^>]*>)?(\\s+const)?\\s*(?:<\\w+>\\s*)?&'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"constructor_args",
"[",
"0",
"]",
".",
"strip",
"(",
")",
")",
")",
"if",
"(",
"not",
"is_marked_explicit",
"and",
"onearg_constructor",
"and",
"not",
"initializer_list_constructor",
"and",
"not",
"copy_constructor",
")",
":",
"if",
"defaulted_args",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Constructors callable with one argument '",
"'should be marked explicit.'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Single-parameter constructors should be marked explicit.'",
")",
"elif",
"is_marked_explicit",
"and",
"not",
"onearg_constructor",
":",
"if",
"noarg_constructor",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Zero-parameter constructors should not be marked explicit.'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"0",
",",
"'Constructors that require multiple arguments '",
"'should not be marked explicit.'",
")"
] | https://github.com/cksystemsgroup/scal/blob/fa2208a97a77d65f4e90f85fef3404c27c1f2ac2/tools/cpplint.py#L2573-L2734 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/utils/profile_analyzer.py | python | TimeFuncHelper._eval_time | (prof_type, end_key, func, opr_prof) | return func(time) | r"""Eval time.
Args:
prof_type: host' or 'device'.
end_key: kern' or 'end'.
func: apply to list of all ``thread`` of ``gpu`` time.
opr_prof: operator profiling result.
Returns:
time. | r"""Eval time. | [
"r",
"Eval",
"time",
"."
] | def _eval_time(prof_type, end_key, func, opr_prof):
r"""Eval time.
Args:
prof_type: host' or 'device'.
end_key: kern' or 'end'.
func: apply to list of all ``thread`` of ``gpu`` time.
opr_prof: operator profiling result.
Returns:
time.
"""
if prof_type not in opr_prof.time_dict:
return None
time = [time[end_key] - time["start"] for time in opr_prof.time_dict[prof_type]]
return func(time) | [
"def",
"_eval_time",
"(",
"prof_type",
",",
"end_key",
",",
"func",
",",
"opr_prof",
")",
":",
"if",
"prof_type",
"not",
"in",
"opr_prof",
".",
"time_dict",
":",
"return",
"None",
"time",
"=",
"[",
"time",
"[",
"end_key",
"]",
"-",
"time",
"[",
"\"start\"",
"]",
"for",
"time",
"in",
"opr_prof",
".",
"time_dict",
"[",
"prof_type",
"]",
"]",
"return",
"func",
"(",
"time",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/utils/profile_analyzer.py#L319-L335 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/TLSRecordLayer.py | python | TLSRecordLayer.getCipherImplementation | (self) | return self._writeState.encContext.implementation | Get the name of the cipher implementation used with
this connection.
@rtype: str
@return: The name of the cipher implementation used with
this connection. Either 'python', 'cryptlib', 'openssl',
or 'pycrypto'. | Get the name of the cipher implementation used with
this connection. | [
"Get",
"the",
"name",
"of",
"the",
"cipher",
"implementation",
"used",
"with",
"this",
"connection",
"."
] | def getCipherImplementation(self):
"""Get the name of the cipher implementation used with
this connection.
@rtype: str
@return: The name of the cipher implementation used with
this connection. Either 'python', 'cryptlib', 'openssl',
or 'pycrypto'.
"""
if not self._writeState.encContext:
return None
return self._writeState.encContext.implementation | [
"def",
"getCipherImplementation",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_writeState",
".",
"encContext",
":",
"return",
"None",
"return",
"self",
".",
"_writeState",
".",
"encContext",
".",
"implementation"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/TLSRecordLayer.py#L371-L382 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/independent.py | python | Independent.__init__ | (
self, distribution, reinterpreted_batch_ndims=None,
validate_args=False, name=None) | Construct a `Independent` distribution.
Args:
distribution: The base distribution instance to transform. Typically an
instance of `Distribution`.
reinterpreted_batch_ndims: Scalar, integer number of rightmost batch dims
which will be regarded as event dims. When `None` all but the first
batch axis (batch axis 0) will be transferred to event dimensions
(analogous to `tf.compat.v1.layers.flatten`).
validate_args: Python `bool`. Whether to validate input with asserts.
If `validate_args` is `False`, and the inputs are invalid,
correct behavior is not guaranteed.
name: The name for ops managed by the distribution.
Default value: `Independent + distribution.name`.
Raises:
ValueError: if `reinterpreted_batch_ndims` exceeds
`distribution.batch_ndims` | Construct a `Independent` distribution. | [
"Construct",
"a",
"Independent",
"distribution",
"."
] | def __init__(
self, distribution, reinterpreted_batch_ndims=None,
validate_args=False, name=None):
"""Construct a `Independent` distribution.
Args:
distribution: The base distribution instance to transform. Typically an
instance of `Distribution`.
reinterpreted_batch_ndims: Scalar, integer number of rightmost batch dims
which will be regarded as event dims. When `None` all but the first
batch axis (batch axis 0) will be transferred to event dimensions
(analogous to `tf.compat.v1.layers.flatten`).
validate_args: Python `bool`. Whether to validate input with asserts.
If `validate_args` is `False`, and the inputs are invalid,
correct behavior is not guaranteed.
name: The name for ops managed by the distribution.
Default value: `Independent + distribution.name`.
Raises:
ValueError: if `reinterpreted_batch_ndims` exceeds
`distribution.batch_ndims`
"""
parameters = dict(locals())
name = name or "Independent" + distribution.name
self._distribution = distribution
with ops.name_scope(name) as name:
if reinterpreted_batch_ndims is None:
reinterpreted_batch_ndims = self._get_default_reinterpreted_batch_ndims(
distribution)
reinterpreted_batch_ndims = ops.convert_to_tensor(
reinterpreted_batch_ndims,
dtype=dtypes.int32,
name="reinterpreted_batch_ndims")
self._reinterpreted_batch_ndims = reinterpreted_batch_ndims
self._static_reinterpreted_batch_ndims = tensor_util.constant_value(
reinterpreted_batch_ndims)
if self._static_reinterpreted_batch_ndims is not None:
self._reinterpreted_batch_ndims = self._static_reinterpreted_batch_ndims
super(Independent, self).__init__(
dtype=self._distribution.dtype,
reparameterization_type=self._distribution.reparameterization_type,
validate_args=validate_args,
allow_nan_stats=self._distribution.allow_nan_stats,
parameters=parameters,
graph_parents=(
[reinterpreted_batch_ndims] +
distribution._graph_parents), # pylint: disable=protected-access
name=name)
self._runtime_assertions = self._make_runtime_assertions(
distribution, reinterpreted_batch_ndims, validate_args) | [
"def",
"__init__",
"(",
"self",
",",
"distribution",
",",
"reinterpreted_batch_ndims",
"=",
"None",
",",
"validate_args",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"parameters",
"=",
"dict",
"(",
"locals",
"(",
")",
")",
"name",
"=",
"name",
"or",
"\"Independent\"",
"+",
"distribution",
".",
"name",
"self",
".",
"_distribution",
"=",
"distribution",
"with",
"ops",
".",
"name_scope",
"(",
"name",
")",
"as",
"name",
":",
"if",
"reinterpreted_batch_ndims",
"is",
"None",
":",
"reinterpreted_batch_ndims",
"=",
"self",
".",
"_get_default_reinterpreted_batch_ndims",
"(",
"distribution",
")",
"reinterpreted_batch_ndims",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"reinterpreted_batch_ndims",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
",",
"name",
"=",
"\"reinterpreted_batch_ndims\"",
")",
"self",
".",
"_reinterpreted_batch_ndims",
"=",
"reinterpreted_batch_ndims",
"self",
".",
"_static_reinterpreted_batch_ndims",
"=",
"tensor_util",
".",
"constant_value",
"(",
"reinterpreted_batch_ndims",
")",
"if",
"self",
".",
"_static_reinterpreted_batch_ndims",
"is",
"not",
"None",
":",
"self",
".",
"_reinterpreted_batch_ndims",
"=",
"self",
".",
"_static_reinterpreted_batch_ndims",
"super",
"(",
"Independent",
",",
"self",
")",
".",
"__init__",
"(",
"dtype",
"=",
"self",
".",
"_distribution",
".",
"dtype",
",",
"reparameterization_type",
"=",
"self",
".",
"_distribution",
".",
"reparameterization_type",
",",
"validate_args",
"=",
"validate_args",
",",
"allow_nan_stats",
"=",
"self",
".",
"_distribution",
".",
"allow_nan_stats",
",",
"parameters",
"=",
"parameters",
",",
"graph_parents",
"=",
"(",
"[",
"reinterpreted_batch_ndims",
"]",
"+",
"distribution",
".",
"_graph_parents",
")",
",",
"# pylint: disable=protected-access",
"name",
"=",
"name",
")",
"self",
".",
"_runtime_assertions",
"=",
"self",
".",
"_make_runtime_assertions",
"(",
"distribution",
",",
"reinterpreted_batch_ndims",
",",
"validate_args",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/independent.py#L107-L156 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/cpplint.py | python | NestingState.Update | (self, filename, clean_lines, linenum, error) | Update nesting state with current line.
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. | Update nesting state with current line. | [
"Update",
"nesting",
"state",
"with",
"current",
"line",
"."
] | def Update(self, filename, clean_lines, linenum, error):
"""Update nesting state with current line.
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]
# Remember top of the previous nesting stack.
#
# The stack is always pushed/popped and not modified in place, so
# we can just do a shallow copy instead of copy.deepcopy. Using
# deepcopy would slow down cpplint by ~28%.
if self.stack:
self.previous_stack_top = self.stack[-1]
else:
self.previous_stack_top = None
# Update pp_stack
self.UpdatePreprocessor(line)
# Count parentheses. This is to avoid adding struct arguments to
# the nesting stack.
if self.stack:
inner_block = self.stack[-1]
depth_change = line.count('(') - line.count(')')
inner_block.open_parentheses += depth_change
# Also check if we are starting or ending an inline assembly block.
if inner_block.inline_asm in (_NO_ASM, _END_ASM):
if (depth_change != 0 and
inner_block.open_parentheses == 1 and
_MATCH_ASM.match(line)):
# Enter assembly block
inner_block.inline_asm = _INSIDE_ASM
else:
# Not entering assembly block. If previous line was _END_ASM,
# we will now shift to _NO_ASM state.
inner_block.inline_asm = _NO_ASM
elif (inner_block.inline_asm == _INSIDE_ASM and
inner_block.open_parentheses == 0):
# Exit assembly block
inner_block.inline_asm = _END_ASM
# Consume namespace declaration at the beginning of the line. Do
# this in a loop so that we catch same line declarations like this:
# namespace proto2 { namespace bridge { class MessageSet; } }
while True:
# Match start of namespace. The "\b\s*" below catches namespace
# declarations even if it weren't followed by a whitespace, this
# is so that we don't confuse our namespace checker. The
# missing spaces will be flagged by CheckSpacing.
namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
if not namespace_decl_match:
break
new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
self.stack.append(new_namespace)
line = namespace_decl_match.group(2)
if line.find('{') != -1:
new_namespace.seen_open_brace = True
line = line[line.find('{') + 1:]
# Look for a class declaration in whatever is left of the line
# after parsing namespaces. The regexp accounts for decorated classes
# such as in:
# class LOCKABLE API Object {
# };
class_decl_match = Match(
r'^(\s*(?:template\s*<[\w\s<>,:=]*>\s*)?'
r'(class|struct)\s+(?:[a-zA-Z0-9_]+\s+)*(\w+(?:::\w+)*))'
r'(.*)$', line)
if (class_decl_match and
(not self.stack or self.stack[-1].open_parentheses == 0)):
# We do not want to accept classes that are actually template arguments:
# template <class Ignore1,
# class Ignore2 = Default<Args>,
# template <Args> class Ignore3>
# void Function() {};
#
# To avoid template argument cases, we scan forward and look for
# an unmatched '>'. If we see one, assume we are inside a
# template argument list.
end_declaration = len(class_decl_match.group(1))
if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
self.stack.append(_ClassInfo(
class_decl_match.group(3), class_decl_match.group(2),
clean_lines, linenum))
line = class_decl_match.group(4)
# If we have not yet seen the opening brace for the innermost block,
# run checks here.
if not self.SeenOpenBrace():
self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
# Update access control if we are inside a class/struct
if self.stack and isinstance(self.stack[-1], _ClassInfo):
classinfo = self.stack[-1]
access_match = Match(
r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
r':(?:[^:]|$)',
line)
if access_match:
classinfo.access = access_match.group(2)
# Check that access keywords are indented +1 space. Skip this
# check if the keywords are not preceded by whitespaces.
indent = access_match.group(1)
if (len(indent) != classinfo.class_indent + 1 and
Match(r'^\s*$', indent)):
if classinfo.is_struct:
parent = 'struct ' + classinfo.name
else:
parent = 'class ' + classinfo.name
slots = ''
if access_match.group(3):
slots = access_match.group(3)
error(filename, linenum, 'whitespace/indent', 3,
'%s%s: should be indented +1 space inside %s' % (
access_match.group(2), slots, parent))
# Consume braces or semicolons from what's left of the line
while True:
# Match first brace, semicolon, or closed parenthesis.
matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
if not matched:
break
token = matched.group(1)
if token == '{':
# If namespace or class hasn't seen a opening brace yet, mark
# namespace/class head as complete. Push a new block onto the
# stack otherwise.
if not self.SeenOpenBrace():
self.stack[-1].seen_open_brace = True
elif Match(r'^extern\s*"[^"]*"\s*\{', line):
self.stack.append(_ExternCInfo(linenum))
else:
self.stack.append(_BlockInfo(linenum, True))
if _MATCH_ASM.match(line):
self.stack[-1].inline_asm = _BLOCK_ASM
elif token == ';' or token == ')':
# If we haven't seen an opening brace yet, but we already saw
# a semicolon, this is probably a forward declaration. Pop
# the stack for these.
#
# Similarly, if we haven't seen an opening brace yet, but we
# already saw a closing parenthesis, then these are probably
# function arguments with extra "class" or "struct" keywords.
# Also pop these stack for these.
if not self.SeenOpenBrace():
self.stack.pop()
else: # token == '}'
# Perform end of block checks and pop the stack.
if self.stack:
self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
self.stack.pop()
line = matched.group(2) | [
"def",
"Update",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Remember top of the previous nesting stack.",
"#",
"# The stack is always pushed/popped and not modified in place, so",
"# we can just do a shallow copy instead of copy.deepcopy. Using",
"# deepcopy would slow down cpplint by ~28%.",
"if",
"self",
".",
"stack",
":",
"self",
".",
"previous_stack_top",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"else",
":",
"self",
".",
"previous_stack_top",
"=",
"None",
"# Update pp_stack",
"self",
".",
"UpdatePreprocessor",
"(",
"line",
")",
"# Count parentheses. This is to avoid adding struct arguments to",
"# the nesting stack.",
"if",
"self",
".",
"stack",
":",
"inner_block",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"depth_change",
"=",
"line",
".",
"count",
"(",
"'('",
")",
"-",
"line",
".",
"count",
"(",
"')'",
")",
"inner_block",
".",
"open_parentheses",
"+=",
"depth_change",
"# Also check if we are starting or ending an inline assembly block.",
"if",
"inner_block",
".",
"inline_asm",
"in",
"(",
"_NO_ASM",
",",
"_END_ASM",
")",
":",
"if",
"(",
"depth_change",
"!=",
"0",
"and",
"inner_block",
".",
"open_parentheses",
"==",
"1",
"and",
"_MATCH_ASM",
".",
"match",
"(",
"line",
")",
")",
":",
"# Enter assembly block",
"inner_block",
".",
"inline_asm",
"=",
"_INSIDE_ASM",
"else",
":",
"# Not entering assembly block. If previous line was _END_ASM,",
"# we will now shift to _NO_ASM state.",
"inner_block",
".",
"inline_asm",
"=",
"_NO_ASM",
"elif",
"(",
"inner_block",
".",
"inline_asm",
"==",
"_INSIDE_ASM",
"and",
"inner_block",
".",
"open_parentheses",
"==",
"0",
")",
":",
"# Exit assembly block",
"inner_block",
".",
"inline_asm",
"=",
"_END_ASM",
"# Consume namespace declaration at the beginning of the line. Do",
"# this in a loop so that we catch same line declarations like this:",
"# namespace proto2 { namespace bridge { class MessageSet; } }",
"while",
"True",
":",
"# Match start of namespace. The \"\\b\\s*\" below catches namespace",
"# declarations even if it weren't followed by a whitespace, this",
"# is so that we don't confuse our namespace checker. The",
"# missing spaces will be flagged by CheckSpacing.",
"namespace_decl_match",
"=",
"Match",
"(",
"r'^\\s*namespace\\b\\s*([:\\w]+)?(.*)$'",
",",
"line",
")",
"if",
"not",
"namespace_decl_match",
":",
"break",
"new_namespace",
"=",
"_NamespaceInfo",
"(",
"namespace_decl_match",
".",
"group",
"(",
"1",
")",
",",
"linenum",
")",
"self",
".",
"stack",
".",
"append",
"(",
"new_namespace",
")",
"line",
"=",
"namespace_decl_match",
".",
"group",
"(",
"2",
")",
"if",
"line",
".",
"find",
"(",
"'{'",
")",
"!=",
"-",
"1",
":",
"new_namespace",
".",
"seen_open_brace",
"=",
"True",
"line",
"=",
"line",
"[",
"line",
".",
"find",
"(",
"'{'",
")",
"+",
"1",
":",
"]",
"# Look for a class declaration in whatever is left of the line",
"# after parsing namespaces. The regexp accounts for decorated classes",
"# such as in:",
"# class LOCKABLE API Object {",
"# };",
"class_decl_match",
"=",
"Match",
"(",
"r'^(\\s*(?:template\\s*<[\\w\\s<>,:=]*>\\s*)?'",
"r'(class|struct)\\s+(?:[a-zA-Z0-9_]+\\s+)*(\\w+(?:::\\w+)*))'",
"r'(.*)$'",
",",
"line",
")",
"if",
"(",
"class_decl_match",
"and",
"(",
"not",
"self",
".",
"stack",
"or",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"open_parentheses",
"==",
"0",
")",
")",
":",
"# We do not want to accept classes that are actually template arguments:",
"# template <class Ignore1,",
"# class Ignore2 = Default<Args>,",
"# template <Args> class Ignore3>",
"# void Function() {};",
"#",
"# To avoid template argument cases, we scan forward and look for",
"# an unmatched '>'. If we see one, assume we are inside a",
"# template argument list.",
"end_declaration",
"=",
"len",
"(",
"class_decl_match",
".",
"group",
"(",
"1",
")",
")",
"if",
"not",
"self",
".",
"InTemplateArgumentList",
"(",
"clean_lines",
",",
"linenum",
",",
"end_declaration",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"_ClassInfo",
"(",
"class_decl_match",
".",
"group",
"(",
"3",
")",
",",
"class_decl_match",
".",
"group",
"(",
"2",
")",
",",
"clean_lines",
",",
"linenum",
")",
")",
"line",
"=",
"class_decl_match",
".",
"group",
"(",
"4",
")",
"# If we have not yet seen the opening brace for the innermost block,",
"# run checks here.",
"if",
"not",
"self",
".",
"SeenOpenBrace",
"(",
")",
":",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"CheckBegin",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"# Update access control if we are inside a class/struct",
"if",
"self",
".",
"stack",
"and",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_ClassInfo",
")",
":",
"classinfo",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"access_match",
"=",
"Match",
"(",
"r'^(.*)\\b(public|private|protected|signals)(\\s+(?:slots\\s*)?)?'",
"r':(?:[^:]|$)'",
",",
"line",
")",
"if",
"access_match",
":",
"classinfo",
".",
"access",
"=",
"access_match",
".",
"group",
"(",
"2",
")",
"# Check that access keywords are indented +1 space. Skip this",
"# check if the keywords are not preceded by whitespaces.",
"indent",
"=",
"access_match",
".",
"group",
"(",
"1",
")",
"if",
"(",
"len",
"(",
"indent",
")",
"!=",
"classinfo",
".",
"class_indent",
"+",
"1",
"and",
"Match",
"(",
"r'^\\s*$'",
",",
"indent",
")",
")",
":",
"if",
"classinfo",
".",
"is_struct",
":",
"parent",
"=",
"'struct '",
"+",
"classinfo",
".",
"name",
"else",
":",
"parent",
"=",
"'class '",
"+",
"classinfo",
".",
"name",
"slots",
"=",
"''",
"if",
"access_match",
".",
"group",
"(",
"3",
")",
":",
"slots",
"=",
"access_match",
".",
"group",
"(",
"3",
")",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/indent'",
",",
"3",
",",
"'%s%s: should be indented +1 space inside %s'",
"%",
"(",
"access_match",
".",
"group",
"(",
"2",
")",
",",
"slots",
",",
"parent",
")",
")",
"# Consume braces or semicolons from what's left of the line",
"while",
"True",
":",
"# Match first brace, semicolon, or closed parenthesis.",
"matched",
"=",
"Match",
"(",
"r'^[^{;)}]*([{;)}])(.*)$'",
",",
"line",
")",
"if",
"not",
"matched",
":",
"break",
"token",
"=",
"matched",
".",
"group",
"(",
"1",
")",
"if",
"token",
"==",
"'{'",
":",
"# If namespace or class hasn't seen a opening brace yet, mark",
"# namespace/class head as complete. Push a new block onto the",
"# stack otherwise.",
"if",
"not",
"self",
".",
"SeenOpenBrace",
"(",
")",
":",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"seen_open_brace",
"=",
"True",
"elif",
"Match",
"(",
"r'^extern\\s*\"[^\"]*\"\\s*\\{'",
",",
"line",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"_ExternCInfo",
"(",
"linenum",
")",
")",
"else",
":",
"self",
".",
"stack",
".",
"append",
"(",
"_BlockInfo",
"(",
"linenum",
",",
"True",
")",
")",
"if",
"_MATCH_ASM",
".",
"match",
"(",
"line",
")",
":",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"inline_asm",
"=",
"_BLOCK_ASM",
"elif",
"token",
"==",
"';'",
"or",
"token",
"==",
"')'",
":",
"# If we haven't seen an opening brace yet, but we already saw",
"# a semicolon, this is probably a forward declaration. Pop",
"# the stack for these.",
"#",
"# Similarly, if we haven't seen an opening brace yet, but we",
"# already saw a closing parenthesis, then these are probably",
"# function arguments with extra \"class\" or \"struct\" keywords.",
"# Also pop these stack for these.",
"if",
"not",
"self",
".",
"SeenOpenBrace",
"(",
")",
":",
"self",
".",
"stack",
".",
"pop",
"(",
")",
"else",
":",
"# token == '}'",
"# Perform end of block checks and pop the stack.",
"if",
"self",
".",
"stack",
":",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"CheckEnd",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
"self",
".",
"stack",
".",
"pop",
"(",
")",
"line",
"=",
"matched",
".",
"group",
"(",
"2",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L3101-L3263 | ||
Xilinx/XRT | dd071c90309df61d3ecdd92dca39f43804915c99 | src/python/xrt_binding.py | python | xclCreateWriteQueue | (handle, q_ctx, q_hdl) | return libcore.xclCreateWriteQueue(handle, q_ctx, q_hdl) | Create Write Queue
:param handle:Device handle
:param q_ctx:Queue Context
:param q_hdl:Queue handle
:return:
This is used to create queue based on information provided in Queue context. Queue handle is generated if creation
successes.
This feature will be enabled in a future release. | Create Write Queue
:param handle:Device handle
:param q_ctx:Queue Context
:param q_hdl:Queue handle
:return: | [
"Create",
"Write",
"Queue",
":",
"param",
"handle",
":",
"Device",
"handle",
":",
"param",
"q_ctx",
":",
"Queue",
"Context",
":",
"param",
"q_hdl",
":",
"Queue",
"handle",
":",
"return",
":"
] | def xclCreateWriteQueue(handle, q_ctx, q_hdl):
"""
Create Write Queue
:param handle:Device handle
:param q_ctx:Queue Context
:param q_hdl:Queue handle
:return:
This is used to create queue based on information provided in Queue context. Queue handle is generated if creation
successes.
This feature will be enabled in a future release.
"""
_xclStreamDeprecation(sys._getframe().f_code.co_name)
libcore.xclCreateWriteQueue.restype = ctypes.c_int
libcore.xclCreateWriteQueue.argtypes = [xclDeviceHandle, ctypes.POINTER(xclQueueContext), ctypes.c_uint64]
return libcore.xclCreateWriteQueue(handle, q_ctx, q_hdl) | [
"def",
"xclCreateWriteQueue",
"(",
"handle",
",",
"q_ctx",
",",
"q_hdl",
")",
":",
"_xclStreamDeprecation",
"(",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_code",
".",
"co_name",
")",
"libcore",
".",
"xclCreateWriteQueue",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"libcore",
".",
"xclCreateWriteQueue",
".",
"argtypes",
"=",
"[",
"xclDeviceHandle",
",",
"ctypes",
".",
"POINTER",
"(",
"xclQueueContext",
")",
",",
"ctypes",
".",
"c_uint64",
"]",
"return",
"libcore",
".",
"xclCreateWriteQueue",
"(",
"handle",
",",
"q_ctx",
",",
"q_hdl",
")"
] | https://github.com/Xilinx/XRT/blob/dd071c90309df61d3ecdd92dca39f43804915c99/src/python/xrt_binding.py#L719-L734 | |
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/importers/common/converters.py | python | LookupTable.get_originating_importer_node_for_output | (self, output_id: str) | return importer_node | Gets the originating ImporterNode for the output identified by output_id. | Gets the originating ImporterNode for the output identified by output_id. | [
"Gets",
"the",
"originating",
"ImporterNode",
"for",
"the",
"output",
"identified",
"by",
"output_id",
"."
] | def get_originating_importer_node_for_output(self, output_id: str) -> ImporterNode:
"""
Gets the originating ImporterNode for the output identified by output_id.
"""
try:
ell_node_id = self.output_id_to_ell_ids[output_id]
importer_node = self.ell_id_to_owning_importer_node[ell_node_id]
except BaseException:
raise Exception("Cannot find originating ImporterNode node for output {}".format(output_id))
return importer_node | [
"def",
"get_originating_importer_node_for_output",
"(",
"self",
",",
"output_id",
":",
"str",
")",
"->",
"ImporterNode",
":",
"try",
":",
"ell_node_id",
"=",
"self",
".",
"output_id_to_ell_ids",
"[",
"output_id",
"]",
"importer_node",
"=",
"self",
".",
"ell_id_to_owning_importer_node",
"[",
"ell_node_id",
"]",
"except",
"BaseException",
":",
"raise",
"Exception",
"(",
"\"Cannot find originating ImporterNode node for output {}\"",
".",
"format",
"(",
"output_id",
")",
")",
"return",
"importer_node"
] | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/common/converters.py#L285-L294 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py | python | FlagValues._RegisterFlagByModule | (self, module_name, flag) | Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module. | Records the module that defines a specific flag. | [
"Records",
"the",
"module",
"that",
"defines",
"a",
"specific",
"flag",
"."
] | def _RegisterFlagByModule(self, module_name, flag):
"""Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module = self.FlagsByModuleDict()
flags_by_module.setdefault(module_name, []).append(flag) | [
"def",
"_RegisterFlagByModule",
"(",
"self",
",",
"module_name",
",",
"flag",
")",
":",
"flags_by_module",
"=",
"self",
".",
"FlagsByModuleDict",
"(",
")",
"flags_by_module",
".",
"setdefault",
"(",
"module_name",
",",
"[",
"]",
")",
".",
"append",
"(",
"flag",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L876-L887 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/lib/httputil.py | python | HeaderMap.values | (self, key) | return [e.value for e in self.elements(key)] | Return a sorted list of HeaderElement.value for the given header. | Return a sorted list of HeaderElement.value for the given header. | [
"Return",
"a",
"sorted",
"list",
"of",
"HeaderElement",
".",
"value",
"for",
"the",
"given",
"header",
"."
] | def values(self, key):
"""Return a sorted list of HeaderElement.value for the given header."""
return [e.value for e in self.elements(key)] | [
"def",
"values",
"(",
"self",
",",
"key",
")",
":",
"return",
"[",
"e",
".",
"value",
"for",
"e",
"in",
"self",
".",
"elements",
"(",
"key",
")",
"]"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/httputil.py#L438-L440 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py | python | _ShardTargets | (target_list, target_dicts) | return (new_target_list, new_target_dicts) | Shard some targets apart to work around the linkers limits.
Arguments:
target_list: List of target pairs: 'base/base.gyp:base'.
target_dicts: Dict of target properties keyed on target pair.
Returns:
Tuple of the new sharded versions of the inputs. | Shard some targets apart to work around the linkers limits. | [
"Shard",
"some",
"targets",
"apart",
"to",
"work",
"around",
"the",
"linkers",
"limits",
"."
] | def _ShardTargets(target_list, target_dicts):
"""Shard some targets apart to work around the linkers limits.
Arguments:
target_list: List of target pairs: 'base/base.gyp:base'.
target_dicts: Dict of target properties keyed on target pair.
Returns:
Tuple of the new sharded versions of the inputs.
"""
# Gather the targets to shard, and how many pieces.
targets_to_shard = {}
for t in target_dicts:
shards = int(target_dicts[t].get('msvs_shard', 0))
if shards:
targets_to_shard[t] = shards
# Shard target_list.
new_target_list = []
for t in target_list:
if t in targets_to_shard:
for i in range(targets_to_shard[t]):
new_target_list.append(_ShardName(t, i))
else:
new_target_list.append(t)
# Shard target_dict.
new_target_dicts = {}
for t in target_dicts:
if t in targets_to_shard:
for i in range(targets_to_shard[t]):
name = _ShardName(t, i)
new_target_dicts[name] = copy.copy(target_dicts[t])
new_target_dicts[name]['target_name'] = _ShardName(
new_target_dicts[name]['target_name'], i)
sources = new_target_dicts[name].get('sources', [])
new_sources = []
for pos in range(i, len(sources), targets_to_shard[t]):
new_sources.append(sources[pos])
new_target_dicts[name]['sources'] = new_sources
else:
new_target_dicts[t] = target_dicts[t]
# Shard dependencies.
for t in new_target_dicts:
dependencies = copy.copy(new_target_dicts[t].get('dependencies', []))
new_dependencies = []
for d in dependencies:
if d in targets_to_shard:
for i in range(targets_to_shard[d]):
new_dependencies.append(_ShardName(d, i))
else:
new_dependencies.append(d)
new_target_dicts[t]['dependencies'] = new_dependencies
return (new_target_list, new_target_dicts) | [
"def",
"_ShardTargets",
"(",
"target_list",
",",
"target_dicts",
")",
":",
"# Gather the targets to shard, and how many pieces.",
"targets_to_shard",
"=",
"{",
"}",
"for",
"t",
"in",
"target_dicts",
":",
"shards",
"=",
"int",
"(",
"target_dicts",
"[",
"t",
"]",
".",
"get",
"(",
"'msvs_shard'",
",",
"0",
")",
")",
"if",
"shards",
":",
"targets_to_shard",
"[",
"t",
"]",
"=",
"shards",
"# Shard target_list.",
"new_target_list",
"=",
"[",
"]",
"for",
"t",
"in",
"target_list",
":",
"if",
"t",
"in",
"targets_to_shard",
":",
"for",
"i",
"in",
"range",
"(",
"targets_to_shard",
"[",
"t",
"]",
")",
":",
"new_target_list",
".",
"append",
"(",
"_ShardName",
"(",
"t",
",",
"i",
")",
")",
"else",
":",
"new_target_list",
".",
"append",
"(",
"t",
")",
"# Shard target_dict.",
"new_target_dicts",
"=",
"{",
"}",
"for",
"t",
"in",
"target_dicts",
":",
"if",
"t",
"in",
"targets_to_shard",
":",
"for",
"i",
"in",
"range",
"(",
"targets_to_shard",
"[",
"t",
"]",
")",
":",
"name",
"=",
"_ShardName",
"(",
"t",
",",
"i",
")",
"new_target_dicts",
"[",
"name",
"]",
"=",
"copy",
".",
"copy",
"(",
"target_dicts",
"[",
"t",
"]",
")",
"new_target_dicts",
"[",
"name",
"]",
"[",
"'target_name'",
"]",
"=",
"_ShardName",
"(",
"new_target_dicts",
"[",
"name",
"]",
"[",
"'target_name'",
"]",
",",
"i",
")",
"sources",
"=",
"new_target_dicts",
"[",
"name",
"]",
".",
"get",
"(",
"'sources'",
",",
"[",
"]",
")",
"new_sources",
"=",
"[",
"]",
"for",
"pos",
"in",
"range",
"(",
"i",
",",
"len",
"(",
"sources",
")",
",",
"targets_to_shard",
"[",
"t",
"]",
")",
":",
"new_sources",
".",
"append",
"(",
"sources",
"[",
"pos",
"]",
")",
"new_target_dicts",
"[",
"name",
"]",
"[",
"'sources'",
"]",
"=",
"new_sources",
"else",
":",
"new_target_dicts",
"[",
"t",
"]",
"=",
"target_dicts",
"[",
"t",
"]",
"# Shard dependencies.",
"for",
"t",
"in",
"new_target_dicts",
":",
"dependencies",
"=",
"copy",
".",
"copy",
"(",
"new_target_dicts",
"[",
"t",
"]",
".",
"get",
"(",
"'dependencies'",
",",
"[",
"]",
")",
")",
"new_dependencies",
"=",
"[",
"]",
"for",
"d",
"in",
"dependencies",
":",
"if",
"d",
"in",
"targets_to_shard",
":",
"for",
"i",
"in",
"range",
"(",
"targets_to_shard",
"[",
"d",
"]",
")",
":",
"new_dependencies",
".",
"append",
"(",
"_ShardName",
"(",
"d",
",",
"i",
")",
")",
"else",
":",
"new_dependencies",
".",
"append",
"(",
"d",
")",
"new_target_dicts",
"[",
"t",
"]",
"[",
"'dependencies'",
"]",
"=",
"new_dependencies",
"return",
"(",
"new_target_list",
",",
"new_target_dicts",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py#L1735-L1786 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/utils/extmath.py | python | stable_cumsum | (arr, axis=None, rtol=1e-05, atol=1e-08) | return out | Use high precision for cumsum and check that final value matches sum
Parameters
----------
arr : array-like
To be cumulatively summed as flat
axis : int, optional
Axis along which the cumulative sum is computed.
The default (None) is to compute the cumsum over the flattened array.
rtol : float
Relative tolerance, see ``np.allclose``
atol : float
Absolute tolerance, see ``np.allclose`` | Use high precision for cumsum and check that final value matches sum | [
"Use",
"high",
"precision",
"for",
"cumsum",
"and",
"check",
"that",
"final",
"value",
"matches",
"sum"
] | def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
"""Use high precision for cumsum and check that final value matches sum
Parameters
----------
arr : array-like
To be cumulatively summed as flat
axis : int, optional
Axis along which the cumulative sum is computed.
The default (None) is to compute the cumsum over the flattened array.
rtol : float
Relative tolerance, see ``np.allclose``
atol : float
Absolute tolerance, see ``np.allclose``
"""
out = np.cumsum(arr, axis=axis, dtype=np.float64)
expected = np.sum(arr, axis=axis, dtype=np.float64)
if not np.all(np.isclose(out.take(-1, axis=axis), expected, rtol=rtol,
atol=atol, equal_nan=True)):
warnings.warn('cumsum was found to be unstable: '
'its last element does not correspond to sum',
RuntimeWarning)
return out | [
"def",
"stable_cumsum",
"(",
"arr",
",",
"axis",
"=",
"None",
",",
"rtol",
"=",
"1e-05",
",",
"atol",
"=",
"1e-08",
")",
":",
"out",
"=",
"np",
".",
"cumsum",
"(",
"arr",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"expected",
"=",
"np",
".",
"sum",
"(",
"arr",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"not",
"np",
".",
"all",
"(",
"np",
".",
"isclose",
"(",
"out",
".",
"take",
"(",
"-",
"1",
",",
"axis",
"=",
"axis",
")",
",",
"expected",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
",",
"equal_nan",
"=",
"True",
")",
")",
":",
"warnings",
".",
"warn",
"(",
"'cumsum was found to be unstable: '",
"'its last element does not correspond to sum'",
",",
"RuntimeWarning",
")",
"return",
"out"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/extmath.py#L810-L832 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/core/cros_interface.py | python | CrOSInterface.GetChromePid | (self) | return None | Returns pid of main chrome browser process. | Returns pid of main chrome browser process. | [
"Returns",
"pid",
"of",
"main",
"chrome",
"browser",
"process",
"."
] | def GetChromePid(self):
"""Returns pid of main chrome browser process."""
result = self.GetChromeProcess()
if result and 'pid' in result:
return result['pid']
return None | [
"def",
"GetChromePid",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"GetChromeProcess",
"(",
")",
"if",
"result",
"and",
"'pid'",
"in",
"result",
":",
"return",
"result",
"[",
"'pid'",
"]",
"return",
"None"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/cros_interface.py#L393-L398 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/function_base.py | python | logspace | (start,stop,num=50,endpoint=True,base=10.0) | return _nx.power(base, y) | Return numbers spaced evenly on a log scale.
In linear space, the sequence starts at ``base ** start``
(`base` to the power of `start`) and ends with ``base ** stop``
(see `endpoint` below).
Parameters
----------
start : float
``base ** start`` is the starting value of the sequence.
stop : float
``base ** stop`` is the final value of the sequence, unless `endpoint`
is False. In that case, ``num + 1`` values are spaced over the
interval in log-space, of which all but the last (a sequence of
length ``num``) are returned.
num : integer, optional
Number of samples to generate. Default is 50.
endpoint : boolean, optional
If true, `stop` is the last sample. Otherwise, it is not included.
Default is True.
base : float, optional
The base of the log space. The step size between the elements in
``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
Default is 10.0.
Returns
-------
samples : ndarray
`num` samples, equally spaced on a log scale.
See Also
--------
arange : Similar to linspace, with the step size specified instead of the
number of samples. Note that, when used with a float endpoint, the
endpoint may or may not be included.
linspace : Similar to logspace, but with the samples uniformly distributed
in linear space, instead of log space.
Notes
-----
Logspace is equivalent to the code
>>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
... # doctest: +SKIP
>>> power(base, y)
... # doctest: +SKIP
Examples
--------
>>> np.logspace(2.0, 3.0, num=4)
array([ 100. , 215.443469 , 464.15888336, 1000. ])
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
array([ 100. , 177.827941 , 316.22776602, 562.34132519])
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
array([ 4. , 5.0396842 , 6.34960421, 8. ])
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 10
>>> x1 = np.logspace(0.1, 1, N, endpoint=True)
>>> x2 = np.logspace(0.1, 1, N, endpoint=False)
>>> y = np.zeros(N)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show() | Return numbers spaced evenly on a log scale. | [
"Return",
"numbers",
"spaced",
"evenly",
"on",
"a",
"log",
"scale",
"."
] | def logspace(start,stop,num=50,endpoint=True,base=10.0):
"""
Return numbers spaced evenly on a log scale.
In linear space, the sequence starts at ``base ** start``
(`base` to the power of `start`) and ends with ``base ** stop``
(see `endpoint` below).
Parameters
----------
start : float
``base ** start`` is the starting value of the sequence.
stop : float
``base ** stop`` is the final value of the sequence, unless `endpoint`
is False. In that case, ``num + 1`` values are spaced over the
interval in log-space, of which all but the last (a sequence of
length ``num``) are returned.
num : integer, optional
Number of samples to generate. Default is 50.
endpoint : boolean, optional
If true, `stop` is the last sample. Otherwise, it is not included.
Default is True.
base : float, optional
The base of the log space. The step size between the elements in
``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
Default is 10.0.
Returns
-------
samples : ndarray
`num` samples, equally spaced on a log scale.
See Also
--------
arange : Similar to linspace, with the step size specified instead of the
number of samples. Note that, when used with a float endpoint, the
endpoint may or may not be included.
linspace : Similar to logspace, but with the samples uniformly distributed
in linear space, instead of log space.
Notes
-----
Logspace is equivalent to the code
>>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
... # doctest: +SKIP
>>> power(base, y)
... # doctest: +SKIP
Examples
--------
>>> np.logspace(2.0, 3.0, num=4)
array([ 100. , 215.443469 , 464.15888336, 1000. ])
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
array([ 100. , 177.827941 , 316.22776602, 562.34132519])
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
array([ 4. , 5.0396842 , 6.34960421, 8. ])
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 10
>>> x1 = np.logspace(0.1, 1, N, endpoint=True)
>>> x2 = np.logspace(0.1, 1, N, endpoint=False)
>>> y = np.zeros(N)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
"""
y = linspace(start, stop, num=num, endpoint=endpoint)
return _nx.power(base, y) | [
"def",
"logspace",
"(",
"start",
",",
"stop",
",",
"num",
"=",
"50",
",",
"endpoint",
"=",
"True",
",",
"base",
"=",
"10.0",
")",
":",
"y",
"=",
"linspace",
"(",
"start",
",",
"stop",
",",
"num",
"=",
"num",
",",
"endpoint",
"=",
"endpoint",
")",
"return",
"_nx",
".",
"power",
"(",
"base",
",",
"y",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/function_base.py#L98-L173 | |
CaoWGG/TensorRT-CenterNet | f949252e37b51e60f873808f46d3683f15735e79 | onnx-tensorrt/third_party/onnx/third_party/benchmark/tools/strip_asm.py | python | process_asm | (asm) | return new_contents | Strip the ASM of unwanted directives and lines | Strip the ASM of unwanted directives and lines | [
"Strip",
"the",
"ASM",
"of",
"unwanted",
"directives",
"and",
"lines"
] | def process_asm(asm):
"""
Strip the ASM of unwanted directives and lines
"""
new_contents = ''
asm = transform_labels(asm)
# TODO: Add more things we want to remove
discard_regexes = [
re.compile("\s+\..*$"), # directive
re.compile("\s*#(NO_APP|APP)$"), #inline ASM
re.compile("\s*#.*$"), # comment line
re.compile("\s*\.globa?l\s*([.a-zA-Z_][a-zA-Z0-9$_.]*)"), #global directive
re.compile("\s*\.(string|asciz|ascii|[1248]?byte|short|word|long|quad|value|zero)"),
]
keep_regexes = [
]
fn_label_def = re.compile("^[a-zA-Z_][a-zA-Z0-9_.]*:")
for l in asm.splitlines():
# Remove Mach-O attribute
l = l.replace('@GOTPCREL', '')
add_line = True
for reg in discard_regexes:
if reg.match(l) is not None:
add_line = False
break
for reg in keep_regexes:
if reg.match(l) is not None:
add_line = True
break
if add_line:
if fn_label_def.match(l) and len(new_contents) != 0:
new_contents += '\n'
l = process_identifiers(l)
new_contents += l
new_contents += '\n'
return new_contents | [
"def",
"process_asm",
"(",
"asm",
")",
":",
"new_contents",
"=",
"''",
"asm",
"=",
"transform_labels",
"(",
"asm",
")",
"# TODO: Add more things we want to remove",
"discard_regexes",
"=",
"[",
"re",
".",
"compile",
"(",
"\"\\s+\\..*$\"",
")",
",",
"# directive",
"re",
".",
"compile",
"(",
"\"\\s*#(NO_APP|APP)$\"",
")",
",",
"#inline ASM",
"re",
".",
"compile",
"(",
"\"\\s*#.*$\"",
")",
",",
"# comment line",
"re",
".",
"compile",
"(",
"\"\\s*\\.globa?l\\s*([.a-zA-Z_][a-zA-Z0-9$_.]*)\"",
")",
",",
"#global directive",
"re",
".",
"compile",
"(",
"\"\\s*\\.(string|asciz|ascii|[1248]?byte|short|word|long|quad|value|zero)\"",
")",
",",
"]",
"keep_regexes",
"=",
"[",
"]",
"fn_label_def",
"=",
"re",
".",
"compile",
"(",
"\"^[a-zA-Z_][a-zA-Z0-9_.]*:\"",
")",
"for",
"l",
"in",
"asm",
".",
"splitlines",
"(",
")",
":",
"# Remove Mach-O attribute",
"l",
"=",
"l",
".",
"replace",
"(",
"'@GOTPCREL'",
",",
"''",
")",
"add_line",
"=",
"True",
"for",
"reg",
"in",
"discard_regexes",
":",
"if",
"reg",
".",
"match",
"(",
"l",
")",
"is",
"not",
"None",
":",
"add_line",
"=",
"False",
"break",
"for",
"reg",
"in",
"keep_regexes",
":",
"if",
"reg",
".",
"match",
"(",
"l",
")",
"is",
"not",
"None",
":",
"add_line",
"=",
"True",
"break",
"if",
"add_line",
":",
"if",
"fn_label_def",
".",
"match",
"(",
"l",
")",
"and",
"len",
"(",
"new_contents",
")",
"!=",
"0",
":",
"new_contents",
"+=",
"'\\n'",
"l",
"=",
"process_identifiers",
"(",
"l",
")",
"new_contents",
"+=",
"l",
"new_contents",
"+=",
"'\\n'",
"return",
"new_contents"
] | https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/benchmark/tools/strip_asm.py#L84-L121 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/dataframe.py | python | DataFrame.apply_chunks | (
self,
func,
incols,
outcols,
kwargs=None,
pessimistic_nulls=True,
chunks=None,
blkct=None,
tpb=None,
) | return applyutils.apply_chunks(
self,
func,
incols,
outcols,
kwargs,
pessimistic_nulls,
chunks,
tpb=tpb,
) | Transform user-specified chunks using the user-provided function.
Parameters
----------
{params}
{params_chunks}
Examples
--------
For ``tpb > 1``, ``func`` is executed by ``tpb`` number of threads
concurrently. To access the thread id and count,
use ``numba.cuda.threadIdx.x`` and ``numba.cuda.blockDim.x``,
respectively (See `numba CUDA kernel documentation`_).
.. _numba CUDA kernel documentation:\
http://numba.pydata.org/numba-doc/latest/cuda/kernels.html
In the example below, the *kernel* is invoked concurrently on each
specified chunk. The *kernel* computes the corresponding output
for the chunk.
By looping over the range
``range(cuda.threadIdx.x, in1.size, cuda.blockDim.x)``, the *kernel*
function can be used with any *tpb* in an efficient manner.
>>> from numba import cuda
>>> @cuda.jit
... def kernel(in1, in2, in3, out1):
... for i in range(cuda.threadIdx.x, in1.size, cuda.blockDim.x):
... x = in1[i]
... y = in2[i]
... z = in3[i]
... out1[i] = x * y + z
See also
--------
DataFrame.apply_rows | Transform user-specified chunks using the user-provided function. | [
"Transform",
"user",
"-",
"specified",
"chunks",
"using",
"the",
"user",
"-",
"provided",
"function",
"."
] | def apply_chunks(
self,
func,
incols,
outcols,
kwargs=None,
pessimistic_nulls=True,
chunks=None,
blkct=None,
tpb=None,
):
"""
Transform user-specified chunks using the user-provided function.
Parameters
----------
{params}
{params_chunks}
Examples
--------
For ``tpb > 1``, ``func`` is executed by ``tpb`` number of threads
concurrently. To access the thread id and count,
use ``numba.cuda.threadIdx.x`` and ``numba.cuda.blockDim.x``,
respectively (See `numba CUDA kernel documentation`_).
.. _numba CUDA kernel documentation:\
http://numba.pydata.org/numba-doc/latest/cuda/kernels.html
In the example below, the *kernel* is invoked concurrently on each
specified chunk. The *kernel* computes the corresponding output
for the chunk.
By looping over the range
``range(cuda.threadIdx.x, in1.size, cuda.blockDim.x)``, the *kernel*
function can be used with any *tpb* in an efficient manner.
>>> from numba import cuda
>>> @cuda.jit
... def kernel(in1, in2, in3, out1):
... for i in range(cuda.threadIdx.x, in1.size, cuda.blockDim.x):
... x = in1[i]
... y = in2[i]
... z = in3[i]
... out1[i] = x * y + z
See also
--------
DataFrame.apply_rows
"""
if kwargs is None:
kwargs = {}
if chunks is None:
raise ValueError("*chunks* must be defined")
return applyutils.apply_chunks(
self,
func,
incols,
outcols,
kwargs,
pessimistic_nulls,
chunks,
tpb=tpb,
) | [
"def",
"apply_chunks",
"(",
"self",
",",
"func",
",",
"incols",
",",
"outcols",
",",
"kwargs",
"=",
"None",
",",
"pessimistic_nulls",
"=",
"True",
",",
"chunks",
"=",
"None",
",",
"blkct",
"=",
"None",
",",
"tpb",
"=",
"None",
",",
")",
":",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"if",
"chunks",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"*chunks* must be defined\"",
")",
"return",
"applyutils",
".",
"apply_chunks",
"(",
"self",
",",
"func",
",",
"incols",
",",
"outcols",
",",
"kwargs",
",",
"pessimistic_nulls",
",",
"chunks",
",",
"tpb",
"=",
"tpb",
",",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/dataframe.py#L3913-L3977 | |
SonarOpenCommunity/sonar-cxx | 6e1d456fdcd45d35bcdc61c980e34d85fe88971e | cxx-squid/dox/tools/grammar_parser/grammar_parser.py | python | GrammarParser.root | (self, rulename) | Define root rule, search all dependant rules and remove all other rules. | Define root rule, search all dependant rules and remove all other rules. | [
"Define",
"root",
"rule",
"search",
"all",
"dependant",
"rules",
"and",
"remove",
"all",
"other",
"rules",
"."
] | def root(self, rulename):
"""
Define root rule, search all dependant rules and remove all other rules.
"""
expressions = {} # use map instead of set to keep order
expressions = self.__dependencies(rulename, expressions)
rules = {}
for expression in expressions:
if expression in self.rules:
rules[expression] = self.rules[expression]
self.rules = rules | [
"def",
"root",
"(",
"self",
",",
"rulename",
")",
":",
"expressions",
"=",
"{",
"}",
"# use map instead of set to keep order",
"expressions",
"=",
"self",
".",
"__dependencies",
"(",
"rulename",
",",
"expressions",
")",
"rules",
"=",
"{",
"}",
"for",
"expression",
"in",
"expressions",
":",
"if",
"expression",
"in",
"self",
".",
"rules",
":",
"rules",
"[",
"expression",
"]",
"=",
"self",
".",
"rules",
"[",
"expression",
"]",
"self",
".",
"rules",
"=",
"rules"
] | https://github.com/SonarOpenCommunity/sonar-cxx/blob/6e1d456fdcd45d35bcdc61c980e34d85fe88971e/cxx-squid/dox/tools/grammar_parser/grammar_parser.py#L117-L127 | ||
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | InputStringArrayBucketArgument.IsPointer2D | (self) | return True | Overridden from Argument. | Overridden from Argument. | [
"Overridden",
"from",
"Argument",
"."
] | def IsPointer2D(self):
"""Overridden from Argument."""
return True | [
"def",
"IsPointer2D",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9084-L9086 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cef_parser.py | python | obj_function.get_capi_name | (self, prefix = None) | return get_capi_name(self.name, False, prefix) | Return the CAPI function name. | Return the CAPI function name. | [
"Return",
"the",
"CAPI",
"function",
"name",
"."
] | def get_capi_name(self, prefix = None):
""" Return the CAPI function name. """
if 'capi_name' in self.attribs:
return self.attribs['capi_name']
return get_capi_name(self.name, False, prefix) | [
"def",
"get_capi_name",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"'capi_name'",
"in",
"self",
".",
"attribs",
":",
"return",
"self",
".",
"attribs",
"[",
"'capi_name'",
"]",
"return",
"get_capi_name",
"(",
"self",
".",
"name",
",",
"False",
",",
"prefix",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cef_parser.py#L1097-L1101 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/mingw32ccompiler.py | python | generate_def | (dll, dfile) | Given a dll file location, get all its exported symbols and dump them
into the given def file.
The .def file will be overwritten | Given a dll file location, get all its exported symbols and dump them
into the given def file. | [
"Given",
"a",
"dll",
"file",
"location",
"get",
"all",
"its",
"exported",
"symbols",
"and",
"dump",
"them",
"into",
"the",
"given",
"def",
"file",
"."
] | def generate_def(dll, dfile):
"""Given a dll file location, get all its exported symbols and dump them
into the given def file.
The .def file will be overwritten"""
dump = dump_table(dll)
for i in range(len(dump)):
if _START.match(dump[i].decode()):
break
else:
raise ValueError("Symbol table not found")
syms = []
for j in range(i+1, len(dump)):
m = _TABLE.match(dump[j].decode())
if m:
syms.append((int(m.group(1).strip()), m.group(2)))
else:
break
if len(syms) == 0:
log.warn('No symbols found in %s' % dll)
d = open(dfile, 'w')
d.write('LIBRARY %s\n' % os.path.basename(dll))
d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n')
d.write(';DATA PRELOAD SINGLE\n')
d.write('\nEXPORTS\n')
for s in syms:
#d.write('@%d %s\n' % (s[0], s[1]))
d.write('%s\n' % s[1])
d.close() | [
"def",
"generate_def",
"(",
"dll",
",",
"dfile",
")",
":",
"dump",
"=",
"dump_table",
"(",
"dll",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"dump",
")",
")",
":",
"if",
"_START",
".",
"match",
"(",
"dump",
"[",
"i",
"]",
".",
"decode",
"(",
")",
")",
":",
"break",
"else",
":",
"raise",
"ValueError",
"(",
"\"Symbol table not found\"",
")",
"syms",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"len",
"(",
"dump",
")",
")",
":",
"m",
"=",
"_TABLE",
".",
"match",
"(",
"dump",
"[",
"j",
"]",
".",
"decode",
"(",
")",
")",
"if",
"m",
":",
"syms",
".",
"append",
"(",
"(",
"int",
"(",
"m",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
",",
"m",
".",
"group",
"(",
"2",
")",
")",
")",
"else",
":",
"break",
"if",
"len",
"(",
"syms",
")",
"==",
"0",
":",
"log",
".",
"warn",
"(",
"'No symbols found in %s'",
"%",
"dll",
")",
"d",
"=",
"open",
"(",
"dfile",
",",
"'w'",
")",
"d",
".",
"write",
"(",
"'LIBRARY %s\\n'",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"dll",
")",
")",
"d",
".",
"write",
"(",
"';CODE PRELOAD MOVEABLE DISCARDABLE\\n'",
")",
"d",
".",
"write",
"(",
"';DATA PRELOAD SINGLE\\n'",
")",
"d",
".",
"write",
"(",
"'\\nEXPORTS\\n'",
")",
"for",
"s",
"in",
"syms",
":",
"#d.write('@%d %s\\n' % (s[0], s[1]))",
"d",
".",
"write",
"(",
"'%s\\n'",
"%",
"s",
"[",
"1",
"]",
")",
"d",
".",
"close",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/mingw32ccompiler.py#L268-L299 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py | python | Babyl._pre_mailbox_hook | (self, f) | Called before writing the mailbox to file f. | Called before writing the mailbox to file f. | [
"Called",
"before",
"writing",
"the",
"mailbox",
"to",
"file",
"f",
"."
] | def _pre_mailbox_hook(self, f):
"""Called before writing the mailbox to file f."""
babyl = b'BABYL OPTIONS:' + linesep
babyl += b'Version: 5' + linesep
labels = self.get_labels()
labels = (label.encode() for label in labels)
babyl += b'Labels:' + b','.join(labels) + linesep
babyl += b'\037'
f.write(babyl) | [
"def",
"_pre_mailbox_hook",
"(",
"self",
",",
"f",
")",
":",
"babyl",
"=",
"b'BABYL OPTIONS:'",
"+",
"linesep",
"babyl",
"+=",
"b'Version: 5'",
"+",
"linesep",
"labels",
"=",
"self",
".",
"get_labels",
"(",
")",
"labels",
"=",
"(",
"label",
".",
"encode",
"(",
")",
"for",
"label",
"in",
"labels",
")",
"babyl",
"+=",
"b'Labels:'",
"+",
"b','",
".",
"join",
"(",
"labels",
")",
"+",
"linesep",
"babyl",
"+=",
"b'\\037'",
"f",
".",
"write",
"(",
"babyl",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py#L1360-L1368 | ||
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | TokenGroup.get_tokens | (tu, extent) | Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place. | Helper method to return all tokens in an extent. | [
"Helper",
"method",
"to",
"return",
"all",
"tokens",
"in",
"an",
"extent",
"."
] | def get_tokens(tu, extent):
"""Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place.
"""
tokens_memory = POINTER(Token)()
tokens_count = c_uint()
conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
byref(tokens_count))
count = int(tokens_count.value)
# If we get no tokens, no memory was allocated. Be sure not to return
# anything and potentially call a destructor on nothing.
if count < 1:
return
tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
token_group = TokenGroup(tu, tokens_memory, tokens_count)
for i in xrange(0, count):
token = Token()
token.int_data = tokens_array[i].int_data
token.ptr_data = tokens_array[i].ptr_data
token._tu = tu
token._group = token_group
yield token | [
"def",
"get_tokens",
"(",
"tu",
",",
"extent",
")",
":",
"tokens_memory",
"=",
"POINTER",
"(",
"Token",
")",
"(",
")",
"tokens_count",
"=",
"c_uint",
"(",
")",
"conf",
".",
"lib",
".",
"clang_tokenize",
"(",
"tu",
",",
"extent",
",",
"byref",
"(",
"tokens_memory",
")",
",",
"byref",
"(",
"tokens_count",
")",
")",
"count",
"=",
"int",
"(",
"tokens_count",
".",
"value",
")",
"# If we get no tokens, no memory was allocated. Be sure not to return",
"# anything and potentially call a destructor on nothing.",
"if",
"count",
"<",
"1",
":",
"return",
"tokens_array",
"=",
"cast",
"(",
"tokens_memory",
",",
"POINTER",
"(",
"Token",
"*",
"count",
")",
")",
".",
"contents",
"token_group",
"=",
"TokenGroup",
"(",
"tu",
",",
"tokens_memory",
",",
"tokens_count",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"count",
")",
":",
"token",
"=",
"Token",
"(",
")",
"token",
".",
"int_data",
"=",
"tokens_array",
"[",
"i",
"]",
".",
"int_data",
"token",
".",
"ptr_data",
"=",
"tokens_array",
"[",
"i",
"]",
".",
"ptr_data",
"token",
".",
"_tu",
"=",
"tu",
"token",
".",
"_group",
"=",
"token_group",
"yield",
"token"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L406-L436 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetExecutableName | (self) | Returns the executable name of the bundle represented by this target.
E.g. Chromium. | Returns the executable name of the bundle represented by this target.
E.g. Chromium. | [
"Returns",
"the",
"executable",
"name",
"of",
"the",
"bundle",
"represented",
"by",
"this",
"target",
".",
"E",
".",
"g",
".",
"Chromium",
"."
] | def GetExecutableName(self):
"""Returns the executable name of the bundle represented by this target.
E.g. Chromium."""
if self._IsBundle():
return self.spec.get('product_name', self.spec['target_name'])
else:
return self._GetStandaloneBinaryPath() | [
"def",
"GetExecutableName",
"(",
"self",
")",
":",
"if",
"self",
".",
"_IsBundle",
"(",
")",
":",
"return",
"self",
".",
"spec",
".",
"get",
"(",
"'product_name'",
",",
"self",
".",
"spec",
"[",
"'target_name'",
"]",
")",
"else",
":",
"return",
"self",
".",
"_GetStandaloneBinaryPath",
"(",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/xcode_emulation.py#L467-L473 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Node/FS.py | python | FS.__init__ | (self, path = None) | Initialize the Node.FS subsystem.
The supplied path is the top of the source tree, where we
expect to find the top-level build file. If no path is
supplied, the current directory is the default.
The path argument must be a valid absolute path. | Initialize the Node.FS subsystem. | [
"Initialize",
"the",
"Node",
".",
"FS",
"subsystem",
"."
] | def __init__(self, path = None):
"""Initialize the Node.FS subsystem.
The supplied path is the top of the source tree, where we
expect to find the top-level build file. If no path is
supplied, the current directory is the default.
The path argument must be a valid absolute path.
"""
if SCons.Debug.track_instances: logInstanceCreation(self, 'Node.FS')
self._memo = {}
self.Root = {}
self.SConstruct_dir = None
self.max_drift = default_max_drift
self.Top = None
if path is None:
self.pathTop = os.getcwd()
else:
self.pathTop = path
self.defaultDrive = _my_normcase(_my_splitdrive(self.pathTop)[0])
self.Top = self.Dir(self.pathTop)
self.Top._path = '.'
self.Top._tpath = '.'
self._cwd = self.Top
DirNodeInfo.fs = self
FileNodeInfo.fs = self | [
"def",
"__init__",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"if",
"SCons",
".",
"Debug",
".",
"track_instances",
":",
"logInstanceCreation",
"(",
"self",
",",
"'Node.FS'",
")",
"self",
".",
"_memo",
"=",
"{",
"}",
"self",
".",
"Root",
"=",
"{",
"}",
"self",
".",
"SConstruct_dir",
"=",
"None",
"self",
".",
"max_drift",
"=",
"default_max_drift",
"self",
".",
"Top",
"=",
"None",
"if",
"path",
"is",
"None",
":",
"self",
".",
"pathTop",
"=",
"os",
".",
"getcwd",
"(",
")",
"else",
":",
"self",
".",
"pathTop",
"=",
"path",
"self",
".",
"defaultDrive",
"=",
"_my_normcase",
"(",
"_my_splitdrive",
"(",
"self",
".",
"pathTop",
")",
"[",
"0",
"]",
")",
"self",
".",
"Top",
"=",
"self",
".",
"Dir",
"(",
"self",
".",
"pathTop",
")",
"self",
".",
"Top",
".",
"_path",
"=",
"'.'",
"self",
".",
"Top",
".",
"_tpath",
"=",
"'.'",
"self",
".",
"_cwd",
"=",
"self",
".",
"Top",
"DirNodeInfo",
".",
"fs",
"=",
"self",
"FileNodeInfo",
".",
"fs",
"=",
"self"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L1165-L1195 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/collections.py | python | Counter.elements | (self) | return _chain.from_iterable(_starmap(_repeat, self.iteritems())) | Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_factors.elements(): # loop over factors
... product *= factor # and multiply them
>>> product
1836
Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it. | Iterator over elements repeating each as many times as its count. | [
"Iterator",
"over",
"elements",
"repeating",
"each",
"as",
"many",
"times",
"as",
"its",
"count",
"."
] | def elements(self):
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_factors.elements(): # loop over factors
... product *= factor # and multiply them
>>> product
1836
Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it.
'''
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
return _chain.from_iterable(_starmap(_repeat, self.iteritems())) | [
"def",
"elements",
"(",
"self",
")",
":",
"# Emulate Bag.do from Smalltalk and Multiset.begin from C++.",
"return",
"_chain",
".",
"from_iterable",
"(",
"_starmap",
"(",
"_repeat",
",",
"self",
".",
"iteritems",
"(",
")",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/collections.py#L464-L484 | |
omnisci/omniscidb | b9c95f1bd602b4ffc8b0edf18bfad61031e08d86 | python/omnisci/cursor.py | python | Cursor.fetchone | (self) | Fetch a single row from the results set | Fetch a single row from the results set | [
"Fetch",
"a",
"single",
"row",
"from",
"the",
"results",
"set"
] | def fetchone(self):
"""Fetch a single row from the results set"""
try:
return next(self.result_set)
except StopIteration:
return None | [
"def",
"fetchone",
"(",
"self",
")",
":",
"try",
":",
"return",
"next",
"(",
"self",
".",
"result_set",
")",
"except",
"StopIteration",
":",
"return",
"None"
] | https://github.com/omnisci/omniscidb/blob/b9c95f1bd602b4ffc8b0edf18bfad61031e08d86/python/omnisci/cursor.py#L150-L155 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/array_algos/quantile.py | python | quantile_compat | (values: ArrayLike, qs: np.ndarray, interpolation: str) | Compute the quantiles of the given values for each quantile in `qs`.
Parameters
----------
values : np.ndarray or ExtensionArray
qs : np.ndarray[float64]
interpolation : str
Returns
-------
np.ndarray or ExtensionArray | Compute the quantiles of the given values for each quantile in `qs`. | [
"Compute",
"the",
"quantiles",
"of",
"the",
"given",
"values",
"for",
"each",
"quantile",
"in",
"qs",
"."
] | def quantile_compat(values: ArrayLike, qs: np.ndarray, interpolation: str) -> ArrayLike:
"""
Compute the quantiles of the given values for each quantile in `qs`.
Parameters
----------
values : np.ndarray or ExtensionArray
qs : np.ndarray[float64]
interpolation : str
Returns
-------
np.ndarray or ExtensionArray
"""
if isinstance(values, np.ndarray):
fill_value = na_value_for_dtype(values.dtype, compat=False)
mask = isna(values)
return _quantile_with_mask(values, mask, fill_value, qs, interpolation)
else:
# In general we don't want to import from arrays here;
# this is temporary pending discussion in GH#41428
from pandas.core.arrays import BaseMaskedArray
if isinstance(values, BaseMaskedArray):
# e.g. IntegerArray, does not implement _from_factorized
out = _quantile_ea_fallback(values, qs, interpolation)
else:
out = _quantile_ea_compat(values, qs, interpolation)
return out | [
"def",
"quantile_compat",
"(",
"values",
":",
"ArrayLike",
",",
"qs",
":",
"np",
".",
"ndarray",
",",
"interpolation",
":",
"str",
")",
"->",
"ArrayLike",
":",
"if",
"isinstance",
"(",
"values",
",",
"np",
".",
"ndarray",
")",
":",
"fill_value",
"=",
"na_value_for_dtype",
"(",
"values",
".",
"dtype",
",",
"compat",
"=",
"False",
")",
"mask",
"=",
"isna",
"(",
"values",
")",
"return",
"_quantile_with_mask",
"(",
"values",
",",
"mask",
",",
"fill_value",
",",
"qs",
",",
"interpolation",
")",
"else",
":",
"# In general we don't want to import from arrays here;",
"# this is temporary pending discussion in GH#41428",
"from",
"pandas",
".",
"core",
".",
"arrays",
"import",
"BaseMaskedArray",
"if",
"isinstance",
"(",
"values",
",",
"BaseMaskedArray",
")",
":",
"# e.g. IntegerArray, does not implement _from_factorized",
"out",
"=",
"_quantile_ea_fallback",
"(",
"values",
",",
"qs",
",",
"interpolation",
")",
"else",
":",
"out",
"=",
"_quantile_ea_compat",
"(",
"values",
",",
"qs",
",",
"interpolation",
")",
"return",
"out"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/array_algos/quantile.py#L21-L51 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/third_party/jinja2/filters.py | python | environmentfilter | (f) | return f | Decorator for marking evironment dependent filters. The current
:class:`Environment` is passed to the filter as first argument. | Decorator for marking evironment dependent filters. The current
:class:`Environment` is passed to the filter as first argument. | [
"Decorator",
"for",
"marking",
"evironment",
"dependent",
"filters",
".",
"The",
"current",
":",
"class",
":",
"Environment",
"is",
"passed",
"to",
"the",
"filter",
"as",
"first",
"argument",
"."
] | def environmentfilter(f):
"""Decorator for marking evironment dependent filters. The current
:class:`Environment` is passed to the filter as first argument.
"""
f.environmentfilter = True
return f | [
"def",
"environmentfilter",
"(",
"f",
")",
":",
"f",
".",
"environmentfilter",
"=",
"True",
"return",
"f"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/filters.py#L46-L51 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/ogl/_diagram.py | python | Diagram.Snap | (self, x, y) | return x, y | Snaps' the coordinate to the nearest grid position, if
snap-to-grid is on. | Snaps' the coordinate to the nearest grid position, if
snap-to-grid is on. | [
"Snaps",
"the",
"coordinate",
"to",
"the",
"nearest",
"grid",
"position",
"if",
"snap",
"-",
"to",
"-",
"grid",
"is",
"on",
"."
] | def Snap(self, x, y):
"""'Snaps' the coordinate to the nearest grid position, if
snap-to-grid is on."""
if self._snapToGrid:
return self._gridSpacing * int(x / self._gridSpacing + 0.5), self._gridSpacing * int(y / self._gridSpacing + 0.5)
return x, y | [
"def",
"Snap",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"self",
".",
"_snapToGrid",
":",
"return",
"self",
".",
"_gridSpacing",
"*",
"int",
"(",
"x",
"/",
"self",
".",
"_gridSpacing",
"+",
"0.5",
")",
",",
"self",
".",
"_gridSpacing",
"*",
"int",
"(",
"y",
"/",
"self",
".",
"_gridSpacing",
"+",
"0.5",
")",
"return",
"x",
",",
"y"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_diagram.py#L115-L120 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py | python | RawTurtle.clear | (self) | Delete the turtle's drawings from the screen. Do not move turtle.
No arguments.
Delete the turtle's drawings from the screen. Do not move turtle.
State and position of the turtle as well as drawings of other
turtles are not affected.
Examples (for a Turtle instance named turtle):
>>> turtle.clear() | Delete the turtle's drawings from the screen. Do not move turtle. | [
"Delete",
"the",
"turtle",
"s",
"drawings",
"from",
"the",
"screen",
".",
"Do",
"not",
"move",
"turtle",
"."
] | def clear(self):
"""Delete the turtle's drawings from the screen. Do not move turtle.
No arguments.
Delete the turtle's drawings from the screen. Do not move turtle.
State and position of the turtle as well as drawings of other
turtles are not affected.
Examples (for a Turtle instance named turtle):
>>> turtle.clear()
"""
self._clear()
self._update() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_clear",
"(",
")",
"self",
".",
"_update",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L2534-L2547 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/mesa/MesaLib/src/mapi/glapi/gen/gl_XML.py | python | classify_category | (name, number) | return [cat_type, key] | Based on the category name and number, select a numerical class for it.
Categories are divided into four classes numbered 0 through 3. The
classes are:
0. Core GL versions, sorted by version number.
1. ARB extensions, sorted by extension number.
2. Non-ARB extensions, sorted by extension number.
3. Un-numbered extensions, sorted by extension name. | Based on the category name and number, select a numerical class for it.
Categories are divided into four classes numbered 0 through 3. The
classes are: | [
"Based",
"on",
"the",
"category",
"name",
"and",
"number",
"select",
"a",
"numerical",
"class",
"for",
"it",
".",
"Categories",
"are",
"divided",
"into",
"four",
"classes",
"numbered",
"0",
"through",
"3",
".",
"The",
"classes",
"are",
":"
] | def classify_category(name, number):
"""Based on the category name and number, select a numerical class for it.
Categories are divided into four classes numbered 0 through 3. The
classes are:
0. Core GL versions, sorted by version number.
1. ARB extensions, sorted by extension number.
2. Non-ARB extensions, sorted by extension number.
3. Un-numbered extensions, sorted by extension name.
"""
try:
core_version = float(name)
except Exception,e:
core_version = 0.0
if core_version > 0.0:
cat_type = 0
key = name
elif name.startswith("GL_ARB_") or name.startswith("GLX_ARB_") or name.startswith("WGL_ARB_"):
cat_type = 1
key = int(number)
else:
if number != None:
cat_type = 2
key = int(number)
else:
cat_type = 3
key = name
return [cat_type, key] | [
"def",
"classify_category",
"(",
"name",
",",
"number",
")",
":",
"try",
":",
"core_version",
"=",
"float",
"(",
"name",
")",
"except",
"Exception",
",",
"e",
":",
"core_version",
"=",
"0.0",
"if",
"core_version",
">",
"0.0",
":",
"cat_type",
"=",
"0",
"key",
"=",
"name",
"elif",
"name",
".",
"startswith",
"(",
"\"GL_ARB_\"",
")",
"or",
"name",
".",
"startswith",
"(",
"\"GLX_ARB_\"",
")",
"or",
"name",
".",
"startswith",
"(",
"\"WGL_ARB_\"",
")",
":",
"cat_type",
"=",
"1",
"key",
"=",
"int",
"(",
"number",
")",
"else",
":",
"if",
"number",
"!=",
"None",
":",
"cat_type",
"=",
"2",
"key",
"=",
"int",
"(",
"number",
")",
"else",
":",
"cat_type",
"=",
"3",
"key",
"=",
"name",
"return",
"[",
"cat_type",
",",
"key",
"]"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/mesa/MesaLib/src/mapi/glapi/gen/gl_XML.py#L272-L304 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py | python | GenerateClasspathFile | (target_list, target_dicts, toplevel_dir,
toplevel_build, out_name) | Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs. | Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs. | [
"Generates",
"a",
"classpath",
"file",
"suitable",
"for",
"symbol",
"navigation",
"and",
"code",
"completion",
"of",
"Java",
"code",
"(",
"such",
"as",
"in",
"Android",
"projects",
")",
"by",
"finding",
"all",
".",
"java",
"and",
".",
"jar",
"files",
"used",
"as",
"action",
"inputs",
"."
] | def GenerateClasspathFile(target_list, target_dicts, toplevel_dir,
toplevel_build, out_name):
'''Generates a classpath file suitable for symbol navigation and code
completion of Java code (such as in Android projects) by finding all
.java and .jar files used as action inputs.'''
gyp.common.EnsureDirExists(out_name)
result = ET.Element('classpath')
def AddElements(kind, paths):
# First, we need to normalize the paths so they are all relative to the
# toplevel dir.
rel_paths = set()
for path in paths:
if os.path.isabs(path):
rel_paths.add(os.path.relpath(path, toplevel_dir))
else:
rel_paths.add(path)
for path in sorted(rel_paths):
entry_element = ET.SubElement(result, 'classpathentry')
entry_element.set('kind', kind)
entry_element.set('path', path)
AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir))
AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir))
# Include the standard JRE container and a dummy out folder
AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER'])
# Include a dummy out folder so that Eclipse doesn't use the default /bin
# folder in the root of the project.
AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')])
ET.ElementTree(result).write(out_name) | [
"def",
"GenerateClasspathFile",
"(",
"target_list",
",",
"target_dicts",
",",
"toplevel_dir",
",",
"toplevel_build",
",",
"out_name",
")",
":",
"gyp",
".",
"common",
".",
"EnsureDirExists",
"(",
"out_name",
")",
"result",
"=",
"ET",
".",
"Element",
"(",
"'classpath'",
")",
"def",
"AddElements",
"(",
"kind",
",",
"paths",
")",
":",
"# First, we need to normalize the paths so they are all relative to the",
"# toplevel dir.",
"rel_paths",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"rel_paths",
".",
"add",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"toplevel_dir",
")",
")",
"else",
":",
"rel_paths",
".",
"add",
"(",
"path",
")",
"for",
"path",
"in",
"sorted",
"(",
"rel_paths",
")",
":",
"entry_element",
"=",
"ET",
".",
"SubElement",
"(",
"result",
",",
"'classpathentry'",
")",
"entry_element",
".",
"set",
"(",
"'kind'",
",",
"kind",
")",
"entry_element",
".",
"set",
"(",
"'path'",
",",
"path",
")",
"AddElements",
"(",
"'lib'",
",",
"GetJavaJars",
"(",
"target_list",
",",
"target_dicts",
",",
"toplevel_dir",
")",
")",
"AddElements",
"(",
"'src'",
",",
"GetJavaSourceDirs",
"(",
"target_list",
",",
"target_dicts",
",",
"toplevel_dir",
")",
")",
"# Include the standard JRE container and a dummy out folder",
"AddElements",
"(",
"'con'",
",",
"[",
"'org.eclipse.jdt.launching.JRE_CONTAINER'",
"]",
")",
"# Include a dummy out folder so that Eclipse doesn't use the default /bin",
"# folder in the root of the project.",
"AddElements",
"(",
"'output'",
",",
"[",
"os",
".",
"path",
".",
"join",
"(",
"toplevel_build",
",",
"'.eclipse-java-build'",
")",
"]",
")",
"ET",
".",
"ElementTree",
"(",
"result",
")",
".",
"write",
"(",
"out_name",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py#L337-L368 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/android/sdk/shared_prefs.py | python | BooleanPref.get | (self) | return type(self).VALUES[super(BooleanPref, self).get()] | Get the value as a Python bool. | Get the value as a Python bool. | [
"Get",
"the",
"value",
"as",
"a",
"Python",
"bool",
"."
] | def get(self):
"""Get the value as a Python bool."""
return type(self).VALUES[super(BooleanPref, self).get()] | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"type",
"(",
"self",
")",
".",
"VALUES",
"[",
"super",
"(",
"BooleanPref",
",",
"self",
")",
".",
"get",
"(",
")",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/sdk/shared_prefs.py#L69-L71 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | clang/tools/scan-build-py/lib/libear/__init__.py | python | build_libear | (compiler, dst_dir) | Returns the full path to the 'libear' library. | Returns the full path to the 'libear' library. | [
"Returns",
"the",
"full",
"path",
"to",
"the",
"libear",
"library",
"."
] | def build_libear(compiler, dst_dir):
""" Returns the full path to the 'libear' library. """
try:
src_dir = os.path.dirname(os.path.realpath(__file__))
toolset = make_toolset(src_dir)
toolset.set_compiler(compiler)
toolset.set_language_standard('c99')
toolset.add_definitions(['-D_GNU_SOURCE'])
configure = do_configure(toolset)
configure.check_function_exists('execve', 'HAVE_EXECVE')
configure.check_function_exists('execv', 'HAVE_EXECV')
configure.check_function_exists('execvpe', 'HAVE_EXECVPE')
configure.check_function_exists('execvp', 'HAVE_EXECVP')
configure.check_function_exists('execvP', 'HAVE_EXECVP2')
configure.check_function_exists('exect', 'HAVE_EXECT')
configure.check_function_exists('execl', 'HAVE_EXECL')
configure.check_function_exists('execlp', 'HAVE_EXECLP')
configure.check_function_exists('execle', 'HAVE_EXECLE')
configure.check_function_exists('posix_spawn', 'HAVE_POSIX_SPAWN')
configure.check_function_exists('posix_spawnp', 'HAVE_POSIX_SPAWNP')
configure.check_symbol_exists('_NSGetEnviron', 'crt_externs.h',
'HAVE_NSGETENVIRON')
configure.write_by_template(
os.path.join(src_dir, 'config.h.in'),
os.path.join(dst_dir, 'config.h'))
target = create_shared_library('ear', toolset)
target.add_include(dst_dir)
target.add_sources('ear.c')
target.link_against(toolset.dl_libraries())
target.link_against(['pthread'])
target.build_release(dst_dir)
return os.path.join(dst_dir, target.name)
except Exception:
logging.info("Could not build interception library.", exc_info=True)
return None | [
"def",
"build_libear",
"(",
"compiler",
",",
"dst_dir",
")",
":",
"try",
":",
"src_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"toolset",
"=",
"make_toolset",
"(",
"src_dir",
")",
"toolset",
".",
"set_compiler",
"(",
"compiler",
")",
"toolset",
".",
"set_language_standard",
"(",
"'c99'",
")",
"toolset",
".",
"add_definitions",
"(",
"[",
"'-D_GNU_SOURCE'",
"]",
")",
"configure",
"=",
"do_configure",
"(",
"toolset",
")",
"configure",
".",
"check_function_exists",
"(",
"'execve'",
",",
"'HAVE_EXECVE'",
")",
"configure",
".",
"check_function_exists",
"(",
"'execv'",
",",
"'HAVE_EXECV'",
")",
"configure",
".",
"check_function_exists",
"(",
"'execvpe'",
",",
"'HAVE_EXECVPE'",
")",
"configure",
".",
"check_function_exists",
"(",
"'execvp'",
",",
"'HAVE_EXECVP'",
")",
"configure",
".",
"check_function_exists",
"(",
"'execvP'",
",",
"'HAVE_EXECVP2'",
")",
"configure",
".",
"check_function_exists",
"(",
"'exect'",
",",
"'HAVE_EXECT'",
")",
"configure",
".",
"check_function_exists",
"(",
"'execl'",
",",
"'HAVE_EXECL'",
")",
"configure",
".",
"check_function_exists",
"(",
"'execlp'",
",",
"'HAVE_EXECLP'",
")",
"configure",
".",
"check_function_exists",
"(",
"'execle'",
",",
"'HAVE_EXECLE'",
")",
"configure",
".",
"check_function_exists",
"(",
"'posix_spawn'",
",",
"'HAVE_POSIX_SPAWN'",
")",
"configure",
".",
"check_function_exists",
"(",
"'posix_spawnp'",
",",
"'HAVE_POSIX_SPAWNP'",
")",
"configure",
".",
"check_symbol_exists",
"(",
"'_NSGetEnviron'",
",",
"'crt_externs.h'",
",",
"'HAVE_NSGETENVIRON'",
")",
"configure",
".",
"write_by_template",
"(",
"os",
".",
"path",
".",
"join",
"(",
"src_dir",
",",
"'config.h.in'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dst_dir",
",",
"'config.h'",
")",
")",
"target",
"=",
"create_shared_library",
"(",
"'ear'",
",",
"toolset",
")",
"target",
".",
"add_include",
"(",
"dst_dir",
")",
"target",
".",
"add_sources",
"(",
"'ear.c'",
")",
"target",
".",
"link_against",
"(",
"toolset",
".",
"dl_libraries",
"(",
")",
")",
"target",
".",
"link_against",
"(",
"[",
"'pthread'",
"]",
")",
"target",
".",
"build_release",
"(",
"dst_dir",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"dst_dir",
",",
"target",
".",
"name",
")",
"except",
"Exception",
":",
"logging",
".",
"info",
"(",
"\"Could not build interception library.\"",
",",
"exc_info",
"=",
"True",
")",
"return",
"None"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/tools/scan-build-py/lib/libear/__init__.py#L19-L58 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/more-itertools/py3/more_itertools/more.py | python | split_before | (iterable, pred, maxsplit=-1) | Yield lists of items from *iterable*, where each list ends just before
an item for which callable *pred* returns ``True``:
>>> list(split_before('OneTwo', lambda s: s.isupper()))
[['O', 'n', 'e'], ['T', 'w', 'o']]
>>> list(split_before(range(10), lambda n: n % 3 == 0))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
then there is no limit on the number of splits:
>>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2))
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]] | Yield lists of items from *iterable*, where each list ends just before
an item for which callable *pred* returns ``True``: | [
"Yield",
"lists",
"of",
"items",
"from",
"*",
"iterable",
"*",
"where",
"each",
"list",
"ends",
"just",
"before",
"an",
"item",
"for",
"which",
"callable",
"*",
"pred",
"*",
"returns",
"True",
":"
] | def split_before(iterable, pred, maxsplit=-1):
"""Yield lists of items from *iterable*, where each list ends just before
an item for which callable *pred* returns ``True``:
>>> list(split_before('OneTwo', lambda s: s.isupper()))
[['O', 'n', 'e'], ['T', 'w', 'o']]
>>> list(split_before(range(10), lambda n: n % 3 == 0))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
then there is no limit on the number of splits:
>>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2))
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
"""
if maxsplit == 0:
yield list(iterable)
return
buf = []
it = iter(iterable)
for item in it:
if pred(item) and buf:
yield buf
if maxsplit == 1:
yield [item] + list(it)
return
buf = []
maxsplit -= 1
buf.append(item)
if buf:
yield buf | [
"def",
"split_before",
"(",
"iterable",
",",
"pred",
",",
"maxsplit",
"=",
"-",
"1",
")",
":",
"if",
"maxsplit",
"==",
"0",
":",
"yield",
"list",
"(",
"iterable",
")",
"return",
"buf",
"=",
"[",
"]",
"it",
"=",
"iter",
"(",
"iterable",
")",
"for",
"item",
"in",
"it",
":",
"if",
"pred",
"(",
"item",
")",
"and",
"buf",
":",
"yield",
"buf",
"if",
"maxsplit",
"==",
"1",
":",
"yield",
"[",
"item",
"]",
"+",
"list",
"(",
"it",
")",
"return",
"buf",
"=",
"[",
"]",
"maxsplit",
"-=",
"1",
"buf",
".",
"append",
"(",
"item",
")",
"if",
"buf",
":",
"yield",
"buf"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py3/more_itertools/more.py#L1365-L1397 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/twodim_base.py | python | triu_indices_from | (arr, k=0) | return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1]) | Return the indices for the upper-triangle of arr.
See `triu_indices` for full details.
Parameters
----------
arr : ndarray, shape(N, N)
The indices will be valid for square arrays.
k : int, optional
Diagonal offset (see `triu` for details).
Returns
-------
triu_indices_from : tuple, shape(2) of ndarray, shape(N)
Indices for the upper-triangle of `arr`.
See Also
--------
triu_indices, triu
Notes
-----
.. versionadded:: 1.4.0 | Return the indices for the upper-triangle of arr. | [
"Return",
"the",
"indices",
"for",
"the",
"upper",
"-",
"triangle",
"of",
"arr",
"."
] | def triu_indices_from(arr, k=0):
"""
Return the indices for the upper-triangle of arr.
See `triu_indices` for full details.
Parameters
----------
arr : ndarray, shape(N, N)
The indices will be valid for square arrays.
k : int, optional
Diagonal offset (see `triu` for details).
Returns
-------
triu_indices_from : tuple, shape(2) of ndarray, shape(N)
Indices for the upper-triangle of `arr`.
See Also
--------
triu_indices, triu
Notes
-----
.. versionadded:: 1.4.0
"""
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1]) | [
"def",
"triu_indices_from",
"(",
"arr",
",",
"k",
"=",
"0",
")",
":",
"if",
"arr",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"input array must be 2-d\"",
")",
"return",
"triu_indices",
"(",
"arr",
".",
"shape",
"[",
"-",
"2",
"]",
",",
"k",
"=",
"k",
",",
"m",
"=",
"arr",
".",
"shape",
"[",
"-",
"1",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/twodim_base.py#L988-L1017 | |
tpfister/caffe-heatmap | 4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e | scripts/cpp_lint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/tpfister/caffe-heatmap/blob/4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e/scripts/cpp_lint.py#L767-L769 | |
PolygonTek/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | Source/ThirdParty/freetype/src/tools/glnames.py | python | filter_glyph_names | ( alist, filter ) | return extras | filter `alist' by taking _out_ all glyph names that are in `filter | filter `alist' by taking _out_ all glyph names that are in `filter | [
"filter",
"alist",
"by",
"taking",
"_out_",
"all",
"glyph",
"names",
"that",
"are",
"in",
"filter"
] | def filter_glyph_names( alist, filter ):
"""filter `alist' by taking _out_ all glyph names that are in `filter'"""
count = 0
extras = []
for name in alist:
try:
filtered_index = filter.index( name )
except:
extras.append( name )
return extras | [
"def",
"filter_glyph_names",
"(",
"alist",
",",
"filter",
")",
":",
"count",
"=",
"0",
"extras",
"=",
"[",
"]",
"for",
"name",
"in",
"alist",
":",
"try",
":",
"filtered_index",
"=",
"filter",
".",
"index",
"(",
"name",
")",
"except",
":",
"extras",
".",
"append",
"(",
"name",
")",
"return",
"extras"
] | https://github.com/PolygonTek/BlueshiftEngine/blob/fbc374cbc391e1147c744649f405a66a27c35d89/Source/ThirdParty/freetype/src/tools/glnames.py#L5196-L5208 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/cygprofile/patch_orderfile.py | python | _SectionMatchingRules | (section_name, name_to_symbol_infos,
offset_to_symbol_infos, section_to_symbols_map,
symbol_to_sections_map, suffixed_sections) | Gets the set of section matching rules for section_name.
These rules will include section_name, but also any sections which may
contain the same code due to cloning, splitting, or identical code folding.
Args:
section_name: The section to expand.
name_to_symbol_infos: {name: [symbol_info1], ...}, as returned by
GetSymbolInfosFromBinary.
offset_to_symbol_infos: {offset: [symbol_info1, ...], ...}
section_to_symbols_map: The mapping from section to symbol name. Missing
section names are treated as per _SectionNameToSymbols.
symbol_to_sections_map: The mapping from symbol name to names of linker
sections containing the symbol. If a symbol isn't in the mapping, the
section names are generated from the set of _PREFIXES with the symbol
name.
suffixed_sections: A set of sections which can have suffixes.
Yields:
Section names including at least section_name. | Gets the set of section matching rules for section_name. | [
"Gets",
"the",
"set",
"of",
"section",
"matching",
"rules",
"for",
"section_name",
"."
] | def _SectionMatchingRules(section_name, name_to_symbol_infos,
offset_to_symbol_infos, section_to_symbols_map,
symbol_to_sections_map, suffixed_sections):
"""Gets the set of section matching rules for section_name.
These rules will include section_name, but also any sections which may
contain the same code due to cloning, splitting, or identical code folding.
Args:
section_name: The section to expand.
name_to_symbol_infos: {name: [symbol_info1], ...}, as returned by
GetSymbolInfosFromBinary.
offset_to_symbol_infos: {offset: [symbol_info1, ...], ...}
section_to_symbols_map: The mapping from section to symbol name. Missing
section names are treated as per _SectionNameToSymbols.
symbol_to_sections_map: The mapping from symbol name to names of linker
sections containing the symbol. If a symbol isn't in the mapping, the
section names are generated from the set of _PREFIXES with the symbol
name.
suffixed_sections: A set of sections which can have suffixes.
Yields:
Section names including at least section_name.
"""
for name in _ExpandSection(section_name, name_to_symbol_infos,
offset_to_symbol_infos, section_to_symbols_map,
symbol_to_sections_map):
yield name
# Since only a subset of methods (mostly those compiled with O2) ever get
# suffixes, don't emit the wildcards for ones where it won't be helpful.
# Otherwise linking takes too long.
if name in suffixed_sections:
# TODO(lizeb,pasko): instead of just appending .*, append .suffix.* for
# _SUFFIXES. We can't do this right now because that many wildcards
# seems to kill the linker (linking libchrome takes 3 hours). This gets
# almost all the benefit at a much lower link-time cost, but could cause
# problems with unexpected suffixes.
yield name + '.*' | [
"def",
"_SectionMatchingRules",
"(",
"section_name",
",",
"name_to_symbol_infos",
",",
"offset_to_symbol_infos",
",",
"section_to_symbols_map",
",",
"symbol_to_sections_map",
",",
"suffixed_sections",
")",
":",
"for",
"name",
"in",
"_ExpandSection",
"(",
"section_name",
",",
"name_to_symbol_infos",
",",
"offset_to_symbol_infos",
",",
"section_to_symbols_map",
",",
"symbol_to_sections_map",
")",
":",
"yield",
"name",
"# Since only a subset of methods (mostly those compiled with O2) ever get",
"# suffixes, don't emit the wildcards for ones where it won't be helpful.",
"# Otherwise linking takes too long.",
"if",
"name",
"in",
"suffixed_sections",
":",
"# TODO(lizeb,pasko): instead of just appending .*, append .suffix.* for",
"# _SUFFIXES. We can't do this right now because that many wildcards",
"# seems to kill the linker (linking libchrome takes 3 hours). This gets",
"# almost all the benefit at a much lower link-time cost, but could cause",
"# problems with unexpected suffixes.",
"yield",
"name",
"+",
"'.*'"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cygprofile/patch_orderfile.py#L221-L258 | ||
manutdzou/KITTI_SSD | 5b620c2f291d36a0fe14489214f22a992f173f44 | scripts/cpp_lint.py | python | ProcessLine | (filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions=[]) | Processes a single line in the file.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
clean_lines: An array of strings, each representing a line of the file,
with comments stripped.
line: Number of line being processed.
include_state: An _IncludeState instance in which the headers are inserted.
function_state: A _FunctionState instance which counts function lines, etc.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Processes a single line in the file. | [
"Processes",
"a",
"single",
"line",
"in",
"the",
"file",
"."
] | def ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions=[]):
"""Processes a single line in the file.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
clean_lines: An array of strings, each representing a line of the file,
with comments stripped.
line: Number of line being processed.
include_state: An _IncludeState instance in which the headers are inserted.
function_state: A _FunctionState instance which counts function lines, etc.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
raw_lines = clean_lines.raw_lines
ParseNolintSuppressions(filename, raw_lines[line], line, error)
nesting_state.Update(filename, clean_lines, line, error)
if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM:
return
CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
CheckLanguage(filename, clean_lines, line, file_extension, include_state,
nesting_state, error)
CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
CheckForNonStandardConstructs(filename, clean_lines, line,
nesting_state, error)
CheckVlogArguments(filename, clean_lines, line, error)
CheckCaffeAlternatives(filename, clean_lines, line, error)
CheckCaffeDataLayerSetUp(filename, clean_lines, line, error)
CheckCaffeRandom(filename, clean_lines, line, error)
CheckPosixThreading(filename, clean_lines, line, error)
CheckInvalidIncrement(filename, clean_lines, line, error)
CheckMakePairUsesDeduction(filename, clean_lines, line, error)
for check_fn in extra_check_functions:
check_fn(filename, clean_lines, line, error) | [
"def",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"raw_lines",
"=",
"clean_lines",
".",
"raw_lines",
"ParseNolintSuppressions",
"(",
"filename",
",",
"raw_lines",
"[",
"line",
"]",
",",
"line",
",",
"error",
")",
"nesting_state",
".",
"Update",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"if",
"nesting_state",
".",
"stack",
"and",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"inline_asm",
"!=",
"_NO_ASM",
":",
"return",
"CheckForFunctionLengths",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"function_state",
",",
"error",
")",
"CheckForMultilineCommentsAndStrings",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckStyle",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"file_extension",
",",
"nesting_state",
",",
"error",
")",
"CheckLanguage",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"file_extension",
",",
"include_state",
",",
"nesting_state",
",",
"error",
")",
"CheckForNonConstReference",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"nesting_state",
",",
"error",
")",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"nesting_state",
",",
"error",
")",
"CheckVlogArguments",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckCaffeAlternatives",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckCaffeDataLayerSetUp",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckCaffeRandom",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckPosixThreading",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckInvalidIncrement",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"CheckMakePairUsesDeduction",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")",
"for",
"check_fn",
"in",
"extra_check_functions",
":",
"check_fn",
"(",
"filename",
",",
"clean_lines",
",",
"line",
",",
"error",
")"
] | https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/scripts/cpp_lint.py#L4604-L4646 | ||
ledger/ledger | 8e79216887cf3c342dfca1ffa52cf4e6389d6de4 | contrib/non-profit-audit-reports/ooolib2/__init__.py | python | Calc.load | (self, filename) | Load .ods spreadsheet.
The load function loads data from a document into the current cells. | Load .ods spreadsheet. | [
"Load",
".",
"ods",
"spreadsheet",
"."
] | def load(self, filename):
"""Load .ods spreadsheet.
The load function loads data from a document into the current cells.
"""
# Read in the important files
# meta.xml
data = self._zip_read(filename, "meta.xml")
self.meta.meta_parse(data)
# content.xml
data = self._zip_read(filename, "content.xml")
self.content_parse(data) | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"# Read in the important files",
"# meta.xml",
"data",
"=",
"self",
".",
"_zip_read",
"(",
"filename",
",",
"\"meta.xml\"",
")",
"self",
".",
"meta",
".",
"meta_parse",
"(",
"data",
")",
"# content.xml",
"data",
"=",
"self",
".",
"_zip_read",
"(",
"filename",
",",
"\"content.xml\"",
")",
"self",
".",
"content_parse",
"(",
"data",
")"
] | https://github.com/ledger/ledger/blob/8e79216887cf3c342dfca1ffa52cf4e6389d6de4/contrib/non-profit-audit-reports/ooolib2/__init__.py#L1028-L1041 | ||
llvm-dcpu16/llvm-dcpu16 | ae6b01fecd03219677e391d4421df5d966d80dcf | bindings/python/llvm/disassembler.py | python | Disassembler.get_instructions | (self, source, pc=0) | Obtain multiple instructions from an input source.
This is like get_instruction() except it is a generator for all
instructions within the source. It starts at the beginning of the
source and reads instructions until no more can be read.
This generator returns 3-tuple of:
long address of instruction.
long size of instruction, in bytes.
str representation of instruction. | Obtain multiple instructions from an input source. | [
"Obtain",
"multiple",
"instructions",
"from",
"an",
"input",
"source",
"."
] | def get_instructions(self, source, pc=0):
"""Obtain multiple instructions from an input source.
This is like get_instruction() except it is a generator for all
instructions within the source. It starts at the beginning of the
source and reads instructions until no more can be read.
This generator returns 3-tuple of:
long address of instruction.
long size of instruction, in bytes.
str representation of instruction.
"""
source_bytes = c_char_p(source)
out_str = cast((c_byte * 255)(), c_char_p)
# This could probably be written cleaner. But, it does work.
buf = cast(source_bytes, POINTER(c_ubyte * len(source))).contents
offset = 0
address = pc
end_address = pc + len(source)
while address < end_address:
b = cast(addressof(buf) + offset, POINTER(c_ubyte))
result = lib.LLVMDisasmInstruction(self, b,
c_uint64(len(source) - offset), c_uint64(address),
out_str, 255)
if result == 0:
break
yield (address, result, out_str.value)
address += result
offset += result | [
"def",
"get_instructions",
"(",
"self",
",",
"source",
",",
"pc",
"=",
"0",
")",
":",
"source_bytes",
"=",
"c_char_p",
"(",
"source",
")",
"out_str",
"=",
"cast",
"(",
"(",
"c_byte",
"*",
"255",
")",
"(",
")",
",",
"c_char_p",
")",
"# This could probably be written cleaner. But, it does work.",
"buf",
"=",
"cast",
"(",
"source_bytes",
",",
"POINTER",
"(",
"c_ubyte",
"*",
"len",
"(",
"source",
")",
")",
")",
".",
"contents",
"offset",
"=",
"0",
"address",
"=",
"pc",
"end_address",
"=",
"pc",
"+",
"len",
"(",
"source",
")",
"while",
"address",
"<",
"end_address",
":",
"b",
"=",
"cast",
"(",
"addressof",
"(",
"buf",
")",
"+",
"offset",
",",
"POINTER",
"(",
"c_ubyte",
")",
")",
"result",
"=",
"lib",
".",
"LLVMDisasmInstruction",
"(",
"self",
",",
"b",
",",
"c_uint64",
"(",
"len",
"(",
"source",
")",
"-",
"offset",
")",
",",
"c_uint64",
"(",
"address",
")",
",",
"out_str",
",",
"255",
")",
"if",
"result",
"==",
"0",
":",
"break",
"yield",
"(",
"address",
",",
"result",
",",
"out_str",
".",
"value",
")",
"address",
"+=",
"result",
"offset",
"+=",
"result"
] | https://github.com/llvm-dcpu16/llvm-dcpu16/blob/ae6b01fecd03219677e391d4421df5d966d80dcf/bindings/python/llvm/disassembler.py#L81-L114 | ||
google/skia | 82d65d0487bd72f5f7332d002429ec2dc61d2463 | infra/bots/recipes/perf_skottietrace.py | python | get_trace_match | (lottie_filename, is_android) | return trace_match | Returns the DM regex to match the specified lottie file name. | Returns the DM regex to match the specified lottie file name. | [
"Returns",
"the",
"DM",
"regex",
"to",
"match",
"the",
"specified",
"lottie",
"file",
"name",
"."
] | def get_trace_match(lottie_filename, is_android):
"""Returns the DM regex to match the specified lottie file name."""
trace_match = '^%s$' % lottie_filename
if is_android and ' ' not in trace_match:
# Punctuation characters confuse DM when shelled out over adb, so escape
# them. Do not need to do this when there is a space in the match because
# subprocess.list2cmdline automatically adds quotes in that case.
for sp_char in string.punctuation:
if sp_char == '\\':
# No need to escape the escape char.
continue
trace_match = trace_match.replace(sp_char, '\%s' % sp_char)
return trace_match | [
"def",
"get_trace_match",
"(",
"lottie_filename",
",",
"is_android",
")",
":",
"trace_match",
"=",
"'^%s$'",
"%",
"lottie_filename",
"if",
"is_android",
"and",
"' '",
"not",
"in",
"trace_match",
":",
"# Punctuation characters confuse DM when shelled out over adb, so escape",
"# them. Do not need to do this when there is a space in the match because",
"# subprocess.list2cmdline automatically adds quotes in that case.",
"for",
"sp_char",
"in",
"string",
".",
"punctuation",
":",
"if",
"sp_char",
"==",
"'\\\\'",
":",
"# No need to escape the escape char.",
"continue",
"trace_match",
"=",
"trace_match",
".",
"replace",
"(",
"sp_char",
",",
"'\\%s'",
"%",
"sp_char",
")",
"return",
"trace_match"
] | https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/recipes/perf_skottietrace.py#L128-L140 | |
OpenGenus/cosmos | 1a94e8880068e51d571543be179c323936bd0936 | code/game_theory/src/minimax/minimax.py | python | minimax | (player: int, board, depth_limit, evaluate) | return placement | Minimax algorithm with limited search depth.
Parameters
----------
player: int
the player that needs to take an action (place a disc in the game)
board: the current game board instance. Should be a class that extends Board
depth_limit: int
the tree depth that the search algorithm needs to go further before stopping
evaluate: fn[Board, int]
Some function that evaluates the board at the current position
Returns
-------
placement: int or None
the column in which a disc should be placed for the specific player
(counted from the most left as 0)
None to give up the game | Minimax algorithm with limited search depth. | [
"Minimax",
"algorithm",
"with",
"limited",
"search",
"depth",
"."
] | def minimax(player: int, board, depth_limit, evaluate):
"""
Minimax algorithm with limited search depth.
Parameters
----------
player: int
the player that needs to take an action (place a disc in the game)
board: the current game board instance. Should be a class that extends Board
depth_limit: int
the tree depth that the search algorithm needs to go further before stopping
evaluate: fn[Board, int]
Some function that evaluates the board at the current position
Returns
-------
placement: int or None
the column in which a disc should be placed for the specific player
(counted from the most left as 0)
None to give up the game
"""
max_player = player
next_player = board.PLAYER2 if player == board.PLAYER1 else board.PLAYER1
def value(board, depth_limit):
""" Evaluate the board at the current state
Args:
board (Board): Current board state
depth_limit (int): Depth limit
Returns:
float: Value of the board
"""
return evaluate(player, board)
def max_value(board, depth_limit: int) -> float:
""" Calculate the maximum value for play if players acts optimally
Args:
player (int): Player token to maximize value of
board (Board): Current board state
depth_limit (int): Depth limit
Returns:
float: Maximum value possible if players play optimally
"""
# Check if terminal or depth limit has been reached
if depth_limit == 0 or board.terminal():
# If leaf node return the calculated board value
return value(board, depth_limit)
# If not leaf then continue searching for maximum value
best_value = -math.inf
# Generate all possible moves for maximizing player and store the
# max possible value while exploring down to terminal nodes
for move, child_board in board.get_child_boards(player):
best_value = max(best_value, min_value(child_board, depth_limit - 1))
return best_value
def min_value(board, depth_limit: int) -> float:
""" Calculate the minimum value for play of players acts optimally
Args:
player (int): Player token to minimize value of
board (Board): Current board state
depth_limit (int): Depth limit
Returns:
float: Minimum value possible if players play optimally
"""
# Check if terminal or depth limit has been reached
if depth_limit == 0 or board.terminal():
# If leaf node return the calculated board value
return value(board, depth_limit)
# If not leaf then continue searching for minimum value
best_value = math.inf
# Generate all possible moves for minimizing player and store the
# min possible value while exploring down to terminal nodes
for move, child_board in board.get_child_boards(next_player):
best_value = min(best_value, max_value(child_board, depth_limit - 1))
return best_value
# Start off with the best score as low as possible. We want to maximize
# this for our turn
best_score = -math.inf
placement = None
# Generate all possible moves and boards for the current player
for pot_move, pot_board in board.get_child_boards(player):
# Calculate the minimum score for the player at this board
pot_score = min_value(pot_board, depth_limit - 1)
# If this is greater than the best_score then update
if pot_score > best_score:
best_score = pot_score
placement = pot_move
return placement | [
"def",
"minimax",
"(",
"player",
":",
"int",
",",
"board",
",",
"depth_limit",
",",
"evaluate",
")",
":",
"max_player",
"=",
"player",
"next_player",
"=",
"board",
".",
"PLAYER2",
"if",
"player",
"==",
"board",
".",
"PLAYER1",
"else",
"board",
".",
"PLAYER1",
"def",
"value",
"(",
"board",
",",
"depth_limit",
")",
":",
"\"\"\" Evaluate the board at the current state\n Args:\n board (Board): Current board state\n depth_limit (int): Depth limit\n\n Returns:\n float: Value of the board\n \"\"\"",
"return",
"evaluate",
"(",
"player",
",",
"board",
")",
"def",
"max_value",
"(",
"board",
",",
"depth_limit",
":",
"int",
")",
"->",
"float",
":",
"\"\"\" Calculate the maximum value for play if players acts optimally\n Args:\n player (int): Player token to maximize value of\n board (Board): Current board state\n depth_limit (int): Depth limit\n\n Returns:\n float: Maximum value possible if players play optimally\n \"\"\"",
"# Check if terminal or depth limit has been reached",
"if",
"depth_limit",
"==",
"0",
"or",
"board",
".",
"terminal",
"(",
")",
":",
"# If leaf node return the calculated board value",
"return",
"value",
"(",
"board",
",",
"depth_limit",
")",
"# If not leaf then continue searching for maximum value",
"best_value",
"=",
"-",
"math",
".",
"inf",
"# Generate all possible moves for maximizing player and store the",
"# max possible value while exploring down to terminal nodes",
"for",
"move",
",",
"child_board",
"in",
"board",
".",
"get_child_boards",
"(",
"player",
")",
":",
"best_value",
"=",
"max",
"(",
"best_value",
",",
"min_value",
"(",
"child_board",
",",
"depth_limit",
"-",
"1",
")",
")",
"return",
"best_value",
"def",
"min_value",
"(",
"board",
",",
"depth_limit",
":",
"int",
")",
"->",
"float",
":",
"\"\"\" Calculate the minimum value for play of players acts optimally\n Args:\n player (int): Player token to minimize value of\n board (Board): Current board state\n depth_limit (int): Depth limit\n\n Returns:\n float: Minimum value possible if players play optimally\n \"\"\"",
"# Check if terminal or depth limit has been reached",
"if",
"depth_limit",
"==",
"0",
"or",
"board",
".",
"terminal",
"(",
")",
":",
"# If leaf node return the calculated board value",
"return",
"value",
"(",
"board",
",",
"depth_limit",
")",
"# If not leaf then continue searching for minimum value",
"best_value",
"=",
"math",
".",
"inf",
"# Generate all possible moves for minimizing player and store the",
"# min possible value while exploring down to terminal nodes",
"for",
"move",
",",
"child_board",
"in",
"board",
".",
"get_child_boards",
"(",
"next_player",
")",
":",
"best_value",
"=",
"min",
"(",
"best_value",
",",
"max_value",
"(",
"child_board",
",",
"depth_limit",
"-",
"1",
")",
")",
"return",
"best_value",
"# Start off with the best score as low as possible. We want to maximize",
"# this for our turn",
"best_score",
"=",
"-",
"math",
".",
"inf",
"placement",
"=",
"None",
"# Generate all possible moves and boards for the current player",
"for",
"pot_move",
",",
"pot_board",
"in",
"board",
".",
"get_child_boards",
"(",
"player",
")",
":",
"# Calculate the minimum score for the player at this board",
"pot_score",
"=",
"min_value",
"(",
"pot_board",
",",
"depth_limit",
"-",
"1",
")",
"# If this is greater than the best_score then update",
"if",
"pot_score",
">",
"best_score",
":",
"best_score",
"=",
"pot_score",
"placement",
"=",
"pot_move",
"return",
"placement"
] | https://github.com/OpenGenus/cosmos/blob/1a94e8880068e51d571543be179c323936bd0936/code/game_theory/src/minimax/minimax.py#L40-L137 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | Gauge.GetBezelFace | (*args, **kwargs) | return _controls_.Gauge_GetBezelFace(*args, **kwargs) | GetBezelFace(self) -> int | GetBezelFace(self) -> int | [
"GetBezelFace",
"(",
"self",
")",
"-",
">",
"int"
] | def GetBezelFace(*args, **kwargs):
"""GetBezelFace(self) -> int"""
return _controls_.Gauge_GetBezelFace(*args, **kwargs) | [
"def",
"GetBezelFace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Gauge_GetBezelFace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L783-L785 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py | python | Index._get_nearest_indexer | (self, target, limit, tolerance) | return indexer | Get the indexer for the nearest index labels; requires an index with
values that can be subtracted from each other (e.g., not strings or
tuples). | Get the indexer for the nearest index labels; requires an index with
values that can be subtracted from each other (e.g., not strings or
tuples). | [
"Get",
"the",
"indexer",
"for",
"the",
"nearest",
"index",
"labels",
";",
"requires",
"an",
"index",
"with",
"values",
"that",
"can",
"be",
"subtracted",
"from",
"each",
"other",
"(",
"e",
".",
"g",
".",
"not",
"strings",
"or",
"tuples",
")",
"."
] | def _get_nearest_indexer(self, target, limit, tolerance):
"""
Get the indexer for the nearest index labels; requires an index with
values that can be subtracted from each other (e.g., not strings or
tuples).
"""
left_indexer = self.get_indexer(target, "pad", limit=limit)
right_indexer = self.get_indexer(target, "backfill", limit=limit)
left_distances = np.abs(self[left_indexer] - target)
right_distances = np.abs(self[right_indexer] - target)
op = operator.lt if self.is_monotonic_increasing else operator.le
indexer = np.where(
op(left_distances, right_distances) | (right_indexer == -1),
left_indexer,
right_indexer,
)
if tolerance is not None:
indexer = self._filter_indexer_tolerance(target, indexer, tolerance)
return indexer | [
"def",
"_get_nearest_indexer",
"(",
"self",
",",
"target",
",",
"limit",
",",
"tolerance",
")",
":",
"left_indexer",
"=",
"self",
".",
"get_indexer",
"(",
"target",
",",
"\"pad\"",
",",
"limit",
"=",
"limit",
")",
"right_indexer",
"=",
"self",
".",
"get_indexer",
"(",
"target",
",",
"\"backfill\"",
",",
"limit",
"=",
"limit",
")",
"left_distances",
"=",
"np",
".",
"abs",
"(",
"self",
"[",
"left_indexer",
"]",
"-",
"target",
")",
"right_distances",
"=",
"np",
".",
"abs",
"(",
"self",
"[",
"right_indexer",
"]",
"-",
"target",
")",
"op",
"=",
"operator",
".",
"lt",
"if",
"self",
".",
"is_monotonic_increasing",
"else",
"operator",
".",
"le",
"indexer",
"=",
"np",
".",
"where",
"(",
"op",
"(",
"left_distances",
",",
"right_distances",
")",
"|",
"(",
"right_indexer",
"==",
"-",
"1",
")",
",",
"left_indexer",
",",
"right_indexer",
",",
")",
"if",
"tolerance",
"is",
"not",
"None",
":",
"indexer",
"=",
"self",
".",
"_filter_indexer_tolerance",
"(",
"target",
",",
"indexer",
",",
"tolerance",
")",
"return",
"indexer"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L2811-L2831 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | buildscripts/resmokelib/utils/__init__.py | python | is_yaml_file | (filename) | return os.path.splitext(filename)[1] in (".yaml", ".yml") | Returns true if 'filename' ends in .yml or .yaml, and false
otherwise. | Returns true if 'filename' ends in .yml or .yaml, and false
otherwise. | [
"Returns",
"true",
"if",
"filename",
"ends",
"in",
".",
"yml",
"or",
".",
"yaml",
"and",
"false",
"otherwise",
"."
] | def is_yaml_file(filename):
"""
Returns true if 'filename' ends in .yml or .yaml, and false
otherwise.
"""
return os.path.splitext(filename)[1] in (".yaml", ".yml") | [
"def",
"is_yaml_file",
"(",
"filename",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
"in",
"(",
"\".yaml\"",
",",
"\".yml\"",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/resmokelib/utils/__init__.py#L38-L43 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | Decimal.scaleb | (self, other, context=None) | return d | Returns self operand after adding the second value to its exp. | Returns self operand after adding the second value to its exp. | [
"Returns",
"self",
"operand",
"after",
"adding",
"the",
"second",
"value",
"to",
"its",
"exp",
"."
] | def scaleb(self, other, context=None):
"""Returns self operand after adding the second value to its exp."""
if context is None:
context = getcontext()
other = _convert_other(other, raiseit=True)
ans = self._check_nans(other, context)
if ans:
return ans
if other._exp != 0:
return context._raise_error(InvalidOperation)
liminf = -2 * (context.Emax + context.prec)
limsup = 2 * (context.Emax + context.prec)
if not (liminf <= int(other) <= limsup):
return context._raise_error(InvalidOperation)
if self._isinfinity():
return Decimal(self)
d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
d = d._fix(context)
return d | [
"def",
"scaleb",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"ans",
"=",
"self",
".",
"_check_nans",
"(",
"other",
",",
"context",
")",
"if",
"ans",
":",
"return",
"ans",
"if",
"other",
".",
"_exp",
"!=",
"0",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
")",
"liminf",
"=",
"-",
"2",
"*",
"(",
"context",
".",
"Emax",
"+",
"context",
".",
"prec",
")",
"limsup",
"=",
"2",
"*",
"(",
"context",
".",
"Emax",
"+",
"context",
".",
"prec",
")",
"if",
"not",
"(",
"liminf",
"<=",
"int",
"(",
"other",
")",
"<=",
"limsup",
")",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
")",
"if",
"self",
".",
"_isinfinity",
"(",
")",
":",
"return",
"Decimal",
"(",
"self",
")",
"d",
"=",
"_dec_from_triple",
"(",
"self",
".",
"_sign",
",",
"self",
".",
"_int",
",",
"self",
".",
"_exp",
"+",
"int",
"(",
"other",
")",
")",
"d",
"=",
"d",
".",
"_fix",
"(",
"context",
")",
"return",
"d"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L3565-L3588 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/framework/ops.py | python | container | (container_name) | return get_default_graph().container(container_name) | Wrapper for `Graph.container()` using the default graph.
Args:
container_name: The container string to use in the context.
Returns:
A context manager that specifies the default container to use for newly
created stateful ops. | Wrapper for `Graph.container()` using the default graph. | [
"Wrapper",
"for",
"Graph",
".",
"container",
"()",
"using",
"the",
"default",
"graph",
"."
] | def container(container_name):
"""Wrapper for `Graph.container()` using the default graph.
Args:
container_name: The container string to use in the context.
Returns:
A context manager that specifies the default container to use for newly
created stateful ops.
"""
return get_default_graph().container(container_name) | [
"def",
"container",
"(",
"container_name",
")",
":",
"return",
"get_default_graph",
"(",
")",
".",
"container",
"(",
"container_name",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L3450-L3460 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/http/cookiejar.py | python | CookiePolicy.return_ok | (self, cookie, request) | Return true if (and only if) cookie should be returned to server. | Return true if (and only if) cookie should be returned to server. | [
"Return",
"true",
"if",
"(",
"and",
"only",
"if",
")",
"cookie",
"should",
"be",
"returned",
"to",
"server",
"."
] | def return_ok(self, cookie, request):
"""Return true if (and only if) cookie should be returned to server."""
raise NotImplementedError() | [
"def",
"return_ok",
"(",
"self",
",",
"cookie",
",",
"request",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/http/cookiejar.py#L852-L854 | ||
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/multiview.py | python | camera_up_vector | (rotation_matrix) | return rotation_matrix[:, 2] | Unit vector pointing to zenit in camera coords.
:param rotation: camera pose rotation | Unit vector pointing to zenit in camera coords. | [
"Unit",
"vector",
"pointing",
"to",
"zenit",
"in",
"camera",
"coords",
"."
] | def camera_up_vector(rotation_matrix):
"""Unit vector pointing to zenit in camera coords.
:param rotation: camera pose rotation
"""
return rotation_matrix[:, 2] | [
"def",
"camera_up_vector",
"(",
"rotation_matrix",
")",
":",
"return",
"rotation_matrix",
"[",
":",
",",
"2",
"]"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/multiview.py#L443-L448 | |
tiny-dnn/tiny-dnn | c0f576f5cb7b35893f62127cb7aec18f77a3bcc5 | third_party/cpplint.py | python | IsBlockInNameSpace | (nesting_state, is_forward_declaration) | return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.stack[-2], _NamespaceInfo)) | Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace. | Checks that the new block is directly in a namespace. | [
"Checks",
"that",
"the",
"new",
"block",
"is",
"directly",
"in",
"a",
"namespace",
"."
] | def IsBlockInNameSpace(nesting_state, is_forward_declaration):
"""Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace.
"""
if is_forward_declaration:
return len(nesting_state.stack) >= 1 and (
isinstance(nesting_state.stack[-1], _NamespaceInfo))
return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.stack[-2], _NamespaceInfo)) | [
"def",
"IsBlockInNameSpace",
"(",
"nesting_state",
",",
"is_forward_declaration",
")",
":",
"if",
"is_forward_declaration",
":",
"return",
"len",
"(",
"nesting_state",
".",
"stack",
")",
">=",
"1",
"and",
"(",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_NamespaceInfo",
")",
")",
"return",
"(",
"len",
"(",
"nesting_state",
".",
"stack",
")",
">",
"1",
"and",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"check_namespace_indentation",
"and",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"2",
"]",
",",
"_NamespaceInfo",
")",
")"
] | https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/cpplint.py#L5878-L5894 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/bijector/bijector.py | python | Bijector.inverse_log_jacobian | (self, value, *args, **kwargs) | return self._inverse_log_jacobian(value, *args, **kwargs) | Logarithm of the derivative of the inverse transformation.
Args:
value (Tensor): the value of the transformed variables.
*args (list): the list of positional arguments forwarded to subclasses.
**kwargs (dict): the dictionary of keyword arguments forwarded to subclasses.
Output:
Tensor, the value of logarithm of the derivative of the inverse transformation. | Logarithm of the derivative of the inverse transformation. | [
"Logarithm",
"of",
"the",
"derivative",
"of",
"the",
"inverse",
"transformation",
"."
] | def inverse_log_jacobian(self, value, *args, **kwargs):
"""
Logarithm of the derivative of the inverse transformation.
Args:
value (Tensor): the value of the transformed variables.
*args (list): the list of positional arguments forwarded to subclasses.
**kwargs (dict): the dictionary of keyword arguments forwarded to subclasses.
Output:
Tensor, the value of logarithm of the derivative of the inverse transformation.
"""
return self._inverse_log_jacobian(value, *args, **kwargs) | [
"def",
"inverse_log_jacobian",
"(",
"self",
",",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_inverse_log_jacobian",
"(",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/bijector/bijector.py#L279-L291 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/datasets/twenty_newsgroups.py | python | strip_newsgroup_footer | (text) | Given text in "news" format, attempt to remove a signature block.
As a rough heuristic, we assume that signatures are set apart by either
a blank line or a line made of hyphens, and that it is the last such line
in the file (disregarding blank lines at the end). | Given text in "news" format, attempt to remove a signature block. | [
"Given",
"text",
"in",
"news",
"format",
"attempt",
"to",
"remove",
"a",
"signature",
"block",
"."
] | def strip_newsgroup_footer(text):
"""
Given text in "news" format, attempt to remove a signature block.
As a rough heuristic, we assume that signatures are set apart by either
a blank line or a line made of hyphens, and that it is the last such line
in the file (disregarding blank lines at the end).
"""
lines = text.strip().split('\n')
for line_num in range(len(lines) - 1, -1, -1):
line = lines[line_num]
if line.strip().strip('-') == '':
break
if line_num > 0:
return '\n'.join(lines[:line_num])
else:
return text | [
"def",
"strip_newsgroup_footer",
"(",
"text",
")",
":",
"lines",
"=",
"text",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line_num",
"in",
"range",
"(",
"len",
"(",
"lines",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"line",
"=",
"lines",
"[",
"line_num",
"]",
"if",
"line",
".",
"strip",
"(",
")",
".",
"strip",
"(",
"'-'",
")",
"==",
"''",
":",
"break",
"if",
"line_num",
">",
"0",
":",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
"[",
":",
"line_num",
"]",
")",
"else",
":",
"return",
"text"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/datasets/twenty_newsgroups.py#L134-L151 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/util/response.py | python | is_fp_closed | (obj) | Checks whether a given file-like object is closed.
:param obj:
The file-like object to check. | Checks whether a given file-like object is closed. | [
"Checks",
"whether",
"a",
"given",
"file",
"-",
"like",
"object",
"is",
"closed",
"."
] | def is_fp_closed(obj):
"""
Checks whether a given file-like object is closed.
:param obj:
The file-like object to check.
"""
try:
# Check via the official file-like-object way.
return obj.closed
except AttributeError:
pass
try:
# Check if the object is a container for another file-like object that
# gets released on exhaustion (e.g. HTTPResponse).
return obj.fp is None
except AttributeError:
pass
raise ValueError("Unable to determine whether fp is closed.") | [
"def",
"is_fp_closed",
"(",
"obj",
")",
":",
"try",
":",
"# Check via the official file-like-object way.",
"return",
"obj",
".",
"closed",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"# Check if the object is a container for another file-like object that",
"# gets released on exhaustion (e.g. HTTPResponse).",
"return",
"obj",
".",
"fp",
"is",
"None",
"except",
"AttributeError",
":",
"pass",
"raise",
"ValueError",
"(",
"\"Unable to determine whether fp is closed.\"",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/util/response.py#L1-L22 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/pdb.py | python | Pdb.handle_command_def | (self,line) | return | Handles one command line during command list definition. | Handles one command line during command list definition. | [
"Handles",
"one",
"command",
"line",
"during",
"command",
"list",
"definition",
"."
] | def handle_command_def(self,line):
"""Handles one command line during command list definition."""
cmd, arg, line = self.parseline(line)
if not cmd:
return
if cmd == 'silent':
self.commands_silent[self.commands_bnum] = True
return # continue to handle other cmd def in the cmd list
elif cmd == 'end':
self.cmdqueue = []
return 1 # end of cmd list
cmdlist = self.commands[self.commands_bnum]
if arg:
cmdlist.append(cmd+' '+arg)
else:
cmdlist.append(cmd)
# Determine if we must stop
try:
func = getattr(self, 'do_' + cmd)
except AttributeError:
func = self.default
# one of the resuming commands
if func.func_name in self.commands_resuming:
self.commands_doprompt[self.commands_bnum] = False
self.cmdqueue = []
return 1
return | [
"def",
"handle_command_def",
"(",
"self",
",",
"line",
")",
":",
"cmd",
",",
"arg",
",",
"line",
"=",
"self",
".",
"parseline",
"(",
"line",
")",
"if",
"not",
"cmd",
":",
"return",
"if",
"cmd",
"==",
"'silent'",
":",
"self",
".",
"commands_silent",
"[",
"self",
".",
"commands_bnum",
"]",
"=",
"True",
"return",
"# continue to handle other cmd def in the cmd list",
"elif",
"cmd",
"==",
"'end'",
":",
"self",
".",
"cmdqueue",
"=",
"[",
"]",
"return",
"1",
"# end of cmd list",
"cmdlist",
"=",
"self",
".",
"commands",
"[",
"self",
".",
"commands_bnum",
"]",
"if",
"arg",
":",
"cmdlist",
".",
"append",
"(",
"cmd",
"+",
"' '",
"+",
"arg",
")",
"else",
":",
"cmdlist",
".",
"append",
"(",
"cmd",
")",
"# Determine if we must stop",
"try",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"'do_'",
"+",
"cmd",
")",
"except",
"AttributeError",
":",
"func",
"=",
"self",
".",
"default",
"# one of the resuming commands",
"if",
"func",
".",
"func_name",
"in",
"self",
".",
"commands_resuming",
":",
"self",
".",
"commands_doprompt",
"[",
"self",
".",
"commands_bnum",
"]",
"=",
"False",
"self",
".",
"cmdqueue",
"=",
"[",
"]",
"return",
"1",
"return"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pdb.py#L283-L309 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/external/bazel_tools/tools/objc/j2objc_dead_code_pruner.py | python | BuildReachableFileSet | (entry_classes, reachability_tree, header_mapping,
archive_source_file_mapping=None) | return reachable_files | Builds a set of reachable translated files from entry Java classes.
Args:
entry_classes: A comma separated list of Java entry classes.
reachability_tree: A dict mapping translated files to their direct
dependencies.
header_mapping: A dict mapping Java class names to translated source files.
archive_source_file_mapping: A dict mapping source files to the associated
archive file that contains them.
Returns:
A set of reachable translated files from the given list of entry classes.
Raises:
Exception: If there is an entry class that is not being transpiled in this
j2objc_library. | Builds a set of reachable translated files from entry Java classes. | [
"Builds",
"a",
"set",
"of",
"reachable",
"translated",
"files",
"from",
"entry",
"Java",
"classes",
"."
] | def BuildReachableFileSet(entry_classes, reachability_tree, header_mapping,
archive_source_file_mapping=None):
"""Builds a set of reachable translated files from entry Java classes.
Args:
entry_classes: A comma separated list of Java entry classes.
reachability_tree: A dict mapping translated files to their direct
dependencies.
header_mapping: A dict mapping Java class names to translated source files.
archive_source_file_mapping: A dict mapping source files to the associated
archive file that contains them.
Returns:
A set of reachable translated files from the given list of entry classes.
Raises:
Exception: If there is an entry class that is not being transpiled in this
j2objc_library.
"""
transpiled_entry_files = []
for entry_class in entry_classes.split(','):
if entry_class not in header_mapping:
raise Exception(entry_class +
'is not in the transitive Java deps of included ' +
'j2objc_library rules.')
transpiled_entry_files.append(header_mapping[entry_class])
# Translated files going into the same static library archive with duplicated
# base names also need to be added to the set of entry files.
#
# This edge case is ignored because we currently cannot correctly perform
# dead code removal in this case. The object file entries in static library
# archives are named by the base names of the original source files. If two
# source files (e.g., foo/bar.m, bar/bar.m) go into the same archive and
# share the same base name (bar.m), their object file entries inside the
# archive will have the same name (bar.o). We cannot correctly handle this
# case because current archive tools (ar, ranlib, etc.) do not handle this
# case very well.
if archive_source_file_mapping:
transpiled_entry_files.extend(_DuplicatedFiles(archive_source_file_mapping))
# Translated files from package-info.java are also added to the entry files
# because they are needed to resolve ObjC class names with prefixes and these
# files may also have dependencies.
for transpiled_file in reachability_tree:
if transpiled_file.endswith('package-info'):
transpiled_entry_files.append(transpiled_file)
reachable_files = set()
for transpiled_entry_file in transpiled_entry_files:
reachable_files.add(transpiled_entry_file)
current_level_deps = []
# We need to check if the transpiled file is in the reachability tree
# because J2ObjC protos are not analyzed for dead code stripping and
# therefore are not in the reachability tree at all.
if transpiled_entry_file in reachability_tree:
current_level_deps = reachability_tree[transpiled_entry_file]
while current_level_deps:
next_level_deps = []
for dep in current_level_deps:
if dep not in reachable_files:
reachable_files.add(dep)
if dep in reachability_tree:
next_level_deps.extend(reachability_tree[dep])
current_level_deps = next_level_deps
return reachable_files | [
"def",
"BuildReachableFileSet",
"(",
"entry_classes",
",",
"reachability_tree",
",",
"header_mapping",
",",
"archive_source_file_mapping",
"=",
"None",
")",
":",
"transpiled_entry_files",
"=",
"[",
"]",
"for",
"entry_class",
"in",
"entry_classes",
".",
"split",
"(",
"','",
")",
":",
"if",
"entry_class",
"not",
"in",
"header_mapping",
":",
"raise",
"Exception",
"(",
"entry_class",
"+",
"'is not in the transitive Java deps of included '",
"+",
"'j2objc_library rules.'",
")",
"transpiled_entry_files",
".",
"append",
"(",
"header_mapping",
"[",
"entry_class",
"]",
")",
"# Translated files going into the same static library archive with duplicated",
"# base names also need to be added to the set of entry files.",
"#",
"# This edge case is ignored because we currently cannot correctly perform",
"# dead code removal in this case. The object file entries in static library",
"# archives are named by the base names of the original source files. If two",
"# source files (e.g., foo/bar.m, bar/bar.m) go into the same archive and",
"# share the same base name (bar.m), their object file entries inside the",
"# archive will have the same name (bar.o). We cannot correctly handle this",
"# case because current archive tools (ar, ranlib, etc.) do not handle this",
"# case very well.",
"if",
"archive_source_file_mapping",
":",
"transpiled_entry_files",
".",
"extend",
"(",
"_DuplicatedFiles",
"(",
"archive_source_file_mapping",
")",
")",
"# Translated files from package-info.java are also added to the entry files",
"# because they are needed to resolve ObjC class names with prefixes and these",
"# files may also have dependencies.",
"for",
"transpiled_file",
"in",
"reachability_tree",
":",
"if",
"transpiled_file",
".",
"endswith",
"(",
"'package-info'",
")",
":",
"transpiled_entry_files",
".",
"append",
"(",
"transpiled_file",
")",
"reachable_files",
"=",
"set",
"(",
")",
"for",
"transpiled_entry_file",
"in",
"transpiled_entry_files",
":",
"reachable_files",
".",
"add",
"(",
"transpiled_entry_file",
")",
"current_level_deps",
"=",
"[",
"]",
"# We need to check if the transpiled file is in the reachability tree",
"# because J2ObjC protos are not analyzed for dead code stripping and",
"# therefore are not in the reachability tree at all.",
"if",
"transpiled_entry_file",
"in",
"reachability_tree",
":",
"current_level_deps",
"=",
"reachability_tree",
"[",
"transpiled_entry_file",
"]",
"while",
"current_level_deps",
":",
"next_level_deps",
"=",
"[",
"]",
"for",
"dep",
"in",
"current_level_deps",
":",
"if",
"dep",
"not",
"in",
"reachable_files",
":",
"reachable_files",
".",
"add",
"(",
"dep",
")",
"if",
"dep",
"in",
"reachability_tree",
":",
"next_level_deps",
".",
"extend",
"(",
"reachability_tree",
"[",
"dep",
"]",
")",
"current_level_deps",
"=",
"next_level_deps",
"return",
"reachable_files"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/tools/objc/j2objc_dead_code_pruner.py#L88-L151 | |
xbmc/xbmc | 091211a754589fc40a2a1f239b0ce9f4ee138268 | addons/metadata.tvshows.themoviedb.org.python/libs/data_utils.py | python | _set_unique_ids | (ext_ids, list_item) | return list_item | Extract unique ID in various online databases | Extract unique ID in various online databases | [
"Extract",
"unique",
"ID",
"in",
"various",
"online",
"databases"
] | def _set_unique_ids(ext_ids, list_item):
# type: (InfoType, ListItem) -> ListItem
"""Extract unique ID in various online databases"""
unique_ids = {}
for key, value in ext_ids.items():
if key in VALIDEXTIDS and value:
key = key[:-3]
unique_ids[key] = str(value)
list_item.setUniqueIDs(unique_ids, 'tmdb')
return list_item | [
"def",
"_set_unique_ids",
"(",
"ext_ids",
",",
"list_item",
")",
":",
"# type: (InfoType, ListItem) -> ListItem",
"unique_ids",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"ext_ids",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"VALIDEXTIDS",
"and",
"value",
":",
"key",
"=",
"key",
"[",
":",
"-",
"3",
"]",
"unique_ids",
"[",
"key",
"]",
"=",
"str",
"(",
"value",
")",
"list_item",
".",
"setUniqueIDs",
"(",
"unique_ids",
",",
"'tmdb'",
")",
"return",
"list_item"
] | https://github.com/xbmc/xbmc/blob/091211a754589fc40a2a1f239b0ce9f4ee138268/addons/metadata.tvshows.themoviedb.org.python/libs/data_utils.py#L115-L124 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/scons.py | python | EscapeSConsVariableExpansion | (s) | return s.replace('$', '$$$$') | SCons has its own variable expansion syntax using $. We must escape it for
strings to be interpreted literally. For some reason this requires four
dollar signs, not two, even without the shell involved. | SCons has its own variable expansion syntax using $. We must escape it for
strings to be interpreted literally. For some reason this requires four
dollar signs, not two, even without the shell involved. | [
"SCons",
"has",
"its",
"own",
"variable",
"expansion",
"syntax",
"using",
"$",
".",
"We",
"must",
"escape",
"it",
"for",
"strings",
"to",
"be",
"interpreted",
"literally",
".",
"For",
"some",
"reason",
"this",
"requires",
"four",
"dollar",
"signs",
"not",
"two",
"even",
"without",
"the",
"shell",
"involved",
"."
] | def EscapeSConsVariableExpansion(s):
"""SCons has its own variable expansion syntax using $. We must escape it for
strings to be interpreted literally. For some reason this requires four
dollar signs, not two, even without the shell involved."""
return s.replace('$', '$$$$') | [
"def",
"EscapeSConsVariableExpansion",
"(",
"s",
")",
":",
"return",
"s",
".",
"replace",
"(",
"'$'",
",",
"'$$$$'",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/scons.py#L189-L193 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.